From 0813be2acf4d8396f7c1f4fdd6e6ffeae63e8e2c Mon Sep 17 00:00:00 2001 From: Hyper <34012267+hyperbx@users.noreply.github.com> Date: Thu, 12 Dec 2024 22:12:29 +0000 Subject: [PATCH] Implemented cross-platform logger framework (and clean-up) --- UnleashedRecomp/CMakeLists.txt | 2 + .../kernel/{FreeList.h => freelist.h} | 0 UnleashedRecomp/kernel/imports.cpp | 567 ++++++++---------- UnleashedRecomp/kernel/io/file_system.cpp | 73 +-- UnleashedRecomp/kernel/xam.cpp | 66 +- UnleashedRecomp/kernel/xdm.cpp | 7 +- UnleashedRecomp/os/logger.cpp | 7 + UnleashedRecomp/os/logger.h | 35 ++ UnleashedRecomp/os/logger_detail.h | 16 + UnleashedRecomp/os/win32/logger_win32.cpp | 47 ++ UnleashedRecomp/os/win32/media_win32.cpp | 9 +- UnleashedRecomp/patches/player_patches.cpp | 5 +- UnleashedRecomp/patches/resident_patches.cpp | 3 +- .../patches/ui/frontend_listener.h | 9 +- UnleashedRecomp/ui/window.h | 5 +- UnleashedRecomp/user/achievement_data.cpp | 11 +- UnleashedRecomp/user/config.cpp | 7 +- 17 files changed, 453 insertions(+), 416 deletions(-) rename UnleashedRecomp/kernel/{FreeList.h => freelist.h} (100%) create mode 100644 UnleashedRecomp/os/logger.cpp create mode 100644 UnleashedRecomp/os/logger.h create mode 100644 UnleashedRecomp/os/logger_detail.h create mode 100644 UnleashedRecomp/os/win32/logger_win32.cpp diff --git a/UnleashedRecomp/CMakeLists.txt b/UnleashedRecomp/CMakeLists.txt index e179973..90f39a8 100644 --- a/UnleashedRecomp/CMakeLists.txt +++ b/UnleashedRecomp/CMakeLists.txt @@ -67,6 +67,7 @@ set(SWA_KERNEL_CXX_SOURCES ) set(SWA_OS_CXX_SOURCES + "os/logger.cpp" "os/media.cpp" "os/process.cpp" "os/version.cpp" @@ -74,6 +75,7 @@ set(SWA_OS_CXX_SOURCES if (WIN32) list(APPEND SWA_OS_CXX_SOURCES + "os/win32/logger_win32.cpp" "os/win32/media_win32.cpp" "os/win32/process_win32.cpp" "os/win32/version_win32.cpp" diff --git a/UnleashedRecomp/kernel/FreeList.h b/UnleashedRecomp/kernel/freelist.h similarity index 100% rename from UnleashedRecomp/kernel/FreeList.h rename to UnleashedRecomp/kernel/freelist.h diff --git a/UnleashedRecomp/kernel/imports.cpp b/UnleashedRecomp/kernel/imports.cpp index 9049b47..32c9127 100644 --- a/UnleashedRecomp/kernel/imports.cpp +++ b/UnleashedRecomp/kernel/imports.cpp @@ -12,6 +12,7 @@ #include "xdm.h" #include #include +#include #include @@ -32,52 +33,51 @@ DWORD GuestTimeoutToMilliseconds(XLPQWORD timeout) void VdHSIOCalibrationLock() { - printf("!!! STUB !!! VdHSIOCalibrationLock\n"); + LOG_UTILITY("!!! STUB !!!"); } void KeCertMonitorData() { - printf("!!! STUB !!! KeCertMonitorData\n"); + LOG_UTILITY("!!! STUB !!!"); } void XexExecutableModuleHandle() { - printf("!!! STUB !!! XexExecutableModuleHandle\n"); + LOG_UTILITY("!!! STUB !!!"); } void ExLoadedCommandLine() { - printf("!!! STUB !!! ExLoadedCommandLine\n"); + LOG_UTILITY("!!! STUB !!!"); } void KeDebugMonitorData() { - printf("!!! STUB !!! KeDebugMonitorData\n"); + LOG_UTILITY("!!! STUB !!!"); } void ExThreadObjectType() { - printf("!!! STUB !!! ExThreadObjectType\n"); + LOG_UTILITY("!!! STUB !!!"); } void KeTimeStampBundle() { - printf("!!! STUB !!! KeTimeStampBundle\n"); + LOG_UTILITY("!!! STUB !!!"); } void XboxHardwareInfo() { - printf("!!! STUB !!! XboxHardwareInfo\n"); + LOG_UTILITY("!!! STUB !!!"); } void XGetVideoMode() { - printf("!!! STUB !!! XGetVideoMode\n"); + LOG_UTILITY("!!! STUB !!!"); } uint32_t XGetGameRegion() { - // printf("!!! STUB !!! XGetGameRegion\n"); if (Config::Language == ELanguage::Japanese) return 0x0101; @@ -86,56 +86,43 @@ uint32_t XGetGameRegion() uint32_t XMsgStartIORequest(DWORD App, DWORD Message, XXOVERLAPPED* lpOverlapped, void* Buffer, DWORD szBuffer) { - // printf("!!! STUB !!! XMsgStartIORequest\n"); return STATUS_SUCCESS; } uint32_t XamUserGetSigninState(uint32_t userIndex) { - // printf("!!! STUB !!! XamUserGetSigninState\n"); return true; } uint32_t XamGetSystemVersion() { - // printf("!!! STUB !!! XamGetSystemVersion\n"); return 0; } - - void XamContentDelete() { - printf("!!! STUB !!! XamContentDelete\n"); + LOG_UTILITY("!!! STUB !!!"); } uint32_t XamContentGetCreator(DWORD userIndex, const XCONTENT_DATA* contentData, PBOOL isCreator, XLPQWORD xuid, XXOVERLAPPED* overlapped) { - // printf("!!! STUB !!! XamContentGetCreator\n"); - if (isCreator) - { *isCreator = true; - } if (xuid) - { *xuid = 0xB13EBABEBABEBABE; - } return 0; } uint32_t XamContentGetDeviceState() { - // printf("!!! STUB !!! XamContentGetDeviceState\n"); return 0; } uint32_t XamUserGetSigninInfo(uint32_t userIndex, uint32_t flags, XUSER_SIGNIN_INFO* info) { - // printf("!!! STUB !!! XamUserGetSigninInfo\n"); if (userIndex == 0) { memset(info, 0, sizeof(*info)); @@ -148,20 +135,21 @@ uint32_t XamUserGetSigninInfo(uint32_t userIndex, uint32_t flags, XUSER_SIGNIN_I return 0x00000525; // ERROR_NO_SUCH_USER } -void XamShowSigninUI(uint32_t userIndex, uint32_t usersNeeded, uint32_t flags) +void XamShowSigninUI() { - printf("!!! STUB !!! XamShowSigninUI %d %d 0x%X\n", userIndex, usersNeeded, flags); + LOG_UTILITY("!!! STUB !!!"); } -uint32_t XamShowDeviceSelectorUI( +uint32_t XamShowDeviceSelectorUI +( uint32_t userIndex, uint32_t contentType, uint32_t contentFlags, uint64_t totalRequested, XDWORD* deviceId, - XXOVERLAPPED* overlapped) + XXOVERLAPPED* overlapped +) { - // printf("!!! STUB !!! XamShowDeviceSelectorUI\n"); XamNotifyEnqueueEvent(9, true); *deviceId = 1; XamNotifyEnqueueEvent(9, false); @@ -170,66 +158,64 @@ uint32_t XamShowDeviceSelectorUI( void XamShowDirtyDiscErrorUI() { - printf("!!! STUB !!! XamShowDirtyDiscErrorUI\n"); + LOG_UTILITY("!!! STUB !!!"); } void XamEnableInactivityProcessing() { - printf("!!! STUB !!! XamEnableInactivityProcessing\n"); + LOG_UTILITY("!!! STUB !!!"); } void XamResetInactivity() { - printf("!!! STUB !!! XamResetInactivity\n"); + LOG_UTILITY("!!! STUB !!!"); } void XamShowMessageBoxUIEx() { - printf("!!! STUB !!! XamShowMessageBoxUIEx\n"); + LOG_UTILITY("!!! STUB !!!"); } uint32_t XGetLanguage() { - // printf("!!! STUB !!! XGetLanguage\n"); return (uint32_t)Config::Language.Value; } uint32_t XGetAVPack() { - // printf("!!! STUB !!! XGetAVPack\n"); return 0; } void XamLoaderTerminateTitle() { - printf("!!! STUB !!! XamLoaderTerminateTitle(void)\n"); + LOG_UTILITY("!!! STUB !!!"); } void XamGetExecutionId() { - printf("!!! STUB !!! XamGetExecutionId\n"); + LOG_UTILITY("!!! STUB !!!"); } void XamLoaderLaunchTitle() { - printf("!!! STUB !!! XamLoaderLaunchTitle(char\n"); + LOG_UTILITY("!!! STUB !!!"); } void NtOpenFile() { - printf("!!! STUB !!! NtOpenFile\n"); + LOG_UTILITY("!!! STUB !!!"); } void RtlInitAnsiString(XANSI_STRING* destination, char* source) { - printf("!!! STUB !!! RtlInitAnsiString %s\n", source); const uint16_t length = source ? (uint16_t)strlen(source) : 0; destination->Length = length; destination->MaximumLength = length + 1; destination->Buffer = source; } -DWORD NtCreateFile( +DWORD NtCreateFile +( XLPDWORD FileHandle, DWORD DesiredAccess, XOBJECT_ATTRIBUTES* Attributes, @@ -238,7 +224,8 @@ DWORD NtCreateFile( uint32_t FileAttributes, uint32_t ShareAccess, uint32_t CreateDisposition, - uint32_t CreateOptions) + uint32_t CreateOptions +) { return 0; } @@ -246,9 +233,7 @@ DWORD NtCreateFile( uint32_t NtClose(uint32_t handle) { if (handle == (uint32_t)INVALID_HANDLE_VALUE) - { return 0xFFFFFFFF; - } if (CHECK_GUEST_HANDLE(handle)) { @@ -256,24 +241,21 @@ uint32_t NtClose(uint32_t handle) return 0; } - // printf("!!! STUB !!! NtClose\n"); return CloseHandle((HANDLE)handle) ? 0 : 0xFFFFFFFF; } void NtSetInformationFile() { - printf("!!! STUB !!! NtSetInformationFile\n"); + LOG_UTILITY("!!! STUB !!!"); } uint32_t FscSetCacheElementCount() { - // printf("!!! STUB !!! FscSetCacheElementCount\n"); return 0; } DWORD NtWaitForSingleObjectEx(DWORD Handle, DWORD WaitMode, DWORD Alertable, XLPQWORD Timeout) { - // printf("!!! STUB !!! NtWaitForSingleObjectEx\n"); const auto status = WaitForSingleObjectEx((HANDLE)Handle, GuestTimeoutToMilliseconds(Timeout), Alertable); if (status == WAIT_IO_COMPLETION) @@ -290,74 +272,73 @@ DWORD NtWaitForSingleObjectEx(DWORD Handle, DWORD WaitMode, DWORD Alertable, XLP void NtWriteFile() { - printf("!!! STUB !!! NtWriteFile\n"); + LOG_UTILITY("!!! STUB !!!"); } void vsprintf_x() { - printf("!!! STUB !!! vsprintf\n"); + LOG_UTILITY("!!! STUB !!!"); } uint32_t ExGetXConfigSetting(uint16_t Category, uint16_t Setting, void* Buffer, uint16_t SizeOfBuffer, XLPDWORD RequiredSize) { - // printf("Invoking method ExGetXConfigSetting\n"); uint32_t data[4]{}; switch (Category) { // XCONFIG_SECURED_CATEGORY - case 0x0002: - { - switch (Setting) - { - // XCONFIG_SECURED_AV_REGION case 0x0002: - data[0] = std::byteswap(0x00001000); // USA/Canada - break; - - default: - return 1; - } - } - - case 0x0003: - { - switch (Setting) { - case 0x0001: // XCONFIG_USER_TIME_ZONE_BIAS - case 0x0002: // XCONFIG_USER_TIME_ZONE_STD_NAME - case 0x0003: // XCONFIG_USER_TIME_ZONE_DLT_NAME - case 0x0004: // XCONFIG_USER_TIME_ZONE_STD_DATE - case 0x0005: // XCONFIG_USER_TIME_ZONE_DLT_DATE - case 0x0006: // XCONFIG_USER_TIME_ZONE_STD_BIAS - case 0x0007: // XCONFIG_USER_TIME_ZONE_DLT_BIAS - data[0] = 0; - break; + switch (Setting) + { + // XCONFIG_SECURED_AV_REGION + case 0x0002: + data[0] = std::byteswap(0x00001000); // USA/Canada + break; - // XCONFIG_USER_LANGUAGE - case 0x0009: - data[0] = std::byteswap((uint32_t)Config::Language.Value); - break; - - // XCONFIG_USER_VIDEO_FLAGS - case 0x000A: - data[0] = std::byteswap(0x00040000); - break; - - // XCONFIG_USER_RETAIL_FLAGS - case 0x000C: - data[0] = std::byteswap(1); - break; - - // XCONFIG_USER_COUNTRY - case 0x000E: - data[0] = std::byteswap(103); - break; - - default: - return 1; + default: + return 1; + } + } + + case 0x0003: + { + switch (Setting) + { + case 0x0001: // XCONFIG_USER_TIME_ZONE_BIAS + case 0x0002: // XCONFIG_USER_TIME_ZONE_STD_NAME + case 0x0003: // XCONFIG_USER_TIME_ZONE_DLT_NAME + case 0x0004: // XCONFIG_USER_TIME_ZONE_STD_DATE + case 0x0005: // XCONFIG_USER_TIME_ZONE_DLT_DATE + case 0x0006: // XCONFIG_USER_TIME_ZONE_STD_BIAS + case 0x0007: // XCONFIG_USER_TIME_ZONE_DLT_BIAS + data[0] = 0; + break; + + // XCONFIG_USER_LANGUAGE + case 0x0009: + data[0] = std::byteswap((uint32_t)Config::Language.Value); + break; + + // XCONFIG_USER_VIDEO_FLAGS + case 0x000A: + data[0] = std::byteswap(0x00040000); + break; + + // XCONFIG_USER_RETAIL_FLAGS + case 0x000C: + data[0] = std::byteswap(1); + break; + + // XCONFIG_USER_COUNTRY + case 0x000E: + data[0] = std::byteswap(103); + break; + + default: + return 1; + } } - } } *RequiredSize = 4; @@ -368,68 +349,64 @@ uint32_t ExGetXConfigSetting(uint16_t Category, uint16_t Setting, void* Buffer, void NtQueryVirtualMemory() { - printf("!!! STUB !!! NtQueryVirtualMemory\n"); + LOG_UTILITY("!!! STUB !!!"); } void MmQueryStatistics() { - printf("!!! STUB !!! MmQueryStatistics\n"); + LOG_UTILITY("!!! STUB !!!"); } uint32_t NtCreateEvent(uint32_t* handle, void* objAttributes, uint32_t eventType, uint32_t initialState) { - //printf("!!! STUB !!! NtCreateEvent\n"); *handle = std::byteswap((uint32_t)CreateEventA(nullptr, !eventType, !!initialState, nullptr)); return 0; } uint32_t XexCheckExecutablePrivilege() { - //printf("!!! STUB !!! XexCheckExecutablePrivilege\n"); return 0; } void DbgPrint() { - printf("!!! STUB !!! DbgPrint\n"); + LOG_UTILITY("!!! STUB !!!"); } void __C_specific_handler_x() { - printf("!!! STUB !!! __C_specific_handler\n"); + LOG_UTILITY("!!! STUB !!!"); } void RtlNtStatusToDosError() { - printf("!!! STUB !!! RtlNtStatusToDosError\n"); + LOG_UTILITY("!!! STUB !!!"); } void XexGetProcedureAddress() { - printf("!!! STUB !!! XexGetProcedureAddress\n"); + LOG_UTILITY("!!! STUB !!!"); } void XexGetModuleSection() { - printf("!!! STUB !!! XexGetModuleSection\n"); + LOG_UTILITY("!!! STUB !!!"); } NTSTATUS RtlUnicodeToMultiByteN(PCHAR MultiByteString, DWORD MaxBytesInMultiByteString, XLPDWORD BytesInMultiByteString, PCWCH UnicodeString, ULONG BytesInUnicodeString) { const auto reqSize = BytesInUnicodeString / sizeof(wchar_t); + if (BytesInMultiByteString) - { *BytesInMultiByteString = reqSize; - } if (reqSize > MaxBytesInMultiByteString) - { return STATUS_FAIL_CHECK; - } for (size_t i = 0; i < reqSize; i++) { const auto c = std::byteswap(UnicodeString[i]); + MultiByteString[i] = c < 256 ? c : '?'; } @@ -438,11 +415,10 @@ NTSTATUS RtlUnicodeToMultiByteN(PCHAR MultiByteString, DWORD MaxBytesInMultiByte DWORD KeDelayExecutionThread(DWORD WaitMode, bool Alertable, XLPQWORD Timeout) { - if (Alertable) // We don't do async file reads + // We don't do async file reads. + if (Alertable) return STATUS_USER_APC; - // printf("!!! STUB !!! KeDelayExecutionThread\n"); - timeBeginPeriod(1); const auto status = SleepEx(GuestTimeoutToMilliseconds(Timeout), Alertable); timeEndPeriod(1); @@ -461,81 +437,83 @@ DWORD KeDelayExecutionThread(DWORD WaitMode, bool Alertable, XLPQWORD Timeout) void ExFreePool() { - printf("!!! STUB !!! ExFreePool\n"); + LOG_UTILITY("!!! STUB !!!"); } void NtQueryInformationFile() { - printf("!!! STUB !!! NtQueryInformationFile\n"); + LOG_UTILITY("!!! STUB !!!"); } void NtQueryVolumeInformationFile() { - printf("!!! STUB !!! NtQueryVolumeInformationFile\n"); + LOG_UTILITY("!!! STUB !!!"); } void NtQueryDirectoryFile() { - printf("!!! STUB !!! NtQueryDirectoryFile\n"); + LOG_UTILITY("!!! STUB !!!"); } void NtReadFileScatter() { - printf("!!! STUB !!! NtReadFileScatter\n"); + LOG_UTILITY("!!! STUB !!!"); } void NtReadFile() { - printf("!!! STUB !!! NtReadFile\n"); + LOG_UTILITY("!!! STUB !!!"); } void NtDuplicateObject() { - printf("!!! STUB !!! NtDuplicateObject\n"); + LOG_UTILITY("!!! STUB !!!"); } void NtAllocateVirtualMemory() { - printf("!!! STUB !!! NtAllocateVirtualMemory\n"); + LOG_UTILITY("!!! STUB !!!"); } void NtFreeVirtualMemory() { - printf("!!! STUB !!! NtFreeVirtualMemory\n"); + LOG_UTILITY("!!! STUB !!!"); } void ObDereferenceObject() { - //printf("!!! STUB !!! ObDereferenceObject\n"); + LOG_UTILITY("!!! STUB !!!"); } void KeSetBasePriorityThread(uint32_t thread, int priority) { - //printf("!!! STUB !!! KeSetBasePriorityThread\n"); if (priority == 16) + { priority = 15; + } else if (priority == -16) + { priority = -15; + } SetThreadPriority((HANDLE)thread, priority); } uint32_t ObReferenceObjectByHandle(uint32_t handle, uint32_t objectType, XLPDWORD object) { - //printf("Invoking method ObReferenceObjectByHandle\n"); *object = handle; return 0; } void KeQueryBasePriorityThread() { - printf("!!! STUB !!! KeQueryBasePriorityThread\n"); + LOG_UTILITY("!!! STUB !!!"); } uint32_t NtSuspendThread(uint32_t hThread, uint32_t* suspendCount) { - //printf("NtSuspendThread(): %x %x\n", hThread, suspendCount); DWORD count = SuspendThread((HANDLE)hThread); + if (count == (DWORD)-1) return E_FAIL; @@ -547,11 +525,9 @@ uint32_t NtSuspendThread(uint32_t hThread, uint32_t* suspendCount) uint32_t KeSetAffinityThread(DWORD Thread, DWORD Affinity, XLPDWORD lpPreviousAffinity) { - // printf("Invoking method KeSetAffinityThread\n"); if (lpPreviousAffinity) - { *lpPreviousAffinity = 2; - } + return 0; } @@ -590,9 +566,9 @@ struct Semaphore : HostObject void RtlLeaveCriticalSection(XRTL_CRITICAL_SECTION* cs) { cs->RecursionCount--; - if (cs->RecursionCount != 0) { + + if (cs->RecursionCount != 0) return; - } InterlockedExchange(&cs->OwningThread, 0); WakeByAddressSingle(&cs->OwningThread); @@ -601,10 +577,13 @@ void RtlLeaveCriticalSection(XRTL_CRITICAL_SECTION* cs) void RtlEnterCriticalSection(XRTL_CRITICAL_SECTION* cs) { DWORD thisThread = GetCurrentThreadId(); + while (true) { DWORD previousOwner = InterlockedCompareExchangeAcquire(&cs->OwningThread, thisThread, 0); - if (previousOwner == 0 || previousOwner == thisThread) { + + if (previousOwner == 0 || previousOwner == thisThread) + { cs->RecursionCount++; return; } @@ -615,17 +594,17 @@ void RtlEnterCriticalSection(XRTL_CRITICAL_SECTION* cs) void RtlImageXexHeaderField() { - printf("!!! STUB !!! RtlImageXexHeaderField\n"); + LOG_UTILITY("!!! STUB !!!"); } void HalReturnToFirmware() { - printf("!!! STUB !!! HalReturnToFirmware\n"); + LOG_UTILITY("!!! STUB !!!"); } void RtlFillMemoryUlong() { - printf("!!! STUB !!! RtlFillMemoryUlong\n"); + LOG_UTILITY("!!! STUB !!!"); } void KeBugCheckEx() @@ -635,18 +614,16 @@ void KeBugCheckEx() uint32_t KeGetCurrentProcessType() { - //printf("!!! STUB !!! KeGetCurrentProcessType\n"); return 1; } void RtlCompareMemoryUlong() { - printf("!!! STUB !!! RtlCompareMemoryUlong\n"); + LOG_UTILITY("!!! STUB !!!"); } uint32_t RtlInitializeCriticalSection(XRTL_CRITICAL_SECTION* cs) { - //printf("!!! STUB !!! RtlInitializeCriticalSection\n"); cs->Header.Absolute = 0; cs->LockCount = -1; cs->RecursionCount = 0; @@ -657,123 +634,110 @@ uint32_t RtlInitializeCriticalSection(XRTL_CRITICAL_SECTION* cs) void RtlRaiseException_x() { - printf("!!! STUB !!! RtlRaiseException\n"); + LOG_UTILITY("!!! STUB !!!"); } void KfReleaseSpinLock(uint32_t* spinLock) { - //printf("!!! STUB !!! KfReleaseSpinLock\n"); InterlockedExchange((volatile long*)spinLock, 0); } void KfAcquireSpinLock(uint32_t* spinLock) { const auto ctx = GetPPCContext(); - //printf("!!! STUB !!! KfAcquireSpinLock\n"); while (InterlockedCompareExchange((volatile long*)spinLock, std::byteswap(*(uint32_t*)(g_memory.Translate(ctx->r13.u32 + 0x110))), 0) != 0) - { Sleep(0); - } } uint64_t KeQueryPerformanceFrequency() { - //printf("!!! STUB !!! KeQueryPerformanceFrequency\n"); return 49875000; } void MmFreePhysicalMemory(uint32_t type, uint32_t guestAddress) { - //printf("!!! STUB !!! MmFreePhysicalMemory\n"); if (guestAddress != NULL) g_userHeap.Free(g_memory.Translate(guestAddress)); } bool VdPersistDisplay(uint32_t a1, uint32_t* a2) { - //printf("!!! STUB !!! VdPersistDisplay\n"); *a2 = NULL; return false; } void VdSwap() { - printf("!!! STUB !!! VdSwap\n"); + LOG_UTILITY("!!! STUB !!!"); } void VdGetSystemCommandBuffer() { - printf("!!! STUB !!! VdGetSystemCommandBuffer\n"); + LOG_UTILITY("!!! STUB !!!"); } void KeReleaseSpinLockFromRaisedIrql(uint32_t* spinLock) { - //printf("!!! STUB !!! KeReleaseSpinLockFromRaisedIrql\n"); InterlockedExchange((volatile long*)spinLock, 0); } void KeAcquireSpinLockAtRaisedIrql(uint32_t* spinLock) { const auto ctx = GetPPCContext(); - //printf("!!! STUB !!! KeAcquireSpinLockAtRaisedIrql\n"); while (InterlockedCompareExchange((volatile long*)spinLock, std::byteswap(*(uint32_t*)(g_memory.Translate(ctx->r13.u32 + 0x110))), 0) != 0) - { Sleep(0); - } } uint32_t KiApcNormalRoutineNop() { - //printf("Invoking method KiApcNormalRoutineNop\n"); return 0; } void VdEnableRingBufferRPtrWriteBack() { - printf("!!! STUB !!! VdEnableRingBufferRPtrWriteBack\n"); + LOG_UTILITY("!!! STUB !!!"); } void VdInitializeRingBuffer() { - printf("!!! STUB !!! VdInitializeRingBuffer\n"); + LOG_UTILITY("!!! STUB !!!"); } uint32_t MmGetPhysicalAddress(uint32_t address) { - printf("MmGetPhysicalAddress(): %x\n", address); + LOGF_UTILITY("0x{:x}", address); return address; } void VdSetSystemCommandBufferGpuIdentifierAddress() { - printf("!!! STUB !!! VdSetSystemCommandBufferGpuIdentifierAddress\n"); + LOG_UTILITY("!!! STUB !!!"); } void _vsnprintf_x() { - printf("!!! STUB !!! _vsnprintf\n"); + LOG_UTILITY("!!! STUB !!!"); } void sprintf_x() { - printf("!!! STUB !!! sprintf\n"); + LOG_UTILITY("!!! STUB !!!"); } void ExRegisterTitleTerminateNotification() { - printf("!!! STUB !!! ExRegisterTitleTerminateNotification\n"); + LOG_UTILITY("!!! STUB !!!"); } void VdShutdownEngines() { - printf("!!! STUB !!! VdShutdownEngines\n"); + LOG_UTILITY("!!! STUB !!!"); } void VdQueryVideoMode(XVIDEO_MODE* vm) { - //printf("!!! STUB !!! VdQueryVideoMode\n"); memset(vm, 0, sizeof(XVIDEO_MODE)); vm->DisplayWidth = 1280; vm->DisplayHeight = 720; @@ -788,90 +752,91 @@ void VdQueryVideoMode(XVIDEO_MODE* vm) void VdGetCurrentDisplayInformation() { - printf("!!! STUB !!! VdGetCurrentDisplayInformation\n"); + LOG_UTILITY("!!! STUB !!!"); } void VdSetDisplayMode() { - printf("!!! STUB !!! VdSetDisplayMode\n"); + LOG_UTILITY("!!! STUB !!!"); } void VdSetGraphicsInterruptCallback() { - printf("!!! STUB !!! VdSetGraphicsInterruptCallback\n"); + LOG_UTILITY("!!! STUB !!!"); } void VdInitializeEngines() { - printf("!!! STUB !!! VdInitializeEngines\n"); + LOG_UTILITY("!!! STUB !!!"); } void VdIsHSIOTrainingSucceeded() { - printf("!!! STUB !!! VdIsHSIOTrainingSucceeded\n"); + LOG_UTILITY("!!! STUB !!!"); } void VdGetCurrentDisplayGamma() { - printf("!!! STUB !!! VdGetCurrentDisplayGamma\n"); + LOG_UTILITY("!!! STUB !!!"); } void VdQueryVideoFlags() { - printf("!!! STUB !!! VdQueryVideoFlags\n"); + LOG_UTILITY("!!! STUB !!!"); } void VdCallGraphicsNotificationRoutines() { - printf("!!! STUB !!! VdCallGraphicsNotificationRoutines\n"); + LOG_UTILITY("!!! STUB !!!"); } void VdInitializeScalerCommandBuffer() { - printf("!!! STUB !!! VdInitializeScalerCommandBuffer\n"); + LOG_UTILITY("!!! STUB !!!"); } void KeLeaveCriticalRegion() { - printf("!!! STUB !!! KeLeaveCriticalRegion\n"); + LOG_UTILITY("!!! STUB !!!"); } uint32_t VdRetrainEDRAM() { - //printf("!!! STUB !!! VdRetrainEDRAM\n"); return 0; } void VdRetrainEDRAMWorker() { - printf("!!! STUB !!! VdRetrainEDRAMWorker\n"); + LOG_UTILITY("!!! STUB !!!"); } void KeEnterCriticalRegion() { - printf("!!! STUB !!! KeEnterCriticalRegion\n"); + LOG_UTILITY("!!! STUB !!!"); } -uint32_t MmAllocatePhysicalMemoryEx( +uint32_t MmAllocatePhysicalMemoryEx +( uint32_t flags, uint32_t size, uint32_t protect, uint32_t minAddress, uint32_t maxAddress, - uint32_t alignment) + uint32_t alignment +) { - printf("MmAllocatePhysicalMemoryEx(): %x %x %x %x %x %x\n", flags, size, protect, minAddress, maxAddress, alignment); + LOGF_UTILITY("0x{:x}, 0x{:x}, 0x{:x}, 0x{:x}, 0x{:x}, 0x{:x}", flags, size, protect, minAddress, maxAddress, alignment); return g_memory.MapVirtual(g_userHeap.AllocPhysical(size, alignment)); } void ObDeleteSymbolicLink() { - printf("!!! STUB !!! ObDeleteSymbolicLink\n"); + LOG_UTILITY("!!! STUB !!!"); } void ObCreateSymbolicLink() { - printf("!!! STUB !!! ObCreateSymbolicLink\n"); + LOG_UTILITY("!!! STUB !!!"); } uint32_t MmQueryAddressProtect(uint32_t guestAddress) @@ -881,7 +846,7 @@ uint32_t MmQueryAddressProtect(uint32_t guestAddress) void VdEnableDisableClockGating() { - printf("!!! STUB !!! VdEnableDisableClockGating\n"); + LOG_UTILITY("!!! STUB !!!"); } void KeBugCheck() @@ -891,47 +856,44 @@ void KeBugCheck() void KeLockL2() { - printf("!!! STUB !!! KeLockL2\n"); + LOG_UTILITY("!!! STUB !!!"); } void KeUnlockL2() { - printf("!!! STUB !!! KeUnlockL2\n"); + LOG_UTILITY("!!! STUB !!!"); } bool KeSetEvent(XKEVENT* pEvent, DWORD Increment, bool Wait) { - // printf("!!! STUB !!! KeSetEvent\n"); return ObQueryObject(*pEvent)->Set(); } bool KeResetEvent(XKEVENT* pEvent) { - // printf("!!! STUB !!! KeResetEvent %X\n", GetCurrentThreadId()); return ObQueryObject(*pEvent)->Reset(); } DWORD KeWaitForSingleObject(XDISPATCHER_HEADER* Object, DWORD WaitReason, DWORD WaitMode, bool Alertable, XLPQWORD Timeout) { - // printf("!!! STUB !!! KeWaitForSingleObject %X\n", GetCurrentThreadId()); const uint64_t timeout = GuestTimeoutToMilliseconds(Timeout); HANDLE handle = nullptr; switch (Object->Type) { - case 0: - case 1: - handle = ObQueryObject(*Object)->handle; - break; + case 0: + case 1: + handle = ObQueryObject(*Object)->handle; + break; - case 5: - handle = ObQueryObject(*Object)->handle; - break; + case 5: + handle = ObQueryObject(*Object)->handle; + break; - default: - assert(false); - break; + default: + assert(false); + break; } return WaitForSingleObjectEx(handle, timeout, Alertable); @@ -939,32 +901,26 @@ DWORD KeWaitForSingleObject(XDISPATCHER_HEADER* Object, DWORD WaitReason, DWORD uint32_t KeTlsGetValue(DWORD dwTlsIndex) { - //printf("!!! STUB !!! KeTlsGetValue\n"); return (uint32_t)TlsGetValue(dwTlsIndex); } BOOL KeTlsSetValue(DWORD dwTlsIndex, DWORD lpTlsValue) { - //printf("!!! STUB !!! KeTlsSetValue\n"); return TlsSetValue(dwTlsIndex, (LPVOID)lpTlsValue); } DWORD KeTlsAlloc() { - //printf("!!! STUB !!! KeTlsAlloc\n"); return TlsAlloc(); } BOOL KeTlsFree(DWORD dwTlsIndex) { - //printf("!!! STUB !!! KeTlsFree\n"); return TlsFree(dwTlsIndex); } DWORD XMsgInProcessCall(uint32_t app, uint32_t message, XDWORD* param1, XDWORD* param2) { - //printf("!!! STUB !!! XMsgInProcessCall\n"); - if (message == 0x7001B) { uint32_t* ptr = (uint32_t*)g_memory.Translate(param1[1]); @@ -975,7 +931,8 @@ DWORD XMsgInProcessCall(uint32_t app, uint32_t message, XDWORD* param1, XDWORD* return 0; } -void XamUserReadProfileSettings( +void XamUserReadProfileSettings +( uint32_t titleId, uint32_t userIndex, uint32_t xuidCount, @@ -984,9 +941,9 @@ void XamUserReadProfileSettings( uint32_t* settingIds, XDWORD* bufferSize, void* buffer, - void* overlapped) + void* overlapped +) { - //printf("!!! STUB !!! XamUserReadProfileSettings\n"); if (buffer != nullptr) { memset(buffer, 0, *bufferSize); @@ -999,82 +956,82 @@ void XamUserReadProfileSettings( void NetDll_WSAStartup() { - printf("!!! STUB !!! NetDll_WSAStartup\n"); + LOG_UTILITY("!!! STUB !!!"); } void NetDll_WSACleanup() { - printf("!!! STUB !!! NetDll_WSACleanup\n"); + LOG_UTILITY("!!! STUB !!!"); } void NetDll_socket() { - printf("!!! STUB !!! NetDll_socket\n"); + LOG_UTILITY("!!! STUB !!!"); } void NetDll_closesocket() { - printf("!!! STUB !!! NetDll_closesocket\n"); + LOG_UTILITY("!!! STUB !!!"); } void NetDll_setsockopt() { - printf("!!! STUB !!! NetDll_setsockopt\n"); + LOG_UTILITY("!!! STUB !!!"); } void NetDll_bind() { - printf("!!! STUB !!! NetDll_bind\n"); + LOG_UTILITY("!!! STUB !!!"); } void NetDll_connect() { - printf("!!! STUB !!! NetDll_connect\n"); + LOG_UTILITY("!!! STUB !!!"); } void NetDll_listen() { - printf("!!! STUB !!! NetDll_listen\n"); + LOG_UTILITY("!!! STUB !!!"); } void NetDll_accept() { - printf("!!! STUB !!! NetDll_accept\n"); + LOG_UTILITY("!!! STUB !!!"); } void NetDll_select() { - printf("!!! STUB !!! NetDll_select\n"); + LOG_UTILITY("!!! STUB !!!"); } void NetDll_recv() { - printf("!!! STUB !!! NetDll_recv\n"); + LOG_UTILITY("!!! STUB !!!"); } void NetDll_send() { - printf("!!! STUB !!! NetDll_send\n"); + LOG_UTILITY("!!! STUB !!!"); } void NetDll_inet_addr() { - printf("!!! STUB !!! NetDll_inet_addr\n"); + LOG_UTILITY("!!! STUB !!!"); } void NetDll___WSAFDIsSet() { - printf("!!! STUB !!! NetDll___WSAFDIsSet\n"); + LOG_UTILITY("!!! STUB !!!"); } void XMsgStartIORequestEx() { - printf("!!! STUB !!! XMsgStartIORequestEx\n"); + LOG_UTILITY("!!! STUB !!!"); } void XexGetModuleHandle() { - printf("!!! STUB !!! XexGetModuleHandle\n"); + LOG_UTILITY("!!! STUB !!!"); } bool RtlTryEnterCriticalSection(XRTL_CRITICAL_SECTION* cs) @@ -1082,7 +1039,8 @@ bool RtlTryEnterCriticalSection(XRTL_CRITICAL_SECTION* cs) DWORD thisThread = GetCurrentThreadId(); DWORD previousOwner = InterlockedCompareExchangeAcquire(&cs->OwningThread, thisThread, 0); - if (previousOwner == 0 || previousOwner == thisThread) { + if (previousOwner == 0 || previousOwner == thisThread) + { cs->RecursionCount++; return true; } @@ -1092,7 +1050,6 @@ bool RtlTryEnterCriticalSection(XRTL_CRITICAL_SECTION* cs) void RtlInitializeCriticalSectionAndSpinCount(XRTL_CRITICAL_SECTION* cs, uint32_t spinCount) { - //printf("!!! STUB !!! RtlInitializeCriticalSectionAndSpinCount\n"); cs->Header.Absolute = (spinCount + 255) >> 8; cs->LockCount = -1; cs->RecursionCount = 0; @@ -1101,79 +1058,76 @@ void RtlInitializeCriticalSectionAndSpinCount(XRTL_CRITICAL_SECTION* cs, uint32_ void _vswprintf_x() { - printf("!!! STUB !!! _vswprintf\n"); + LOG_UTILITY("!!! STUB !!!"); } void _vscwprintf_x() { - printf("!!! STUB !!! _vscwprintf\n"); + LOG_UTILITY("!!! STUB !!!"); } void _swprintf_x() { - printf("!!! STUB !!! _swprintf\n"); + LOG_UTILITY("!!! STUB !!!"); } void _snwprintf_x() { - printf("!!! STUB !!! _snwprintf\n"); + LOG_UTILITY("!!! STUB !!!"); } void XeCryptBnQwBeSigVerify() { - printf("!!! STUB !!! XeCryptBnQwBeSigVerify\n"); + LOG_UTILITY("!!! STUB !!!"); } void XeKeysGetKey() { - printf("!!! STUB !!! XeKeysGetKey\n"); + LOG_UTILITY("!!! STUB !!!"); } void XeCryptRotSumSha() { - printf("!!! STUB !!! XeCryptRotSumSha\n"); + LOG_UTILITY("!!! STUB !!!"); } void XeCryptSha() { - printf("!!! STUB !!! XeCryptSha\n"); + LOG_UTILITY("!!! STUB !!!"); } void KeEnableFpuExceptions() { - printf("!!! STUB !!! KeEnableFpuExceptions\n"); + LOG_UTILITY("!!! STUB !!!"); } void RtlUnwind_x() { - printf("!!! STUB !!! RtlUnwind\n"); + LOG_UTILITY("!!! STUB !!!"); } void RtlCaptureContext_x() { - printf("!!! STUB !!! RtlCaptureContext\n"); + LOG_UTILITY("!!! STUB !!!"); } void NtQueryFullAttributesFile() { - printf("!!! STUB !!! NtQueryFullAttributesFile\n"); + LOG_UTILITY("!!! STUB !!!"); } NTSTATUS RtlMultiByteToUnicodeN(PWCH UnicodeString, ULONG MaxBytesInUnicodeString, XLPDWORD BytesInUnicodeString, const CHAR* MultiByteString, ULONG BytesInMultiByteString) { // i am lazy const auto n = MultiByteToWideChar(CP_UTF8, 0, MultiByteString, BytesInMultiByteString, UnicodeString, MaxBytesInUnicodeString); + if (BytesInUnicodeString) - { *BytesInUnicodeString = n * sizeof(wchar_t); - } if (n) { for (size_t i = 0; i < n; i++) - { UnicodeString[i] = std::byteswap(UnicodeString[i]); - } } return STATUS_SUCCESS; @@ -1181,24 +1135,23 @@ NTSTATUS RtlMultiByteToUnicodeN(PWCH UnicodeString, ULONG MaxBytesInUnicodeStrin void DbgBreakPoint() { - printf("!!! STUB !!! DbgBreakPoint\n"); + LOG_UTILITY("!!! STUB !!!"); } void MmQueryAllocationSize() { - printf("!!! STUB !!! MmQueryAllocationSize\n"); + LOG_UTILITY("!!! STUB !!!"); } uint32_t NtClearEvent(uint32_t handle, uint32_t* previousState) { - //printf("!!! STUB !!! NtClearEvent\n"); return ResetEvent((HANDLE)handle) ? 0 : 0xFFFFFFFF; } uint32_t NtResumeThread(uint32_t hThread, uint32_t* suspendCount) { - //printf("NtResumeThread(): %x %x\n", hThread, suspendCount); DWORD count = ResumeThread((HANDLE)hThread); + if (count == (DWORD)-1) return E_FAIL; @@ -1210,7 +1163,6 @@ uint32_t NtResumeThread(uint32_t hThread, uint32_t* suspendCount) uint32_t NtSetEvent(uint32_t handle, uint32_t* previousState) { - //printf("!!! STUB !!! NtSetEvent\n"); return SetEvent((HANDLE)handle) ? 0 : 0xFFFFFFFF; } @@ -1222,49 +1174,46 @@ NTSTATUS NtCreateSemaphore(XLPDWORD Handle, XOBJECT_ATTRIBUTES* ObjectAttributes NTSTATUS NtReleaseSemaphore(uint32_t Handle, DWORD ReleaseCount, LONG* PreviousCount) { - //printf("!!! STUB !!! NtReleaseSemaphore\n"); ReleaseSemaphore((HANDLE)Handle, ReleaseCount, PreviousCount); + if (PreviousCount) - { *PreviousCount = std::byteswap(*PreviousCount); - } return STATUS_SUCCESS; } void NtWaitForMultipleObjectsEx() { - printf("!!! STUB !!! NtWaitForMultipleObjectsEx\n"); + LOG_UTILITY("!!! STUB !!!"); } void RtlCompareStringN() { - printf("!!! STUB !!! RtlCompareStringN\n"); + LOG_UTILITY("!!! STUB !!!"); } void _snprintf_x() { - printf("!!! STUB !!! _snprintf\n"); + LOG_UTILITY("!!! STUB !!!"); } void StfsControlDevice() { - printf("!!! STUB !!! StfsControlDevice\n"); + LOG_UTILITY("!!! STUB !!!"); } void StfsCreateDevice() { - printf("!!! STUB !!! StfsCreateDevice\n"); + LOG_UTILITY("!!! STUB !!!"); } void NtFlushBuffersFile() { - printf("!!! STUB !!! NtFlushBuffersFile\n"); + LOG_UTILITY("!!! STUB !!!"); } void KeQuerySystemTime(uint64_t* time) { - //printf("!!! STUB !!! KeQuerySystemTime\n"); FILETIME t; GetSystemTimeAsFileTime(&t); *time = std::byteswap((uint64_t(t.dwHighDateTime) << 32) | t.dwLowDateTime); @@ -1272,35 +1221,38 @@ void KeQuerySystemTime(uint64_t* time) void RtlTimeToTimeFields() { - printf("!!! STUB !!! RtlTimeToTimeFields\n"); + LOG_UTILITY("!!! STUB !!!"); } void RtlFreeAnsiString() { - printf("!!! STUB !!! RtlFreeAnsiString\n"); + LOG_UTILITY("!!! STUB !!!"); } void RtlUnicodeStringToAnsiString() { - printf("!!! STUB !!! RtlUnicodeStringToAnsiString\n"); + LOG_UTILITY("!!! STUB !!!"); } void RtlInitUnicodeString() { - printf("!!! STUB !!! RtlInitUnicodeString\n"); + LOG_UTILITY("!!! STUB !!!"); } void ExTerminateThread() { - printf("!!! STUB !!! ExTerminateThread\n"); + LOG_UTILITY("!!! STUB !!!"); } uint32_t ExCreateThread(XLPDWORD handle, uint32_t stackSize, XLPDWORD threadId, uint32_t xApiThreadStartup, uint32_t startAddress, uint32_t startContext, uint32_t creationFlags) { - printf("ExCreateThread(): %p %x %p %x %x %x %x\n", handle, stackSize, threadId, xApiThreadStartup, startAddress, startContext, creationFlags); + LOGF_UTILITY("0x{:X}, 0x{:X}, 0x{:X}, 0x{:X}, 0x{:X}, 0x{:X}, 0x{:X}", + (intptr_t)handle, stackSize, (intptr_t)threadId, xApiThreadStartup, startAddress, startContext, creationFlags); + DWORD hostThreadId; *handle = (uint32_t)GuestThread::Start(startAddress, startContext, creationFlags, &hostThreadId); + if (threadId != nullptr) *threadId = hostThreadId; @@ -1309,77 +1261,77 @@ uint32_t ExCreateThread(XLPDWORD handle, uint32_t stackSize, XLPDWORD threadId, void IoInvalidDeviceRequest() { - printf("!!! STUB !!! IoInvalidDeviceRequest\n"); + LOG_UTILITY("!!! STUB !!!"); } void ObReferenceObject() { - printf("!!! STUB !!! ObReferenceObject\n"); + LOG_UTILITY("!!! STUB !!!"); } void IoCreateDevice() { - printf("!!! STUB !!! IoCreateDevice\n"); + LOG_UTILITY("!!! STUB !!!"); } void IoDeleteDevice() { - printf("!!! STUB !!! IoDeleteDevice\n"); + LOG_UTILITY("!!! STUB !!!"); } void ExAllocatePoolTypeWithTag() { - printf("!!! STUB !!! ExAllocatePoolTypeWithTag\n"); + LOG_UTILITY("!!! STUB !!!"); } void RtlTimeFieldsToTime() { - printf("!!! STUB !!! RtlTimeFieldsToTime\n"); + LOG_UTILITY("!!! STUB !!!"); } void IoCompleteRequest() { - printf("!!! STUB !!! IoCompleteRequest\n"); + LOG_UTILITY("!!! STUB !!!"); } void RtlUpcaseUnicodeChar() { - printf("!!! STUB !!! RtlUpcaseUnicodeChar\n"); + LOG_UTILITY("!!! STUB !!!"); } void ObIsTitleObject() { - printf("!!! STUB !!! ObIsTitleObject\n"); + LOG_UTILITY("!!! STUB !!!"); } void IoCheckShareAccess() { - printf("!!! STUB !!! IoCheckShareAccess\n"); + LOG_UTILITY("!!! STUB !!!"); } void IoSetShareAccess() { - printf("!!! STUB !!! IoSetShareAccess\n"); + LOG_UTILITY("!!! STUB !!!"); } void IoRemoveShareAccess() { - printf("!!! STUB !!! IoRemoveShareAccess\n"); + LOG_UTILITY("!!! STUB !!!"); } void NetDll_XNetStartup() { - printf("!!! STUB !!! NetDll_XNetStartup\n"); + LOG_UTILITY("!!! STUB !!!"); } void NetDll_XNetGetTitleXnAddr() { - printf("!!! STUB !!! NetDll_XNetGetTitleXnAddr\n"); + LOG_UTILITY("!!! STUB !!!"); } DWORD KeWaitForMultipleObjects(DWORD Count, xpointer* Objects, DWORD WaitType, DWORD WaitReason, DWORD WaitMode, DWORD Alertable, XLPQWORD Timeout) { - // TODO: Create actual objects by type + // TODO: create actual objects by type. const uint64_t timeout = GuestTimeoutToMilliseconds(Timeout); thread_local std::vector events; @@ -1396,80 +1348,73 @@ DWORD KeWaitForMultipleObjects(DWORD Count, xpointer* Object uint32_t KeRaiseIrqlToDpcLevel() { - //printf("!!! STUB !!! KeRaiseIrqlToDpcLevel\n"); return 0; } -void KfLowerIrql() -{ - //printf("!!! STUB !!! KfLowerIrql\n"); -} +void KfLowerIrql() { } uint32_t KeReleaseSemaphore(XKSEMAPHORE* semaphore, uint32_t increment, uint32_t adjustment, uint32_t wait) { - //printf("!!! STUB !!! KeReleaseSemaphore\n"); auto* object = ObQueryObject(semaphore->Header); return ReleaseSemaphore(object->handle, adjustment, nullptr) ? 0 : 0xFFFFFFFF; } void XAudioGetVoiceCategoryVolume() { - printf("!!! STUB !!! XAudioGetVoiceCategoryVolume\n"); + LOG_UTILITY("!!! STUB !!!"); } DWORD XAudioGetVoiceCategoryVolumeChangeMask(DWORD Driver, XLPDWORD Mask) { - // printf("Invoking method XAudioGetVoiceCategoryVolumeChangeMask\n"); *Mask = 0; - return 0; } uint32_t KeResumeThread(uint32_t object) { - printf("KeResumeThread(): %x\n", object); + LOGF_UTILITY("0x{:x}", object); return ResumeThread((HANDLE)object); } void KeInitializeSemaphore(XKSEMAPHORE* semaphore, uint32_t count, uint32_t limit) { - //printf("!!! STUB !!! KeInitializeSemaphore\n"); semaphore->Header.Type = 5; semaphore->Header.SignalState = count; semaphore->Limit = limit; + auto* object = ObQueryObject(semaphore->Header); } void XMAReleaseContext() { - printf("!!! STUB !!! XMAReleaseContext\n"); + LOG_UTILITY("!!! STUB !!!"); } void XMACreateContext() { - printf("!!! STUB !!! XMACreateContext\n"); + LOG_UTILITY("!!! STUB !!!"); } -//uint32_t XAudioRegisterRenderDriverClient(XLPDWORD callback, XLPDWORD driver) -//{ -// //printf("XAudioRegisterRenderDriverClient(): %x %x\n"); -// -// *driver = apu::RegisterClient(callback[0], callback[1]); -// return 0; -//} -// -//void XAudioUnregisterRenderDriverClient() -//{ -// printf("!!! STUB !!! XAudioUnregisterRenderDriverClient\n"); -//} -// -//uint32_t XAudioSubmitRenderDriverFrame(uint32_t driver, void* samples) -//{ -// // printf("!!! STUB !!! XAudioSubmitRenderDriverFrame\n"); -// apu::SubmitFrames(samples); -// -// return 0; -//} +// uint32_t XAudioRegisterRenderDriverClient(XLPDWORD callback, XLPDWORD driver) +// { +// //printf("XAudioRegisterRenderDriverClient(): %x %x\n"); +// +// *driver = apu::RegisterClient(callback[0], callback[1]); +// return 0; +// } + +// void XAudioUnregisterRenderDriverClient() +// { +// printf("!!! STUB !!! XAudioUnregisterRenderDriverClient\n"); +// } + +// uint32_t XAudioSubmitRenderDriverFrame(uint32_t driver, void* samples) +// { +// // printf("!!! STUB !!! XAudioSubmitRenderDriverFrame\n"); +// apu::SubmitFrames(samples); +// +// return 0; +// } GUEST_FUNCTION_HOOK(__imp__XGetVideoMode, VdQueryVideoMode); // XGetVideoMode GUEST_FUNCTION_HOOK(__imp__XNotifyGetNext, XNotifyGetNext); diff --git a/UnleashedRecomp/kernel/io/file_system.cpp b/UnleashedRecomp/kernel/io/file_system.cpp index 7d5ded7..16c5ed4 100644 --- a/UnleashedRecomp/kernel/io/file_system.cpp +++ b/UnleashedRecomp/kernel/io/file_system.cpp @@ -4,6 +4,7 @@ #include #include #include +#include bool FindHandleCloser(void* handle) { @@ -11,13 +12,15 @@ bool FindHandleCloser(void* handle) return false; } -SWA_API uint32_t XCreateFileA( +SWA_API uint32_t XCreateFileA +( LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, - DWORD dwFlagsAndAttributes) + DWORD dwFlagsAndAttributes +) { const auto handle = (uint32_t)CreateFileA( FileSystem::TransformPath(lpFileName), @@ -29,49 +32,53 @@ SWA_API uint32_t XCreateFileA( nullptr); GuestThread::SetLastError(GetLastError()); - printf("CreateFileA(%s, %lx, %lx, %p, %lx, %lx): %x\n", lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, handle); + + LOGF_UTILITY("\"{}\", 0x{:X}, 0x{:X}, 0x{:X}, 0x{:X}, 0x{:X} -> 0x{:X}", + lpFileName, dwDesiredAccess, dwShareMode, (intptr_t)lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, handle); return handle; } -static DWORD XGetFileSizeA( - uint32_t hFile, - LPDWORD lpFileSizeHigh) +static DWORD XGetFileSizeA(uint32_t hFile, LPDWORD lpFileSizeHigh) { DWORD fileSize = GetFileSize((HANDLE)hFile, lpFileSizeHigh); + if (lpFileSizeHigh != nullptr) *lpFileSizeHigh = std::byteswap(*lpFileSizeHigh); return fileSize; } -BOOL XGetFileSizeExA( - uint32_t hFile, - PLARGE_INTEGER lpFileSize) +BOOL XGetFileSizeExA(uint32_t hFile, PLARGE_INTEGER lpFileSize) { BOOL result = GetFileSizeEx((HANDLE)hFile, lpFileSize); + if (result) lpFileSize->QuadPart = std::byteswap(lpFileSize->QuadPart); return result; } -BOOL XReadFile( +BOOL XReadFile +( uint32_t hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, XLPDWORD lpNumberOfBytesRead, - XOVERLAPPED* lpOverlapped) + XOVERLAPPED* lpOverlapped +) { if (lpOverlapped != nullptr) { LONG distanceToMoveHigh = lpOverlapped->OffsetHigh; + if (SetFilePointer((HANDLE)hFile, lpOverlapped->Offset, &distanceToMoveHigh, FILE_BEGIN) == INVALID_SET_FILE_POINTER) return FALSE; } DWORD numberOfBytesRead; BOOL result = ReadFile((HANDLE)hFile, lpBuffer, nNumberOfBytesToRead, &numberOfBytesRead, nullptr); + if (result) { if (lpOverlapped != nullptr) @@ -88,52 +95,44 @@ BOOL XReadFile( } } - //printf("ReadFile(): %x %x %x %x %x %x\n", hFile, lpBuffer, nNumberOfBytesToRead, lpNumberOfBytesRead, lpOverlapped, result); + // printf("ReadFile(): %x %x %x %x %x %x\n", hFile, lpBuffer, nNumberOfBytesToRead, lpNumberOfBytesRead, lpOverlapped, result); return result; } -DWORD XSetFilePointer( - uint32_t hFile, - LONG lDistanceToMove, - PLONG lpDistanceToMoveHigh, - DWORD dwMoveMethod) +DWORD XSetFilePointer(uint32_t hFile, LONG lDistanceToMove, PLONG lpDistanceToMoveHigh, DWORD dwMoveMethod) { LONG distanceToMoveHigh = lpDistanceToMoveHigh ? std::byteswap(*lpDistanceToMoveHigh) : 0; DWORD result = SetFilePointer((HANDLE)hFile, lDistanceToMove, lpDistanceToMoveHigh ? &distanceToMoveHigh : nullptr, dwMoveMethod); + if (lpDistanceToMoveHigh != nullptr) *lpDistanceToMoveHigh = std::byteswap(distanceToMoveHigh); return result; } -BOOL XSetFilePointerEx( - uint32_t hFile, - LONG lDistanceToMove, - PLARGE_INTEGER lpNewFilePointer, - DWORD dwMoveMethod) +BOOL XSetFilePointerEx(uint32_t hFile, LONG lDistanceToMove, PLARGE_INTEGER lpNewFilePointer, DWORD dwMoveMethod) { LARGE_INTEGER distanceToMove; distanceToMove.QuadPart = lDistanceToMove; DWORD result = SetFilePointerEx((HANDLE)hFile, distanceToMove, lpNewFilePointer, dwMoveMethod); + if (lpNewFilePointer != nullptr) lpNewFilePointer->QuadPart = std::byteswap(lpNewFilePointer->QuadPart); return result; } -uint32_t XFindFirstFileA( - LPCSTR lpFileName, - LPWIN32_FIND_DATAA lpFindFileData) +uint32_t XFindFirstFileA(LPCSTR lpFileName, LPWIN32_FIND_DATAA lpFindFileData) { auto& data = *lpFindFileData; const auto handle = FindFirstFileA(FileSystem::TransformPath(lpFileName), &data); + GuestThread::SetLastError(GetLastError()); + if (handle == INVALID_HANDLE_VALUE) - { return 0xFFFFFFFF; - } ByteSwap(data.dwFileAttributes); ByteSwap(*(uint64_t*)&data.ftCreationTime); @@ -159,19 +158,16 @@ uint32_t XFindNextFileA(uint32_t Handle, LPWIN32_FIND_DATAA lpFindFileData) return result; } -BOOL XReadFileEx( - uint32_t hFile, - LPVOID lpBuffer, - DWORD nNumberOfBytesToRead, - XOVERLAPPED* lpOverlapped, - uint32_t lpCompletionRoutine) +BOOL XReadFileEx(uint32_t hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, XOVERLAPPED* lpOverlapped, uint32_t lpCompletionRoutine) { LONG distanceToMoveHigh = lpOverlapped->OffsetHigh; + if (SetFilePointer((HANDLE)hFile, lpOverlapped->Offset, &distanceToMoveHigh, FILE_BEGIN) == INVALID_SET_FILE_POINTER) return FALSE; DWORD numberOfBytesRead; BOOL result = ReadFile((HANDLE)hFile, lpBuffer, nNumberOfBytesToRead, &numberOfBytesRead, nullptr); + if (result) { lpOverlapped->Internal = 0; @@ -181,7 +177,7 @@ BOOL XReadFileEx( SetEvent((HANDLE)lpOverlapped->hEvent.get()); } - //printf("ReadFileEx(): %x %x %x %x %x %x\n", hFile, lpBuffer, nNumberOfBytesToRead, lpOverlapped, lpCompletionRoutine, result); + // printf("ReadFileEx(): %x %x %x %x %x %x\n", hFile, lpBuffer, nNumberOfBytesToRead, lpOverlapped, lpCompletionRoutine, result); return result; } @@ -191,16 +187,12 @@ DWORD XGetFileAttributesA(LPCSTR lpFileName) return GetFileAttributesA(FileSystem::TransformPath(lpFileName)); } -BOOL XWriteFile( - uint32_t hFile, - LPCVOID lpBuffer, - DWORD nNumberOfBytesToWrite, - LPDWORD lpNumberOfBytesWritten, - LPOVERLAPPED lpOverlapped) +BOOL XWriteFile(uint32_t hFile, LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite, LPDWORD lpNumberOfBytesWritten, LPOVERLAPPED lpOverlapped) { assert(lpOverlapped == nullptr); BOOL result = WriteFile((HANDLE)hFile, lpBuffer, nNumberOfBytesToWrite, lpNumberOfBytesWritten, nullptr); + if (result && lpNumberOfBytesWritten != nullptr) ByteSwap(*lpNumberOfBytesWritten); @@ -211,6 +203,7 @@ const char* FileSystem::TransformPath(const char* path) { thread_local char builtPath[2048]{}; const char* relativePath = strstr(path, ":\\"); + if (relativePath != nullptr) { // rooted folder, handle direction diff --git a/UnleashedRecomp/kernel/xam.cpp b/UnleashedRecomp/kernel/xam.cpp index 70245e8..82a7324 100644 --- a/UnleashedRecomp/kernel/xam.cpp +++ b/UnleashedRecomp/kernel/xam.cpp @@ -20,10 +20,9 @@ xxHashMap gRootMap; std::string_view XamGetRootPath(const std::string_view& root) { const auto result = gRootMap.find(StringHash(root)); + if (result == gRootMap.end()) - { return ""; - } return result->second; } @@ -46,6 +45,7 @@ XamListener::~XamListener() XCONTENT_DATA XamMakeContent(DWORD type, const std::string_view& name) { XCONTENT_DATA data{ 1, type }; + strncpy(data.szFileName, name.data(), sizeof(data.szFileName)); return data; @@ -54,12 +54,14 @@ XCONTENT_DATA XamMakeContent(DWORD type, const std::string_view& name) void XamRegisterContent(const XCONTENT_DATA& data, const std::string_view& root) { const auto idx = data.dwContentType - 1; + gContentRegistry[idx].emplace(StringHash(data.szFileName), XHOSTCONTENT_DATA{ data }).first->second.szRoot = root; } void XamRegisterContent(DWORD type, const std::string_view name, const std::string_view& root) { XCONTENT_DATA data{ 1, type, {}, "" }; + strncpy(data.szFileName, name.data(), sizeof(data.szFileName)); XamRegisterContent(data, root); @@ -69,6 +71,7 @@ SWA_API DWORD XamNotifyCreateListener(uint64_t qwAreas) { int handle; auto* listener = ObCreateObject(handle); + listener->areas = qwAreas; return GUEST_HANDLE(handle); @@ -79,9 +82,7 @@ SWA_API void XamNotifyEnqueueEvent(DWORD dwId, DWORD dwParam) for (const auto& listener : gListeners) { if (((1 << MSG_AREA(dwId)) & listener->areas) == 0) - { continue; - } listener->notifications.emplace_back(dwId, dwParam); } @@ -90,6 +91,7 @@ SWA_API void XamNotifyEnqueueEvent(DWORD dwId, DWORD dwParam) SWA_API bool XNotifyGetNext(DWORD hNotification, DWORD dwMsgFilter, XDWORD* pdwId, XDWORD* pParam) { auto& listener = *ObTryQueryObject(HOST_HANDLE(hNotification)); + if (dwMsgFilter) { for (size_t i = 0; i < listener.notifications.size(); i++) @@ -97,16 +99,13 @@ SWA_API bool XNotifyGetNext(DWORD hNotification, DWORD dwMsgFilter, XDWORD* pdwI if (std::get<0>(listener.notifications[i]) == dwMsgFilter) { if (pdwId) - { *pdwId = std::get<0>(listener.notifications[i]); - } if (pParam) - { *pParam = std::get<1>(listener.notifications[i]); - } listener.notifications.erase(listener.notifications.begin() + i); + return true; } } @@ -114,53 +113,42 @@ SWA_API bool XNotifyGetNext(DWORD hNotification, DWORD dwMsgFilter, XDWORD* pdwI else { if (listener.notifications.empty()) - { return false; - } if (pdwId) - { *pdwId = std::get<0>(listener.notifications[0]); - } if (pParam) - { *pParam = std::get<1>(listener.notifications[0]); - } listener.notifications.erase(listener.notifications.begin()); + return true; } + return false; } SWA_API uint32_t XamShowMessageBoxUI(DWORD dwUserIndex, XWORD* wszTitle, XWORD* wszText, DWORD cButtons, xpointer* pwszButtons, DWORD dwFocusButton, DWORD dwFlags, XLPDWORD pResult, XXOVERLAPPED* pOverlapped) { - // printf("!!! STUB !!! XamShowMessageBoxUI\n"); - std::vector texts{}; std::vector buttons{}; + texts.emplace_back(reinterpret_cast(wszTitle)); texts.emplace_back(reinterpret_cast(wszText)); for (size_t i = 0; i < cButtons; i++) - { texts.emplace_back(reinterpret_cast(pwszButtons[i].get())); - } for (auto& text : texts) { for (size_t i = 0; i < text.size(); i++) - { ByteSwap(text[i]); - } } for (size_t i = 0; i < cButtons; i++) - { buttons.emplace_back(i, texts[2 + i].c_str()); - } XamNotifyEnqueueEvent(9, 1); @@ -176,6 +164,7 @@ SWA_API uint32_t XamShowMessageBoxUI(DWORD dwUserIndex, XWORD* wszTitle, XWORD* TaskDialogIndirect(&config, &button, nullptr, nullptr); *pResult = button; + if (pOverlapped) { pOverlapped->dwCompletionContext = GetCurrentThreadId(); @@ -202,11 +191,10 @@ SWA_API uint32_t XamContentCreateEnumerator(DWORD dwUserIndex, DWORD DeviceID, D const int handle = ObInsertObject(new XamEnumerator(cItem, sizeof(_XCONTENT_DATA), values.begin(), values.end())); if (pcbBuffer) - { *pcbBuffer = sizeof(_XCONTENT_DATA) * cItem; - } *phEnum = GUEST_HANDLE(handle); + return 0; } @@ -214,15 +202,13 @@ SWA_API uint32_t XamEnumerate(uint32_t hEnum, DWORD dwFlags, PVOID pvBuffer, DWO { auto* enumerator = ObTryQueryObject(HOST_HANDLE(hEnum)); const auto count = enumerator->Next(pvBuffer); + if (count == -1) - { return ERROR_NO_MORE_FILES; - } if (pcItemsReturned) - { *pcItemsReturned = count; - } + return ERROR_SUCCESS; } @@ -230,15 +216,14 @@ SWA_API uint32_t XamContentCreateEx(DWORD dwUserIndex, LPCSTR szRootName, const DWORD dwContentFlags, XLPDWORD pdwDisposition, XLPDWORD pdwLicenseMask, DWORD dwFileCacheSize, uint64_t uliContentSize, PXXOVERLAPPED pOverlapped) { - // printf("!!! STUB !!! XamContentCreateEx\n"); - const auto& registry = gContentRegistry[pContentData->dwContentType - 1]; const auto exists = registry.contains(StringHash(pContentData->szFileName)); const auto mode = dwContentFlags & 0xF; if (mode == CREATE_ALWAYS) { - if (pdwDisposition) *pdwDisposition = XCONTENT_NEW; + if (pdwDisposition) + *pdwDisposition = XCONTENT_NEW; if (!exists) { @@ -268,18 +253,23 @@ SWA_API uint32_t XamContentCreateEx(DWORD dwUserIndex, LPCSTR szRootName, const return ERROR_SUCCESS; } + if (mode == OPEN_EXISTING) { if (exists) { - if (pdwDisposition) *pdwDisposition = XCONTENT_EXISTING; + if (pdwDisposition) + *pdwDisposition = XCONTENT_EXISTING; XamRootCreate(szRootName, registry.find(StringHash(pContentData->szFileName))->second.szRoot); + return ERROR_SUCCESS; } else { - if (pdwDisposition) *pdwDisposition = XCONTENT_NEW; + if (pdwDisposition) + *pdwDisposition = XCONTENT_NEW; + return ERROR_PATH_NOT_FOUND; } } @@ -289,15 +279,12 @@ SWA_API uint32_t XamContentCreateEx(DWORD dwUserIndex, LPCSTR szRootName, const SWA_API uint32_t XamContentClose(LPCSTR szRootName, XXOVERLAPPED* pOverlapped) { - // printf("!!! STUB !!! XamContentClose %s\n", szRootName); gRootMap.erase(StringHash(szRootName)); return 0; } SWA_API uint32_t XamContentGetDeviceData(DWORD DeviceID, XDEVICE_DATA* pDeviceData) { - // printf("!!! STUB !!! XamContentGetDeviceData\n"); - pDeviceData->DeviceID = DeviceID; pDeviceData->DeviceType = XCONTENTDEVICETYPE_HDD; pDeviceData->ulDeviceBytes = 0x10000000; @@ -314,8 +301,8 @@ SWA_API uint32_t XamContentGetDeviceData(DWORD DeviceID, XDEVICE_DATA* pDeviceDa SWA_API uint32_t XamInputGetCapabilities(uint32_t unk, uint32_t userIndex, uint32_t flags, XAMINPUT_CAPABILITIES* caps) { - //printf("!!! STUB !!! XamInputGetCapabilities\n"); uint32_t result = hid::GetCapabilities(userIndex, caps); + if (result == ERROR_SUCCESS) { ByteSwap(caps->Flags); @@ -327,13 +314,12 @@ SWA_API uint32_t XamInputGetCapabilities(uint32_t unk, uint32_t userIndex, uint3 ByteSwap(caps->Vibration.wLeftMotorSpeed); ByteSwap(caps->Vibration.wRightMotorSpeed); } + return result; } SWA_API uint32_t XamInputGetState(uint32_t userIndex, uint32_t flags, XAMINPUT_STATE* state) { - //printf("!!! STUB !!! XamInputGetState\n"); - uint32_t result = hid::GetState(userIndex, state); if (result == ERROR_SUCCESS) @@ -405,8 +391,8 @@ SWA_API uint32_t XamInputGetState(uint32_t userIndex, uint32_t flags, XAMINPUT_S SWA_API uint32_t XamInputSetState(uint32_t userIndex, uint32_t flags, XAMINPUT_VIBRATION* vibration) { - //printf("!!! STUB !!! XamInputSetState\n"); ByteSwap(vibration->wLeftMotorSpeed); ByteSwap(vibration->wRightMotorSpeed); + return hid::SetState(userIndex, vibration); } diff --git a/UnleashedRecomp/kernel/xdm.cpp b/UnleashedRecomp/kernel/xdm.cpp index 15cf442..10a99b1 100644 --- a/UnleashedRecomp/kernel/xdm.cpp +++ b/UnleashedRecomp/kernel/xdm.cpp @@ -1,6 +1,6 @@ #include #include "xdm.h" -#include "FreeList.h" +#include "freelist.h" FreeList, TypeDestructor_t>> gKernelObjects; Mutex gKernelLock; @@ -10,9 +10,7 @@ void* ObQueryObject(size_t handle) std::lock_guard guard{ gKernelLock }; if (handle >= gKernelObjects.items.size()) - { return nullptr; - } return std::get<0>(gKernelObjects[handle]).get(); } @@ -36,6 +34,7 @@ void ObCloseHandle(uint32_t handle) std::lock_guard guard{ gKernelLock }; auto& obj = gKernelObjects[handle]; + if (std::get<1>(obj)(std::get<0>(obj).get())) { std::get<0>(obj).reset(); @@ -46,4 +45,4 @@ void ObCloseHandle(uint32_t handle) } gKernelObjects.Free(handle); -} \ No newline at end of file +} diff --git a/UnleashedRecomp/os/logger.cpp b/UnleashedRecomp/os/logger.cpp new file mode 100644 index 0000000..07a1778 --- /dev/null +++ b/UnleashedRecomp/os/logger.cpp @@ -0,0 +1,7 @@ +#include +#include + +void os::logger::Log(const std::string& str, detail::ELogType type, const char* func) +{ + detail::Log(str, type, func); +} diff --git a/UnleashedRecomp/os/logger.h b/UnleashedRecomp/os/logger.h new file mode 100644 index 0000000..9683185 --- /dev/null +++ b/UnleashedRecomp/os/logger.h @@ -0,0 +1,35 @@ +#pragma once + +#include + +#define LOG_IMPL(type, func, str) os::logger::Log(str, os::logger::detail::ELogType::type, func) +#define LOGF_IMPL(type, func, str, ...) os::logger::Log(std::format(str, __VA_ARGS__), os::logger::detail::ELogType::type, func) + +// Function-specific logging. + +#define LOG(str) LOG_IMPL(None, __func__, str) +#define LOG_UTILITY(str) LOG_IMPL(Utility, __func__, str) +#define LOG_WARNING(str) LOG_IMPL(Warning, __func__, str) +#define LOG_ERROR(str) LOG_IMPL(Error, __func__, str) + +#define LOGF(str, ...) LOGF_IMPL(None, __func__, str, __VA_ARGS__) +#define LOGF_UTILITY(str, ...) LOGF_IMPL(Utility, __func__, str, __VA_ARGS__) +#define LOGF_WARNING(str, ...) LOGF_IMPL(Warning, __func__, str, __VA_ARGS__) +#define LOGF_ERROR(str, ...) LOGF_IMPL(Error, __func__, str, __VA_ARGS__) + +// Non-function-specific logging. + +#define LOGN(str) LOG_IMPL(None, "*", str) +#define LOGN_UTILITY(str) LOG_IMPL(Utility, "*", str) +#define LOGN_WARNING(str) LOG_IMPL(Warning, "*", str) +#define LOGN_ERROR(str) LOG_IMPL(Error, "*", str) + +#define LOGFN(str, ...) LOGF_IMPL(None, "*", str, __VA_ARGS__) +#define LOGFN_UTILITY(str, ...) LOGF_IMPL(Utility, "*", str, __VA_ARGS__) +#define LOGFN_WARNING(str, ...) LOGF_IMPL(Warning, "*", str, __VA_ARGS__) +#define LOGFN_ERROR(str, ...) LOGF_IMPL(Error, "*", str, __VA_ARGS__) + +namespace os::logger +{ + void Log(const std::string& str, detail::ELogType type = detail::ELogType::None, const char* func = nullptr); +} diff --git a/UnleashedRecomp/os/logger_detail.h b/UnleashedRecomp/os/logger_detail.h new file mode 100644 index 0000000..dde36f5 --- /dev/null +++ b/UnleashedRecomp/os/logger_detail.h @@ -0,0 +1,16 @@ +#pragma once + +#include + +namespace os::logger::detail +{ + enum class ELogType + { + None, + Utility, + Warning, + Error + }; + + void Log(const std::string& str, ELogType type = ELogType::None, const char* func = nullptr); +} diff --git a/UnleashedRecomp/os/win32/logger_win32.cpp b/UnleashedRecomp/os/win32/logger_win32.cpp new file mode 100644 index 0000000..f606da7 --- /dev/null +++ b/UnleashedRecomp/os/win32/logger_win32.cpp @@ -0,0 +1,47 @@ +#include + +#define FOREGROUND_WHITE (FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE) +#define FOREGROUND_YELLOW (FOREGROUND_RED | FOREGROUND_GREEN) + +HANDLE g_hStandardOutput = nullptr; + +void os::logger::detail::Log(const std::string& str, detail::ELogType type, const char* func) +{ +#if !_DEBUG + if (type == ELogType::Utility) + return; +#endif + + if (!g_hStandardOutput) + g_hStandardOutput = GetStdHandle(STD_OUTPUT_HANDLE); + + switch (type) + { + case ELogType::Utility: + SetConsoleTextAttribute(g_hStandardOutput, FOREGROUND_GREEN | FOREGROUND_INTENSITY); + break; + + case ELogType::Warning: + SetConsoleTextAttribute(g_hStandardOutput, FOREGROUND_YELLOW | FOREGROUND_INTENSITY); + break; + + case ELogType::Error: + SetConsoleTextAttribute(g_hStandardOutput, FOREGROUND_RED | FOREGROUND_INTENSITY); + break; + + default: + SetConsoleTextAttribute(g_hStandardOutput, FOREGROUND_WHITE); + break; + } + + if (func) + { + printf("[%s] %s\n", func, str.c_str()); + } + else + { + printf("%s\n", str.c_str()); + } + + SetConsoleTextAttribute(g_hStandardOutput, FOREGROUND_WHITE); +} diff --git a/UnleashedRecomp/os/win32/media_win32.cpp b/UnleashedRecomp/os/win32/media_win32.cpp index 0b797a6..c6e77a5 100644 --- a/UnleashedRecomp/os/win32/media_win32.cpp +++ b/UnleashedRecomp/os/win32/media_win32.cpp @@ -1,4 +1,5 @@ #include +#include #include #include @@ -20,7 +21,7 @@ static GlobalSystemMediaTransportControlsSessionManager GetSessionManager() } catch (...) { - printf("[*] Failed to retrieve GSMTC session manager: 0x%08X\n", to_hresult().value); + LOGF_ERROR("Failed to retrieve GSMTC session manager: 0x{:X}", to_hresult().value); return nullptr; } } @@ -38,7 +39,7 @@ static GlobalSystemMediaTransportControlsSession GetCurrentSession() } catch (...) { - printf("[*] Failed to retrieve current GSMTC session: 0x%08X\n", to_hresult().value); + LOGF_ERROR("Failed to retrieve current GSMTC session: 0x{:X}", to_hresult().value); return nullptr; } } @@ -56,7 +57,7 @@ static GlobalSystemMediaTransportControlsSessionPlaybackInfo GetPlaybackInfo() } catch (...) { - printf("[*] Failed to retrieve GSMTC playback info: 0x%08X\n", to_hresult().value); + LOGF_ERROR("Failed to retrieve GSMTC playback info: 0x{:X}", to_hresult().value); return nullptr; } } @@ -74,7 +75,7 @@ bool os::media::detail::IsExternalMediaPlaying() } catch (...) { - printf("[*] Failed to retrieve GSMTC playback status: 0x%08X\n", to_hresult().value); + LOGF_ERROR("Failed to retrieve GSMTC playback status: 0x{:X}", to_hresult().value); return false; } } diff --git a/UnleashedRecomp/patches/player_patches.cpp b/UnleashedRecomp/patches/player_patches.cpp index 6e129a7..c3699fd 100644 --- a/UnleashedRecomp/patches/player_patches.cpp +++ b/UnleashedRecomp/patches/player_patches.cpp @@ -3,6 +3,7 @@ #include #include #include +#include uint32_t m_lastCheckpointScore = 0; float m_lastDarkGaiaEnergy = 0.0f; @@ -25,7 +26,7 @@ PPC_FUNC(sub_82624308) m_lastCheckpointScore = pGameDocument->m_pMember->m_Score; - printf("[*] Score: %d\n", m_lastCheckpointScore); + LOGFN("Score: {}", m_lastCheckpointScore); } /* Hook function that resets the score @@ -43,7 +44,7 @@ PPC_FUNC(sub_8245F048) if (!pGameDocument) return; - printf("[*] Score: %d\n", m_lastCheckpointScore); + LOGFN("Score: {}", m_lastCheckpointScore); pGameDocument->m_pMember->m_Score = m_lastCheckpointScore; } diff --git a/UnleashedRecomp/patches/resident_patches.cpp b/UnleashedRecomp/patches/resident_patches.cpp index 52f09a6..42efec6 100644 --- a/UnleashedRecomp/patches/resident_patches.cpp +++ b/UnleashedRecomp/patches/resident_patches.cpp @@ -2,6 +2,7 @@ #include #include #include +#include const char* m_pStageID; @@ -57,7 +58,7 @@ PPC_FUNC(sub_824E5170) { if (!m_isSavedAchievementData) { - printf("[*] Saving achievements...\n"); + LOGN("Saving achievements..."); AchievementData::Save(); diff --git a/UnleashedRecomp/patches/ui/frontend_listener.h b/UnleashedRecomp/patches/ui/frontend_listener.h index eb149dd..64cd9f8 100644 --- a/UnleashedRecomp/patches/ui/frontend_listener.h +++ b/UnleashedRecomp/patches/ui/frontend_listener.h @@ -1,8 +1,9 @@ #pragma once -#include "kernel/memory.h" -#include "ui/sdl_listener.h" -#include "ui/options_menu.h" +#include +#include +#include +#include class FrontendListener : public SDLEventListener { @@ -26,7 +27,7 @@ public: *ms_IsRenderHud = !*ms_IsRenderHud; - printf("[*] HUD %s\n", *ms_IsRenderHud ? "On" : "Off"); + LOGFN("HUD {}", *ms_IsRenderHud ? "ON" : "OFF"); m_isF8KeyDown = true; diff --git a/UnleashedRecomp/ui/window.h b/UnleashedRecomp/ui/window.h index 9ace629..96ec75c 100644 --- a/UnleashedRecomp/ui/window.h +++ b/UnleashedRecomp/ui/window.h @@ -2,6 +2,7 @@ #include #include +#include #include #include #include @@ -35,7 +36,7 @@ public: auto surface = SDL_LoadBMP_RW(rw, 1); if (!surface) - printf("Failed to load icon: %s\n", SDL_GetError()); + LOGF_ERROR("Failed to load icon: {}", SDL_GetError()); return surface; } @@ -190,7 +191,7 @@ public: if (displayCount <= 0) { - printf("Failed to validate window position: %s\n", SDL_GetError()); + LOGF_ERROR("Failed to validate window position: {}", SDL_GetError()); return false; } diff --git a/UnleashedRecomp/user/achievement_data.cpp b/UnleashedRecomp/user/achievement_data.cpp index be0dba4..00c1296 100644 --- a/UnleashedRecomp/user/achievement_data.cpp +++ b/UnleashedRecomp/user/achievement_data.cpp @@ -1,6 +1,7 @@ #include "achievement_data.h" #include #include +#include #define NUM_RECORDS sizeof(Data.Records) / sizeof(Record) @@ -112,7 +113,7 @@ void AchievementData::Load() if (!file) { - printf("[*] ERROR: failed to read achievement data.\n"); + LOGN_ERROR("Failed to read achievement data."); return; } @@ -120,7 +121,7 @@ void AchievementData::Load() if (!VerifySignature()) { - printf("[*] ERROR: invalid achievement data signature.\n"); + LOGN_ERROR("Invalid achievement data signature."); char sig[4] = ACH_SIGNATURE; @@ -138,7 +139,7 @@ void AchievementData::Load() if (!VerifyVersion()) { - printf("[*] ERROR: unsupported achievement data version.\n"); + LOGN_ERROR("Unsupported achievement data version."); Data.Version = ACH_VERSION; file.close(); return; @@ -150,7 +151,7 @@ void AchievementData::Load() // TODO: display error message to user before wiping data? if (!VerifyChecksum()) { - printf("[*] ERROR: achievement data checksum mismatch.\n"); + LOGN_ERROR("Achievement data checksum mismatch."); memset(&Data.Records, 0, sizeof(Data.Records)); } @@ -163,7 +164,7 @@ void AchievementData::Save() if (!file) { - printf("[*] ERROR: failed to write achievement data.\n"); + LOGN_ERROR("Failed to write achievement data."); return; } diff --git a/UnleashedRecomp/user/config.cpp b/UnleashedRecomp/user/config.cpp index 100097a..6113915 100644 --- a/UnleashedRecomp/user/config.cpp +++ b/UnleashedRecomp/user/config.cpp @@ -1,4 +1,5 @@ #include "config.h" +#include void Config::Load() { @@ -18,13 +19,13 @@ void Config::Load() { def->ReadValue(toml); #if _DEBUG - printf("%s (0x%p)\n", def->GetDefinition().c_str(), def->GetValue()); + LOGFN_UTILITY("{} (0x{:X})", def->GetDefinition().c_str(), (intptr_t)def->GetValue()); #endif } } catch (toml::parse_error& err) { - printf("[*] Failed to parse configuration: %s\n", err.what()); + LOGFN_ERROR("Failed to parse configuration: {}", err.what()); } } @@ -62,6 +63,6 @@ void Config::Save() } else { - printf("[*] Failed to write configuration.\n"); + LOGN_ERROR("Failed to write configuration."); } }