windows_utils.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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()), nullptr, 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, nullptr);
  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. if (!FileAccess::exists(copy_pdb_path)) {
  132. // The PDB file may be distributed separately on purpose, so we don't consider this an error.
  133. WARN_VERBOSE(vformat("PDB file '%s' for library '%s' was not found, skipping copy/rename.", copy_pdb_path, p_dll_path));
  134. return ERR_SKIP;
  135. }
  136. String new_pdb_base_name = p_dll_path.get_file().get_basename() + "_";
  137. // Checking the available space for the updated string
  138. // and trying to shorten it if there is not much space.
  139. {
  140. // e.g. 999.pdb
  141. const uint8_t suffix_size = String::num_characters((int64_t)max_pdb_names - 1) + 4;
  142. // e.g. ~lib_ + 1 for the \0
  143. const uint8_t min_base_size = 5 + 1;
  144. int original_path_size = pdb_info.path.utf8().length();
  145. CharString utf8_name = new_pdb_base_name.utf8();
  146. int new_expected_buffer_size = utf8_name.length() + suffix_size;
  147. // Since we have limited space inside the DLL to patch the path to the PDB,
  148. // it is necessary to limit the size based on the number of bytes occupied by the string.
  149. if (new_expected_buffer_size > original_path_size) {
  150. 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));
  151. new_pdb_base_name.parse_utf8(utf8_name, original_path_size - suffix_size);
  152. new_pdb_base_name[new_pdb_base_name.length() - 1] = '_'; // Restore the last '_'
  153. 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));
  154. }
  155. }
  156. // Delete old PDB files.
  157. for (const String &file : DirAccess::get_files_at(dll_base_dir)) {
  158. if (file.begins_with(new_pdb_base_name) && file.ends_with(".pdb")) {
  159. String path = dll_base_dir.path_join(file);
  160. // Just try to delete without showing any errors.
  161. Error err = DirAccess::remove_absolute(path);
  162. if (err == OK && temp_pdbs[p_dll_path].has(path)) {
  163. temp_pdbs[p_dll_path].erase(path);
  164. }
  165. }
  166. }
  167. // Try to copy PDB with new name and patch DLL.
  168. Ref<DirAccess> d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  169. for (int i = 0; i < max_pdb_names; i++) {
  170. String new_pdb_name = vformat("%s%d.pdb", new_pdb_base_name, i);
  171. String new_pdb_path = dll_base_dir.path_join(new_pdb_name);
  172. Error err = OK;
  173. Ref<FileAccess> test_pdb_is_locked = FileAccess::open(new_pdb_path, FileAccess::READ_WRITE, &err);
  174. if (err == ERR_FILE_CANT_OPEN) {
  175. // If the file is blocked, continue searching.
  176. continue;
  177. } else if (err != OK && err != ERR_FILE_NOT_FOUND) {
  178. ERR_FAIL_V_MSG(err, vformat("Failed to open '%s' to check if it is locked.", new_pdb_path));
  179. }
  180. err = d->copy(copy_pdb_path, new_pdb_path);
  181. ERR_FAIL_COND_V_MSG(err != OK, err, vformat("Failed to copy PDB from '%s' to '%s'.", copy_pdb_path, new_pdb_path));
  182. temp_pdbs[p_dll_path].append(new_pdb_path);
  183. Ref<FileAccess> file = FileAccess::open(p_dll_path, FileAccess::READ_WRITE, &err);
  184. ERR_FAIL_COND_V_MSG(err != OK, err, vformat("Failed to open '%s' to patch the PDB path.", p_dll_path));
  185. int original_path_size = pdb_info.path.utf8().length();
  186. // Double-check file bounds.
  187. ERR_FAIL_UNSIGNED_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));
  188. Vector<uint8_t> u8 = new_pdb_name.to_utf8_buffer();
  189. file->seek(pdb_info.address);
  190. file->store_buffer(u8);
  191. // Terminate string and fill the remaining part of the original string with the '\0'.
  192. // Can be replaced by file->store_8('\0');
  193. Vector<uint8_t> padding_buffer;
  194. padding_buffer.resize((int64_t)original_path_size - u8.size());
  195. padding_buffer.fill('\0');
  196. file->store_buffer(padding_buffer);
  197. ERR_FAIL_COND_V_MSG(err != OK, err, vformat("Failed to write a new PDB path to '%s'.", p_dll_path));
  198. return OK;
  199. }
  200. ERR_FAIL_V_MSG(FAILED, vformat("Failed to find an unblocked PDB name for '%s' among %d files.", p_dll_path, max_pdb_names));
  201. #else
  202. 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.");
  203. return ERR_SKIP;
  204. #endif
  205. }
  206. void WindowsUtils::remove_temp_pdbs(const String &p_dll_path) {
  207. #ifdef DEBUG_ENABLED
  208. if (temp_pdbs.has(p_dll_path)) {
  209. Vector<String> removed;
  210. int failed = 0;
  211. const int failed_limit = 10;
  212. for (const String &pdb : temp_pdbs[p_dll_path]) {
  213. if (FileAccess::exists(pdb)) {
  214. Error err = DirAccess::remove_absolute(pdb);
  215. if (err == OK) {
  216. removed.append(pdb);
  217. } else {
  218. failed++;
  219. if (failed <= failed_limit) {
  220. print_verbose("Failed to remove temp PDB: " + pdb);
  221. }
  222. }
  223. } else {
  224. removed.append(pdb);
  225. }
  226. }
  227. if (failed > failed_limit) {
  228. print_verbose(vformat("And %d more PDB files could not be removed....", failed - failed_limit));
  229. }
  230. for (const String &pdb : removed) {
  231. temp_pdbs[p_dll_path].erase(pdb);
  232. }
  233. }
  234. #endif
  235. }
  236. #endif // WINDOWS_ENABLED