/Python/dynload_win.c

http://unladen-swallow.googlecode.com/ · C · 274 lines · 170 code · 40 blank · 64 comment · 41 complexity · 43b5ff1e4f596d744b871de59cbf23ed MD5 · raw file

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