Path: blob/master/platform/windows/windows_utils.cpp
10277 views
/**************************************************************************/1/* windows_utils.cpp */2/**************************************************************************/3/* This file is part of: */4/* GODOT ENGINE */5/* https://godotengine.org */6/**************************************************************************/7/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */8/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */9/* */10/* Permission is hereby granted, free of charge, to any person obtaining */11/* a copy of this software and associated documentation files (the */12/* "Software"), to deal in the Software without restriction, including */13/* without limitation the rights to use, copy, modify, merge, publish, */14/* distribute, sublicense, and/or sell copies of the Software, and to */15/* permit persons to whom the Software is furnished to do so, subject to */16/* the following conditions: */17/* */18/* The above copyright notice and this permission notice shall be */19/* included in all copies or substantial portions of the Software. */20/* */21/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */22/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */23/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */24/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */25/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */26/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */27/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */28/**************************************************************************/2930#include "windows_utils.h"3132#ifdef WINDOWS_ENABLED3334#include "core/error/error_macros.h"35#include "core/io/dir_access.h"36#include "core/io/file_access.h"3738#define WIN32_LEAN_AND_MEAN39#include <windows.h>40#undef FAILED // Overrides Error::FAILED4142// dbghelp is linked only in DEBUG_ENABLED builds.43#ifdef DEBUG_ENABLED44#include <dbghelp.h>45#endif46#include <winnt.h>4748HashMap<String, Vector<String>> WindowsUtils::temp_pdbs;4950Error WindowsUtils::copy_and_rename_pdb(const String &p_dll_path) {51#ifdef DEBUG_ENABLED52// 1000 ought to be enough for anybody, in case the debugger does not unblock previous PDBs.53// Usually no more than 2 will be used.54const int max_pdb_names = 1000;5556struct PDBResourceInfo {57uint32_t address = 0;58String path;59} pdb_info;6061// Open and read the PDB information if available.62{63ULONG dbg_info_size = 0;64DWORD dbg_info_position = 0;6566{67// The custom LoadLibraryExW is used instead of open_dynamic_library68// to avoid loading the original PDB into the debugger.69HMODULE library_ptr = LoadLibraryExW((LPCWSTR)(p_dll_path.utf16().get_data()), nullptr, LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE);7071ERR_FAIL_NULL_V_MSG(library_ptr, ERR_FILE_CANT_OPEN, vformat("Failed to load library '%s'.", p_dll_path));7273IMAGE_DEBUG_DIRECTORY *dbg_dir = (IMAGE_DEBUG_DIRECTORY *)ImageDirectoryEntryToDataEx(library_ptr, FALSE, IMAGE_DIRECTORY_ENTRY_DEBUG, &dbg_info_size, nullptr);7475bool has_debug = dbg_dir && dbg_dir->Type == IMAGE_DEBUG_TYPE_CODEVIEW;76if (has_debug) {77dbg_info_position = dbg_dir->PointerToRawData;78dbg_info_size = dbg_dir->SizeOfData;79}8081ERR_FAIL_COND_V_MSG(!FreeLibrary((HMODULE)library_ptr), FAILED, vformat("Failed to free library '%s'.", p_dll_path));8283if (!has_debug) {84// Skip with no debugging symbols.85return ERR_SKIP;86}87}8889struct CV_HEADER {90DWORD Signature;91DWORD Offset;92};9394const DWORD nb10_magic = 0x3031424e; // "01BN" (little-endian)95struct CV_INFO_PDB20 {96CV_HEADER CvHeader; // CvHeader.Signature = "NB10"97DWORD Signature;98DWORD Age;99BYTE PdbFileName[1];100};101102const DWORD rsds_magic = 0x53445352; // "SDSR" (little-endian)103struct CV_INFO_PDB70 {104DWORD Signature; // "RSDS"105BYTE Guid[16];106DWORD Age;107BYTE PdbFileName[1];108};109110Vector<uint8_t> dll_data;111112{113Error err = OK;114Ref<FileAccess> file = FileAccess::open(p_dll_path, FileAccess::READ, &err);115ERR_FAIL_COND_V_MSG(err != OK, err, vformat("Failed to read library '%s'.", p_dll_path));116117file->seek(dbg_info_position);118dll_data = file->get_buffer(dbg_info_size);119ERR_FAIL_COND_V_MSG(file->get_error() != OK, file->get_error(), vformat("Failed to read data from library '%s'.", p_dll_path));120}121122const char *raw_pdb_path = nullptr;123int raw_pdb_offset = 0;124DWORD *pdb_info_signature = (DWORD *)dll_data.ptr();125126if (*pdb_info_signature == rsds_magic) {127raw_pdb_path = (const char *)(((CV_INFO_PDB70 *)pdb_info_signature)->PdbFileName);128raw_pdb_offset = offsetof(CV_INFO_PDB70, PdbFileName);129} else if (*pdb_info_signature == nb10_magic) {130// Not even sure if this format still exists anywhere...131raw_pdb_path = (const char *)(((CV_INFO_PDB20 *)pdb_info_signature)->PdbFileName);132raw_pdb_offset = offsetof(CV_INFO_PDB20, PdbFileName);133} else {134ERR_FAIL_V_MSG(FAILED, vformat("Unknown PDB format in '%s'.", p_dll_path));135}136137String utf_path;138Error err = utf_path.append_utf8(raw_pdb_path);139ERR_FAIL_COND_V_MSG(err != OK, err, vformat("Failed to read PDB path from '%s'.", p_dll_path));140141pdb_info.path = utf_path;142pdb_info.address = dbg_info_position + raw_pdb_offset;143}144145String dll_base_dir = p_dll_path.get_base_dir();146String copy_pdb_path = pdb_info.path;147148// Attempting to find the PDB by absolute and relative paths.149if (copy_pdb_path.is_relative_path()) {150copy_pdb_path = dll_base_dir.path_join(copy_pdb_path);151if (!FileAccess::exists(copy_pdb_path)) {152copy_pdb_path = dll_base_dir.path_join(copy_pdb_path.get_file());153}154} else if (!FileAccess::exists(copy_pdb_path)) {155copy_pdb_path = dll_base_dir.path_join(copy_pdb_path.get_file());156}157if (!FileAccess::exists(copy_pdb_path)) {158// The PDB file may be distributed separately on purpose, so we don't consider this an error.159WARN_VERBOSE(vformat("PDB file '%s' for library '%s' was not found, skipping copy/rename.", copy_pdb_path, p_dll_path));160return ERR_SKIP;161}162163String new_pdb_base_name = p_dll_path.get_file().get_basename() + "_";164165// Checking the available space for the updated string166// and trying to shorten it if there is not much space.167{168// e.g. 999.pdb169const uint8_t suffix_size = String::num_characters((int64_t)max_pdb_names - 1) + 4;170// e.g. ~lib_ + 1 for the \0171const uint8_t min_base_size = 5 + 1;172int original_path_size = pdb_info.path.utf8().length();173CharString utf8_name = new_pdb_base_name.utf8();174int new_expected_buffer_size = utf8_name.length() + suffix_size;175176// Since we have limited space inside the DLL to patch the path to the PDB,177// it is necessary to limit the size based on the number of bytes occupied by the string.178if (new_expected_buffer_size > original_path_size) {179ERR_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));180181new_pdb_base_name.clear();182new_pdb_base_name.append_utf8(utf8_name.get_data(), original_path_size - suffix_size);183new_pdb_base_name[new_pdb_base_name.length() - 1] = '_'; // Restore the last '_'184WARN_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));185}186}187188// Delete old PDB files.189for (const String &file : DirAccess::get_files_at(dll_base_dir)) {190if (file.begins_with(new_pdb_base_name) && file.ends_with(".pdb")) {191String path = dll_base_dir.path_join(file);192193// Just try to delete without showing any errors.194Error err = DirAccess::remove_absolute(path);195if (err == OK && temp_pdbs[p_dll_path].has(path)) {196temp_pdbs[p_dll_path].erase(path);197}198}199}200201// Try to copy PDB with new name and patch DLL.202Ref<DirAccess> d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);203for (int i = 0; i < max_pdb_names; i++) {204String new_pdb_name = vformat("%s%d.pdb", new_pdb_base_name, i);205String new_pdb_path = dll_base_dir.path_join(new_pdb_name);206Error err = OK;207208Ref<FileAccess> test_pdb_is_locked = FileAccess::open(new_pdb_path, FileAccess::READ_WRITE, &err);209if (err == ERR_FILE_CANT_OPEN) {210// If the file is blocked, continue searching.211continue;212} else if (err != OK && err != ERR_FILE_NOT_FOUND) {213ERR_FAIL_V_MSG(err, vformat("Failed to open '%s' to check if it is locked.", new_pdb_path));214}215216err = d->copy(copy_pdb_path, new_pdb_path);217ERR_FAIL_COND_V_MSG(err != OK, err, vformat("Failed to copy PDB from '%s' to '%s'.", copy_pdb_path, new_pdb_path));218temp_pdbs[p_dll_path].append(new_pdb_path);219220Ref<FileAccess> file = FileAccess::open(p_dll_path, FileAccess::READ_WRITE, &err);221ERR_FAIL_COND_V_MSG(err != OK, err, vformat("Failed to open '%s' to patch the PDB path.", p_dll_path));222223int original_path_size = pdb_info.path.utf8().length();224// Double-check file bounds.225ERR_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));226227Vector<uint8_t> u8 = new_pdb_name.to_utf8_buffer();228file->seek(pdb_info.address);229file->store_buffer(u8);230231// Terminate string and fill the remaining part of the original string with the '\0'.232Vector<uint8_t> padding_buffer;233padding_buffer.resize_initialized((int64_t)original_path_size - u8.size());234file->store_buffer(padding_buffer);235ERR_FAIL_COND_V_MSG(err != OK, err, vformat("Failed to write a new PDB path to '%s'.", p_dll_path));236237return OK;238}239240ERR_FAIL_V_MSG(FAILED, vformat("Failed to find an unblocked PDB name for '%s' among %d files.", p_dll_path, max_pdb_names));241#else242WARN_PRINT_ONCE("Renaming PDB files is only available in debug builds. If your libraries use PDB files, then the original ones will be used.");243return ERR_SKIP;244#endif245}246247void WindowsUtils::remove_temp_pdbs(const String &p_dll_path) {248#ifdef DEBUG_ENABLED249if (temp_pdbs.has(p_dll_path)) {250Vector<String> removed;251int failed = 0;252const int failed_limit = 10;253for (const String &pdb : temp_pdbs[p_dll_path]) {254if (FileAccess::exists(pdb)) {255Error err = DirAccess::remove_absolute(pdb);256if (err == OK) {257removed.append(pdb);258} else {259failed++;260if (failed <= failed_limit) {261print_verbose("Failed to remove temp PDB: " + pdb);262}263}264} else {265removed.append(pdb);266}267}268269if (failed > failed_limit) {270print_verbose(vformat("And %d more PDB files could not be removed....", failed - failed_limit));271}272273for (const String &pdb : removed) {274temp_pdbs[p_dll_path].erase(pdb);275}276}277#endif278}279280#endif // WINDOWS_ENABLED281282283