home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / pyth_os2.zip / python-1.0.2 / Python / import.c < prev    next >
C/C++ Source or Header  |  1994-05-03  |  13KB  |  592 lines

  1. /***********************************************************
  2. Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
  3. Amsterdam, 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 not be used in advertising or publicity pertaining to
  13. distribution of the software without specific, written prior permission.
  14.  
  15. STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
  16. THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  17. FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
  18. FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  19. WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  20. ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  21. OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  22.  
  23. ******************************************************************/
  24.  
  25. /* Module definition and import implementation */
  26.  
  27. #include "allobjects.h"
  28.  
  29. #include "node.h"
  30. #include "token.h"
  31. #include "graminit.h"
  32. #include "import.h"
  33. #include "errcode.h"
  34. #include "sysmodule.h"
  35. #include "pythonrun.h"
  36. #include "marshal.h"
  37. #include "compile.h"
  38. #include "eval.h"
  39. #include "osdefs.h"
  40.  
  41. extern int verbose; /* Defined in pythonmain.c */
  42.  
  43. extern long getmtime(); /* Defined in posixmodule.c */
  44.  
  45. #ifdef DEBUG
  46. #define D(x) x
  47. #else
  48. #define D(x)
  49. #endif
  50.  
  51. #ifdef WITH_SGI_DL
  52. #define USE_DL
  53. #endif
  54.  
  55. #ifdef WITH_DL_DLD
  56. #define USE_DL
  57. #endif
  58.  
  59. #if !defined(USE_DL) && defined(HAVE_DLFCN_H) && defined(HAVE_DLOPEN)
  60. #define USE_SHLIB
  61. #define USE_DL
  62. #endif
  63.  
  64.  
  65. #ifdef _AIX
  66. #include <sys/ldr.h>
  67. typedef void (*dl_funcptr)();
  68. #define _DL_FUNCPTR_DEFINED
  69. static void aix_loaderror( char *name  );
  70. #endif
  71.  
  72. #ifdef USE_DL
  73.  
  74. #ifdef USE_SHLIB
  75. #include <dlfcn.h>
  76. #ifndef _DL_FUNCPTR_DEFINED
  77. typedef void (*dl_funcptr)();
  78. #endif
  79. #ifndef RTLD_LAZY
  80. #define RTLD_LAZY 1
  81. #endif
  82. #else /* !USE_SHLIB */
  83. #include "dl.h"
  84. #endif /* !USE_SHLIB */
  85.  
  86. extern char *getprogramname();
  87.  
  88. #endif /* USE_DL */
  89.  
  90. /* Magic word to reject .pyc files generated by other Python versions */
  91.  
  92. #define MAGIC 0x999902L /* Increment by one for each incompatible change */
  93.  
  94. static object *modules;
  95.  
  96. /* Forward */
  97. static int init_builtin PROTO((char *));
  98.  
  99. /* Initialization */
  100.  
  101. void
  102. initimport()
  103. {
  104.     if ((modules = newdictobject()) == NULL)
  105.         fatal("no mem for dictionary of modules");
  106. }
  107.  
  108. object *
  109. get_modules()
  110. {
  111.     return modules;
  112. }
  113.  
  114. object *
  115. add_module(name)
  116.     char *name;
  117. {
  118.     object *m;
  119.     if ((m = dictlookup(modules, name)) != NULL && is_moduleobject(m))
  120.         return m;
  121.     m = newmoduleobject(name);
  122.     if (m == NULL)
  123.         return NULL;
  124.     if (dictinsert(modules, name, m) != 0) {
  125.         DECREF(m);
  126.         return NULL;
  127.     }
  128.     DECREF(m); /* Yes, it still exists, in modules! */
  129.     return m;
  130. }
  131.  
  132. enum filetype {SEARCH_ERROR, PY_SOURCE, PY_COMPILED, C_EXTENSION};
  133.  
  134. static struct filedescr {
  135.     char *suffix;
  136.     char *mode;
  137.     enum filetype type;
  138. } filetab[] = {
  139. #if  defined(USE_DL) || defined(_AIX)
  140. #ifdef USE_SHLIB
  141.     {"module.so", "rb", C_EXTENSION},
  142. #else /* !USE_SHLIB */
  143.     {"module.o", "rb", C_EXTENSION},
  144. #endif /* !USE_SHLIB */
  145. #endif /* USE_DL  ||  _AIX */
  146.     {".py", "r", PY_SOURCE},
  147.     {".pyc", "rb", PY_COMPILED},
  148.     {0, 0}
  149. };
  150.  
  151. static object *
  152. get_module(m, name, m_ret)
  153.     /*module*/object *m;
  154.     char *name;
  155.     object **m_ret;
  156. {
  157.     int err, npath, i, len;
  158.     long magic;
  159.     long mtime, pyc_mtime;
  160.     char namebuf[MAXPATHLEN+1];
  161.     struct filedescr *fdp;
  162.     FILE *fp = NULL, *fpc = NULL;
  163.     node *n = NULL;
  164.     object *path, *v, *d;
  165.     codeobject *co = NULL;
  166.  
  167.     path = sysget("path");
  168.     if (path == NULL || !is_listobject(path)) {
  169.         err_setstr(ImportError,
  170.                "sys.path must be list of directory names");
  171.         return NULL;
  172.     }
  173.     npath = getlistsize(path);
  174.     for (i = 0; i < npath; i++) {
  175.         v = getlistitem(path, i);
  176.         if (!is_stringobject(v))
  177.             continue;
  178.         strcpy(namebuf, getstringvalue(v));
  179.         len = getstringsize(v);
  180.         if (len > 0 && namebuf[len-1] != SEP)
  181.             namebuf[len++] = SEP;
  182.         strcpy(namebuf+len, name);
  183.         len += strlen(name);
  184.         for (fdp = filetab; fdp->suffix != NULL; fdp++) {
  185.             strcpy(namebuf+len, fdp->suffix);
  186.             if (verbose > 1)
  187.                 fprintf(stderr, "# trying %s\n", namebuf);
  188.             fp = fopen(namebuf, fdp->mode);
  189.             if (fp != NULL)
  190.                 break;
  191.         }
  192.         if (fp != NULL)
  193.             break;
  194.     }
  195.     if (fp == NULL) {
  196.         sprintf(namebuf, "No module named %s", name);
  197.         err_setstr(ImportError, namebuf);
  198.         return NULL;
  199.     }
  200.  
  201.     switch (fdp->type) {
  202.  
  203.     case PY_SOURCE:
  204.         mtime = getmtime(namebuf);
  205.         len = strlen(namebuf);
  206.         strcpy(namebuf + len, "c");
  207.         fpc = fopen(namebuf, "rb");
  208.         if (fpc != NULL) {
  209.             magic = rd_long(fpc);
  210.             if (magic != MAGIC) {
  211.                 if (verbose)
  212.                     fprintf(stderr,
  213.                         "# %s has bad magic\n",
  214.                         namebuf);
  215.             }
  216.             else {
  217.                 pyc_mtime = rd_long(fpc);
  218.                 if (pyc_mtime != mtime) {
  219.                     if (verbose)
  220.                         fprintf(stderr,
  221.                           "# %s has bad mtime\n",
  222.                           namebuf);
  223.                 }
  224.                 else {
  225.                     fclose(fp);
  226.                     fp = fpc;
  227.                     if (verbose)
  228.                        fprintf(stderr,
  229.                          "# %s matches %s.py\n",
  230.                            namebuf, name);
  231.                     goto use_compiled;
  232.                 }
  233.             }
  234.             fclose(fpc);
  235.         }
  236.         namebuf[len] = '\0';
  237.         n = parse_file(fp, namebuf, file_input);
  238.         fclose(fp);
  239.         if (n == NULL)
  240.             return NULL;
  241.         co = compile(n, namebuf);
  242.         freetree(n);
  243.         if (co == NULL)
  244.             return NULL;
  245.         if (verbose)
  246.             fprintf(stderr,
  247.                 "import %s # from %s\n", name, namebuf);
  248.         /* Now write the code object to the ".pyc" file */
  249.         strcpy(namebuf + len, "c");
  250.         fpc = fopen(namebuf, "wb");
  251.         if (fpc == NULL) {
  252.             if (verbose)
  253.                 fprintf(stderr,
  254.                     "# can't create %s\n", namebuf);
  255.         }
  256.         else {
  257.             wr_long(MAGIC, fpc);
  258.             /* First write a 0 for mtime */
  259.             wr_long(0L, fpc);
  260.             wr_object((object *)co, fpc);
  261.             if (ferror(fpc)) {
  262.                 if (verbose)
  263.                     fprintf(stderr,
  264.                         "# can't write %s\n", namebuf);
  265.                 /* Don't keep partial file */
  266.                 fclose(fpc);
  267.                 (void) unlink(namebuf);
  268.             }
  269.             else {
  270.                 /* Now write the true mtime */
  271.                 fseek(fpc, 4L, 0);
  272.                 wr_long(mtime, fpc);
  273.                 fflush(fpc);
  274.                 fclose(fpc);
  275.                 if (verbose)
  276.                     fprintf(stderr,
  277.                         "# wrote %s\n", namebuf);
  278.             }
  279.         }
  280.         break;
  281.  
  282.     case PY_COMPILED:
  283.         if (verbose)
  284.             fprintf(stderr, "# %s without %s.py\n",
  285.                 namebuf, name);
  286.         magic = rd_long(fp);
  287.         if (magic != MAGIC) {
  288.             err_setstr(ImportError,
  289.                    "Bad magic number in .pyc file");
  290.             return NULL;
  291.         }
  292.         (void) rd_long(fp);
  293.     use_compiled:
  294.         v = rd_object(fp);
  295.         fclose(fp);
  296.         if (v == NULL || !is_codeobject(v)) {
  297.             XDECREF(v);
  298.             err_setstr(ImportError,
  299.                    "Bad code object in .pyc file");
  300.             return NULL;
  301.         }
  302.         co = (codeobject *)v;
  303.         if (verbose)
  304.             fprintf(stderr,
  305.                 "import %s # precompiled from %s\n",
  306.                 name, namebuf);
  307.         break;
  308.  
  309. #if defined( USE_DL ) || defined( _AIX )
  310.     case C_EXTENSION:
  311.           {
  312.         char funcname[258];
  313.         dl_funcptr p;
  314.         fclose(fp);
  315.         if (m != NULL) {
  316.             err_setstr(ImportError,
  317.                    "cannot reload dynamically loaded module");
  318.             return NULL;
  319.         }
  320.         sprintf(funcname, "init%s", name);
  321. #ifdef USE_SHLIB
  322.         {
  323. #ifdef RTLD_NOW
  324.             /* RTLD_NOW: resolve externals now
  325.                (i.e. core dump now if some are missing) */
  326.             void *handle = dlopen(namebuf, RTLD_NOW);
  327. #else
  328.             void *handle;
  329.             printf("dlopen(\"%s\", %d);\n",
  330.                    namebuf, RTLD_LAZY);
  331.             handle = dlopen(namebuf, RTLD_LAZY);
  332. #endif
  333.             if (handle == NULL) {
  334.                 err_setstr(ImportError, dlerror());
  335.                 return NULL;
  336.             }
  337.             p = (dl_funcptr) dlsym(handle, funcname);
  338.         }
  339. #else /* !USE_SHLIB */
  340. #ifdef _AIX
  341.         p = (dl_funcptr) load( namebuf, 1, 0 );
  342.         if ( p == NULL ) { aix_loaderror( namebuf ); return NULL; }
  343. #else /* _AIX */
  344.         p =  dl_loadmod(getprogramname(), namebuf, funcname);
  345. #endif 
  346. #endif /* !USE_SHLIB */
  347.  
  348.         if (p == NULL) {
  349.             err_setstr(ImportError,
  350.                "dynamic module does not define init function");
  351.             return NULL;
  352.         }
  353.         (*p)();
  354.         *m_ret = m = dictlookup(modules, name);
  355.         if (m == NULL) {
  356.             err_setstr(SystemError,
  357.                    "dynamic module not initialized properly");
  358.             return NULL;
  359.         }
  360.         if (verbose)
  361.             fprintf(stderr,
  362.                 "import %s # dynamically loaded from %s\n",
  363.                 name, namebuf);
  364.         INCREF(None);
  365.         return None;
  366.         break;
  367.           }
  368. #endif /* USE_DL */
  369.  
  370.     default:
  371.         fclose(fp);
  372.         err_setstr(SystemError,
  373.                "search loop returned unexpected result");
  374.         return NULL;
  375.  
  376.     }
  377.  
  378.     /* We get here for either PY_SOURCE or PY_COMPILED */
  379.     if (m == NULL) {
  380.         m = add_module(name);
  381.         if (m == NULL) {
  382.             freetree(n);
  383.             return NULL;
  384.         }
  385.         *m_ret = m;
  386.     }
  387.     d = getmoduledict(m);
  388.     v = eval_code(co, d, d, d, (object *)NULL);
  389.     DECREF(co);
  390.     return v;
  391. }
  392.  
  393. static object *
  394. load_module(name)
  395.     char *name;
  396. {
  397.     object *m, *v;
  398.     v = get_module((object *)NULL, name, &m);
  399.     if (v == NULL)
  400.         return NULL;
  401.     DECREF(v);
  402.     return m;
  403. }
  404.  
  405. object *
  406. import_module(name)
  407.     char *name;
  408. {
  409.     object *m;
  410.     int n;
  411.     if ((m = dictlookup(modules, name)) == NULL) {
  412.         if ((n = init_builtin(name)) || (n = init_frozen(name))) {
  413.             if (n < 0)
  414.                 return NULL;
  415.             if ((m = dictlookup(modules, name)) == NULL)
  416.                 err_setstr(SystemError,
  417.                        "builtin module missing");
  418.         }
  419.         else {
  420.             m = load_module(name);
  421.         }
  422.     }
  423.     return m;
  424. }
  425.  
  426. object *
  427. reload_module(m)
  428.     object *m;
  429. {
  430.     char *name;
  431.     int i;
  432.     if (m == NULL || !is_moduleobject(m)) {
  433.         err_setstr(TypeError, "reload() argument must be module");
  434.         return NULL;
  435.     }
  436.     name = getmodulename(m);
  437.     if (name == NULL)
  438.         return NULL;
  439.     /* Check for built-in modules */
  440.     for (i = 0; inittab[i].name != NULL; i++) {
  441.         if (strcmp(name, inittab[i].name) == 0) {
  442.             err_setstr(ImportError,
  443.                    "cannot reload built-in module");
  444.             return NULL;
  445.         }
  446.     }
  447.     /* Check for frozen modules */
  448.     if ((i = init_frozen(name)) != 0) {
  449.         if (i < 0)
  450.             return NULL;
  451.         INCREF(None);
  452.         return None;
  453.     }
  454.     return get_module(m, name, (object **)NULL);
  455. }
  456.  
  457. void
  458. doneimport()
  459. {
  460.     if (modules != NULL) {
  461.         int pos;
  462.         object *modname, *module;
  463.         /* Explicitly erase all modules; this is the safest way
  464.            to get rid of at least *some* circular dependencies */
  465.         pos = 0;
  466.         while (mappinggetnext(modules, &pos, &modname, &module)) {
  467.             if (is_moduleobject(module)) {
  468.                 object *dict;
  469.                 dict = getmoduledict(module);
  470.                 if (dict != NULL && is_dictobject(dict))
  471.                     mappingclear(dict);
  472.             }
  473.         }
  474.         mappingclear(modules);
  475.     }
  476.     DECREF(modules);
  477.     modules = NULL;
  478. }
  479.  
  480.  
  481. /* Initialize built-in modules when first imported */
  482.  
  483. static int
  484. init_builtin(name)
  485.     char *name;
  486. {
  487.     int i;
  488.     for (i = 0; inittab[i].name != NULL; i++) {
  489.         if (strcmp(name, inittab[i].name) == 0) {
  490.             if (inittab[i].initfunc == NULL) {
  491.                 err_setstr(ImportError,
  492.                        "cannot re-init internal module");
  493.                 return -1;
  494.             }
  495.             if (verbose)
  496.                 fprintf(stderr, "import %s # builtin\n",
  497.                     name);
  498.             (*inittab[i].initfunc)();
  499.             return 1;
  500.         }
  501.     }
  502.     return 0;
  503. }
  504.  
  505. extern struct frozen {
  506.     char *name;
  507.     char *code;
  508.     int size;
  509. } frozen_modules[];
  510.  
  511. int
  512. init_frozen(name)
  513.     char *name;
  514. {
  515.     struct frozen *p;
  516.     codeobject *co;
  517.     object *m, *d, *v;
  518.     for (p = frozen_modules; ; p++) {
  519.         if (p->name == NULL)
  520.             return 0;
  521.         if (strcmp(p->name, name) == 0)
  522.             break;
  523.     }
  524.     if (verbose)
  525.         fprintf(stderr, "import %s # frozen\n", name);
  526.     co = (codeobject *) rds_object(p->code, p->size);
  527.     if (co == NULL)
  528.         return -1;
  529.     if ((m = add_module(name)) == NULL ||
  530.         (d = getmoduledict(m)) == NULL ||
  531.         (v = eval_code(co, d, d, d, (object*)NULL)) == NULL) {
  532.         DECREF(co);
  533.         return -1;
  534.     }
  535.     DECREF(co);
  536.     DECREF(v);
  537.     return 1;
  538. }
  539.  
  540.  
  541. #ifdef _AIX
  542.  
  543. #include <ctype.h>    /* for isdigit()    */
  544. #include <errno.h>    /* for global errno    */
  545. #include <string.h>    /* for strerror()    */
  546.  
  547. void aix_loaderror( char *namebuf )
  548. {
  549.  
  550.     char *message[8], errbuf[1024];
  551.     int i,j;
  552.  
  553.     struct errtab { 
  554.         int errno;
  555.         char *errstr;
  556.     } load_errtab[] = {
  557.         { L_ERROR_TOOMANY,    "to many errors, rest skipped." },
  558.         { L_ERROR_NOLIB,    "can't load library:" },
  559.         { L_ERROR_UNDEF,    "can't find symbol in library:"},
  560.         { L_ERROR_RLDBAD,    "RLD index out of range or bad relocation type:" },
  561.         { L_ERROR_FORMAT,    "not a valid, executable xcoff file:" },
  562.         { L_ERROR_MEMBER,    "file not an archive or does not contain requested member:" },
  563.         { L_ERROR_TYPE,        "symbol table mismatch:" },
  564.         { L_ERROR_ALIGN,    "text allignment in file is wrong." },
  565.         { L_ERROR_SYSTEM,    "System error:" },
  566.         { L_ERROR_ERRNO,    NULL }
  567.     };
  568.  
  569. #define LOAD_ERRTAB_LEN    (sizeof(load_errtab)/sizeof(load_errtab[0]))
  570. #define ERRBUF_APPEND(s)    strncat(errbuf, s, sizeof(errbuf))
  571.  
  572.     sprintf( errbuf, " from module %s ", namebuf );
  573.  
  574.     if ( !loadquery( 1, &message[0], sizeof(message) ) ) 
  575.         ERRBUF_APPEND( strerror( errno ) );
  576.     for( i = 0; message[i] && *message[i]; i++ ) {
  577.         int nerr = atoi(message[i]);
  578.         for (j=0; j<LOAD_ERRTAB_LEN ; j++ ) {
  579.             if ((nerr == load_errtab[i].errno) && load_errtab[i].errstr)
  580.             ERRBUF_APPEND(load_errtab[i].errstr);
  581.         }
  582.         while ( isdigit(*message[i]) ) message[i]++ ; 
  583.         ERRBUF_APPEND( message[i] );
  584.         ERRBUF_APPEND( "\n" );
  585.     }
  586.     errbuf[strlen(errbuf)-1] = '\0' ;    /* trim off last newline */
  587.     err_setstr( ImportError, errbuf ); 
  588.     return; 
  589. }
  590.  
  591. #endif    /* _AIX */
  592.