windows_utils.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. /**************************************************************************/
  2. /* windows_utils.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "windows_utils.h"
  31. #ifdef WINDOWS_ENABLED
  32. #include "core/error/error_macros.h"
  33. #include "core/io/dir_access.h"
  34. #include "core/io/file_access.h"
  35. #define WIN32_LEAN_AND_MEAN
  36. #include <windows.h>
  37. #undef FAILED // Overrides Error::FAILED
  38. // dbghelp is linked only in DEBUG_ENABLED builds.
  39. #ifdef DEBUG_ENABLED
  40. #include <dbghelp.h>
  41. #endif
  42. #include <winnt.h>
  43. HashMap<String, Vector<String>> WindowsUtils::temp_pdbs;
  44. Error WindowsUtils::copy_and_rename_pdb(const String &p_dll_path) {
  45. #ifdef DEBUG_ENABLED
  46. // 1000 ought to be enough for anybody, in case the debugger does not unblock previous PDBs.
  47. // Usually no more than 2 will be used.
  48. const int max_pdb_names = 1000;
  49. struct PDBResourceInfo {
  50. uint32_t address = 0;
  51. String path;
  52. } pdb_info;
  53. // Open and read the PDB information if available.
  54. {
  55. ULONG dbg_info_size = 0;
  56. DWORD dbg_info_position = 0;
  57. {
  58. // The custom LoadLibraryExW is used instead of open_dynamic_library
  59. // to avoid loading the original PDB into the debugger.
  60. HMODULE library_ptr = LoadLibraryExW((LPCWSTR)(p_dll_path.utf16().get_data()), NULL, LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE);
  61. ERR_FAIL_NULL_V_MSG(library_ptr, ERR_FILE_CANT_OPEN, vformat("Failed to load library '%s'.", p_dll_path));
  62. IMAGE_DEBUG_DIRECTORY *dbg_dir = (IMAGE_DEBUG_DIRECTORY *)ImageDirectoryEntryToDataEx(library_ptr, FALSE, IMAGE_DIRECTORY_ENTRY_DEBUG, &dbg_info_size, NULL);
  63. bool has_debug = dbg_dir && dbg_dir->Type == IMAGE_DEBUG_TYPE_CODEVIEW;
  64. if (has_debug) {
  65. dbg_info_position = dbg_dir->PointerToRawData;
  66. dbg_info_size = dbg_dir->SizeOfData;
  67. }
  68. ERR_FAIL_COND_V_MSG(!FreeLibrary((HMODULE)library_ptr), FAILED, vformat("Failed to free library '%s'.", p_dll_path));
  69. if (!has_debug) {
  70. // Skip with no debugging symbols.
  71. return ERR_SKIP;
  72. }
  73. }
  74. struct CV_HEADER {
  75. DWORD Signature;
  76. DWORD Offset;
  77. };
  78. const DWORD nb10_magic = 0x3031424e; // "01BN" (little-endian)
  79. struct CV_INFO_PDB20 {
  80. CV_HEADER CvHeader; // CvHeader.Signature = "NB10"
  81. DWORD Signature;
  82. DWORD Age;
  83. BYTE PdbFileName[1];
  84. };
  85. const DWORD rsds_magic = 0x53445352; // "SDSR" (little-endian)
  86. struct CV_INFO_PDB70 {
  87. DWORD Signature; // "RSDS"
  88. BYTE Guid[16];
  89. DWORD Age;
  90. BYTE PdbFileName[1];
  91. };
  92. Vector<uint8_t> dll_data;
  93. {
  94. Error err = OK;
  95. Ref<FileAccess> file = FileAccess::open(p_dll_path, FileAccess::READ, &err);
  96. ERR_FAIL_COND_V_MSG(err != OK, err, vformat("Failed to read library '%s'.", p_dll_path));
  97. file->seek(dbg_info_position);
  98. dll_data = file->get_buffer(dbg_info_size);
  99. ERR_FAIL_COND_V_MSG(file->get_error() != OK, file->get_error(), vformat("Failed to read data from library '%s'.", p_dll_path));
  100. }
  101. const char *raw_pdb_path = nullptr;
  102. int raw_pdb_offset = 0;
  103. DWORD *pdb_info_signature = (DWORD *)dll_data.ptr();
  104. if (*pdb_info_signature == rsds_magic) {
  105. raw_pdb_path = (const char *)(((CV_INFO_PDB70 *)pdb_info_signature)->PdbFileName);
  106. raw_pdb_offset = offsetof(CV_INFO_PDB70, PdbFileName);
  107. } else if (*pdb_info_signature == nb10_magic) {
  108. // Not even sure if this format still exists anywhere...
  109. raw_pdb_path = (const char *)(((CV_INFO_PDB20 *)pdb_info_signature)->PdbFileName);
  110. raw_pdb_offset = offsetof(CV_INFO_PDB20, PdbFileName);
  111. } else {
  112. ERR_FAIL_V_MSG(FAILED, vformat("Unknown PDB format in '%s'.", p_dll_path));
  113. }
  114. String utf_path;
  115. Error err = utf_path.parse_utf8(raw_pdb_path);
  116. ERR_FAIL_COND_V_MSG(err != OK, err, vformat("Failed to read PDB path from '%s'.", p_dll_path));
  117. pdb_info.path = utf_path;
  118. pdb_info.address = dbg_info_position + raw_pdb_offset;
  119. }
  120. String dll_base_dir = p_dll_path.get_base_dir();
  121. String copy_pdb_path = pdb_info.path;
  122. // Attempting to find the PDB by absolute and relative paths.
  123. if (copy_pdb_path.is_relative_path()) {
  124. copy_pdb_path = dll_base_dir.path_join(copy_pdb_path);
  125. if (!FileAccess::exists(copy_pdb_path)) {
  126. copy_pdb_path = dll_base_dir.path_join(copy_pdb_path.get_file());
  127. }
  128. } else if (!FileAccess::exists(copy_pdb_path)) {
  129. copy_pdb_path = dll_base_dir.path_join(copy_pdb_path.get_file());
  130. }
  131. ERR_FAIL_COND_V_MSG(!FileAccess::exists(copy_pdb_path), FAILED, vformat("File '%s' does not exist.", copy_pdb_path));
  132. String new_pdb_base_name = p_dll_path.get_file().get_basename() + "_";
  133. // Checking the available space for the updated string
  134. // and trying to shorten it if there is not much space.
  135. {
  136. // e.g. 999.pdb
  137. const uint8_t suffix_size = String::num_characters((int64_t)max_pdb_names - 1) + 4;
  138. // e.g. ~lib_ + 1 for the \0
  139. const uint8_t min_base_size = 5 + 1;
  140. int original_path_size = pdb_info.path.utf8().length();
  141. CharString utf8_name = new_pdb_base_name.utf8();
  142. int new_expected_buffer_size = utf8_name.length() + suffix_size;
  143. // Since we have limited space inside the DLL to patch the path to the PDB,
  144. // it is necessary to limit the size based on the number of bytes occupied by the string.
  145. if (new_expected_buffer_size > original_path_size) {
  146. ERR_FAIL_COND_V_MSG(original_path_size < min_base_size + suffix_size, FAILED, vformat("The original PDB path size in bytes is too small: '%s'. Expected size: %d or more bytes, but available %d.", pdb_info.path, min_base_size + suffix_size, original_path_size));
  147. utf8_name.resize(original_path_size - suffix_size + 1); // +1 for the \0
  148. utf8_name[utf8_name.size() - 1] = '\0';
  149. new_pdb_base_name.parse_utf8(utf8_name);
  150. new_pdb_base_name[new_pdb_base_name.length() - 1] = '_'; // Restore the last '_'
  151. WARN_PRINT(vformat("The original path size of '%s' in bytes was too small to fit the new name, so it was shortened to '%s%d.pdb'.", pdb_info.path, new_pdb_base_name, max_pdb_names - 1));
  152. }
  153. }
  154. // Delete old PDB files.
  155. for (const String &file : DirAccess::get_files_at(dll_base_dir)) {
  156. if (file.begins_with(new_pdb_base_name) && file.ends_with(".pdb")) {
  157. String path = dll_base_dir.path_join(file);
  158. // Just try to delete without showing any errors.
  159. Error err = DirAccess::remove_absolute(path);
  160. if (err == OK && temp_pdbs[p_dll_path].has(path)) {
  161. temp_pdbs[p_dll_path].erase(path);
  162. }
  163. }
  164. }
  165. // Try to copy PDB with new name and patch DLL.
  166. Ref<DirAccess> d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  167. for (int i = 0; i < max_pdb_names; i++) {
  168. String new_pdb_name = vformat("%s%d.pdb", new_pdb_base_name, i);
  169. String new_pdb_path = dll_base_dir.path_join(new_pdb_name);
  170. Error err = OK;
  171. Ref<FileAccess> test_pdb_is_locked = FileAccess::open(new_pdb_path, FileAccess::READ_WRITE, &err);
  172. if (err == ERR_FILE_CANT_OPEN) {
  173. // If the file is blocked, continue searching.
  174. continue;
  175. } else if (err != OK && err != ERR_FILE_NOT_FOUND) {
  176. ERR_FAIL_V_MSG(err, vformat("Failed to open '%s' to check if it is locked.", new_pdb_path));
  177. }
  178. err = d->copy(copy_pdb_path, new_pdb_path);
  179. ERR_FAIL_COND_V_MSG(err != OK, err, vformat("Failed to copy PDB from '%s' to '%s'.", copy_pdb_path, new_pdb_path));
  180. temp_pdbs[p_dll_path].append(new_pdb_path);
  181. Ref<FileAccess> file = FileAccess::open(p_dll_path, FileAccess::READ_WRITE, &err);
  182. ERR_FAIL_COND_V_MSG(err != OK, err, vformat("Failed to open '%s' to patch the PDB path.", p_dll_path));
  183. int original_path_size = pdb_info.path.utf8().length();
  184. // Double-check file bounds.
  185. ERR_FAIL_INDEX_V_MSG(pdb_info.address + original_path_size, file->get_length(), FAILED, vformat("Failed to write a new PDB path. Probably '%s' has been changed.", p_dll_path));
  186. Vector<uint8_t> u8 = new_pdb_name.to_utf8_buffer();
  187. file->seek(pdb_info.address);
  188. file->store_buffer(u8);
  189. // Terminate string and fill the remaining part of the original string with the '\0'.
  190. // Can be replaced by file->store_8('\0');
  191. Vector<uint8_t> padding_buffer;
  192. padding_buffer.resize((int64_t)original_path_size - u8.size());
  193. padding_buffer.fill('\0');
  194. file->store_buffer(padding_buffer);
  195. ERR_FAIL_COND_V_MSG(err != OK, err, vformat("Failed to write a new PDB path to '%s'.", p_dll_path));
  196. return OK;
  197. }
  198. ERR_FAIL_V_MSG(FAILED, vformat("Failed to find an unblocked PDB name for '%s' among %d files.", p_dll_path, max_pdb_names));
  199. #else
  200. WARN_PRINT_ONCE("Renaming PDB files is only available in debug builds. If your libraries use PDB files, then the original ones will be used.");
  201. return ERR_SKIP;
  202. #endif
  203. }
  204. void WindowsUtils::remove_temp_pdbs(const String &p_dll_path) {
  205. #ifdef DEBUG_ENABLED
  206. if (temp_pdbs.has(p_dll_path)) {
  207. Vector<String> removed;
  208. int failed = 0;
  209. const int failed_limit = 10;
  210. for (const String &pdb : temp_pdbs[p_dll_path]) {
  211. if (FileAccess::exists(pdb)) {
  212. Error err = DirAccess::remove_absolute(pdb);
  213. if (err == OK) {
  214. removed.append(pdb);
  215. } else {
  216. failed++;
  217. if (failed <= failed_limit) {
  218. print_verbose("Failed to remove temp PDB: " + pdb);
  219. }
  220. }
  221. } else {
  222. removed.append(pdb);
  223. }
  224. }
  225. if (failed > failed_limit) {
  226. print_verbose(vformat("And %d more PDB files could not be removed....", failed - failed_limit));
  227. }
  228. for (const String &pdb : removed) {
  229. temp_pdbs[p_dll_path].erase(pdb);
  230. }
  231. }
  232. #endif
  233. }
  234. #endif // WINDOWS_ENABLED