From 2f4c0bbc97cc8690c0cd00d24c37a196df4131db Mon Sep 17 00:00:00 2001 From: kizer Date: Fri, 17 Jun 2022 17:28:10 +0900 Subject: [PATCH] Update logging to reflect msvc updates on std::format (#883) --- Dalamud.Boot/Dalamud.Boot.vcxproj | 2 +- Dalamud.Boot/dllmain.cpp | 40 ++--- Dalamud.Boot/hooks.cpp | 8 +- Dalamud.Boot/logging.cpp | 95 ++++++------ Dalamud.Boot/logging.h | 144 ++++++++++++------ Dalamud.Boot/rewrite_entrypoint.cpp | 2 +- Dalamud.Boot/unicode.h | 2 +- Dalamud.Boot/utils.cpp | 4 +- Dalamud.Boot/utils.h | 8 +- Dalamud.Boot/veh.cpp | 8 +- Dalamud.Boot/xivfixes.cpp | 68 ++++----- .../Dalamud.Injector.Boot.vcxproj | 2 +- Dalamud.Injector.Boot/main.cpp | 8 +- lib/CoreCLR/CoreCLR.cpp | 2 +- lib/CoreCLR/boot.cpp | 28 ++-- 15 files changed, 238 insertions(+), 183 deletions(-) diff --git a/Dalamud.Boot/Dalamud.Boot.vcxproj b/Dalamud.Boot/Dalamud.Boot.vcxproj index 458969974..891eb0275 100644 --- a/Dalamud.Boot/Dalamud.Boot.vcxproj +++ b/Dalamud.Boot/Dalamud.Boot.vcxproj @@ -25,7 +25,7 @@ DynamicLibrary true - v142 + v143 false Unicode ..\bin\$(Configuration)\ diff --git a/Dalamud.Boot/dllmain.cpp b/Dalamud.Boot/dllmain.cpp index d8b295fde..3c516039c 100644 --- a/Dalamud.Boot/dllmain.cpp +++ b/Dalamud.Boot/dllmain.cpp @@ -13,32 +13,32 @@ DllExport DWORD WINAPI Initialize(LPVOID lpParam, HANDLE hMainThreadContinue) { ConsoleSetup(L"Dalamud Boot"); if (const auto logFilePath = utils::get_env("DALAMUD_BOOT_LOGFILE"); logFilePath.empty()) - logging::print("No log file path given; not logging to file."); + logging::I("No log file path given; not logging to file."); else { try { logging::start_file_logging(logFilePath, !bootconfig::is_show_console()); - logging::print(L"Logging to file: {}", logFilePath); + logging::I("Logging to file: {}", logFilePath); } catch (const std::exception& e) { - logging::print(L"Couldn't open log file: {}", logFilePath); - logging::print("Error: {} / {}", errno, e.what()); + logging::E("Couldn't open log file: {}", logFilePath); + logging::E("Error: {} / {}", errno, e.what()); } } - logging::print("Dalamud.Boot Injectable, (c) 2021 XIVLauncher Contributors"); - logging::print("Built at: " __DATE__ "@" __TIME__); + logging::I("Dalamud.Boot Injectable, (c) 2021 XIVLauncher Contributors"); + logging::I("Built at: " __DATE__ "@" __TIME__); if (bootconfig::wait_messagebox() & bootconfig::WaitMessageboxFlags::BeforeInitialize) MessageBoxW(nullptr, L"Press OK to continue", L"Dalamud Boot", MB_OK); - logging::print("Applying fixes..."); + logging::I("Applying fixes..."); xivfixes::apply_all(true); - logging::print("Fixes OK"); + logging::I("Fixes OK"); if (bootconfig::is_wait_debugger()) { - logging::print("Waiting for debugger to attach..."); + logging::I("Waiting for debugger to attach..."); while (!IsDebuggerPresent()) Sleep(100); - logging::print("Debugger attached."); + logging::I("Debugger attached."); } const auto fs_module_path = utils::get_module_path(g_hModule); @@ -47,7 +47,7 @@ DllExport DWORD WINAPI Initialize(LPVOID lpParam, HANDLE hMainThreadContinue) { // ============================== CLR ========================================= // - logging::print("Calling InitializeClrAndGetEntryPoint"); + logging::I("Calling InitializeClrAndGetEntryPoint"); void* entrypoint_vfn; int result = InitializeClrAndGetEntryPoint( @@ -67,16 +67,16 @@ DllExport DWORD WINAPI Initialize(LPVOID lpParam, HANDLE hMainThreadContinue) { // ============================== VEH ======================================== // - logging::print("Initializing VEH..."); + logging::I("Initializing VEH..."); if (utils::is_running_on_linux()) { - logging::print("=> VEH was disabled, running on linux"); + logging::I("=> VEH was disabled, running on linux"); } else if (bootconfig::is_veh_enabled()) { if (veh::add_handler(bootconfig::is_veh_full())) - logging::print("=> Done!"); + logging::I("=> Done!"); else - logging::print("=> Failed!"); + logging::I("=> Failed!"); } else { - logging::print("VEH was disabled manually"); + logging::I("VEH was disabled manually"); } // ============================== Dalamud ==================================== // @@ -91,9 +91,9 @@ DllExport DWORD WINAPI Initialize(LPVOID lpParam, HANDLE hMainThreadContinue) { utils::wait_for_game_window(); - logging::print("Initializing Dalamud..."); + logging::I("Initializing Dalamud..."); entrypoint_fn(lpParam, hMainThreadContinue); - logging::print("Done!"); + logging::I("Done!"); return 0; } @@ -105,7 +105,7 @@ BOOL APIENTRY DllMain(const HMODULE hModule, const DWORD dwReason, LPVOID lpRese case DLL_PROCESS_ATTACH: g_hModule = hModule; if (const auto mhStatus = MH_Initialize(); MH_OK != mhStatus) { - logging::print("Failed to initialize MinHook (status={})", static_cast(mhStatus)); + logging::E("Failed to initialize MinHook (status={})", static_cast(mhStatus)); return FALSE; } @@ -118,7 +118,7 @@ BOOL APIENTRY DllMain(const HMODULE hModule, const DWORD dwReason, LPVOID lpRese xivfixes::apply_all(false); if (const auto mhStatus = MH_Uninitialize(); MH_OK != mhStatus) { - logging::print("Failed to uninitialize MinHook (status={})", static_cast(mhStatus)); + logging::E("Failed to uninitialize MinHook (status={})", static_cast(mhStatus)); __fastfail(logging::MinHookUnload); } diff --git a/Dalamud.Boot/hooks.cpp b/Dalamud.Boot/hooks.cpp index a0d341786..2619ffa72 100644 --- a/Dalamud.Boot/hooks.cpp +++ b/Dalamud.Boot/hooks.cpp @@ -103,7 +103,7 @@ void hooks::getprocaddress_singleton_import_hook::initialize() { LdrRegisterDllNotification(0, [](ULONG notiReason, const LDR_DLL_NOTIFICATION_DATA* pData, void* context) { if (notiReason == LDR_DLL_NOTIFICATION_REASON_LOADED) { const auto dllName = unicode::convert(pData->Loaded.FullDllName->Buffer); - logging::print(R"({} "{}" has been loaded at 0x{:X} ~ 0x{:X} (0x{:X}); finding import table items to hook.)", + logging::I(R"({} "{}" has been loaded at 0x{:X} ~ 0x{:X} (0x{:X}); finding import table items to hook.)", LogTag, dllName, reinterpret_cast(pData->Loaded.DllBase), reinterpret_cast(pData->Loaded.DllBase) + pData->Loaded.SizeOfImage, @@ -111,7 +111,7 @@ void hooks::getprocaddress_singleton_import_hook::initialize() { reinterpret_cast(context)->hook_module(utils::loaded_module(pData->Loaded.DllBase)); } else if (notiReason == LDR_DLL_NOTIFICATION_REASON_UNLOADED) { const auto dllName = unicode::convert(pData->Unloaded.FullDllName->Buffer); - logging::print(R"({} "{}" has been unloaded.)", LogTag, dllName); + logging::I(R"({} "{}" has been unloaded.)", LogTag, dllName); } }, this, &m_ldrDllNotificationCookie); } @@ -119,7 +119,7 @@ void hooks::getprocaddress_singleton_import_hook::initialize() { FARPROC hooks::getprocaddress_singleton_import_hook::get_proc_address_handler(HMODULE hModule, LPCSTR lpProcName) { if (const auto it1 = m_targetFns.find(hModule); it1 != m_targetFns.end()) { if (const auto it2 = it1->second.find(lpProcName); it2 != it1->second.end()) { - logging::print(R"({} Redirecting GetProcAddress("{}", "{}"))", LogTag, m_dllNameMap[hModule], lpProcName); + logging::I(R"({} Redirecting GetProcAddress("{}", "{}"))", LogTag, m_dllNameMap[hModule], lpProcName); return reinterpret_cast(it2->second); } @@ -139,7 +139,7 @@ void hooks::getprocaddress_singleton_import_hook::hook_module(const utils::loade if (void* pGetProcAddressImport; mod.find_imported_function_pointer(dllName.c_str(), targetFn.c_str(), 0, pGetProcAddressImport)) { auto& hook = m_hooks[hModule][targetFn][mod]; if (!hook) { - logging::print("{} Hooking {}!{} imported by {}", LogTag, dllName, targetFn, unicode::convert(mod.path().wstring())); + logging::I("{} Hooking {}!{} imported by {}", LogTag, dllName, targetFn, unicode::convert(mod.path().wstring())); hook.emplace(std::format("getprocaddress_singleton_import_hook::hook_module({}!{})", dllName, targetFn), static_cast(pGetProcAddressImport), pfnThunk); } diff --git a/Dalamud.Boot/logging.cpp b/Dalamud.Boot/logging.cpp index c9d729b18..cac9584c0 100644 --- a/Dalamud.Boot/logging.cpp +++ b/Dalamud.Boot/logging.cpp @@ -10,48 +10,6 @@ static bool s_bLoaded = false; static bool s_bSkipLogFileWrite = false; static std::shared_ptr s_hLogFile; -void logging::print(Level level, const char* s) { - SYSTEMTIME st; - GetLocalTime(&st); - - std::string estr; - switch (level) { - case Verbose: - estr = std::format("[{:02}:{:02}:{:02} CPP/VRB] {}\n", st.wHour, st.wMinute, st.wSecond, s); - break; - case Debug: - estr = std::format("[{:02}:{:02}:{:02} CPP/DBG] {}\n", st.wHour, st.wMinute, st.wSecond, s); - break; - case Info: - estr = std::format("[{:02}:{:02}:{:02} CPP/INF] {}\n", st.wHour, st.wMinute, st.wSecond, s); - break; - case Warning: - estr = std::format("[{:02}:{:02}:{:02} CPP/WRN] {}\n", st.wHour, st.wMinute, st.wSecond, s); - break; - case Error: - estr = std::format("[{:02}:{:02}:{:02} CPP/ERR] {}\n", st.wHour, st.wMinute, st.wSecond, s); - break; - case Fatal: - estr = std::format("[{:02}:{:02}:{:02} CPP/FTL] {}\n", st.wHour, st.wMinute, st.wSecond, s); - break; - default: - estr = std::format("[{:02}:{:02}:{:02} CPP/???] {}\n", st.wHour, st.wMinute, st.wSecond, s); - break; - } - - OutputDebugStringW(unicode::convert(estr).c_str()); - - // Handle accesses should not be done during DllMain process attach/detach calls - if (s_bLoaded) { - DWORD wr{}; - WriteFile(GetStdHandle(STD_ERROR_HANDLE), &estr[0], static_cast(estr.size()), &wr, nullptr); - - if (s_hLogFile && !s_bSkipLogFileWrite) { - WriteFile(s_hLogFile.get(), &estr[0], static_cast(estr.size()), &wr, nullptr); - } - } -} - void logging::start_file_logging(const std::filesystem::path& path, bool redirect_stderrout) { if (s_hLogFile) return; @@ -69,14 +27,14 @@ void logging::start_file_logging(const std::filesystem::path& path, bool redirec } const auto h = CreateFile(path.wstring().c_str(), - GENERIC_WRITE, - FILE_SHARE_READ | FILE_SHARE_WRITE, - nullptr, OPEN_ALWAYS, 0, nullptr); + GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_WRITE, + nullptr, OPEN_ALWAYS, 0, nullptr); if (h == INVALID_HANDLE_VALUE) throw std::runtime_error(std::format("Win32 error {}(0x{:x})", GetLastError(), GetLastError())); - + SetFilePointer(h, 0, 0, FILE_END); - s_hLogFile = { h, &CloseHandle }; + s_hLogFile = {h, &CloseHandle}; if (redirect_stderrout) { SetStdHandle(STD_ERROR_HANDLE, h); @@ -88,3 +46,46 @@ void logging::start_file_logging(const std::filesystem::path& path, bool redirec void logging::update_dll_load_status(bool loaded) { s_bLoaded = loaded; } + +template<> +void logging::print(Level level, const char* s) { + SYSTEMTIME st; + GetLocalTime(&st); + + std::string estr; + switch (level) { + case Level::Verbose: + estr = std::format("[{:02}:{:02}:{:02} CPP/VRB] {}\n", st.wHour, st.wMinute, st.wSecond, s); + break; + case Level::Debug: + estr = std::format("[{:02}:{:02}:{:02} CPP/DBG] {}\n", st.wHour, st.wMinute, st.wSecond, s); + break; + case Level::Info: + estr = std::format("[{:02}:{:02}:{:02} CPP/INF] {}\n", st.wHour, st.wMinute, st.wSecond, s); + break; + case Level::Warning: + estr = std::format("[{:02}:{:02}:{:02} CPP/WRN] {}\n", st.wHour, st.wMinute, st.wSecond, s); + break; + case Level::Error: + estr = std::format("[{:02}:{:02}:{:02} CPP/ERR] {}\n", st.wHour, st.wMinute, st.wSecond, s); + break; + case Level::Fatal: + estr = std::format("[{:02}:{:02}:{:02} CPP/FTL] {}\n", st.wHour, st.wMinute, st.wSecond, s); + break; + default: + estr = std::format("[{:02}:{:02}:{:02} CPP/???] {}\n", st.wHour, st.wMinute, st.wSecond, s); + break; + } + + OutputDebugStringW(unicode::convert(estr).c_str()); + + // Handle accesses should not be done during DllMain process attach/detach calls + if (s_bLoaded) { + DWORD wr{}; + WriteFile(GetStdHandle(STD_ERROR_HANDLE), &estr[0], static_cast(estr.size()), &wr, nullptr); + + if (s_hLogFile && !s_bSkipLogFileWrite) { + WriteFile(s_hLogFile.get(), &estr[0], static_cast(estr.size()), &wr, nullptr); + } + } +} diff --git a/Dalamud.Boot/logging.h b/Dalamud.Boot/logging.h index c3d7634c9..ad6a9d73e 100644 --- a/Dalamud.Boot/logging.h +++ b/Dalamud.Boot/logging.h @@ -2,25 +2,18 @@ #include #include -#include #include #include "unicode.h" namespace logging { - enum Level : int { + enum class Level : int { Verbose = 0, - V = 0, Debug = 1, - D = 1, Info = 2, - I = 2, Warning = 3, - W = 3, Error = 4, - E = 4, Fatal = 5, - F = 5, }; enum FastFailErrorCode : int { @@ -28,42 +21,105 @@ namespace logging { MinHookUnload, }; - void print(Level level, const char* s); - - inline void print(Level level, const wchar_t* s) { - const auto cs = unicode::convert(s); - print(level, cs.c_str()); - } - - inline void print(Level level, const std::string& s) { - print(level, s.c_str()); - } - - inline void print(Level level, const std::wstring& s) { - print(level, s.c_str()); - } - - template - inline void print(const T* s) { - print(level, s); - } - - template - inline void print(Level level, const char* pcszFormat, Arg arg1, Args...args) { - print(level, std::format(pcszFormat, std::forward(arg1), std::forward(args)...)); - } - - template - inline void print(Level level, const wchar_t* pcszFormat, Arg arg1, Args...args) { - print(level, std::format(pcszFormat, std::forward(arg1), std::forward(args)...)); - } - - template>> - inline void print(const T* pcszFormat, Arg arg1, Args...args) { - print(level, std::format(pcszFormat, std::forward(arg1), std::forward(args)...)); - } - + /** + * @brief Starts writing log to specified file. + */ void start_file_logging(const std::filesystem::path& path, bool redirect_stderrout = false); + /** + * @brief Marks this DLL either as loaded or unloaded, top prevent accessing handles when the DLL is not loaded. + */ void update_dll_load_status(bool loaded); -}; + + /** + * @brief Prints log, unformatted. + * @param level Log level. + * @param s Log to print, as a C-string. + */ + template + void print(Level level, const TElem* s) { print(level, unicode::convert(s).c_str()); } + + /** + * @brief Prints log, unformatted. + * @param level Log level. + * @param s Log to print, as a basic_string. + */ + template, typename TAlloc = std::allocator> + void print(Level level, const std::basic_string& s) { print(level, s.c_str()); } + + /** + * @brief Prints log, unformatted. + * @param level Log level. + * @param s Log to print, as a basic_string_view. + */ + template> + void print(Level level, const std::basic_string_view& s) { print(level, unicode::convert(s).c_str()); } + + template<> + void print(Level level, const char* s); + + template + struct is_basic_string : std::false_type {}; + + template + struct is_basic_string> : std::true_type {}; + + template + inline constexpr auto is_basic_string_v = is_basic_string::value; + + template + struct is_basic_string_view : std::false_type {}; + + template + struct is_basic_string_view> : std::true_type {}; + + template + inline constexpr auto is_basic_string_view_v = is_basic_string_view::value; + + template + auto to_format_arg(T&& x) { + using Td = std::remove_cvref_t; + if constexpr (std::is_pointer_v) { + using Tdd = std::remove_cvref_t>; + if constexpr (std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v) + return unicode::convert(x); + else + return std::forward(x); + + } else { + if constexpr (is_basic_string_v || is_basic_string_view_v) { + using Tdd = Td::value_type; + if constexpr (std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v) + return unicode::convert(x); + else + return std::forward(x); + + } else if constexpr (std::is_same_v) { + auto u8s = x.u8string(); + return std::move(*reinterpret_cast(&u8s)); + + } else { + return std::forward(x); + } + } + } + + /** + * @brief Prints log, formatted. + * @param level Log level. + * @param fmt C-string. + * @param arg1 First format parameter. + * @param args Second and further format parameters, if any. + */ + template + void print(Level level, const char* fmt, Arg&& arg1, Args&&...args) { + print(level, std::vformat(fmt, std::make_format_args(to_format_arg(std::forward(arg1)), to_format_arg(std::forward(args))...))); + } + + template void V(Args&&...args) { print(Level::Verbose, std::forward(args)...); } + template void D(Args&&...args) { print(Level::Debug, std::forward(args)...); } + template void I(Args&&...args) { print(Level::Info, std::forward(args)...); } + template void W(Args&&...args) { print(Level::Warning, std::forward(args)...); } + template void E(Args&&...args) { print(Level::Error, std::forward(args)...); } + template void F(Args&&...args) { print(Level::Fatal, std::forward(args)...); } +} diff --git a/Dalamud.Boot/rewrite_entrypoint.cpp b/Dalamud.Boot/rewrite_entrypoint.cpp index 9e96ad35e..5a585da7a 100644 --- a/Dalamud.Boot/rewrite_entrypoint.cpp +++ b/Dalamud.Boot/rewrite_entrypoint.cpp @@ -234,7 +234,7 @@ void* get_mapped_image_base_address(HANDLE hProcess, const std::filesystem::path return mbi.AllocationBase; } catch (const std::exception& e) { - logging::print("Failed to check memory block 0x{:X}(len=0x{:X}): {}", mbi.BaseAddress, mbi.RegionSize, e.what()); + logging::W("Failed to check memory block 0x{:X}(len=0x{:X}): {}", mbi.BaseAddress, mbi.RegionSize, e.what()); continue; } } diff --git a/Dalamud.Boot/unicode.h b/Dalamud.Boot/unicode.h index 53e584eeb..1cc8c8349 100644 --- a/Dalamud.Boot/unicode.h +++ b/Dalamud.Boot/unicode.h @@ -48,7 +48,7 @@ namespace unicode { char32_t c{}; for (size_t decLen = 0, decIdx = 0; decIdx < in.size() && (decLen = unicode::decode(c, &in[decIdx], in.size() - decIdx, strict)); decIdx += decLen) { const auto encIdx = out.size(); - const auto encLen = unicode::encode(nullptr, c, strict); + const auto encLen = unicode::encode(nullptr, c, strict); out.resize(encIdx + encLen); unicode::encode(&out[encIdx], c, strict); } diff --git a/Dalamud.Boot/utils.cpp b/Dalamud.Boot/utils.cpp index 74c9b7208..bc54ecf14 100644 --- a/Dalamud.Boot/utils.cpp +++ b/Dalamud.Boot/utils.cpp @@ -55,8 +55,8 @@ std::span utils::loaded_module::section(const char* pcszSectionName) const template static bool find_imported_function_pointer_helper(const char* pcBaseAddress, const IMAGE_IMPORT_DESCRIPTOR& desc, const IMAGE_DATA_DIRECTORY& dir, std::string_view reqFunc, uint32_t hintOrOrdinal, void*& ppFunctionAddress) { - const auto importLookupsOversizedSpan = std::span(reinterpret_cast(&pcBaseAddress[desc.OriginalFirstThunk]), (dir.Size - desc.OriginalFirstThunk) / sizeof TEntryType); - const auto importAddressesOversizedSpan = std::span(reinterpret_cast(&pcBaseAddress[desc.FirstThunk]), (dir.Size - desc.FirstThunk) / sizeof TEntryType); + const auto importLookupsOversizedSpan = std::span(reinterpret_cast(&pcBaseAddress[desc.OriginalFirstThunk]), (dir.Size - desc.OriginalFirstThunk) / sizeof(TEntryType)); + const auto importAddressesOversizedSpan = std::span(reinterpret_cast(&pcBaseAddress[desc.FirstThunk]), (dir.Size - desc.FirstThunk) / sizeof(TEntryType)); for (size_t i = 0, i_ = (std::min)(importLookupsOversizedSpan.size(), importAddressesOversizedSpan.size()); i < i_ && importLookupsOversizedSpan[i] && importAddressesOversizedSpan[i]; i++) { const auto& importLookup = importLookupsOversizedSpan[i]; diff --git a/Dalamud.Boot/utils.h b/Dalamud.Boot/utils.h index 53dc13146..04bf4fbd9 100644 --- a/Dalamud.Boot/utils.h +++ b/Dalamud.Boot/utils.h @@ -218,9 +218,7 @@ namespace utils { } template - T get_env(const wchar_t* pcwzName) { - static_assert(false); - } + T get_env(const wchar_t* pcwzName) = delete; template<> std::wstring get_env(const wchar_t* pcwzName); @@ -240,9 +238,7 @@ namespace utils { } template - std::vector get_env_list(const wchar_t* pcwzName) { - static_assert(false); - } + std::vector get_env_list(const wchar_t* pcwzName) = delete; template<> std::vector get_env_list(const wchar_t* pcwzName); diff --git a/Dalamud.Boot/veh.cpp b/Dalamud.Boot/veh.cpp index 933502c20..5691d5b24 100644 --- a/Dalamud.Boot/veh.cpp +++ b/Dalamud.Boot/veh.cpp @@ -269,16 +269,18 @@ LONG exception_handler(EXCEPTION_POINTERS* ex) L"Dalamud.EntryPoint+VehDelegate, Dalamud", nullptr, nullptr, &fn))) { - const auto msg = L"An error within the game has occurred.\n\n" + const auto formatted = std::format( + L"An error within the game has occurred.\n\n" L"This may be caused by a faulty plugin, a broken TexTools modification, any other third-party tool or simply a bug in the game.\n" L"Please try \"Start Over\" or \"Download Index Backup\" in TexTools, an integrity check in the XIVLauncher settings, and disabling plugins you don't need.\n\n" L"The log file is located at:\n" L"{1}\n\n" - L"Press OK to exit the application.\n\nFailed to read stack trace: {2:08x}"; + L"Press OK to exit the application.\n\nFailed to read stack trace: {2:08x}", + dmp_path, log_path, err); // show in another thread to prevent messagebox from pumping messages of current thread std::thread([&]() { - MessageBoxW(nullptr, std::format(msg, dmp_path, log_path, err).c_str(), L"Dalamud Error", MB_OK | MB_ICONERROR | MB_TOPMOST); + MessageBoxW(nullptr, formatted.c_str(), L"Dalamud Error", MB_OK | MB_ICONERROR | MB_TOPMOST); }).join(); } else diff --git a/Dalamud.Boot/xivfixes.cpp b/Dalamud.Boot/xivfixes.cpp index 93bb09575..7a72c4147 100644 --- a/Dalamud.Boot/xivfixes.cpp +++ b/Dalamud.Boot/xivfixes.cpp @@ -29,9 +29,9 @@ void xivfixes::unhook_dll(bool bApply) { std::filesystem::path path; try { path = mod.path(); - logging::print(L"{} [{}/{}] Module 0x{:X} ~ 0x{:X} (0x{:X}): \"{}\"", LogTagW, i + 1, mods.size(), mod.address_int(), mod.address_int() + mod.image_size(), mod.image_size(), path.wstring()); + logging::I("{} [{}/{}] Module 0x{:X} ~ 0x{:X} (0x{:X}): \"{}\"", LogTagW, i + 1, mods.size(), mod.address_int(), mod.address_int() + mod.image_size(), mod.image_size(), path.wstring()); } catch (const std::exception& e) { - logging::print("{} [{}/{}] Module 0x{:X}: Failed to resolve path: {}", LogTag, i + 1, mods.size(), mod.address_int(), e.what()); + logging::W("{} [{}/{}] Module 0x{:X}: Failed to resolve path: {}", LogTag, i + 1, mods.size(), mod.address_int(), e.what()); continue; } @@ -44,7 +44,7 @@ void xivfixes::unhook_dll(bool bApply) { const auto section = assume_nonempty_span(mod.span_as(sectionHeader.VirtualAddress, sectionHeader.Misc.VirtualSize), ".text[VA:VA+VS]"); auto hFsDllRaw = CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); if (hFsDllRaw == INVALID_HANDLE_VALUE) { - logging::print("{} Module loaded in current process but could not open file: Win32 error {}", LogTag, GetLastError()); + logging::W("{} Module loaded in current process but could not open file: Win32 error {}", LogTag, GetLastError()); continue; } auto hFsDll = std::unique_ptr(hFsDllRaw, &CloseHandle); @@ -53,11 +53,11 @@ void xivfixes::unhook_dll(bool bApply) { SetFilePointer(hFsDll.get(), sectionHeader.PointerToRawData, nullptr, FILE_CURRENT); if (DWORD read{}; ReadFile(hFsDll.get(), &buf[0], static_cast(buf.size()), &read, nullptr)) { if (read < section.size_bytes()) { - logging::print(L"{} ReadFile: read {} bytes < requested {} bytes", LogTagW, read, section.size_bytes()); + logging::W("{} ReadFile: read {} bytes < requested {} bytes", LogTagW, read, section.size_bytes()); continue; } } else { - logging::print(L"{} ReadFile: Win32 error {}", LogTagW, GetLastError()); + logging::I("{} ReadFile: Win32 error {}", LogTagW, GetLastError()); continue; } @@ -81,7 +81,7 @@ void xivfixes::unhook_dll(bool bApply) { if (!nmd_x86_decode(§ion[i], section.size() - i, &instruction, NMD_X86_MODE_64, NMD_X86_DECODER_FLAGS_ALL)) { instructionLength = 1; if (printed < 64) { - logging::print("{} {}+0x{:0X}: dd {:02X}", LogTag, moduleName, rva, static_cast(section[i])); + logging::W("{} {}+0x{:0X}: dd {:02X}", LogTag, moduleName, rva, static_cast(section[i])); printed++; } } else { @@ -102,16 +102,16 @@ void xivfixes::unhook_dll(bool bApply) { std::string_view name; if (const char* pcszName = mod.address_as(names[j]); pcszName < mod.address() || pcszName >= mod.address() + mod.image_size()) { if (IsBadReadPtr(pcszName, 256)) { - logging::print("{} Name #{} points to an invalid address outside the executable. Skipping.", LogTag, j); + logging::W("{} Name #{} points to an invalid address outside the executable. Skipping.", LogTag, j); continue; } name = std::string_view(pcszName, strnlen(pcszName, 256)); - logging::print("{} Name #{} points to a seemingly valid address outside the executable: {}", LogTag, j, name); + logging::W("{} Name #{} points to a seemingly valid address outside the executable: {}", LogTag, j, name); } if (ordinals[j] >= functions.size()) { - logging::print("{} Ordinal #{} points to function index #{} >= #{}. Skipping.", LogTag, j, ordinals[j], functions.size()); + logging::W("{} Ordinal #{} points to function index #{} >= #{}. Skipping.", LogTag, j, ordinals[j], functions.size()); continue; } @@ -122,7 +122,7 @@ void xivfixes::unhook_dll(bool bApply) { } } - logging::print("{} {}+0x{:0X}{}: {}", LogTag, moduleName, rva, resolvedExportName, formatBuf); + logging::W("{} {}+0x{:0X}{}: {}", LogTag, moduleName, rva, resolvedExportName, formatBuf); printed++; } } @@ -135,12 +135,12 @@ void xivfixes::unhook_dll(bool bApply) { } if (tenderizer) - logging::print("{} Verification and overwriting complete.", LogTag); + logging::I("{} Verification and overwriting complete.", LogTag); else if (doRestore) - logging::print("{} Verification complete. Overwriting was not required.", LogTag); + logging::I("{} Verification complete. Overwriting was not required.", LogTag); } catch (const std::exception& e) { - logging::print("{} Error: {}", LogTag, e.what()); + logging::W("{} Error: {}", LogTag, e.what()); } } } @@ -180,7 +180,7 @@ void xivfixes::prevent_devicechange_crashes(bool bApply) { if (bApply) { if (!bootconfig::gamefix_is_enabled(L"prevent_devicechange_crashes")) { - logging::print("{} Turned off via environment variable.", LogTag); + logging::I("{} Turned off via environment variable.", LogTag); return; } @@ -193,7 +193,7 @@ void xivfixes::prevent_devicechange_crashes(bool bApply) { || 0 != strcmp(lpClassName, "FFXIVGAME")) return hWnd; - logging::print(R"({} CreateWindow(0x{:08X}, "{}", "{}", 0x{:08X}, {}, {}, {}, {}, 0x{:X}, 0x{:X}, 0x{:X}, 0x{:X}) called; unhooking CreateWindowExA and hooking WndProc.)", + logging::I(R"({} CreateWindow(0x{:08X}, "{}", "{}", 0x{:08X}, {}, {}, {}, {}, 0x{:X}, 0x{:X}, 0x{:X}, 0x{:X}) called; unhooking CreateWindowExA and hooking WndProc.)", LogTag, dwExStyle, lpClassName, lpWindowName, dwStyle, X, Y, nWidth, nHeight, reinterpret_cast(hWndParent), reinterpret_cast(hMenu), reinterpret_cast(hInstance), reinterpret_cast(lpParam)); s_hookCreateWindowExA.reset(); @@ -202,7 +202,7 @@ void xivfixes::prevent_devicechange_crashes(bool bApply) { s_hookWndProc->set_detour([](HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) -> LRESULT { if (uMsg == WM_DEVICECHANGE && wParam == DBT_DEVNODES_CHANGED) { if (!GetGetInputDeviceManager(hWnd)()) { - logging::print("{} WndProc(0x{:X}, WM_DEVICECHANGE, DBT_DEVNODES_CHANGED, {}) called but the game does not have InputDeviceManager initialized; doing nothing.", LogTag, reinterpret_cast(hWnd), lParam); + logging::I("{} WndProc(0x{:X}, WM_DEVICECHANGE, DBT_DEVNODES_CHANGED, {}) called but the game does not have InputDeviceManager initialized; doing nothing.", LogTag, reinterpret_cast(hWnd), lParam); return 0; } } @@ -213,17 +213,17 @@ void xivfixes::prevent_devicechange_crashes(bool bApply) { return hWnd; }); - logging::print("{} Enable", LogTag); + logging::I("{} Enable", LogTag); } else { if (s_hookCreateWindowExA) { - logging::print("{} Disable CreateWindowExA", LogTag); + logging::I("{} Disable CreateWindowExA", LogTag); s_hookCreateWindowExA.reset(); } // This will effectively revert any other WndProc alterations, including Dalamud. if (s_hookWndProc) { - logging::print("{} Disable WndProc", LogTag); + logging::I("{} Disable WndProc", LogTag); s_hookWndProc.reset(); } } @@ -235,18 +235,18 @@ void xivfixes::disable_game_openprocess_access_check(bool bApply) { if (bApply) { if (!bootconfig::gamefix_is_enabled(L"disable_game_openprocess_access_check")) { - logging::print("{} Turned off via environment variable.", LogTag); + logging::I("{} Turned off via environment variable.", LogTag); return; } s_hook.emplace("kernel32.dll!OpenProcess (import, disable_game_openprocess_access_check)", "kernel32.dll", "OpenProcess", 0); s_hook->set_detour([](DWORD dwDesiredAccess, BOOL bInheritHandle, DWORD dwProcessId)->HANDLE { - logging::print("{} OpenProcess(0x{:08X}, {}, {}) was invoked by thread {}.", LogTag, dwDesiredAccess, bInheritHandle, dwProcessId, GetCurrentThreadId()); + logging::I("{} OpenProcess(0x{:08X}, {}, {}) was invoked by thread {}.", LogTag, dwDesiredAccess, bInheritHandle, dwProcessId, GetCurrentThreadId()); if (dwProcessId == GetCurrentProcessId()) { // Prevent game from feeling unsafe that it restarts if (dwDesiredAccess & PROCESS_VM_WRITE) { - logging::print("{} Returning failure with last error code set to ERROR_ACCESS_DENIED(5).", LogTag); + logging::I("{} Returning failure with last error code set to ERROR_ACCESS_DENIED(5).", LogTag); SetLastError(ERROR_ACCESS_DENIED); return {}; } @@ -255,10 +255,10 @@ void xivfixes::disable_game_openprocess_access_check(bool bApply) { return s_hook->call_original(dwDesiredAccess, bInheritHandle, dwProcessId); }); - logging::print("{} Enable", LogTag); + logging::I("{} Enable", LogTag); } else { if (s_hook) { - logging::print("{} Disable OpenProcess", LogTag); + logging::I("{} Disable OpenProcess", LogTag); s_hook.reset(); } } @@ -272,7 +272,7 @@ void xivfixes::redirect_openprocess(bool bApply) { if (bApply) { if (!bootconfig::gamefix_is_enabled(L"redirect_openprocess")) { - logging::print("{} Turned off via environment variable.", LogTag); + logging::I("{} Turned off via environment variable.", LogTag); return; } @@ -281,7 +281,7 @@ void xivfixes::redirect_openprocess(bool bApply) { hook->set_detour([hook = hook.get()](DWORD dwDesiredAccess, BOOL bInheritHandle, DWORD dwProcessId)->HANDLE { if (dwProcessId == GetCurrentProcessId()) { if (s_silenceSet.emplace(GetCurrentThreadId()).second) - logging::print("{} OpenProcess(0x{:08X}, {}, {}) was invoked by thread {}. Redirecting to DuplicateHandle.", LogTag, dwDesiredAccess, bInheritHandle, dwProcessId, GetCurrentThreadId()); + logging::I("{} OpenProcess(0x{:08X}, {}, {}) was invoked by thread {}. Redirecting to DuplicateHandle.", LogTag, dwDesiredAccess, bInheritHandle, dwProcessId, GetCurrentThreadId()); if (HANDLE res; DuplicateHandle(GetCurrentProcess(), GetCurrentProcess(), GetCurrentProcess(), &res, dwDesiredAccess, bInheritHandle, 0)) return res; @@ -292,14 +292,14 @@ void xivfixes::redirect_openprocess(bool bApply) { }); s_hook = std::dynamic_pointer_cast(std::move(hook)); - logging::print("{} Enable via import_hook", LogTag); + logging::I("{} Enable via import_hook", LogTag); } else { auto hook = std::make_shared>("kernel32.dll!OpenProcess (direct, redirect_openprocess)", OpenProcess); hook->set_detour([hook = hook.get()](DWORD dwDesiredAccess, BOOL bInheritHandle, DWORD dwProcessId)->HANDLE { if (dwProcessId == GetCurrentProcessId()) { if (s_silenceSet.emplace(GetCurrentThreadId()).second) - logging::print("{} OpenProcess(0x{:08X}, {}, {}) was invoked by thread {}. Redirecting to DuplicateHandle.", LogTag, dwDesiredAccess, bInheritHandle, dwProcessId, GetCurrentThreadId()); + logging::I("{} OpenProcess(0x{:08X}, {}, {}) was invoked by thread {}. Redirecting to DuplicateHandle.", LogTag, dwDesiredAccess, bInheritHandle, dwProcessId, GetCurrentThreadId()); if (HANDLE res; DuplicateHandle(GetCurrentProcess(), GetCurrentProcess(), GetCurrentProcess(), &res, dwDesiredAccess, bInheritHandle, 0)) return res; @@ -310,7 +310,7 @@ void xivfixes::redirect_openprocess(bool bApply) { }); s_hook = std::dynamic_pointer_cast(std::move(hook)); - logging::print("{} Enable via direct_hook", LogTag); + logging::I("{} Enable via direct_hook", LogTag); } //std::thread([]() { @@ -321,7 +321,7 @@ void xivfixes::redirect_openprocess(bool bApply) { } else { if (s_hook) { - logging::print("{} Disable OpenProcess", LogTag); + logging::I("{} Disable OpenProcess", LogTag); s_hook.reset(); } } @@ -341,16 +341,16 @@ void xivfixes::apply_all(bool bApply) { } catch (const std::exception& e) { if (bApply) - logging::print("Error trying to activate fixup [{}]: {}", taskName, e.what()); + logging::W("Error trying to activate fixup [{}]: {}", taskName, e.what()); else - logging::print("Error trying to deactivate fixup [{}]: {}", taskName, e.what()); + logging::W("Error trying to deactivate fixup [{}]: {}", taskName, e.what()); continue; } if (bApply) - logging::print("Fixup [{}] activated.", taskName); + logging::I("Fixup [{}] activated.", taskName); else - logging::print("Fixup [{}] deactivated.", taskName); + logging::I("Fixup [{}] deactivated.", taskName); } } diff --git a/Dalamud.Injector.Boot/Dalamud.Injector.Boot.vcxproj b/Dalamud.Injector.Boot/Dalamud.Injector.Boot.vcxproj index a553f5ef7..c293e258c 100644 --- a/Dalamud.Injector.Boot/Dalamud.Injector.Boot.vcxproj +++ b/Dalamud.Injector.Boot/Dalamud.Injector.Boot.vcxproj @@ -26,7 +26,7 @@ Application true - v142 + v143 false Unicode ..\bin\$(Configuration)\ diff --git a/Dalamud.Injector.Boot/main.cpp b/Dalamud.Injector.Boot/main.cpp index 49c020093..5147b91e4 100644 --- a/Dalamud.Injector.Boot/main.cpp +++ b/Dalamud.Injector.Boot/main.cpp @@ -9,8 +9,8 @@ int wmain(int argc, wchar_t** argv) { - logging::print("Dalamud Injector, (c) 2021 XIVLauncher Contributors"); - logging::print("Built at : " __DATE__ "@" __TIME__); + logging::I("Dalamud Injector, (c) 2021 XIVLauncher Contributors"); + logging::I("Built at : " __DATE__ "@" __TIME__); wchar_t _module_path[MAX_PATH]; GetModuleFileNameW(NULL, _module_path, sizeof _module_path / 2); @@ -37,9 +37,9 @@ int wmain(int argc, wchar_t** argv) typedef void (CORECLR_DELEGATE_CALLTYPE* custom_component_entry_point_fn)(int, wchar_t**); custom_component_entry_point_fn entrypoint_fn = reinterpret_cast(entrypoint_vfn); - logging::print("Running Dalamud Injector..."); + logging::I("Running Dalamud Injector..."); entrypoint_fn(argc, argv); - logging::print("Done!"); + logging::I("Done!"); return 0; } diff --git a/lib/CoreCLR/CoreCLR.cpp b/lib/CoreCLR/CoreCLR.cpp index 6e36443e2..e4a62eeba 100644 --- a/lib/CoreCLR/CoreCLR.cpp +++ b/lib/CoreCLR/CoreCLR.cpp @@ -83,7 +83,7 @@ int CoreCLR::load_runtime(const std::wstring& runtime_config_path, const struct // Success_HostAlreadyInitialized if (result == 1) { - logging::print("Success_HostAlreadyInitialized (0x1)"); + logging::I("Success_HostAlreadyInitialized (0x1)"); result = 0; } diff --git a/lib/CoreCLR/boot.cpp b/lib/CoreCLR/boot.cpp index 01b15811d..9e6dbe143 100644 --- a/lib/CoreCLR/boot.cpp +++ b/lib/CoreCLR/boot.cpp @@ -63,7 +63,7 @@ int InitializeClrAndGetEntryPoint( if (result != 0) { - logging::print("Unable to get RoamingAppData path (err={})", result); + logging::E("Unable to get RoamingAppData path (err={})", result); return result; } @@ -73,13 +73,13 @@ int InitializeClrAndGetEntryPoint( // =========================================================================== // - logging::print(L"with dotnet_path: {}", dotnet_path); - logging::print(L"with config_path: {}", runtimeconfig_path.c_str()); - logging::print(L"with module_path: {}", module_path.c_str()); + logging::I("with dotnet_path: {}", dotnet_path); + logging::I("with config_path: {}", runtimeconfig_path); + logging::I("with module_path: {}", module_path); if (!std::filesystem::exists(dotnet_path)) { - logging::print("Error: Unable to find .NET runtime path"); + logging::E("Error: Unable to find .NET runtime path"); return 1; } @@ -90,13 +90,13 @@ int InitializeClrAndGetEntryPoint( dotnet_path, }; - logging::print("Loading hostfxr..."); + logging::I("Loading hostfxr..."); if ((result = g_clr->load_hostfxr(&init_parameters)) != 0) { - logging::print("Failed to load the `hostfxr` library (err=0x{:08x})", result); + logging::E("Failed to load the `hostfxr` library (err=0x{:08x})", result); return result; } - logging::print("Done!"); + logging::I("Done!"); // =========================================================================== // @@ -107,17 +107,17 @@ int InitializeClrAndGetEntryPoint( dotnet_path, }; - logging::print("Loading coreclr... "); + logging::I("Loading coreclr... "); if ((result = g_clr->load_runtime(runtimeconfig_path, &runtime_parameters)) != 0) { - logging::print("Failed to load coreclr (err=0x{:08X})", static_cast(result)); + logging::E("Failed to load coreclr (err=0x{:08X})", static_cast(result)); return result; } - logging::print("Done!"); + logging::I("Done!"); // =========================================================================== // - logging::print("Loading module..."); + logging::I("Loading module..."); if ((result = g_clr->load_assembly_and_get_function_pointer( module_path.c_str(), entrypoint_assembly_name.c_str(), @@ -125,10 +125,10 @@ int InitializeClrAndGetEntryPoint( entrypoint_delegate_type_name.c_str(), nullptr, entrypoint_fn)) != 0) { - logging::print("Failed to load module (err={})", result); + logging::E("Failed to load module (err={})", result); return result; } - logging::print("Done!"); + logging::I("Done!"); // =========================================================================== //