dynload_win.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. /* Support for dynamic loading of extension modules */
  2. #include "Python.h"
  3. #include "pycore_fileutils.h" // _Py_add_relfile()
  4. #include "pycore_pystate.h" // _PyInterpreterState_GET()
  5. #ifdef HAVE_DIRECT_H
  6. #include <direct.h>
  7. #endif
  8. #include <ctype.h>
  9. #include "importdl.h"
  10. #include "patchlevel.h"
  11. #include <windows.h>
  12. #ifdef _DEBUG
  13. #define PYD_DEBUG_SUFFIX "_d"
  14. #else
  15. #define PYD_DEBUG_SUFFIX ""
  16. #endif
  17. #ifdef PYD_PLATFORM_TAG
  18. #define PYD_TAGGED_SUFFIX PYD_DEBUG_SUFFIX ".cp" Py_STRINGIFY(PY_MAJOR_VERSION) Py_STRINGIFY(PY_MINOR_VERSION) "-" PYD_PLATFORM_TAG ".pyd"
  19. #else
  20. #define PYD_TAGGED_SUFFIX PYD_DEBUG_SUFFIX ".cp" Py_STRINGIFY(PY_MAJOR_VERSION) Py_STRINGIFY(PY_MINOR_VERSION) ".pyd"
  21. #endif
  22. #define PYD_UNTAGGED_SUFFIX PYD_DEBUG_SUFFIX ".pyd"
  23. const char *_PyImport_DynLoadFiletab[] = {
  24. PYD_TAGGED_SUFFIX,
  25. PYD_UNTAGGED_SUFFIX,
  26. NULL
  27. };
  28. /* Function to return the name of the "python" DLL that the supplied module
  29. directly imports. Looks through the list of imported modules and
  30. returns the first entry that starts with "python" (case sensitive) and
  31. is followed by nothing but numbers until the separator (period).
  32. Returns a pointer to the import name, or NULL if no matching name was
  33. located.
  34. This function parses through the PE header for the module as loaded in
  35. memory by the system loader. The PE header is accessed as documented by
  36. Microsoft in the MSDN PE and COFF specification (2/99), and handles
  37. both PE32 and PE32+. It only worries about the direct import table and
  38. not the delay load import table since it's unlikely an extension is
  39. going to be delay loading Python (after all, it's already loaded).
  40. If any magic values are not found (e.g., the PE header or optional
  41. header magic), then this function simply returns NULL. */
  42. #define DWORD_AT(mem) (*(DWORD *)(mem))
  43. #define WORD_AT(mem) (*(WORD *)(mem))
  44. static char *GetPythonImport (HINSTANCE hModule)
  45. {
  46. unsigned char *dllbase, *import_data, *import_name;
  47. DWORD pe_offset, opt_offset;
  48. WORD opt_magic;
  49. int num_dict_off, import_off;
  50. /* Safety check input */
  51. if (hModule == NULL) {
  52. return NULL;
  53. }
  54. /* Module instance is also the base load address. First portion of
  55. memory is the MS-DOS loader, which holds the offset to the PE
  56. header (from the load base) at 0x3C */
  57. dllbase = (unsigned char *)hModule;
  58. pe_offset = DWORD_AT(dllbase + 0x3C);
  59. /* The PE signature must be "PE\0\0" */
  60. if (memcmp(dllbase+pe_offset,"PE\0\0",4)) {
  61. return NULL;
  62. }
  63. /* Following the PE signature is the standard COFF header (20
  64. bytes) and then the optional header. The optional header starts
  65. with a magic value of 0x10B for PE32 or 0x20B for PE32+ (PE32+
  66. uses 64-bits for some fields). It might also be 0x107 for a ROM
  67. image, but we don't process that here.
  68. The optional header ends with a data dictionary that directly
  69. points to certain types of data, among them the import entries
  70. (in the second table entry). Based on the header type, we
  71. determine offsets for the data dictionary count and the entry
  72. within the dictionary pointing to the imports. */
  73. opt_offset = pe_offset + 4 + 20;
  74. opt_magic = WORD_AT(dllbase+opt_offset);
  75. if (opt_magic == 0x10B) {
  76. /* PE32 */
  77. num_dict_off = 92;
  78. import_off = 104;
  79. } else if (opt_magic == 0x20B) {
  80. /* PE32+ */
  81. num_dict_off = 108;
  82. import_off = 120;
  83. } else {
  84. /* Unsupported */
  85. return NULL;
  86. }
  87. /* Now if an import table exists, offset to it and walk the list of
  88. imports. The import table is an array (ending when an entry has
  89. empty values) of structures (20 bytes each), which contains (at
  90. offset 12) a relative address (to the module base) at which a
  91. string constant holding the import name is located. */
  92. if (DWORD_AT(dllbase + opt_offset + num_dict_off) >= 2) {
  93. /* We have at least 2 tables - the import table is the second
  94. one. But still it may be that the table size is zero */
  95. if (0 == DWORD_AT(dllbase + opt_offset + import_off + sizeof(DWORD)))
  96. return NULL;
  97. import_data = dllbase + DWORD_AT(dllbase +
  98. opt_offset +
  99. import_off);
  100. while (DWORD_AT(import_data)) {
  101. import_name = dllbase + DWORD_AT(import_data+12);
  102. if (strlen(import_name) >= 6 &&
  103. !strncmp(import_name,"python",6)) {
  104. char *pch;
  105. /* Don't claim that python3.dll is a Python DLL. */
  106. #ifdef _DEBUG
  107. if (strcmp(import_name, "python3_d.dll") == 0) {
  108. #else
  109. if (strcmp(import_name, "python3.dll") == 0) {
  110. #endif
  111. import_data += 20;
  112. continue;
  113. }
  114. /* Ensure python prefix is followed only
  115. by numbers to the end of the basename */
  116. pch = import_name + 6;
  117. #ifdef _DEBUG
  118. while (*pch && pch[0] != '_' && pch[1] != 'd' && pch[2] != '.') {
  119. #else
  120. while (*pch && *pch != '.') {
  121. #endif
  122. if (*pch >= '0' && *pch <= '9') {
  123. pch++;
  124. } else {
  125. pch = NULL;
  126. break;
  127. }
  128. }
  129. if (pch) {
  130. /* Found it - return the name */
  131. return import_name;
  132. }
  133. }
  134. import_data += 20;
  135. }
  136. }
  137. return NULL;
  138. }
  139. #ifdef Py_ENABLE_SHARED
  140. /* Load python3.dll before loading any extension module that might refer
  141. to it. That way, we can be sure that always the python3.dll corresponding
  142. to this python DLL is loaded, not a python3.dll that might be on the path
  143. by chance.
  144. Return whether the DLL was found.
  145. */
  146. extern HMODULE PyWin_DLLhModule;
  147. static int
  148. _Py_CheckPython3(void)
  149. {
  150. static int python3_checked = 0;
  151. static HANDLE hPython3;
  152. #define MAXPATHLEN 512
  153. wchar_t py3path[MAXPATHLEN+1];
  154. if (python3_checked) {
  155. return hPython3 != NULL;
  156. }
  157. python3_checked = 1;
  158. /* If there is a python3.dll next to the python3y.dll,
  159. use that DLL */
  160. if (PyWin_DLLhModule && GetModuleFileNameW(PyWin_DLLhModule, py3path, MAXPATHLEN)) {
  161. wchar_t *p = wcsrchr(py3path, L'\\');
  162. if (p) {
  163. wcscpy(p + 1, PY3_DLLNAME);
  164. hPython3 = LoadLibraryExW(py3path, NULL, LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
  165. if (hPython3 != NULL) {
  166. return 1;
  167. }
  168. }
  169. }
  170. /* If we can locate python3.dll in our application dir,
  171. use that DLL */
  172. hPython3 = LoadLibraryExW(PY3_DLLNAME, NULL, LOAD_LIBRARY_SEARCH_APPLICATION_DIR);
  173. if (hPython3 != NULL) {
  174. return 1;
  175. }
  176. /* For back-compat, also search {sys.prefix}\DLLs, though
  177. that has not been a normal install layout for a while */
  178. PyInterpreterState *interp = _PyInterpreterState_GET();
  179. PyConfig *config = (PyConfig*)_PyInterpreterState_GetConfig(interp);
  180. assert(config->prefix);
  181. if (config->prefix) {
  182. wcscpy_s(py3path, MAXPATHLEN, config->prefix);
  183. if (py3path[0] && _Py_add_relfile(py3path, L"DLLs\\" PY3_DLLNAME, MAXPATHLEN) >= 0) {
  184. hPython3 = LoadLibraryExW(py3path, NULL, LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
  185. }
  186. }
  187. return hPython3 != NULL;
  188. #undef MAXPATHLEN
  189. }
  190. #endif /* Py_ENABLE_SHARED */
  191. dl_funcptr _PyImport_FindSharedFuncptrWindows(const char *prefix,
  192. const char *shortname,
  193. PyObject *pathname, FILE *fp)
  194. {
  195. dl_funcptr p;
  196. char funcname[258], *import_python;
  197. #ifdef Py_ENABLE_SHARED
  198. _Py_CheckPython3();
  199. #endif /* Py_ENABLE_SHARED */
  200. wchar_t *wpathname = PyUnicode_AsWideCharString(pathname, NULL);
  201. if (wpathname == NULL)
  202. return NULL;
  203. PyOS_snprintf(funcname, sizeof(funcname), "%.20s_%.200s", prefix, shortname);
  204. {
  205. HINSTANCE hDLL = NULL;
  206. #ifdef MS_WINDOWS_DESKTOP
  207. unsigned int old_mode;
  208. /* Don't display a message box when Python can't load a DLL */
  209. old_mode = SetErrorMode(SEM_FAILCRITICALERRORS);
  210. #endif
  211. /* bpo-36085: We use LoadLibraryEx with restricted search paths
  212. to avoid DLL preloading attacks and enable use of the
  213. AddDllDirectory function. We add SEARCH_DLL_LOAD_DIR to
  214. ensure DLLs adjacent to the PYD are preferred. */
  215. Py_BEGIN_ALLOW_THREADS
  216. hDLL = LoadLibraryExW(wpathname, NULL,
  217. LOAD_LIBRARY_SEARCH_DEFAULT_DIRS |
  218. LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR);
  219. Py_END_ALLOW_THREADS
  220. PyMem_Free(wpathname);
  221. #ifdef MS_WINDOWS_DESKTOP
  222. /* restore old error mode settings */
  223. SetErrorMode(old_mode);
  224. #endif
  225. if (hDLL==NULL){
  226. PyObject *message;
  227. unsigned int errorCode;
  228. /* Get an error string from Win32 error code */
  229. wchar_t theInfo[256]; /* Pointer to error text
  230. from system */
  231. int theLength; /* Length of error text */
  232. errorCode = GetLastError();
  233. theLength = FormatMessageW(
  234. FORMAT_MESSAGE_FROM_SYSTEM |
  235. FORMAT_MESSAGE_IGNORE_INSERTS, /* flags */
  236. NULL, /* message source */
  237. errorCode, /* the message (error) ID */
  238. MAKELANGID(LANG_NEUTRAL,
  239. SUBLANG_DEFAULT),
  240. /* Default language */
  241. theInfo, /* the buffer */
  242. sizeof(theInfo) / sizeof(wchar_t), /* size in wchars */
  243. NULL); /* no additional format args. */
  244. /* Problem: could not get the error message.
  245. This should not happen if called correctly. */
  246. if (theLength == 0) {
  247. message = PyUnicode_FromFormat(
  248. "DLL load failed with error code %u while importing %s",
  249. errorCode, shortname);
  250. } else {
  251. /* For some reason a \r\n
  252. is appended to the text */
  253. if (theLength >= 2 &&
  254. theInfo[theLength-2] == '\r' &&
  255. theInfo[theLength-1] == '\n') {
  256. theLength -= 2;
  257. theInfo[theLength] = '\0';
  258. }
  259. message = PyUnicode_FromFormat(
  260. "DLL load failed while importing %s: ", shortname);
  261. PyUnicode_AppendAndDel(&message,
  262. PyUnicode_FromWideChar(
  263. theInfo,
  264. theLength));
  265. }
  266. if (message != NULL) {
  267. PyObject *shortname_obj = PyUnicode_FromString(shortname);
  268. PyErr_SetImportError(message, shortname_obj, pathname);
  269. Py_XDECREF(shortname_obj);
  270. Py_DECREF(message);
  271. }
  272. return NULL;
  273. } else {
  274. char buffer[256];
  275. PyOS_snprintf(buffer, sizeof(buffer),
  276. #ifdef _DEBUG
  277. "python%d%d_d.dll",
  278. #else
  279. "python%d%d.dll",
  280. #endif
  281. PY_MAJOR_VERSION,PY_MINOR_VERSION);
  282. import_python = GetPythonImport(hDLL);
  283. if (import_python &&
  284. _stricmp(buffer,import_python)) {
  285. PyErr_Format(PyExc_ImportError,
  286. "Module use of %.150s conflicts "
  287. "with this version of Python.",
  288. import_python);
  289. Py_BEGIN_ALLOW_THREADS
  290. FreeLibrary(hDLL);
  291. Py_END_ALLOW_THREADS
  292. return NULL;
  293. }
  294. }
  295. Py_BEGIN_ALLOW_THREADS
  296. p = GetProcAddress(hDLL, funcname);
  297. Py_END_ALLOW_THREADS
  298. }
  299. return p;
  300. }