home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 4 / Apprentice-Release4.iso / Source Code / C / Applications / Python 1.3 / source code / Python / importdl.c < prev    next >
Encoding:
C/C++ Source or Header  |  1995-12-17  |  13.8 KB  |  521 lines  |  [TEXT/R*ch]

  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 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. /* Support for dynamic loading of extension modules */
  26. /* If no dynamic linking is supported, this file still generates some code! */
  27.  
  28. #include "allobjects.h"
  29. #include "osdefs.h"
  30. #include "importdl.h"
  31.  
  32. extern int verbose; /* Defined in pythonrun.c */
  33.  
  34. /* Explanation of some of the the various #defines used by dynamic linking...
  35.  
  36.    symbol    -- defined for:
  37.  
  38.    DYNAMIC_LINK -- any kind of dynamic linking
  39.    USE_RLD    -- NeXT dynamic linking
  40.    USE_DL    -- Jack's dl for IRIX 4 or GNU dld with emulation for Jack's dl
  41.    USE_SHLIB    -- SunOS or IRIX 5 (SVR4?) shared libraries
  42.    _AIX        -- AIX style dynamic linking
  43.    NT        -- NT style dynamic linking (using DLLs)
  44.    _DL_FUNCPTR_DEFINED    -- if the typedef dl_funcptr has been defined
  45.    USE_MAC_DYNAMIC_LOADING -- Mac CFM shared libraries
  46.    SHORT_EXT    -- short extension for dynamic module, e.g. ".so"
  47.    LONG_EXT    -- long extension, e.g. "module.so"
  48.    hpux        -- HP-UX Dynamic Linking - defined by the compiler
  49.    __NetBSD__    -- NetBSD shared libraries (not quite SVR4 compatible)
  50.  
  51.    (The other WITH_* symbols are used only once, to set the
  52.    appropriate symbols.)
  53. */
  54.  
  55. /* Configure dynamic linking */
  56.  
  57. #ifdef hpux
  58. #define DYNAMIC_LINK
  59. #include <errno.h>
  60. typedef void (*dl_funcptr)();
  61. #define _DL_FUNCPTR_DEFINED 1
  62. #define SHORT_EXT ".sl"
  63. #define LONG_EXT "module.sl"
  64. #endif 
  65.  
  66. #ifdef __NetBSD__
  67. #define DYNAMIC_LINK
  68. #define USE_SHLIB
  69.  
  70. #define dlerror() "error in dynamic linking"
  71. #endif
  72.  
  73. #ifdef __WIN32__
  74. #define NT
  75. #endif
  76.  
  77. #ifdef NT
  78. #define DYNAMIC_LINK
  79. #include <windows.h>
  80. typedef FARPROC dl_funcptr;
  81. #define _DL_FUNCPTR_DEFINED
  82. #define SHORT_EXT ".pyd"
  83. #define LONG_EXT "module.pyd"
  84. #endif
  85.  
  86. #ifdef NeXT
  87. #define DYNAMIC_LINK
  88. #define USE_RLD
  89. #endif
  90.  
  91. #ifdef WITH_SGI_DL
  92. #define DYNAMIC_LINK
  93. #define USE_DL
  94. #endif
  95.  
  96. #ifdef WITH_DL_DLD
  97. #define DYNAMIC_LINK
  98. #define USE_DL
  99. #endif
  100.  
  101. #ifdef __CFM68K__
  102. #define USE_MAC_DYNAMIC_LOADING
  103. #endif
  104.  
  105. #ifdef USE_MAC_DYNAMIC_LOADING
  106. #define DYNAMIC_LINK
  107. #define SHORT_EXT ".slb"
  108. #define LONG_EXT "module.slb"
  109. #ifndef _DL_FUNCPTR_DEFINED
  110. typedef void (*dl_funcptr)();
  111. #endif
  112. #endif
  113.  
  114. #if !defined(DYNAMIC_LINK) && defined(HAVE_DLFCN_H) && defined(HAVE_DLOPEN)
  115. #define DYNAMIC_LINK
  116. #define USE_SHLIB
  117. #endif
  118.  
  119. #ifdef _AIX
  120. #define DYNAMIC_LINK
  121. #include <sys/ldr.h>
  122. typedef void (*dl_funcptr)();
  123. #define _DL_FUNCPTR_DEFINED
  124. static void aix_loaderror(char *name);
  125. #endif
  126.  
  127. #ifdef DYNAMIC_LINK
  128.  
  129. #ifdef USE_SHLIB
  130. #include <sys/types.h>
  131. #include <sys/stat.h>
  132. #ifdef __NetBSD__
  133. #include <nlist.h>
  134. #include <link.h>
  135. #else
  136. #include <dlfcn.h>
  137. #endif
  138. #ifndef _DL_FUNCPTR_DEFINED
  139. typedef void (*dl_funcptr)();
  140. #endif
  141. #ifndef RTLD_LAZY
  142. #define RTLD_LAZY 1
  143. #endif
  144. #define SHORT_EXT ".so"
  145. #define LONG_EXT "module.so"
  146. #endif /* USE_SHLIB */
  147.  
  148. #if defined(USE_DL) || defined(hpux)
  149. #include "dl.h"
  150. #endif
  151.  
  152. #ifdef USE_MAC_DYNAMIC_LOADING
  153. #include <CodeFragments.h>
  154. #ifdef SYMANTEC__CFM68K__ /* Really just an older version of Universal Headers */
  155. #define CFragConnectionID ConnectionID
  156. #define kLoadCFrag 0x01
  157. #endif
  158. #include <Files.h>
  159. #include "macdefs.h"
  160. #include "macglue.h"
  161. #endif
  162.  
  163. #ifdef USE_RLD
  164. #include <mach-o/rld.h>
  165. #define FUNCNAME_PATTERN "_init%.200s"
  166. #ifndef _DL_FUNCPTR_DEFINED
  167. typedef void (*dl_funcptr)();
  168. #endif
  169. #endif /* USE_RLD */
  170.  
  171. extern char *getprogramname();
  172.  
  173. #ifndef FUNCNAME_PATTERN
  174. #if defined(__hp9000s300) || defined(__NetBSD__) || defined(__BORLANDC__)
  175. #define FUNCNAME_PATTERN "_init%.200s"
  176. #else
  177. #define FUNCNAME_PATTERN "init%.200s"
  178. #endif
  179. #endif
  180.  
  181. #if !defined(SHORT_EXT) && !defined(LONG_EXT)
  182. #define SHORT_EXT ".o"
  183. #define LONG_EXT "module.o"
  184. #endif /* !SHORT_EXT && !LONG_EXT */
  185.  
  186. #endif /* DYNAMIC_LINK */
  187.  
  188. /* Max length of module suffix searched for -- accommodates "module.slb" */
  189. #ifndef MAXSUFFIXSIZE
  190. #define MAXSUFFIXSIZE 12
  191. #endif
  192.  
  193. /* Pass it on to import.c */
  194. int import_maxsuffixsize = MAXSUFFIXSIZE;
  195.  
  196. struct filedescr import_filetab[] = {
  197. #ifdef SHORT_EXT
  198.     {SHORT_EXT, "rb", C_EXTENSION},
  199. #endif /* !SHORT_EXT */
  200. #ifdef LONG_EXT
  201.     {LONG_EXT, "rb", C_EXTENSION},
  202. #endif /* !LONG_EXT */
  203.     {".py", "r", PY_SOURCE},
  204.     {".pyc", "rb", PY_COMPILED},
  205.     {0, 0}
  206. };
  207.  
  208. object *
  209. load_dynamic_module(name, pathname, fp)
  210.     char *name;
  211.     char *pathname;
  212.     FILE *fp;
  213. {
  214. #ifndef DYNAMIC_LINK
  215.     err_setstr(ImportError, "dynamically linked modules not supported");
  216.     return NULL;
  217. #else
  218.     object *m;
  219.     char funcname[258];
  220.     dl_funcptr p = NULL;
  221. #ifdef USE_SHLIB
  222.     static struct {
  223.         dev_t dev;
  224.         ino_t ino;
  225.         void *handle;
  226.     } handles[128];
  227.     static int nhandles = 0;
  228. #endif
  229.     sprintf(funcname, FUNCNAME_PATTERN, name);
  230. #ifdef USE_SHLIB
  231.     if (fp != NULL) {
  232.         int i;
  233.         struct stat statb;
  234.         fstat(fileno(fp), &statb);
  235.         for (i = 0; i < nhandles; i++) {
  236.             if (statb.st_dev == handles[i].dev &&
  237.                 statb.st_ino == handles[i].ino) {
  238.                 p = (dl_funcptr) dlsym(handles[i].handle,
  239.                                funcname);
  240.                 goto got_it;
  241.             }
  242.         }
  243.         if (nhandles < 128) {
  244.             handles[nhandles].dev = statb.st_dev;
  245.             handles[nhandles].ino = statb.st_ino;
  246.         }
  247.     }
  248. #endif /* USE_SHLIB */
  249. #ifdef USE_MAC_DYNAMIC_LOADING
  250.     /*
  251.     ** Dynamic loading of CFM shared libraries on the Mac.
  252.     ** The code has become more convoluted than it was, because we want to be able
  253.     ** to put multiple modules in a single file. For this reason, we have to determine
  254.     ** the fragment name, and we cannot use the library entry point but we have to locate
  255.     ** the correct init routine "by hand".
  256.     */
  257.     {
  258.         FSSpec libspec;
  259.         CFragConnectionID connID;
  260.         Ptr mainAddr;
  261.         Str255 errMessage;
  262.         OSErr err;
  263.         Boolean isfolder, didsomething;
  264.         char buf[512];
  265.         Str63 fragname;
  266.         Ptr symAddr;
  267.         CFragSymbolClass class;
  268.         
  269.         /* First resolve any aliases to find the real file */
  270.         (void)FSMakeFSSpec(0, 0, Pstring(pathname), &libspec);
  271. #if !(defined(__MWERKS__) && defined(__CFM68K__))
  272.         /* Bug: not in library */
  273.         err = ResolveAliasFile(&libspec, 1, &isfolder, &didsomething);
  274. #endif
  275.         if ( err ) {
  276.             sprintf(buf, "%s: %s", pathname, PyMac_StrError(err));
  277.             err_setstr(ImportError, buf);
  278.             return NULL;
  279.         }
  280.         /* Next, determine the fragment name, by stripping '.slb' and 'module' */
  281.         memcpy(fragname+1, libspec.name+1, libspec.name[0]);
  282.         fragname[0] = libspec.name[0];
  283.         if( strncmp((char *)(fragname+1+fragname[0]-4), ".slb", 4) == 0 )
  284.             fragname[0] -= 4;
  285.         if ( strncmp((char *)(fragname+1+fragname[0]-6), "module", 6) == 0 )
  286.             fragname[0] -= 6;
  287.         /* Load the fragment (or return the connID if it is already loaded */
  288.         err = GetDiskFragment(&libspec, 0, 0, fragname, 
  289.                       kLoadCFrag, &connID, &mainAddr,
  290.                       errMessage);
  291.         if ( err ) {
  292.             sprintf(buf, "%.*s: %s", errMessage[0], errMessage+1, PyMac_StrError(err));
  293.             err_setstr(ImportError, buf);
  294.             return NULL;
  295.         }
  296.         /* Locate the address of the correct init function */
  297.         err = FindSymbol(connID, Pstring(funcname), &symAddr, &class);
  298.         if ( err ) {
  299.             sprintf(buf, "%s: %s", funcname, PyMac_StrError(err));
  300.             err_setstr(ImportError, buf);
  301.             return NULL;
  302.         }
  303.         p = (dl_funcptr)symAddr;
  304.     }
  305. #endif /* USE_MAC_DYNAMIC_LOADING */
  306. #ifdef USE_SHLIB
  307.     {
  308. #ifdef RTLD_NOW
  309.         /* RTLD_NOW: resolve externals now
  310.            (i.e. core dump now if some are missing) */
  311.         void *handle = dlopen(pathname, RTLD_NOW);
  312. #else
  313.         void *handle;
  314.         if (verbose)
  315.             printf("dlopen(\"%s\", %d);\n", pathname, RTLD_LAZY);
  316.         handle = dlopen(pathname, RTLD_LAZY);
  317. #endif /* RTLD_NOW */
  318.         if (handle == NULL) {
  319.             err_setstr(ImportError, dlerror());
  320.             return NULL;
  321.         }
  322.         if (fp != NULL && nhandles < 128)
  323.             handles[nhandles++].handle = handle;
  324.         p = (dl_funcptr) dlsym(handle, funcname);
  325.     }
  326. #endif /* USE_SHLIB */
  327. #ifdef _AIX
  328.     p = (dl_funcptr) load(pathname, 1, 0);
  329.     if (p == NULL) {
  330.         aix_loaderror(pathname);
  331.         return NULL;
  332.     }
  333. #endif /* _AIX */
  334. #ifdef NT
  335.     {
  336.         HINSTANCE hDLL;
  337.         hDLL = LoadLibrary(pathname);
  338.         if (hDLL==NULL){
  339.             char errBuf[256];
  340.             unsigned int errorCode;
  341.  
  342.             /* Get an error string from Win32 error code */
  343.             char theInfo[256];           /* Pointer to error text from system */
  344.             int theLength;               /* Length of error text */
  345.  
  346.             errorCode = GetLastError();
  347.  
  348.             theLength = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, /* flags */
  349.                 NULL,                              /* message source */
  350.                 errorCode,                         /* the message (error) ID */
  351.                 0,                                 /* default language environment */
  352.                 (LPTSTR) theInfo,                  /* the buffer */
  353.                 sizeof(theInfo),                   /* the buffer size */
  354.                 NULL);                             /* no additional format args. */
  355.  
  356.             /* Problem: could not get the error message. This should not happen if called correctly. */
  357.             if (theLength == 0) {
  358.                 sprintf(errBuf, "DLL load failed with error code %d", errorCode);
  359.             } else {
  360.                 int len;
  361.                 /* For some reason a \r\n is appended to the text */
  362.                 if (theLength >= 2 && theInfo[theLength-2] == '\r' && theInfo[theLength-1] == '\n') {
  363.                     theLength -= 2;
  364.                     theInfo[theLength] = '\0';
  365.                 }
  366.                 strcpy(errBuf, "DLL load failed: ");
  367.                 len = strlen(errBuf);
  368.                 strncpy(errBuf+len, theInfo, sizeof(errBuf)-len);
  369.                 errBuf[sizeof(errBuf)-1] = '\0';
  370.             }
  371.             err_setstr(ImportError, errBuf);
  372.         return NULL;
  373.         }
  374.         p = GetProcAddress(hDLL, funcname);
  375.     }
  376. #endif /* NT */
  377. #ifdef USE_DL
  378.     p =  dl_loadmod(getprogramname(), pathname, funcname);
  379. #endif /* USE_DL */
  380. #ifdef USE_RLD
  381.     {
  382.         NXStream *errorStream;
  383.         struct mach_header *new_header;
  384.         const char *filenames[2];
  385.         long ret;
  386.         unsigned long ptr;
  387.  
  388.         errorStream = NXOpenMemory(NULL, 0, NX_WRITEONLY);
  389.         filenames[0] = pathname;
  390.         filenames[1] = NULL;
  391.         ret = rld_load(errorStream, &new_header, 
  392.                 filenames, NULL);
  393.  
  394.         /* extract the error messages for the exception */
  395.         if(!ret) {
  396.             char *streamBuf;
  397.             int len, maxLen;
  398.  
  399.             NXPutc(errorStream, (char)0);
  400.  
  401.             NXGetMemoryBuffer(errorStream,
  402.                 &streamBuf, &len, &maxLen);
  403.             err_setstr(ImportError, streamBuf);
  404.         }
  405.  
  406.         if(ret && rld_lookup(errorStream, funcname, &ptr))
  407.             p = (dl_funcptr) ptr;
  408.  
  409.         NXCloseMemory(errorStream, NX_FREEBUFFER);
  410.  
  411.         if(!ret)
  412.             return NULL;
  413.     }
  414. #endif /* USE_RLD */
  415. #ifdef hpux
  416.     {
  417.         shl_t lib;
  418.         int flags;
  419.  
  420.         flags = BIND_DEFERRED;
  421.         if (verbose)
  422.                 {
  423.                         flags = BIND_IMMEDIATE | BIND_NONFATAL | BIND_VERBOSE;
  424.                         printf("shl_load %s\n",pathname);
  425.                 }
  426.                 lib = shl_load(pathname, flags, 0);
  427.                 if (lib == NULL)
  428.                 {
  429.                         char buf[256];
  430.                         if (verbose)
  431.                                 perror(pathname);
  432.                         sprintf(buf, "Failed to load %.200s", pathname);
  433.                         err_setstr(ImportError, buf);
  434.                         return NULL;
  435.                 }
  436.                 if (verbose)
  437.                         printf("shl_findsym %s\n", funcname);
  438.                 shl_findsym(&lib, funcname, TYPE_UNDEFINED, (void *) &p);
  439.                 if (p == NULL && verbose)
  440.                         perror(funcname);
  441.     }
  442. #endif /* hpux */
  443.   got_it:
  444.     if (p == NULL) {
  445.         err_setstr(ImportError,
  446.            "dynamic module does not define init function");
  447.         return NULL;
  448.     }
  449.     (*p)();
  450.  
  451.     m = dictlookup(import_modules, name);
  452.     if (m == NULL) {
  453.         if (err_occurred() == NULL)
  454.             err_setstr(SystemError,
  455.                    "dynamic module not initialized properly");
  456.         return NULL;
  457.     }
  458.     if (verbose)
  459.         fprintf(stderr,
  460.             "import %s # dynamically loaded from %s\n",
  461.             name, pathname);
  462.     INCREF(m);
  463.     return m;
  464. #endif /* DYNAMIC_LINK */
  465. }
  466.  
  467.  
  468. #ifdef _AIX
  469.  
  470. #include <ctype.h>    /* for isdigit()    */
  471. #include <errno.h>    /* for global errno    */
  472. #include <string.h>    /* for strerror()    */
  473.  
  474. void aix_loaderror(char *pathname)
  475. {
  476.  
  477.     char *message[8], errbuf[1024];
  478.     int i,j;
  479.  
  480.     struct errtab { 
  481.         int errno;
  482.         char *errstr;
  483.     } load_errtab[] = {
  484.         {L_ERROR_TOOMANY,    "too many errors, rest skipped."},
  485.         {L_ERROR_NOLIB,        "can't load library:"},
  486.         {L_ERROR_UNDEF,        "can't find symbol in library:"},
  487.         {L_ERROR_RLDBAD,
  488.          "RLD index out of range or bad relocation type:"},
  489.         {L_ERROR_FORMAT,    "not a valid, executable xcoff file:"},
  490.         {L_ERROR_MEMBER,
  491.          "file not an archive or does not contain requested member:"},
  492.         {L_ERROR_TYPE,        "symbol table mismatch:"},
  493.         {L_ERROR_ALIGN,        "text allignment in file is wrong."},
  494.         {L_ERROR_SYSTEM,    "System error:"},
  495.         {L_ERROR_ERRNO,        NULL}
  496.     };
  497.  
  498. #define LOAD_ERRTAB_LEN    (sizeof(load_errtab)/sizeof(load_errtab[0]))
  499. #define ERRBUF_APPEND(s) strncat(errbuf, s, sizeof(errbuf)-strlen(errbuf)-1)
  500.  
  501.     sprintf(errbuf, " from module %.200s ", pathname);
  502.  
  503.     if (!loadquery(1, &message[0], sizeof(message))) 
  504.         ERRBUF_APPEND(strerror(errno));
  505.     for(i = 0; message[i] && *message[i]; i++) {
  506.         int nerr = atoi(message[i]);
  507.         for (j=0; j<LOAD_ERRTAB_LEN ; j++) {
  508.             if (nerr == load_errtab[i].errno && load_errtab[i].errstr)
  509.             ERRBUF_APPEND(load_errtab[i].errstr);
  510.         }
  511.         while (isdigit(*message[i])) message[i]++ ; 
  512.         ERRBUF_APPEND(message[i]);
  513.         ERRBUF_APPEND("\n");
  514.     }
  515.     errbuf[strlen(errbuf)-1] = '\0';    /* trim off last newline */
  516.     err_setstr(ImportError, errbuf); 
  517.     return; 
  518. }
  519.  
  520. #endif /* _AIX */
  521.