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

  1.  
  2. /* Support for dynamic loading of extension modules */
  3.  
  4. #include <windows.h>
  5. #include <direct.h>
  6. #include <ctype.h>
  7.  
  8. #include "Python.h"
  9. #include "importdl.h"
  10.  
  11. const struct filedescr _PyImport_DynLoadFiletab[] = {
  12. #ifdef _DEBUG
  13.     {"_d.pyd", "rb", C_EXTENSION},
  14.     {"_d.dll", "rb", C_EXTENSION},
  15. #else
  16.     {".pyd", "rb", C_EXTENSION},
  17.     {".dll", "rb", C_EXTENSION},
  18. #endif
  19.     {0, 0}
  20. };
  21.  
  22.  
  23. #ifdef MS_WIN32
  24.  
  25. /* Case insensitive string compare, to avoid any dependencies on particular
  26.    C RTL implementations */
  27.  
  28. static int strcasecmp (char *string1, char *string2)
  29.     int first, second;
  30.  
  31.     do {
  32.         first  = tolower(*string1);
  33.         second = tolower(*string2);
  34.         string1++;
  35.         string2++;
  36.     } while (first && first == second);
  37.  
  38.     return (first - second);
  39.  
  40.  
  41. /* Function to return the name of the "python" DLL that the supplied module
  42.    directly imports.  Looks through the list of imported modules and
  43.    returns the first entry that starts with "python" (case sensitive) and
  44.    is followed by nothing but numbers until the separator (period).
  45.  
  46.    Returns a pointer to the import name, or NULL if no matching name was
  47.    located.
  48.  
  49.    This function parses through the PE header for the module as loaded in
  50.    memory by the system loader.  The PE header is accessed as documented by
  51.    Microsoft in the MSDN PE and COFF specification (2/99), and handles
  52.    both PE32 and PE32+.  It only worries about the direct import table and
  53.    not the delay load import table since it's unlikely an extension is
  54.    going to be delay loading Python (after all, it's already loaded).
  55.  
  56.    If any magic values are not found (e.g., the PE header or optional
  57.    header magic), then this function simply returns NULL. */
  58.  
  59. #define DWORD_AT(mem) (*(DWORD *)(mem))
  60. #define WORD_AT(mem)  (*(WORD *)(mem))
  61.  
  62. static char *GetPythonImport (HINSTANCE hModule)
  63. {
  64.     unsigned char *dllbase, *import_data, *import_name;
  65.     DWORD pe_offset, opt_offset;
  66.     WORD opt_magic;
  67.     int num_dict_off, import_off;
  68.  
  69.     /* Safety check input */
  70.     if (hModule == NULL) {
  71.         return NULL;
  72.     }
  73.  
  74.     /* Module instance is also the base load address.  First portion of
  75.        memory is the MS-DOS loader, which holds the offset to the PE
  76.        header (from the load base) at 0x3C */
  77.     dllbase = (unsigned char *)hModule;
  78.     pe_offset = DWORD_AT(dllbase + 0x3C);
  79.  
  80.     /* The PE signature must be "PE\0\0" */
  81.     if (memcmp(dllbase+pe_offset,"PE\0\0",4)) {
  82.         return NULL;
  83.     }
  84.  
  85.     /* Following the PE signature is the standard COFF header (20
  86.        bytes) and then the optional header.  The optional header starts
  87.        with a magic value of 0x10B for PE32 or 0x20B for PE32+ (PE32+
  88.        uses 64-bits for some fields).  It might also be 0x107 for a ROM
  89.        image, but we don't process that here.
  90.  
  91.        The optional header ends with a data dictionary that directly
  92.        points to certain types of data, among them the import entries
  93.        (in the second table entry). Based on the header type, we
  94.        determine offsets for the data dictionary count and the entry
  95.        within the dictionary pointing to the imports. */
  96.  
  97.     opt_offset = pe_offset + 4 + 20;
  98.     opt_magic = WORD_AT(dllbase+opt_offset);
  99.     if (opt_magic == 0x10B) {
  100.         /* PE32 */
  101.         num_dict_off = 92;
  102.         import_off   = 104;
  103.     } else if (opt_magic == 0x20B) {
  104.         /* PE32+ */
  105.         num_dict_off = 108;
  106.         import_off   = 120;
  107.     } else {
  108.         /* Unsupported */
  109.         return NULL;
  110.     }
  111.  
  112.     /* Now if an import table exists, offset to it and walk the list of
  113.        imports.  The import table is an array (ending when an entry has
  114.        empty values) of structures (20 bytes each), which contains (at
  115.        offset 12) a relative address (to the module base) at which a
  116.        string constant holding the import name is located. */
  117.  
  118.     if (DWORD_AT(dllbase + opt_offset + num_dict_off) >= 2) {
  119.         import_data = dllbase + DWORD_AT(dllbase +
  120.                          opt_offset +
  121.                          import_off);
  122.         while (DWORD_AT(import_data)) {
  123.             import_name = dllbase + DWORD_AT(import_data+12);
  124.             if (strlen(import_name) >= 6 &&
  125.                 !strncmp(import_name,"python",6)) {
  126.                 char *pch;
  127.  
  128.                 /* Ensure python prefix is followed only
  129.                    by numbers to the end of the basename */
  130.                 pch = import_name + 6;
  131.                 while (*pch && *pch != '.') {
  132.                     if (*pch >= '0' && *pch <= '9') {
  133.                         pch++;
  134.                     } else {
  135.                         pch = NULL;
  136.                         break;
  137.                     }
  138.                 }
  139.         
  140.                 if (pch) {
  141.                     /* Found it - return the name */
  142.                     return import_name;
  143.                 }
  144.             }
  145.             import_data += 20;
  146.         }
  147.     }
  148.  
  149.     return NULL;
  150. }
  151. #endif /* MS_WIN32 */
  152.  
  153.  
  154. dl_funcptr _PyImport_GetDynLoadFunc(const char *fqname, const char *shortname,
  155.                     const char *pathname, FILE *fp)
  156. {
  157.     dl_funcptr p;
  158.     char funcname[258], *import_python;
  159.  
  160.     sprintf(funcname, "init%.200s", shortname);
  161.  
  162. #ifdef MS_WIN32
  163.     {
  164.         HINSTANCE hDLL;
  165.         char pathbuf[260];
  166.         if (strchr(pathname, '\\') == NULL &&
  167.             strchr(pathname, '/') == NULL)
  168.         {
  169.             /* Prefix bare filename with ".\" */
  170.             char *p = pathbuf;
  171.             *p = '\0';
  172.             _getcwd(pathbuf, sizeof pathbuf);
  173.             if (*p != '\0' && p[1] == ':')
  174.                 p += 2;
  175.             sprintf(p, ".\\%-.255s", pathname);
  176.             pathname = pathbuf;
  177.         }
  178.         /* Look for dependent DLLs in directory of pathname first */
  179.         /* XXX This call doesn't exist in Windows CE */
  180.         hDLL = LoadLibraryEx(pathname, NULL,
  181.                      LOAD_WITH_ALTERED_SEARCH_PATH);
  182.         if (hDLL==NULL){
  183.             char errBuf[256];
  184.             unsigned int errorCode;
  185.  
  186.             /* Get an error string from Win32 error code */
  187.             char theInfo[256]; /* Pointer to error text
  188.                           from system */
  189.             int theLength; /* Length of error text */
  190.  
  191.             errorCode = GetLastError();
  192.  
  193.             theLength = FormatMessage(
  194.                 FORMAT_MESSAGE_FROM_SYSTEM, /* flags */
  195.                 NULL, /* message source */
  196.                 errorCode, /* the message (error) ID */
  197.                 0, /* default language environment */
  198.                 (LPTSTR) theInfo, /* the buffer */
  199.                 sizeof(theInfo), /* the buffer size */
  200.                 NULL); /* no additional format args. */
  201.  
  202.             /* Problem: could not get the error message.
  203.                This should not happen if called correctly. */
  204.             if (theLength == 0) {
  205.                 sprintf(errBuf,
  206.                     "DLL load failed with error code %d",
  207.                     errorCode);
  208.             } else {
  209.                 size_t len;
  210.                 /* For some reason a \r\n
  211.                    is appended to the text */
  212.                 if (theLength >= 2 &&
  213.                     theInfo[theLength-2] == '\r' &&
  214.                     theInfo[theLength-1] == '\n') {
  215.                     theLength -= 2;
  216.                     theInfo[theLength] = '\0';
  217.                 }
  218.                 strcpy(errBuf, "DLL load failed: ");
  219.                 len = strlen(errBuf);
  220.                 strncpy(errBuf+len, theInfo,
  221.                     sizeof(errBuf)-len);
  222.                 errBuf[sizeof(errBuf)-1] = '\0';
  223.             }
  224.             PyErr_SetString(PyExc_ImportError, errBuf);
  225.         return NULL;
  226.         } else {
  227.             char buffer[256];
  228.  
  229.             sprintf(buffer,"python%d%d.dll",
  230.                 PY_MAJOR_VERSION,PY_MINOR_VERSION);
  231.             import_python = GetPythonImport(hDLL);
  232.  
  233.             if (import_python &&
  234.                 strcasecmp(buffer,import_python)) {
  235.                 sprintf(buffer,
  236.                     "Module use of %s conflicts "
  237.                     "with this version of Python.",
  238.                     import_python);
  239.                 PyErr_SetString(PyExc_ImportError,buffer);
  240.                 FreeLibrary(hDLL);
  241.                 return NULL;
  242.             }
  243.         }
  244.         p = GetProcAddress(hDLL, funcname);
  245.     }
  246. #endif /* MS_WIN32 */
  247. #ifdef MS_WIN16
  248.     {
  249.         HINSTANCE hDLL;
  250.         char pathbuf[16];
  251.         if (strchr(pathname, '\\') == NULL &&
  252.             strchr(pathname, '/') == NULL)
  253.         {
  254.             /* Prefix bare filename with ".\" */
  255.             sprintf(pathbuf, ".\\%-.13s", pathname);
  256.             pathname = pathbuf;
  257.         }
  258.         hDLL = LoadLibrary(pathname);
  259.         if (hDLL < HINSTANCE_ERROR){
  260.             char errBuf[256];
  261.             sprintf(errBuf,
  262.                 "DLL load failed with error code %d", hDLL);
  263.             PyErr_SetString(PyExc_ImportError, errBuf);
  264.             return NULL;
  265.         }
  266.         p = GetProcAddress(hDLL, funcname);
  267.     }
  268. #endif /* MS_WIN16 */
  269.  
  270.     return p;
  271. }
  272.