From cd09cf8dfd10c2d6c2f491d20ecc4e643d4d5759 Mon Sep 17 00:00:00 2001 From: RadWolfie Date: Wed, 13 Apr 2022 09:31:49 -0500 Subject: [PATCH 1/3] remove emu codebase from gui's side --- CMakeLists.txt | 46 +-- projects/cxbx/CMakeLists.txt | 19 -- src/common/EmuEEPROM.cpp | 11 +- src/common/FilePaths.cpp | 186 ++++++++++++ src/common/FilePaths.hpp | 146 +--------- src/common/ReservedMemory.h | 55 ---- src/common/Settings.cpp | 4 - src/common/Settings.hpp | 2 +- src/common/Timer.cpp | 1 - src/common/cxbxr.cpp | 135 +++++++++ src/common/cxbxr.hpp | 59 ++++ src/common/input/InputManager.cpp | 18 +- src/common/input/SdlJoystick.cpp | 1 - src/common/util/CxbxUtil.cpp | 1 - src/common/win32/EmuShared.cpp | 10 +- src/common/win32/IPCWindows.cpp | 5 +- src/common/win32/InlineFunc.cpp | 7 +- src/common/win32/Threads.cpp | 2 +- src/common/xbe/Xbe.cpp | 18 +- src/common/xbe/XbePrinter.cpp | 29 +- src/common/xbe/XbePrinter.h | 2 + src/core/common/imgui/ui.cpp | 4 +- src/core/hle/D3D8/Direct3D9/Direct3D9.cpp | 269 ++---------------- src/core/hle/D3D8/Direct3D9/Direct3D9.h | 19 -- src/core/hle/D3D8/Direct3D9/TextureStates.cpp | 4 +- src/core/hle/D3D8/Direct3D9/VertexShader.cpp | 1 + src/core/hle/D3D8/XbConvert.cpp | 227 ++++++++++++++- src/core/hle/D3D8/XbConvert.h | 36 ++- src/core/hle/D3D8/XbPixelShader.cpp | 5 +- src/core/hle/D3D8/XbVertexBuffer.cpp | 12 +- src/core/hle/D3D8/XbVertexShader.cpp | 6 +- .../hle/DSOUND/DirectSound/DirectSound.cpp | 12 +- .../DSOUND/DirectSound/DirectSoundBuffer.cpp | 6 +- .../DSOUND/DirectSound/DirectSoundInline.hpp | 14 +- .../DSOUND/DirectSound/DirectSoundStream.cpp | 4 +- src/core/hle/Intercept.cpp | 5 +- src/core/hle/XAPI/Xapi.cpp | 23 +- src/core/hle/XAPI/Xapi.h | 3 +- src/core/hle/XGRAPHIC/XGraphic.cpp | 10 +- src/core/kernel/exports/EmuKrnl.cpp | 2 +- src/core/kernel/exports/EmuKrnlEx.cpp | 2 +- src/core/kernel/exports/EmuKrnlHal.cpp | 6 +- src/core/kernel/exports/EmuKrnlIo.cpp | 2 +- src/core/kernel/exports/EmuKrnlKe.cpp | 4 +- src/core/kernel/exports/EmuKrnlMm.cpp | 2 +- src/core/kernel/exports/EmuKrnlNt.cpp | 6 +- src/core/kernel/exports/EmuKrnlOb.cpp | 2 +- src/core/kernel/exports/EmuKrnlRtl.cpp | 4 +- src/core/kernel/exports/EmuKrnlXbox.cpp | 6 +- src/core/kernel/exports/EmuKrnlXe.cpp | 8 +- src/core/kernel/init/CxbxKrnl.cpp | 110 ++----- src/core/kernel/init/CxbxKrnl.h | 22 +- .../kernel/memory-manager/PoolManager.cpp | 2 +- src/core/kernel/memory-manager/VMManager.cpp | 14 +- src/core/kernel/support/Emu.cpp | 28 -- src/core/kernel/support/EmuFile.cpp | 23 +- src/core/kernel/support/NativeHandle.cpp | 2 +- src/devices/SMCDevice.cpp | 2 +- src/devices/usb/OHCI.cpp | 4 +- src/devices/usb/USBDevice.cpp | 2 +- src/devices/video/nv2a.cpp | 2 +- src/gui/DlgEepromConfig.cpp | 3 +- src/gui/WinMain.cpp | 17 +- src/gui/WndMain.cpp | 28 +- src/gui/resource/Cxbx.rc | 1 - src/gui/resource/ResCxbx.h | 7 +- src/loader/cxbxr-ldr.cpp | 2 + 67 files changed, 925 insertions(+), 805 deletions(-) create mode 100644 src/common/FilePaths.cpp delete mode 100644 src/common/ReservedMemory.h create mode 100644 src/common/cxbxr.cpp create mode 100644 src/common/cxbxr.hpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 4fb37ce21..ff2451ce3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -49,13 +49,16 @@ add_subdirectory("${CMAKE_CURRENT_LIST_DIR}/projects/libusb") # Common (GUI and Emulator) file (GLOB CXBXR_HEADER_COMMON + "${CXBXR_ROOT_DIR}/src/common/AddressRanges.h" "${CXBXR_ROOT_DIR}/src/common/crypto/EmuDes.h" "${CXBXR_ROOT_DIR}/src/common/crypto/EmuRsa.h" "${CXBXR_ROOT_DIR}/src/common/crypto/EmuSha.h" "${CXBXR_ROOT_DIR}/src/common/crypto/LibRc4.h" "${CXBXR_ROOT_DIR}/src/common/CxbxDebugger.h" + "${CXBXR_ROOT_DIR}/src/common/cxbxr.hpp" "${CXBXR_ROOT_DIR}/src/common/EmuEEPROM.h" "${CXBXR_ROOT_DIR}/src/common/Error.h" + "${CXBXR_ROOT_DIR}/src/common/FilePaths.hpp" "${CXBXR_ROOT_DIR}/src/common/input/DInputKeyboardCodes.h" "${CXBXR_ROOT_DIR}/src/common/input/DInputKeyboardMouse.h" "${CXBXR_ROOT_DIR}/src/common/input/layout_xbox_device.h" @@ -67,9 +70,7 @@ file (GLOB CXBXR_HEADER_COMMON "${CXBXR_ROOT_DIR}/src/common/input/RawDevice.h" "${CXBXR_ROOT_DIR}/src/common/IPCHybrid.hpp" "${CXBXR_ROOT_DIR}/src/common/Logging.h" - "${CXBXR_ROOT_DIR}/src/common/ReservedMemory.h" "${CXBXR_ROOT_DIR}/src/common/Settings.hpp" - "${CXBXR_ROOT_DIR}/src/common/Timer.h" "${CXBXR_ROOT_DIR}/src/common/util/cliConfig.hpp" "${CXBXR_ROOT_DIR}/src/common/util/cliConverter.hpp" "${CXBXR_ROOT_DIR}/src/common/util/CPUID.h" @@ -81,15 +82,19 @@ file (GLOB CXBXR_HEADER_COMMON "${CXBXR_ROOT_DIR}/src/common/win32/AlignPrefix1.h" "${CXBXR_ROOT_DIR}/src/common/win32/EmuShared.h" "${CXBXR_ROOT_DIR}/src/common/win32/Mutex.h" - "${CXBXR_ROOT_DIR}/src/common/win32/Threads.h" "${CXBXR_ROOT_DIR}/src/common/win32/Util.h" "${CXBXR_ROOT_DIR}/src/common/win32/WineEnv.h" "${CXBXR_ROOT_DIR}/src/common/xbdm/CxbxXbdm.h" "${CXBXR_ROOT_DIR}/src/common/xbe/Xbe.h" "${CXBXR_ROOT_DIR}/src/common/xbe/XbePrinter.h" + "${CXBXR_ROOT_DIR}/src/common/xbox/Logging.hpp" "${CXBXR_ROOT_DIR}/src/common/xbox/Types.hpp" "${CXBXR_ROOT_DIR}/src/common/xdvdfs-tools/buffered_io.h" "${CXBXR_ROOT_DIR}/src/common/xdvdfs-tools/xdvdfs.h" + "${CXBXR_ROOT_DIR}/src/core/hle/D3D8/XbConvert.h" + "${CXBXR_ROOT_DIR}/src/core/hle/D3D8/XbD3D8Types.h" + "${CXBXR_ROOT_DIR}/src/core/hle/XAPI/Xapi.h" + "${CXBXR_ROOT_DIR}/src/core/kernel/exports/EmuKrnlLogging.h" "${CXBXR_ROOT_DIR}/src/Cxbx.h" "${CXBXR_ROOT_DIR}/src/CxbxVersion.h" "${CXBXR_ROOT_DIR}/src/version.h" @@ -122,13 +127,12 @@ file (GLOB CXBXR_HEADER_EMU_IMPORT "${CXBXR_ROOT_DIR}/import/imgui/backends/imgui_impl_win32.h" ) file (GLOB CXBXR_HEADER_EMU - "${CXBXR_ROOT_DIR}/src/common/AddressRanges.h" - "${CXBXR_ROOT_DIR}/src/common/FilePaths.hpp" "${CXBXR_ROOT_DIR}/src/common/audio/converter.hpp" + "${CXBXR_ROOT_DIR}/src/common/audio/XADPCM.h" + "${CXBXR_ROOT_DIR}/src/common/Timer.h" "${CXBXR_ROOT_DIR}/src/common/util/gloffscreen/glextensions.h" "${CXBXR_ROOT_DIR}/src/common/util/gloffscreen/gloffscreen.h" - "${CXBXR_ROOT_DIR}/src/common/audio/XADPCM.h" - "${CXBXR_ROOT_DIR}/src/common/xbox/Logging.hpp" + "${CXBXR_ROOT_DIR}/src/common/win32/Threads.h" "${CXBXR_ROOT_DIR}/src/core/common/imgui/audio.hpp" "${CXBXR_ROOT_DIR}/src/core/common/imgui/ui.hpp" "${CXBXR_ROOT_DIR}/src/core/common/imgui/settings.h" @@ -148,9 +152,7 @@ file (GLOB CXBXR_HEADER_EMU "${CXBXR_ROOT_DIR}/src/core/hle/D3D8/Direct3D9/WalkIndexBuffer.h" "${CXBXR_ROOT_DIR}/src/core/hle/D3D8/FixedFunctionState.h" "${CXBXR_ROOT_DIR}/src/core/hle/D3D8/ResourceTracker.h" - "${CXBXR_ROOT_DIR}/src/core/hle/D3D8/XbConvert.h" "${CXBXR_ROOT_DIR}/src/core/hle/D3D8/XbD3D8Logging.h" - "${CXBXR_ROOT_DIR}/src/core/hle/D3D8/XbD3D8Types.h" "${CXBXR_ROOT_DIR}/src/core/hle/D3D8/XbPixelShader.h" "${CXBXR_ROOT_DIR}/src/core/hle/D3D8/XbPushBuffer.h" "${CXBXR_ROOT_DIR}/src/core/hle/D3D8/XbState.h" @@ -169,14 +171,12 @@ file (GLOB CXBXR_HEADER_EMU "${CXBXR_ROOT_DIR}/src/core/hle/Intercept.hpp" "${CXBXR_ROOT_DIR}/src/core/hle/Patches.hpp" "${CXBXR_ROOT_DIR}/src/core/hle/XACTENG/XactEng.h" - "${CXBXR_ROOT_DIR}/src/core/hle/XAPI/Xapi.h" "${CXBXR_ROOT_DIR}/src/core/hle/XGRAPHIC/XGraphic.h" "${CXBXR_ROOT_DIR}/src/core/hle/XONLINE/XOnline.h" "${CXBXR_ROOT_DIR}/src/core/kernel/common/strings.hpp" "${CXBXR_ROOT_DIR}/src/core/kernel/exports/EmuKrnlAvModes.h" "${CXBXR_ROOT_DIR}/src/core/kernel/exports/EmuKrnlKe.h" "${CXBXR_ROOT_DIR}/src/core/kernel/exports/EmuKrnlKi.h" - "${CXBXR_ROOT_DIR}/src/core/kernel/exports/EmuKrnlLogging.h" "${CXBXR_ROOT_DIR}/src/core/kernel/exports/EmuKrnlPs.hpp" "${CXBXR_ROOT_DIR}/src/core/kernel/init/CxbxKrnl.h" "${CXBXR_ROOT_DIR}/src/core/kernel/init/KrnlPatches.hpp" @@ -227,13 +227,16 @@ list(FILTER CXBXR_HEADER_HLSL INCLUDE REGEX ".*\\.hlsl$") # Common (GUI and Emulator) file (GLOB CXBXR_SOURCE_COMMON + "${CXBXR_ROOT_DIR}/src/common/AddressRanges.cpp" "${CXBXR_ROOT_DIR}/src/common/crypto/EmuDes.cpp" "${CXBXR_ROOT_DIR}/src/common/crypto/EmuRsa.cpp" "${CXBXR_ROOT_DIR}/src/common/crypto/EmuSha.cpp" "${CXBXR_ROOT_DIR}/src/common/crypto/LibRc4.cpp" "${CXBXR_ROOT_DIR}/src/common/CxbxDebugger.cpp" + "${CXBXR_ROOT_DIR}/src/common/cxbxr.cpp" "${CXBXR_ROOT_DIR}/src/common/EmuEEPROM.cpp" "${CXBXR_ROOT_DIR}/src/common/Error.cpp" + "${CXBXR_ROOT_DIR}/src/common/FilePaths.cpp" "${CXBXR_ROOT_DIR}/src/common/input/DInputKeyboardMouse.cpp" "${CXBXR_ROOT_DIR}/src/common/input/InputDevice.cpp" "${CXBXR_ROOT_DIR}/src/common/input/InputManager.cpp" @@ -243,7 +246,6 @@ file (GLOB CXBXR_SOURCE_COMMON "${CXBXR_ROOT_DIR}/src/common/input/RawDevice.cpp" "${CXBXR_ROOT_DIR}/src/common/Logging.cpp" "${CXBXR_ROOT_DIR}/src/common/Settings.cpp" - "${CXBXR_ROOT_DIR}/src/common/Timer.cpp" "${CXBXR_ROOT_DIR}/src/common/util/cliConfig.cpp" "${CXBXR_ROOT_DIR}/src/common/util/cliConverter.cpp" "${CXBXR_ROOT_DIR}/src/common/util/crc32c.cpp" @@ -253,15 +255,21 @@ file (GLOB CXBXR_SOURCE_COMMON "${CXBXR_ROOT_DIR}/src/common/win32/InlineFunc.cpp" "${CXBXR_ROOT_DIR}/src/common/win32/IPCWindows.cpp" "${CXBXR_ROOT_DIR}/src/common/win32/Mutex.cpp" - "${CXBXR_ROOT_DIR}/src/common/win32/Threads.cpp" "${CXBXR_ROOT_DIR}/src/common/win32/Util.cpp" "${CXBXR_ROOT_DIR}/src/common/win32/WineEnv.cpp" "${CXBXR_ROOT_DIR}/src/common/xbdm/CxbxXbdm.cpp" "${CXBXR_ROOT_DIR}/src/common/xbe/Xbe.cpp" "${CXBXR_ROOT_DIR}/src/common/xbe/XbePrinter.cpp" + "${CXBXR_ROOT_DIR}/src/common/xbox/Logging.cpp" "${CXBXR_ROOT_DIR}/src/common/xbox/Types.cpp" "${CXBXR_ROOT_DIR}/src/common/xdvdfs-tools/buffered_io.cpp" "${CXBXR_ROOT_DIR}/src/common/xdvdfs-tools/xdvdfs.cpp" + "${CXBXR_ROOT_DIR}/src/core/hle/D3D8/XbConvert.cpp" + "${CXBXR_ROOT_DIR}/src/core/hle/XAPI/Xapi.cpp" + "${CXBXR_ROOT_DIR}/src/core/kernel/exports/EmuKrnlLogging.cpp" + "${CXBXR_ROOT_DIR}/src/core/kernel/exports/EmuKrnlXbox.cpp" + "${CXBXR_ROOT_DIR}/src/core/kernel/exports/EmuKrnlXc.cpp" + "${CXBXR_ROOT_DIR}/src/core/kernel/exports/EmuKrnlXe.cpp" "${CXBXR_ROOT_DIR}/src/CxbxVersion.cpp" "${CXBXR_ROOT_DIR}/src/HighPerformanceGraphicsEnabler.c" ) @@ -299,12 +307,12 @@ file (GLOB CXBXR_SOURCE_EMU_IMPORT ) file (GLOB CXBXR_SOURCE_EMU "${CXBXR_KRNL_CPP}" - "${CXBXR_ROOT_DIR}/src/common/AddressRanges.cpp" - "${CXBXR_ROOT_DIR}/src/common/VerifyAddressRanges.cpp" + "${CXBXR_ROOT_DIR}/src/common/Timer.cpp" "${CXBXR_ROOT_DIR}/src/common/util/gloffscreen/glextensions.cpp" "${CXBXR_ROOT_DIR}/src/common/util/gloffscreen/gloffscreen_common.cpp" "${CXBXR_ROOT_DIR}/src/common/util/gloffscreen/gloffscreen_wgl.cpp" - "${CXBXR_ROOT_DIR}/src/common/xbox/Logging.cpp" + "${CXBXR_ROOT_DIR}/src/common/VerifyAddressRanges.cpp" + "${CXBXR_ROOT_DIR}/src/common/win32/Threads.cpp" "${CXBXR_ROOT_DIR}/src/core/common/imgui/audio.cpp" "${CXBXR_ROOT_DIR}/src/core/common/imgui/ui.cpp" "${CXBXR_ROOT_DIR}/src/core/common/imgui/video.cpp" @@ -319,7 +327,6 @@ file (GLOB CXBXR_SOURCE_EMU "${CXBXR_ROOT_DIR}/src/core/hle/D3D8/Direct3D9/WalkIndexBuffer.cpp" "${CXBXR_ROOT_DIR}/src/core/hle/D3D8/FixedFunctionState.cpp" "${CXBXR_ROOT_DIR}/src/core/hle/D3D8/ResourceTracker.cpp" - "${CXBXR_ROOT_DIR}/src/core/hle/D3D8/XbConvert.cpp" "${CXBXR_ROOT_DIR}/src/core/hle/D3D8/XbD3D8Logging.cpp" "${CXBXR_ROOT_DIR}/src/core/hle/D3D8/XbPixelShader.cpp" "${CXBXR_ROOT_DIR}/src/core/hle/D3D8/XbPushBuffer.cpp" @@ -339,7 +346,6 @@ file (GLOB CXBXR_SOURCE_EMU "${CXBXR_ROOT_DIR}/src/core/hle/Intercept.cpp" "${CXBXR_ROOT_DIR}/src/core/hle/Patches.cpp" "${CXBXR_ROOT_DIR}/src/core/hle/XACTENG/XactEng.cpp" - "${CXBXR_ROOT_DIR}/src/core/hle/XAPI/Xapi.cpp" "${CXBXR_ROOT_DIR}/src/core/hle/XGRAPHIC/XGraphic.cpp" "${CXBXR_ROOT_DIR}/src/core/kernel/exports/EmuKrnl.cpp" "${CXBXR_ROOT_DIR}/src/core/kernel/exports/EmuKrnlAv.cpp" @@ -351,16 +357,12 @@ file (GLOB CXBXR_SOURCE_EMU "${CXBXR_ROOT_DIR}/src/core/kernel/exports/EmuKrnlKd.cpp" "${CXBXR_ROOT_DIR}/src/core/kernel/exports/EmuKrnlKe.cpp" "${CXBXR_ROOT_DIR}/src/core/kernel/exports/EmuKrnlKi.cpp" - "${CXBXR_ROOT_DIR}/src/core/kernel/exports/EmuKrnlLogging.cpp" "${CXBXR_ROOT_DIR}/src/core/kernel/exports/EmuKrnlMm.cpp" "${CXBXR_ROOT_DIR}/src/core/kernel/exports/EmuKrnlNt.cpp" "${CXBXR_ROOT_DIR}/src/core/kernel/exports/EmuKrnlOb.cpp" "${CXBXR_ROOT_DIR}/src/core/kernel/exports/EmuKrnlPhy.cpp" "${CXBXR_ROOT_DIR}/src/core/kernel/exports/EmuKrnlPs.cpp" "${CXBXR_ROOT_DIR}/src/core/kernel/exports/EmuKrnlRtl.cpp" - "${CXBXR_ROOT_DIR}/src/core/kernel/exports/EmuKrnlXbox.cpp" - "${CXBXR_ROOT_DIR}/src/core/kernel/exports/EmuKrnlXc.cpp" - "${CXBXR_ROOT_DIR}/src/core/kernel/exports/EmuKrnlXe.cpp" "${CXBXR_ROOT_DIR}/src/core/kernel/exports/KernelThunk.cpp" "${CXBXR_ROOT_DIR}/src/core/kernel/memory-manager/PhysicalMemory.cpp" "${CXBXR_ROOT_DIR}/src/core/kernel/memory-manager/PoolManager.cpp" diff --git a/projects/cxbx/CMakeLists.txt b/projects/cxbx/CMakeLists.txt index ac9216462..b33f1bea9 100644 --- a/projects/cxbx/CMakeLists.txt +++ b/projects/cxbx/CMakeLists.txt @@ -78,14 +78,9 @@ file (GLOB RESOURCES "${CXBXR_ROOT_DIR}/src/.editorconfig" ) -source_group(TREE ${CXBXR_ROOT_DIR}/import PREFIX import FILES - ${CXBXR_HEADER_EMU_IMPORT} -) - source_group(TREE ${CXBXR_ROOT_DIR}/src PREFIX header FILES ${CXBXR_HEADER_GUIv1} ${CXBXR_HEADER_COMMON} - ${CXBXR_HEADER_EMU} ) source_group(TREE ${CXBXR_ROOT_DIR}/import PREFIX import FILES @@ -95,7 +90,6 @@ source_group(TREE ${CXBXR_ROOT_DIR}/import PREFIX import FILES source_group(TREE ${CXBXR_ROOT_DIR}/src PREFIX source FILES ${CXBXR_SOURCE_GUIv1} ${CXBXR_SOURCE_COMMON} - ${CXBXR_SOURCE_EMU} ) source_group(TREE ${CXBXR_ROOT_DIR} FILES ${RESOURCES}) @@ -103,12 +97,8 @@ source_group(TREE ${CXBXR_ROOT_DIR} FILES ${RESOURCES}) add_executable(cxbx WIN32 ${RESOURCES} ${CXBXR_HEADER_GUIv1} ${CXBXR_HEADER_COMMON} - ${CXBXR_HEADER_EMU_IMPORT} - ${CXBXR_HEADER_EMU} ${CXBXR_SOURCE_GUIv1} ${CXBXR_SOURCE_COMMON} - ${CXBXR_SOURCE_EMU_IMPORT} - ${CXBXR_SOURCE_EMU} ${CXBXR_GIT_VERSION_H} ) @@ -118,15 +108,7 @@ if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") # Reference: https://docs.microsoft.com/en-us/cpp/build/reference/linker-options set_target_properties(cxbx PROPERTIES LINK_FLAGS " - /INCREMENTAL:NO \ - /LARGEADDRESSAWARE \ - /FIXED \ - /SAFESEH:NO \ - /DYNAMICBASE:NO \ - /BASE:0x10000 \ - /STACK:65536,65536 \ /NODEFAULTLIB:libcmt \ - /DELAYLOAD:wpcap.dll \ " LINK_FLAGS_RELEASE " /LTCG \ @@ -185,7 +167,6 @@ set(WINS_LIB comctl32 XINPUT9_1_0 Iphlpapi - wpcap ) target_link_libraries(cxbx diff --git a/src/common/EmuEEPROM.cpp b/src/common/EmuEEPROM.cpp index 1d1fb885f..7a411c699 100644 --- a/src/common/EmuEEPROM.cpp +++ b/src/common/EmuEEPROM.cpp @@ -27,8 +27,8 @@ #define LOG_PREFIX CXBXR_MODULE::EEPR #define LOG_PREFIX_INIT CXBXR_MODULE::INIT - #include // For XC_VALUE_INDEX and XBOX_EEPROM +#include "cxbxr.hpp" // For CxbxrAbort #include // For printf #include // For HANDLE, CreateFile, CreateFileMapping, MapViewOfFile #include @@ -36,7 +36,6 @@ #include "EmuEEPROM.h" // For EEPROMInfo, EEPROMInfos #include "core\kernel\support\Emu.h" // For EmuWarning #include "..\..\src\devices\LED.h" // For SetLEDSequence -#include "..\core\kernel\init\CxbxKrnl.h" xbox::XBOX_EEPROM *EEPROM = nullptr; // Set using CxbxRestoreEEPROM() @@ -90,6 +89,7 @@ void gen_section_CRCs(xbox::XBOX_EEPROM* eeprom) { ); } +#ifdef CXBXR_EMU xbox::XBOX_EEPROM *CxbxRestoreEEPROM(char *szFilePath_EEPROM_bin) { xbox::XBOX_EEPROM *pEEPROM; @@ -141,10 +141,8 @@ xbox::XBOX_EEPROM *CxbxRestoreEEPROM(char *szFilePath_EEPROM_bin) LARGE_INTEGER len_li; GetFileSizeEx(hFileEEPROM, &len_li); unsigned int FileSize = len_li.u.LowPart; - if (FileSize != 256) - { - CxbxrKrnlAbort("%s : EEPROM.bin file is not 256 bytes large!\n", __func__); - return nullptr; + if (FileSize != 256) { + CxbxrAbort("%s : EEPROM.bin file is not 256 bytes large!\n", __func__); } // Map EEPROM.bin contents into memory : @@ -194,6 +192,7 @@ xbox::XBOX_EEPROM *CxbxRestoreEEPROM(char *szFilePath_EEPROM_bin) return pEEPROM; } +#endif void EmuEEPROMReset(xbox::XBOX_EEPROM* eeprom) { diff --git a/src/common/FilePaths.cpp b/src/common/FilePaths.cpp new file mode 100644 index 000000000..50f68d99c --- /dev/null +++ b/src/common/FilePaths.cpp @@ -0,0 +1,186 @@ +// This is an open source non-commercial project. Dear PVS-Studio, please check it. +// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com +// ****************************************************************** +// * +// * This file is part of the Cxbx-Reloaded project. +// * +// * Cxbx and Cxbe are free software; you can redistribute them +// * and/or modify them under the terms of the GNU General Public +// * License as published by the Free Software Foundation; either +// * version 2 of the license, or (at your option) any later version. +// * +// * This program is distributed in the hope that it will be useful, +// * but WITHOUT ANY WARRANTY; without even the implied warranty of +// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// * GNU General Public License for more details. +// * +// * You should have recieved a copy of the GNU General Public License +// * along with this program; see the file COPYING. +// * If not, write to the Free Software Foundation, Inc., +// * 59 Temple Place - Suite 330, Bostom, MA 02111-1307, USA. +// * +// * All rights reserved +// * +// ****************************************************************** +#define LOG_PREFIX CXBXR_MODULE::FILE +#define LOG_PREFIX_INIT CXBXR_MODULE::INIT + +#include "common/cxbxr.hpp" +#include "Settings.hpp" +#include "EmuShared.h" +#include "xxhash.h" // for XXH3_64bits +#include "core/kernel/common/xbox.h" +#include "Logging.h" + +char szFilePath_CxbxReloaded_Exe[MAX_PATH] = { 0 }; +char szFilePath_EEPROM_bin[MAX_PATH] = { 0 }; + +std::string g_DataFilePath; +std::string g_DiskBasePath; +std::string g_MuBasePath; + +//TODO: Possible move CxbxResolveHostToFullPath inline function someplace else if become useful elsewhere. +// Let filesystem library clean it up for us, including resolve host's symbolic link path. +// Since internal kernel do translate to full path than preserved host symoblic link path. +void CxbxResolveHostToFullPath(std::filesystem::path& file_path, std::string_view finish_error_sentence) { + std::error_code error; + std::filesystem::path sanityPath = std::filesystem::canonical(file_path, error); + if (error) { + + // The MS implementation of std::filesystem::canonical internally calls GetFinalPathNameByHandleW, which fails with ERROR_FILE_NOT_FOUND when called + // on a file inside a mounted xiso under Windows with the xbox-iso-vfs tool because of this known dokany bug https://github.com/dokan-dev/dokany/issues/343 + EmuLogInit(LOG_LEVEL::WARNING, "Could not resolve to %s: %s, dokany in use? The error was: %s", + finish_error_sentence.data(), file_path.string().c_str(), error.message().c_str()); + + sanityPath = std::filesystem::absolute(std::filesystem::weakly_canonical(file_path, error), error); + if (error) { + CxbxrAbortEx(LOG_PREFIX_INIT, "Could not resolve to %s: %s. The error was: %s", finish_error_sentence.data(), file_path.string().c_str(), error.message().c_str()); + } + } + file_path = sanityPath; +} +// TODO: Eventually, we should remove this function to start using std::filesystem::path method for all host paths. +void CxbxResolveHostToFullPath(std::string& file_path, std::string_view finish_error_sentence) { + std::filesystem::path sanityPath(file_path); + CxbxResolveHostToFullPath(sanityPath, finish_error_sentence); + file_path = sanityPath.string(); +} + +// NOTE: Do NOT modify g_BasePath variables after this call! +void CxbxrInitFilePaths() +{ + if (g_Settings) { + g_DataFilePath = g_Settings->GetDataLocation(); + } + else { + char dataLoc[MAX_PATH]; + g_EmuShared->GetDataLocation(dataLoc); + g_DataFilePath = dataLoc; + } + + // Make sure our data folder exists : + bool result = std::filesystem::exists(g_DataFilePath); + if (!result && !std::filesystem::create_directory(g_DataFilePath)) { + CxbxrAbort("%s : Couldn't create Cxbx-Reloaded's data folder!", __func__); + } + + // Make sure the EmuDisk folder exists + g_DiskBasePath = g_DataFilePath + "\\EmuDisk"; + result = std::filesystem::exists(g_DiskBasePath); + if (!result && !std::filesystem::create_directory(g_DiskBasePath)) { + CxbxrAbort("%s : Couldn't create Cxbx-Reloaded EmuDisk folder!", __func__); + } + CxbxResolveHostToFullPath(g_DiskBasePath, "Cxbx-Reloaded's EmuDisk directory"); + g_DiskBasePath = std::filesystem::path(g_DiskBasePath).append("").string(); + + // Make sure the EmuDMu folder exists + g_MuBasePath = g_DataFilePath + "\\EmuMu"; + result = std::filesystem::exists(g_MuBasePath); + if (!result && !std::filesystem::create_directory(g_MuBasePath)) { + CxbxrAbort("%s : Couldn't create Cxbx-Reloaded EmuMu folder!", __func__); + } + CxbxResolveHostToFullPath(g_MuBasePath, "Cxbx-Reloaded's EmuMu directory"); + g_MuBasePath = std::filesystem::path(g_MuBasePath).append("").string(); + + snprintf(szFilePath_EEPROM_bin, MAX_PATH, "%s\\EEPROM.bin", g_DataFilePath.c_str()); + + GetModuleFileName(GetModuleHandle(nullptr), szFilePath_CxbxReloaded_Exe, MAX_PATH); +} + +// Loads a keys.bin file as generated by dump-xbox +// See https://github.com/JayFoxRox/xqemu-tools/blob/master/dump-xbox.c +void LoadXboxKeys() +{ + std::string keys_path = g_DataFilePath + "\\keys.bin"; + + // Attempt to open Keys.bin + FILE* fp = fopen(keys_path.c_str(), "rb"); + + if (fp != nullptr) { + // Determine size of Keys.bin + xbox::XBOX_KEY_DATA keys[2]; + fseek(fp, 0, SEEK_END); + long size = ftell(fp); + rewind(fp); + + // If the size of Keys.bin is correct (two keys), read it + if (size == xbox::XBOX_KEY_LENGTH * 2) { + fread(keys, xbox::XBOX_KEY_LENGTH, 2, fp); + + memcpy(xbox::XboxEEPROMKey, &keys[0], xbox::XBOX_KEY_LENGTH); + memcpy(xbox::XboxCertificateKey, &keys[1], xbox::XBOX_KEY_LENGTH); + } + else { + EmuLog(LOG_LEVEL::WARNING, "Keys.bin has an incorrect filesize. Should be %d bytes", xbox::XBOX_KEY_LENGTH * 2); + } + + fclose(fp); + return; + } + + // If we didn't already exit the function, keys.bin could not be loaded + EmuLog(LOG_LEVEL::WARNING, "Failed to load Keys.bin. Cxbx-Reloaded will be unable to read Save Data from a real Xbox"); +} + +static HANDLE hMapDataHash = nullptr; + +bool CxbxrLockFilePath() +{ + std::stringstream filePathHash("Local\\"); + uint64_t hashValue = XXH3_64bits(g_DataFilePath.c_str(), g_DataFilePath.length() + 1); + if (!hashValue) { + CxbxrAbort("%s : Couldn't generate Cxbx-Reloaded's data folder hash!", __func__); + } + + filePathHash << std::hex << hashValue; + + hMapDataHash = CreateFileMapping( + INVALID_HANDLE_VALUE, // Paging file + nullptr, // default security attributes + PAGE_READONLY, // readonly access + 0, // size: high 32 bits + /*Dummy size*/4, // size: low 32 bits + filePathHash.str().c_str() // name of map object + ); + + if (hMapDataHash == nullptr) { + return false; + } + + if (GetLastError() == ERROR_ALREADY_EXISTS) { + PopupError(nullptr, "Data path directory is currently in use.\nUse a different data path directory or stop emulation from another process."); + CloseHandle(hMapDataHash); + return false; + } + + return true; +} + +void CxbxrUnlockFilePath() +{ + // Close opened file path lockdown shared memory. + if (hMapDataHash) { + CloseHandle(hMapDataHash); + hMapDataHash = nullptr; + } +} diff --git a/src/common/FilePaths.hpp b/src/common/FilePaths.hpp index 8de99a862..0a1934e85 100644 --- a/src/common/FilePaths.hpp +++ b/src/common/FilePaths.hpp @@ -24,148 +24,28 @@ // ****************************************************************** #pragma once +extern char szFilePath_CxbxReloaded_Exe[MAX_PATH]; +extern char szFilePath_EEPROM_bin[MAX_PATH]; + +extern std::string g_DataFilePath; +extern std::string g_DiskBasePath; +extern std::string g_MuBasePath; + //TODO: Possible move CxbxResolveHostToFullPath inline function someplace else if become useful elsewhere. // Let filesystem library clean it up for us, including resolve host's symbolic link path. // Since internal kernel do translate to full path than preserved host symoblic link path. -static inline void CxbxResolveHostToFullPath(std::filesystem::path& file_path, std::string_view finish_error_sentence) { - std::error_code error; - std::filesystem::path sanityPath = std::filesystem::canonical(file_path, error); - if (error) { +void CxbxResolveHostToFullPath(std::filesystem::path& file_path, std::string_view finish_error_sentence); - // The MS implementation of std::filesystem::canonical internally calls GetFinalPathNameByHandleW, which fails with ERROR_FILE_NOT_FOUND when called - // on a file inside a mounted xiso under Windows with the xbox-iso-vfs tool because of this known dokany bug https://github.com/dokan-dev/dokany/issues/343 - EmuLogInit(LOG_LEVEL::WARNING, "Could not resolve to %s: %s, dokany in use? The error was: %s", - finish_error_sentence.data(), file_path.string().c_str(), error.message().c_str()); - - sanityPath = std::filesystem::absolute(std::filesystem::weakly_canonical(file_path, error), error); - if (error) { - CxbxrKrnlAbortEx(LOG_PREFIX_INIT, "Could not resolve to %s: %s. The error was: %s", finish_error_sentence.data(), file_path.string().c_str(), error.message().c_str()); - } - } - file_path = sanityPath; -} // TODO: Eventually, we should remove this function to start using std::filesystem::path method for all host paths. -static inline void CxbxResolveHostToFullPath(std::string& file_path, std::string_view finish_error_sentence) { - std::filesystem::path sanityPath(file_path); - CxbxResolveHostToFullPath(sanityPath, finish_error_sentence); - file_path = sanityPath.string(); -} +void CxbxResolveHostToFullPath(std::string& file_path, std::string_view finish_error_sentence); // NOTE: Do NOT modify g_BasePath variables after this call! -void CxbxrInitFilePaths() -{ - if (g_Settings) { - g_DataFilePath = g_Settings->GetDataLocation(); - } - else { - char dataLoc[MAX_PATH]; - g_EmuShared->GetDataLocation(dataLoc); - g_DataFilePath = dataLoc; - } - - // Make sure our data folder exists : - bool result = std::filesystem::exists(g_DataFilePath); - if (!result && !std::filesystem::create_directory(g_DataFilePath)) { - CxbxrKrnlAbort("%s : Couldn't create Cxbx-Reloaded's data folder!", __func__); - } - - // Make sure the EmuDisk folder exists - g_DiskBasePath = g_DataFilePath + "\\EmuDisk"; - result = std::filesystem::exists(g_DiskBasePath); - if (!result && !std::filesystem::create_directory(g_DiskBasePath)) { - CxbxrKrnlAbort("%s : Couldn't create Cxbx-Reloaded EmuDisk folder!", __func__); - } - CxbxResolveHostToFullPath(g_DiskBasePath, "Cxbx-Reloaded's EmuDisk directory"); - g_DiskBasePath = std::filesystem::path(g_DiskBasePath).append("").string(); - - // Make sure the EmuDMu folder exists - g_MuBasePath = g_DataFilePath + "\\EmuMu"; - result = std::filesystem::exists(g_MuBasePath); - if (!result && !std::filesystem::create_directory(g_MuBasePath)) { - CxbxrKrnlAbort("%s : Couldn't create Cxbx-Reloaded EmuMu folder!", __func__); - } - CxbxResolveHostToFullPath(g_MuBasePath, "Cxbx-Reloaded's EmuMu directory"); - g_MuBasePath = std::filesystem::path(g_MuBasePath).append("").string(); - - snprintf(szFilePath_EEPROM_bin, MAX_PATH, "%s\\EEPROM.bin", g_DataFilePath.c_str()); - - GetModuleFileName(GetModuleHandle(nullptr), szFilePath_CxbxReloaded_Exe, MAX_PATH); -} +void CxbxrInitFilePaths(); // Loads a keys.bin file as generated by dump-xbox // See https://github.com/JayFoxRox/xqemu-tools/blob/master/dump-xbox.c -static void LoadXboxKeys() -{ - std::string keys_path = g_DataFilePath + "\\keys.bin"; +void LoadXboxKeys(); - // Attempt to open Keys.bin - FILE* fp = fopen(keys_path.c_str(), "rb"); +bool CxbxrLockFilePath(); - if (fp != nullptr) { - // Determine size of Keys.bin - xbox::XBOX_KEY_DATA keys[2]; - fseek(fp, 0, SEEK_END); - long size = ftell(fp); - rewind(fp); - - // If the size of Keys.bin is correct (two keys), read it - if (size == xbox::XBOX_KEY_LENGTH * 2) { - fread(keys, xbox::XBOX_KEY_LENGTH, 2, fp); - - memcpy(xbox::XboxEEPROMKey, &keys[0], xbox::XBOX_KEY_LENGTH); - memcpy(xbox::XboxCertificateKey, &keys[1], xbox::XBOX_KEY_LENGTH); - } - else { - EmuLog(LOG_LEVEL::WARNING, "Keys.bin has an incorrect filesize. Should be %d bytes", xbox::XBOX_KEY_LENGTH * 2); - } - - fclose(fp); - return; - } - - // If we didn't already exit the function, keys.bin could not be loaded - EmuLog(LOG_LEVEL::WARNING, "Failed to load Keys.bin. Cxbx-Reloaded will be unable to read Save Data from a real Xbox"); -} - -static HANDLE hMapDataHash = nullptr; - -static bool CxbxLockFilePath() -{ - std::stringstream filePathHash("Local\\"); - uint64_t hashValue = XXH3_64bits(g_DataFilePath.c_str(), g_DataFilePath.length() + 1); - if (!hashValue) { - CxbxrKrnlAbort("%s : Couldn't generate Cxbx-Reloaded's data folder hash!", __func__); - } - - filePathHash << std::hex << hashValue; - - hMapDataHash = CreateFileMapping( - INVALID_HANDLE_VALUE, // Paging file - nullptr, // default security attributes - PAGE_READONLY, // readonly access - 0, // size: high 32 bits - /*Dummy size*/4, // size: low 32 bits - filePathHash.str().c_str() // name of map object - ); - - if (hMapDataHash == nullptr) { - return false; - } - - if (GetLastError() == ERROR_ALREADY_EXISTS) { - PopupError(nullptr, "Data path directory is currently in use.\nUse a different data path directory or stop emulation from another process."); - CloseHandle(hMapDataHash); - return false; - } - - return true; -} - -static void CxbxUnlockFilePath() -{ - // Close opened file path lockdown shared memory. - if (hMapDataHash) { - CloseHandle(hMapDataHash); - hMapDataHash = nullptr; - } -} +void CxbxrUnlockFilePath(); diff --git a/src/common/ReservedMemory.h b/src/common/ReservedMemory.h deleted file mode 100644 index 6901b4bd7..000000000 --- a/src/common/ReservedMemory.h +++ /dev/null @@ -1,55 +0,0 @@ -// ****************************************************************** -// * -// * This file is part of the Cxbx project. -// * -// * Cxbx is free software; you can redistribute it -// * and/or modify it under the terms of the GNU General Public -// * License as published by the Free Software Foundation; either -// * version 2 of the license, or (at your option) any later version. -// * -// * This program is distributed in the hope that it will be useful, -// * but WITHOUT ANY WARRANTY; without even the implied warranty of -// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// * GNU General Public License for more details. -// * -// * You should have recieved a copy of the GNU General Public License -// * along with this program; see the file COPYING. -// * If not, write to the Free Software Foundation, Inc., -// * 59 Temple Place - Suite 330, Bostom, MA 02111-1307, USA. -// * -// * (c) 2016 Patrick van Logchem -// * -// * All rights reserved -// * -// ****************************************************************** -#ifndef RESERVEDMEMORY_H -#define RESERVEDMEMORY_H - -#ifndef CXBXR_EMU -#if defined(__cplusplus) -extern "C" -{ -#endif - -#include "EmuShared.h" // For XBE_MAX_VA, XBE_IMAGE_BASE and CXBX_BASE_OF_CODE - -// The following code reserves virtual addresses from 0x00011000 upwards; -#define VM_PLACEHOLDER_SIZE (XBE_MAX_VA - XBE_IMAGE_BASE - CXBX_BASE_OF_CODE) - -// First, declare the '.text' section again : -#pragma section(".text") // Note : 'read,write,execute' would cause a warning -// Then place the following variable into the '.text' section : -__declspec(allocate(".text")) -// This variable *MUST* be this large, for it to take up address space -// so that all other code and data in this module are placed outside of the -// maximum virtual memory range. -unsigned char virtual_memory_placeholder[VM_PLACEHOLDER_SIZE]; // = { OPCODE_NOP_90 }; -// TODO : Try to get the same result without enlarging our executable by 128 MB! - - -#if defined(__cplusplus) -} -#endif -#endif - -#endif // RESERVEDMEMORY_H diff --git a/src/common/Settings.cpp b/src/common/Settings.cpp index 266db907e..9e7ce069f 100644 --- a/src/common/Settings.cpp +++ b/src/common/Settings.cpp @@ -378,8 +378,6 @@ bool Settings::LoadConfig() } m_core.bLogPopupTestCase = m_si.GetBoolValue(section_core, sect_core_keys.LogPopupTestCase, /*Default=*/true); - m_core.bUseLoaderExec = m_si.GetBoolValue(section_core, sect_core_keys.LoaderExecutable, /*Default=*/true); - // ==== Core End ============ // Delete/update legacy configs from previous revisions @@ -601,8 +599,6 @@ bool Settings::Save(std::string file_path) } m_si.SetBoolValue(section_core, sect_core_keys.LogPopupTestCase, m_core.bLogPopupTestCase, nullptr, true); - m_si.SetBoolValue(section_core, sect_core_keys.LoaderExecutable, m_core.bUseLoaderExec, nullptr, true); - // ==== Core End ============ // ==== Video Begin ========= diff --git a/src/common/Settings.hpp b/src/common/Settings.hpp index c6e4a675d..27093cc8b 100644 --- a/src/common/Settings.hpp +++ b/src/common/Settings.hpp @@ -103,7 +103,7 @@ public: char szStorageLocation[xbox::max_path] = ""; unsigned int LoggedModules[NUM_INTEGERS_LOG]; int LogLevel = 1; - bool bUseLoaderExec; + bool bUnused_WasUseLoaderExec; bool allowAdminPrivilege; bool bLogPopupTestCase; bool Reserved4 = 0; diff --git a/src/common/Timer.cpp b/src/common/Timer.cpp index af569c1fd..72881273a 100644 --- a/src/common/Timer.cpp +++ b/src/common/Timer.cpp @@ -35,7 +35,6 @@ #include #include "Timer.h" #include "common\util\CxbxUtil.h" -#include "core\kernel\init\CxbxKrnl.h" #include "core\kernel\support\EmuFS.h" #ifdef __linux__ #include diff --git a/src/common/cxbxr.cpp b/src/common/cxbxr.cpp new file mode 100644 index 000000000..7ae51cac1 --- /dev/null +++ b/src/common/cxbxr.cpp @@ -0,0 +1,135 @@ +// This is an open source non-commercial project. Dear PVS-Studio, please check it. +// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com +// ****************************************************************** +// * +// * This file is part of the Cxbx-Reloaded project. +// * +// * Cxbx and Cxbe are free software; you can redistribute them +// * and/or modify them under the terms of the GNU General Public +// * License as published by the Free Software Foundation; either +// * version 2 of the license, or (at your option) any later version. +// * +// * This program is distributed in the hope that it will be useful, +// * but WITHOUT ANY WARRANTY; without even the implied warranty of +// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// * GNU General Public License for more details. +// * +// * You should have recieved a copy of the GNU General Public License +// * along with this program; see the file COPYING. +// * If not, write to the Free Software Foundation, Inc., +// * 59 Temple Place - Suite 330, Bostom, MA 02111-1307, USA. +// * +// * All rights reserved +// * +// ****************************************************************** +#define LOG_PREFIX CXBXR_MODULE::FILE + +#include "cxbxr.hpp" + +#include "EmuShared.h" +#include "Settings.hpp" +#include "Logging.h" +#include "win32/WineEnv.h" + +#include "Settings.hpp" + +volatile bool g_bPrintfOn = true; + +bool CreateSettings() +{ + g_Settings = new Settings(); + if (g_Settings == nullptr) { + PopupError(nullptr, szSettings_alloc_error); + return false; + } + + if (!g_Settings->Init()) { + return false; + } + + log_get_settings(); + return true; +} + +bool HandleFirstLaunch() +{ + bool bFirstLaunch; + g_EmuShared->GetIsFirstLaunch(&bFirstLaunch); + + /* check if process is launch with elevated access then prompt for continue on or not. */ + if (!bFirstLaunch) { + if (!CreateSettings()) { + return false; + } + + // Wine will always run programs as administrator by default, it can be safely disregard. + // Since Wine doesn't use root permission. Unless user is running Wine as root. + bool bElevated = CxbxrIsElevated(); + if (bElevated && !isWineEnv() && !g_Settings->m_core.allowAdminPrivilege) { + PopupReturn ret = PopupWarningEx(nullptr, PopupButtons::YesNo, PopupReturn::No, + "Cxbx-Reloaded has detected that it has been launched with Administrator rights.\n" + "\nThis is dangerous, as a maliciously modified Xbox titles could take control of your system.\n" + "\nAre you sure you want to continue?"); + if (ret != PopupReturn::Yes) { + return false; + } + } + + g_EmuShared->SetIsFirstLaunch(true); + } + + return true; +} + +#ifndef CXBXR_EMU +[[noreturn]] void CxbxrShutDown(bool is_reboot) +{ + if (!is_reboot) { + // Clear all kernel boot flags. These (together with the shared memory) persist until Cxbx-Reloaded is closed otherwise. + int BootFlags = 0; + g_EmuShared->SetBootFlags(&BootFlags); + } + + // NOTE: This causes a hang when exiting while NV2A is processing + // This is okay for now: It won't leak memory or resources since TerminateProcess will free everything + // delete g_NV2A; // TODO : g_pXbox + + // Shutdown the input device manager + g_InputDeviceManager.Shutdown(); + + EmuShared::Cleanup(); + + TerminateProcess(GetCurrentProcess(), 0); +} + +[[noreturn]] void CxbxrAbortEx(CXBXR_MODULE cxbxr_module, const char* szErrorMessage, ...) +{ + // print out error message (if exists) + if (szErrorMessage != NULL) + { + char szBuffer2[1024]; + va_list argp; + + va_start(argp, szErrorMessage); + vsprintf(szBuffer2, szErrorMessage, argp); + va_end(argp); + + (void)PopupCustomEx(nullptr, cxbxr_module, LOG_LEVEL::FATAL, PopupIcon::Error, PopupButtons::Ok, PopupReturn::Ok, "Received Fatal Message:\n\n* %s\n", szBuffer2); // Will also EmuLogEx + } + + EmuLogInit(LOG_LEVEL::INFO, "MAIN: Terminating Process"); + fflush(stdout); + + // cleanup debug output + { + FreeConsole(); + + char buffer[16]; + + if (GetConsoleTitle(buffer, 16) != NULL) + freopen("nul", "w", stdout); + } + + CxbxrShutDown(); +} +#endif diff --git a/src/common/cxbxr.hpp b/src/common/cxbxr.hpp new file mode 100644 index 000000000..1effc465f --- /dev/null +++ b/src/common/cxbxr.hpp @@ -0,0 +1,59 @@ +// This is an open source non-commercial project. Dear PVS-Studio, please check it. +// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com +// ****************************************************************** +// * +// * This file is part of the Cxbx-Reloaded project. +// * +// * Cxbx and Cxbe are free software; you can redistribute them +// * and/or modify them under the terms of the GNU General Public +// * License as published by the Free Software Foundation; either +// * version 2 of the license, or (at your option) any later version. +// * +// * This program is distributed in the hope that it will be useful, +// * but WITHOUT ANY WARRANTY; without even the implied warranty of +// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// * GNU General Public License for more details. +// * +// * You should have recieved a copy of the GNU General Public License +// * along with this program; see the file COPYING. +// * If not, write to the Free Software Foundation, Inc., +// * 59 Temple Place - Suite 330, Bostom, MA 02111-1307, USA. +// * +// * All rights reserved +// * +// ****************************************************************** +#pragma once + +#include +#include +#include + +#include "Logging.h" + +bool CreateSettings(); + +bool HandleFirstLaunch(); + +// TODO: Eventually, we should remove this function to start using std::filesystem::path method for all host paths. +void CxbxResolveHostToFullPath(std::string& file_path, std::string_view finish_error_sentence); + +// Loads a keys.bin file as generated by dump-xbox +// See https://github.com/JayFoxRox/xqemu-tools/blob/master/dump-xbox.c +void LoadXboxKeys(); + +bool CxbxrLockFilePath(); + +void CxbxrUnlockFilePath(); + +// Hybrid functions depending on specific platforms +bool CxbxrIsElevated(); + +std::optional CxbxrExec(bool useDebugger, void** hProcess, bool requestHandleProcess); + +/*! cleanup emulation */ +[[noreturn]] void CxbxrAbortEx(CXBXR_MODULE cxbxr_module, const char* szErrorMessage, ...); + +#define CxbxrAbort(fmt, ...) CxbxrAbortEx(LOG_PREFIX, fmt, ##__VA_ARGS__) + +/*! terminate gracefully the emulation */ +[[noreturn]] void CxbxrShutDown(bool is_reboot = false); diff --git a/src/common/input/InputManager.cpp b/src/common/input/InputManager.cpp index ad5eeee3a..f28ed2272 100644 --- a/src/common/input/InputManager.cpp +++ b/src/common/input/InputManager.cpp @@ -35,8 +35,9 @@ #define _XBOXKRNL_DEFEXTRN_ #define LOG_PREFIX CXBXR_MODULE::INPSYS - #include // For PKINTERRUPT, etc. +#include "common/cxbxr.hpp" + #include "SdlJoystick.h" #include "XInputPad.h" #include "RawDevice.h" @@ -47,12 +48,17 @@ #include "core\kernel\exports\EmuKrnl.h" // For EmuLog #include "EmuShared.h" #include "devices\usb\OHCI.h" +#ifdef CXBXR_EMU #include "core/common/video/RenderBase.hpp" +#endif #include // hle input specific #include "core\hle\XAPI\Xapi.h" +// Allocate enough memory for the max number of devices we can support simultaneously +// 4 duke / S / sbc / arcade joystick / lightgun (mutually exclusive) + 8 memory units +DeviceState g_devs[MAX_DEVS]; int dev_num_buttons[to_underlying(XBOX_INPUT_DEVICE::DEVICE_MAX)] = { XBOX_CTRL_NUM_BUTTONS, // MS_CONTROLLER_DUKE @@ -78,11 +84,13 @@ void InputDeviceManager::Initialize(bool is_gui, HWND hwnd) m_hwnd = hwnd; m_PollingThread = std::thread([this, is_gui]() { +#ifdef CXBXR_EMU // This code can run in both cxbx.exe and cxbxr-ldr.exe, but will not have // the affinity policy when running in the former. if (g_AffinityPolicy) { g_AffinityPolicy->SetAffinityOther(); } +#endif XInput::Init(m_Mtx); RawInput::Init(m_Mtx, is_gui, m_hwnd); @@ -99,7 +107,7 @@ void InputDeviceManager::Initialize(bool is_gui, HWND hwnd) lck.unlock(); if (Sdl::InitStatus < 0 || XInput::InitStatus < 0 || RawInput::InitStatus < 0 || Libusb::InitStatus < 0) { - CxbxrKrnlAbort("Failed to initialize input subsystem! Consult debug log for more information"); + CxbxrAbort("Failed to initialize input subsystem! Consult debug log for more information"); } UpdateOpt(is_gui); @@ -367,7 +375,11 @@ bool InputDeviceManager::UpdateXboxPortInput(int port, void* buffer, int directi // First check if ImGui is focus, then ignore any input update occur. // If somebody else is currently holding the lock, we won't wait and instead report no input changes - if (!g_renderbase->IsImGuiFocus() && m_Mtx.try_lock()) { + if ( +#ifdef CXBXR_EMU + !g_renderbase->IsImGuiFocus() && +#endif + m_Mtx.try_lock()) { for (auto &dev : m_Devices) { std::string port_str = std::to_string(port); if (dev->GetPort(port_str)) { diff --git a/src/common/input/SdlJoystick.cpp b/src/common/input/SdlJoystick.cpp index f3981d5b7..aca266e24 100644 --- a/src/common/input/SdlJoystick.cpp +++ b/src/common/input/SdlJoystick.cpp @@ -37,7 +37,6 @@ #include #include #include "core\kernel\support\Emu.h" -#include "core\kernel\init\CxbxKrnl.h" #include "SdlJoystick.h" #include "XInputPad.h" #include "DInputKeyboardMouse.h" diff --git a/src/common/util/CxbxUtil.cpp b/src/common/util/CxbxUtil.cpp index edd43e0e3..c521dc638 100644 --- a/src/common/util/CxbxUtil.cpp +++ b/src/common/util/CxbxUtil.cpp @@ -52,7 +52,6 @@ #include // For memcpy #include "common\util\CxbxUtil.h" -#include "core\kernel\init\CxbxKrnl.h" #ifndef MIN #define MIN(a, b) (((a) < (b)) ? (a) : (b)) diff --git a/src/common/win32/EmuShared.cpp b/src/common/win32/EmuShared.cpp index 4df2be0bd..1ba72952c 100644 --- a/src/common/win32/EmuShared.cpp +++ b/src/common/win32/EmuShared.cpp @@ -25,7 +25,8 @@ // * // ****************************************************************** -#include "core\kernel\init\CxbxKrnl.h" +#include "cxbxr.hpp" + #include "core\kernel\support\Emu.h" #include "EmuShared.h" @@ -83,8 +84,9 @@ bool EmuShared::Init(long long sessionID) emuSharedStr.c_str() // name of map object ); - if(hMapObject == NULL) - return false; // CxbxrKrnlAbortEx(CXBXR_MODULE::INIT, "Could not map shared memory!"); + if (hMapObject == NULL) { + CxbxrAbortEx(CXBXR_MODULE::INIT, "Could not map shared memory!"); + } if(GetLastError() == ERROR_ALREADY_EXISTS) bRequireConstruction = false; @@ -105,7 +107,7 @@ bool EmuShared::Init(long long sessionID) if (g_EmuShared == nullptr) { CloseHandle(hMapObject); - return false; // CxbxrKrnlAbortEx(CXBXR_MODULE::INIT, "Could not map view of shared memory!"); + CxbxrAbortEx(CXBXR_MODULE::INIT, "Could not map view of shared memory!"); } } diff --git a/src/common/win32/IPCWindows.cpp b/src/common/win32/IPCWindows.cpp index f95083b6a..82a342d89 100644 --- a/src/common/win32/IPCWindows.cpp +++ b/src/common/win32/IPCWindows.cpp @@ -30,7 +30,6 @@ #include #include "Cxbx.h" -#include "core\kernel\init\CxbxKrnl.h" #include "gui/resource/ResCxbx.h" #include "common\IPCHybrid.hpp" @@ -38,6 +37,9 @@ #include "common\Settings.hpp" #include "Logging.h" +#ifdef CXBXR_EMU +/*! parent window handle */ +extern "C" HWND CxbxKrnl_hEmuParent = NULL; void ipc_send_gui_update(IPC_UPDATE_GUI command, const unsigned int value) { @@ -79,6 +81,7 @@ void ipc_send_gui_update(IPC_UPDATE_GUI command, const unsigned int value) SendMessage(CxbxKrnl_hEmuParent, WM_PARENTNOTIFY, MAKEWPARAM(WM_COMMAND, cmdParam), value); } } +#endif void ipc_send_kernel_update(IPC_UPDATE_KERNEL command, const int value, const unsigned int hwnd) { diff --git a/src/common/win32/InlineFunc.cpp b/src/common/win32/InlineFunc.cpp index ce0d2701e..045f796e6 100644 --- a/src/common/win32/InlineFunc.cpp +++ b/src/common/win32/InlineFunc.cpp @@ -27,12 +27,13 @@ #if defined(_WIN32) || defined(WIN32) -#include "core\kernel\init\CxbxKrnl.h" +#include +#include #include "common/util/cliConfig.hpp" #include "Util.h" // Source: https://stackoverflow.com/questions/8046097/how-to-check-if-a-process-has-the-administrative-rights -bool CxbxIsElevated() { +bool CxbxrIsElevated() { bool fRet = false; HANDLE hToken = NULL; if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken)) { @@ -48,7 +49,7 @@ bool CxbxIsElevated() { return fRet; } -std::optional CxbxExec(bool useDebugger, HANDLE* hProcess, bool requestHandleProcess) { +std::optional CxbxrExec(bool useDebugger, void** hProcess, bool requestHandleProcess) { STARTUPINFO startupInfo = { 0 }; PROCESS_INFORMATION processInfo = { 0 }; diff --git a/src/common/win32/Threads.cpp b/src/common/win32/Threads.cpp index d14e7b076..04755560e 100644 --- a/src/common/win32/Threads.cpp +++ b/src/common/win32/Threads.cpp @@ -200,7 +200,7 @@ class Win7Policy final : public AffinityPolicy public: bool Initialize() { if (!GetProcessAffinityMask(g_CurrentProcessHandle, &CPUXbox, &CPUOthers)) - CxbxrKrnlAbortEx(CXBXR_MODULE::INIT, "GetProcessAffinityMask failed."); + CxbxrAbortEx(CXBXR_MODULE::INIT, "GetProcessAffinityMask failed."); // For the other threads, remove one bit from the processor mask: CPUOthers = ((CPUXbox - 1) & CPUXbox); diff --git a/src/common/xbe/Xbe.cpp b/src/common/xbe/Xbe.cpp index 6c50a597b..31e0343c2 100644 --- a/src/common/xbe/Xbe.cpp +++ b/src/common/xbe/Xbe.cpp @@ -34,7 +34,6 @@ #include // For ctime #include #include "devices\LED.h" // For LED::Sequence -#include "core\kernel\init\CxbxKrnl.h" // For CxbxKrnlPrintUEM #include "common\crypto\EmuSha.h" // For the SHA functions #include "common\crypto\EmuRsa.h" // For the RSA functions #include "core\hle\XAPI\Xapi.h" // For LDT_FROM_DASHBOARD @@ -44,7 +43,9 @@ namespace fs = std::filesystem; - +#ifdef CXBXR_EMU +extern "C" void CxbxKrnlPrintUEM(ULONG); +#endif // construct via Xbe file Xbe::Xbe(const char *x_szFilename, bool bFromGUI) @@ -63,12 +64,13 @@ Xbe::Xbe(const char *x_szFilename, bool bFromGUI) using namespace fs; // limit its scope inside here std::string XbeName = path(x_szFilename).filename().string(); // recover the xbe name - // NOTE: the check for the existence of the child window is necessary because the user could have previously loaded the dashboard, // removed/changed the path and attempt to load it again from the recent list, which will crash CxbxInitWindow below // Note that GetHwnd(), CxbxKrnl_hEmuParent and HalReturnToFirmware are all not suitable here for various reasons - if (XbeName.compare(std::string("xboxdash.xbe")) == 0 && !bFromGUI) - { + if (XbeName.compare(std::string("xboxdash.xbe")) == 0 +#ifdef CXBXR_EMU + && !bFromGUI + ) { // The dashboard could not be found on partition2. This is a fatal error on the Xbox so we display the UEM. The // error code is different if we have a launch data page @@ -86,8 +88,10 @@ Xbe::Xbe(const char *x_szFilename, bool bFromGUI) // TODO: FATAL_ERROR_XBE_DASH_X2_PASS (requires DVD drive authentication emulation...) } - else - { + else { +#else + ) { +#endif // Report which xbe could not be found SetFatalError(std::string("Could not open the Xbe file ") + XbeName); return; diff --git a/src/common/xbe/XbePrinter.cpp b/src/common/xbe/XbePrinter.cpp index 77291d8f0..0cf0537d2 100644 --- a/src/common/xbe/XbePrinter.cpp +++ b/src/common/xbe/XbePrinter.cpp @@ -33,8 +33,6 @@ #include // For std::setfill, std::uppercase, std::hex #include "common/util/strConverter.hpp" // for utf16le_to_ascii -extern std::string FormatTitleId(uint32_t title_id); // Exposed in Emu.cpp - // better time static char *BetterTime(uint32_t x_timeDate) { @@ -61,6 +59,33 @@ std::string DumpInformation(Xbe* Xbe_object) #define SSTREAM_SET_HEX(stream_name) stream_name << std::setfill('0') << std::uppercase << std::hex; +std::string FormatTitleId(uint32_t title_id) +{ + std::stringstream ss; + + // If the Title ID prefix is a printable character, parse it + // This shows the correct game serial number for retail titles! + // EG: MS-001 for 1st tile published by MS, EA-002 for 2nd title by EA, etc + // Some special Xbes (Dashboard, XDK Samples) use non-alphanumeric serials + // We fall back to Hex for those + // ergo720: we cannot use isalnum() here because it will treat chars in the range -1 - 255 as valid ascii chars which can + // lead to unicode characters being printed in the title (e.g.: dashboard uses 0xFE and 0xFF) + uint8_t pTitleId1 = (title_id >> 24) & 0xFF; + uint8_t pTitleId2 = (title_id >> 16) & 0xFF; + + if ((pTitleId1 < 65 || pTitleId1 > 90) || (pTitleId2 < 65 || pTitleId2 > 90)) { + // Prefix was non-printable, so we need to print a hex reprentation of the entire title_id + ss << std::setfill('0') << std::setw(8) << std::hex << std::uppercase << title_id; + return ss.str(); + } + + ss << pTitleId1 << pTitleId2; + ss << "-"; + ss << std::setfill('0') << std::setw(3) << std::dec << (title_id & 0x0000FFFF); + + return ss.str(); +} + XbePrinter::XbePrinter(Xbe* Xbe_object) { Xbe_to_print = Xbe_object; diff --git a/src/common/xbe/XbePrinter.h b/src/common/xbe/XbePrinter.h index 5d656eeb7..a3463aea1 100644 --- a/src/common/xbe/XbePrinter.h +++ b/src/common/xbe/XbePrinter.h @@ -30,6 +30,8 @@ #include +extern std::string FormatTitleId(uint32_t title_id); + extern std::string DumpInformation(Xbe* Xbe_object); class XbePrinter diff --git a/src/core/common/imgui/ui.cpp b/src/core/common/imgui/ui.cpp index 680a2bf93..ac1d02fde 100644 --- a/src/core/common/imgui/ui.cpp +++ b/src/core/common/imgui/ui.cpp @@ -20,7 +20,7 @@ bool ImGuiUI::Initialize() IMGUI_CHECKVERSION(); m_imgui_context = ImGui::CreateContext(); if (!m_imgui_context) { - CxbxrKrnlAbort("Unable to create ImGui context!"); + CxbxrAbort("Unable to create ImGui context!"); return false; } @@ -61,7 +61,7 @@ void ImGuiUI::Shutdown() size_t ini_size = IMGUI_INI_SIZE_MAX; const char* temp_ini_settings = ImGui::SaveIniSettingsToMemory(&ini_size); if (ini_size > IMGUI_INI_SIZE_MAX) { - CxbxrKrnlAbort("ImGui ini settings is too large: %d > %d (IMGUI_INI_SIZE_MAX)", ini_size, IMGUI_INI_SIZE_MAX); + CxbxrAbort("ImGui ini settings is too large: %d > %d (IMGUI_INI_SIZE_MAX)", ini_size, IMGUI_INI_SIZE_MAX); } g_EmuShared->SetImGuiIniSettings(temp_ini_settings); g_EmuShared->SetOverlaySettings(&m_settings); diff --git a/src/core/hle/D3D8/Direct3D9/Direct3D9.cpp b/src/core/hle/D3D8/Direct3D9/Direct3D9.cpp index 02b457f84..7fa19ea84 100644 --- a/src/core/hle/D3D8/Direct3D9/Direct3D9.cpp +++ b/src/core/hle/D3D8/Direct3D9/Direct3D9.cpp @@ -785,20 +785,6 @@ inline DWORD GetXboxCommonResourceType(const xbox::X_D3DResource* pXboxResource) return GetXboxCommonResourceType(pXboxResource->Common); } -xbox::X_D3DFORMAT GetXboxPixelContainerFormat(const xbox::dword_xt XboxPixelContainer_Format) -{ - xbox::X_D3DFORMAT d3d_format = (xbox::X_D3DFORMAT)((XboxPixelContainer_Format & X_D3DFORMAT_FORMAT_MASK) >> X_D3DFORMAT_FORMAT_SHIFT); - return d3d_format; -} - -xbox::X_D3DFORMAT GetXboxPixelContainerFormat(const xbox::X_D3DPixelContainer *pXboxPixelContainer) -{ - // Don't pass in unassigned Xbox pixel container - assert(pXboxPixelContainer != xbox::zeroptr); - - return GetXboxPixelContainerFormat(pXboxPixelContainer->Format); -} - inline int GetXboxPixelContainerDimensionCount(const xbox::X_D3DPixelContainer *pXboxPixelContainer) { // Don't pass in unassigned Xbox pixel container @@ -867,7 +853,7 @@ inline bool IsResourceTypeGPUReadable(const DWORD ResourceType) // assert(false); // Fixup's are not allowed to be registered break; default: - CxbxrKrnlAbort("Unhandled resource type"); + CxbxrAbort("Unhandled resource type"); } return false; @@ -1337,50 +1323,6 @@ xbox::X_D3DSurface *EmuNewD3DSurface() } */ -void CxbxSetPixelContainerHeader -( - xbox::X_D3DPixelContainer* pPixelContainer, - DWORD Common, - UINT Width, - UINT Height, - UINT Levels, - xbox::X_D3DFORMAT Format, - UINT Dimensions, - UINT Pitch -) -{ - // Set X_D3DResource field(s) : - pPixelContainer->Common = Common; - // DON'T SET pPixelContainer->Data - // DON'T SET pPixelContainer->Lock - - // Are Width and Height both a power of two? - DWORD l2w; _BitScanReverse(&l2w, Width); // MSVC intrinsic; GCC has __builtin_clz - DWORD l2h; _BitScanReverse(&l2h, Height); - DWORD l2d = 0; // TODO : Set this via input argument - if (((1 << l2w) == Width) && ((1 << l2h) == Height)) { - Width = Height = Pitch = 1; // When setting Format, clear Size field - } - else { - l2w = l2h = l2d = 0; // When setting Size, clear D3DFORMAT_USIZE, VSIZE and PSIZE - } - - // Set X_D3DPixelContainer field(s) : - pPixelContainer->Format = 0 - | ((Dimensions << X_D3DFORMAT_DIMENSION_SHIFT) & X_D3DFORMAT_DIMENSION_MASK) - | (((DWORD)Format << X_D3DFORMAT_FORMAT_SHIFT) & X_D3DFORMAT_FORMAT_MASK) - | ((Levels << X_D3DFORMAT_MIPMAP_SHIFT) & X_D3DFORMAT_MIPMAP_MASK) - | ((l2w << X_D3DFORMAT_USIZE_SHIFT) & X_D3DFORMAT_USIZE_MASK) - | ((l2h << X_D3DFORMAT_VSIZE_SHIFT) & X_D3DFORMAT_VSIZE_MASK) - | ((l2d << X_D3DFORMAT_PSIZE_SHIFT) & X_D3DFORMAT_PSIZE_MASK) - ; - pPixelContainer->Size = 0 - | (((Width - 1) /*X_D3DSIZE_WIDTH_SHIFT*/) & X_D3DSIZE_WIDTH_MASK) - | (((Height - 1) << X_D3DSIZE_HEIGHT_SHIFT) & X_D3DSIZE_HEIGHT_MASK) - | (((Pitch - 1) << X_D3DSIZE_PITCH_SHIFT) & X_D3DSIZE_PITCH_MASK) - ; -} - unsigned int CxbxGetPixelContainerDepth ( xbox::X_D3DPixelContainer *pPixelContainer @@ -1440,48 +1382,6 @@ uint32_t GetPixelContainerHeight(xbox::X_D3DPixelContainer *pPixelContainer) return Result; } -void CxbxGetPixelContainerMeasures -( - xbox::X_D3DPixelContainer *pPixelContainer, - // TODO : Add X_D3DCUBEMAP_FACES argument - DWORD dwMipMapLevel, // unused - TODO : Use - UINT *pWidth, - UINT *pHeight, - UINT *pDepth, - UINT *pRowPitch, - UINT *pSlicePitch -) -{ - DWORD Size = pPixelContainer->Size; - xbox::X_D3DFORMAT X_Format = GetXboxPixelContainerFormat(pPixelContainer); - - if (Size != 0) - { - *pDepth = 1; - *pWidth = ((Size & X_D3DSIZE_WIDTH_MASK) /* >> X_D3DSIZE_WIDTH_SHIFT*/) + 1; - *pHeight = ((Size & X_D3DSIZE_HEIGHT_MASK) >> X_D3DSIZE_HEIGHT_SHIFT) + 1; - *pRowPitch = (((Size & X_D3DSIZE_PITCH_MASK) >> X_D3DSIZE_PITCH_SHIFT) + 1) * X_D3DTEXTURE_PITCH_ALIGNMENT; - } - else - { - DWORD l2w = (pPixelContainer->Format & X_D3DFORMAT_USIZE_MASK) >> X_D3DFORMAT_USIZE_SHIFT; - DWORD l2h = (pPixelContainer->Format & X_D3DFORMAT_VSIZE_MASK) >> X_D3DFORMAT_VSIZE_SHIFT; - DWORD l2d = (pPixelContainer->Format & X_D3DFORMAT_PSIZE_MASK) >> X_D3DFORMAT_PSIZE_SHIFT; - DWORD dwBPP = EmuXBFormatBitsPerPixel(X_Format); - - *pDepth = 1 << l2d; - *pHeight = 1 << l2h; - *pWidth = 1 << l2w; - *pRowPitch = (*pWidth) * dwBPP / 8; - } - - *pSlicePitch = (*pRowPitch) * (*pHeight); - - if (EmuXBFormatIsCompressed(X_Format)) { - *pRowPitch *= 4; - } -} - void GetSurfaceFaceAndLevelWithinTexture(xbox::X_D3DSurface* pSurface, xbox::X_D3DBaseTexture* pTexture, UINT& Level, D3DCUBEMAP_FACES& Face) { auto pSurfaceData = (uintptr_t)GetDataFromXboxResource(pSurface); @@ -1570,119 +1470,6 @@ void GetSurfaceFaceAndLevelWithinTexture(xbox::X_D3DSurface* pSurface, xbox::X_D GetSurfaceFaceAndLevelWithinTexture(pSurface, pBaseTexture, Level, face); } -bool ConvertD3DTextureToARGBBuffer( - xbox::X_D3DFORMAT X_Format, - uint8_t *pSrc, - int SrcWidth, int SrcHeight, int SrcRowPitch, int SrcSlicePitch, - uint8_t *pDst, int DstRowPitch, int DstSlicePitch, - unsigned int uiDepth = 1, - int iTextureStage = 0 -) -{ - const FormatToARGBRow ConvertRowToARGB = EmuXBFormatComponentConverter(X_Format); - if (ConvertRowToARGB == nullptr) - return false; // Unhandled conversion - - uint8_t *unswizleBuffer = nullptr; - if (EmuXBFormatIsSwizzled(X_Format)) { - unswizleBuffer = (uint8_t*)malloc(SrcSlicePitch * uiDepth); // TODO : Reuse buffer when performance is important - // First we need to unswizzle the texture data - EmuUnswizzleBox( - pSrc, SrcWidth, SrcHeight, uiDepth, - EmuXBFormatBytesPerPixel(X_Format), - // Note : use src pitch on dest, because this is an intermediate step : - unswizleBuffer, SrcRowPitch, SrcSlicePitch - ); - // Convert colors from the unswizzled buffer - pSrc = unswizleBuffer; - } - - int AdditionalArgument; - if (X_Format == xbox::X_D3DFMT_P8) - AdditionalArgument = (int)g_pXbox_Palette_Data[iTextureStage]; - else - AdditionalArgument = DstRowPitch; - - if (EmuXBFormatIsCompressed(X_Format)) { - if (SrcWidth < 4 || SrcHeight < 4) { - // HACK: The compressed DXT conversion code currently writes more pixels than it should, which can cause a crash. - // This code will get hit when converting compressed texture mipmaps on hardware that somehow doesn't support DXT natively - // (or lied when Cxbx asked it if it does!) - EmuLog(LOG_LEVEL::WARNING, "Converting DXT textures smaller than a block is not currently implemented. Ignoring conversion!"); - return true; - } - - // All compressed formats (DXT1, DXT3 and DXT5) encode blocks of 4 pixels on 4 lines - SrcHeight = (SrcHeight + 3) / 4; - DstRowPitch *= 4; - } - - uint8_t *pSrcSlice = pSrc; - uint8_t *pDstSlice = pDst; - for (unsigned int z = 0; z < uiDepth; z++) { - uint8_t *pSrcRow = pSrcSlice; - uint8_t *pDstRow = pDstSlice; - for (int y = 0; y < SrcHeight; y++) { - *(int*)pDstRow = AdditionalArgument; // Dirty hack, to avoid an extra parameter to all conversion callbacks - ConvertRowToARGB(pSrcRow, pDstRow, SrcWidth); - pSrcRow += SrcRowPitch; - pDstRow += DstRowPitch; - } - - pSrcSlice += SrcSlicePitch; - pDstSlice += DstSlicePitch; - } - - if (unswizleBuffer) - free(unswizleBuffer); - - return true; -} - -// Called by WndMain::LoadGameLogo() to load game logo bitmap -uint8_t *ConvertD3DTextureToARGB( - xbox::X_D3DPixelContainer *pXboxPixelContainer, - uint8_t *pSrc, - int *pWidth, int *pHeight, - int TextureStage // default = 0 -) -{ - // Avoid allocating pDest when ConvertD3DTextureToARGBBuffer will fail anyway - xbox::X_D3DFORMAT X_Format = GetXboxPixelContainerFormat(pXboxPixelContainer); - const FormatToARGBRow ConvertRowToARGB = EmuXBFormatComponentConverter(X_Format); - if (ConvertRowToARGB == nullptr) - return nullptr; // Unhandled conversion - - unsigned int SrcDepth, SrcRowPitch, SrcSlicePitch; - CxbxGetPixelContainerMeasures( - pXboxPixelContainer, - 0, // dwMipMapLevel - (UINT*)pWidth, - (UINT*)pHeight, - &SrcDepth, - &SrcRowPitch, - &SrcSlicePitch - ); - - // Now we know ConvertD3DTextureToARGBBuffer will do it's thing, allocate the resulting buffer - int DstDepth = 1; // for now TODO : Use SrcDepth when supporting volume textures - int DstRowPitch = (*pWidth) * sizeof(DWORD); // = sizeof ARGB pixel. TODO : Is this correct? - int DstSlicePitch = DstRowPitch * (*pHeight); // TODO : Is this correct? - int DstSize = DstSlicePitch * DstDepth; - uint8_t *pDst = (uint8_t *)malloc(DstSize); - - // And convert the source towards that buffer - /*ignore result*/ConvertD3DTextureToARGBBuffer( - X_Format, - pSrc, *pWidth, *pHeight, SrcRowPitch, SrcSlicePitch, - pDst, DstRowPitch, DstSlicePitch, - DstDepth, - TextureStage); - - // NOTE : Caller must take ownership! - return pDst; -} - extern void HLE_init_pgraph_plugins(); // implemented in XbPushBuffer.cpp // Direct3D initialization (called before emulation begins) @@ -1700,7 +1487,7 @@ void EmuD3DInit() { // xbox Direct3DCreate8 returns "1" always, so we need our own ptr if(FAILED(Direct3DCreate9Ex(D3D_SDK_VERSION, &g_pDirect3D))) - CxbxrKrnlAbort("Could not initialize Direct3D8!"); + CxbxrAbort("Could not initialize Direct3D8!"); g_pDirect3D->GetDeviceCaps(g_EmuCDPD.Adapter, g_EmuCDPD.DeviceType, &g_D3DCaps); @@ -1804,14 +1591,14 @@ static DWORD WINAPI EmuRenderWindow(LPVOID lpParam) { if(bRet == -1) { - CxbxrKrnlAbort("GetMessage failed!"); + CxbxrAbort("GetMessage failed!"); } TranslateMessage(&msg); DispatchMessage(&msg); } - CxbxrKrnlAbort(nullptr); + CxbxrAbort(nullptr); } return 0; @@ -2040,7 +1827,7 @@ static LRESULT WINAPI EmuMsgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lPar case SIZE_MINIMIZED: { if(g_XBVideo.bFullScreen) - CxbxrKrnlAbort(nullptr); + CxbxrAbort(nullptr); } break; } @@ -2094,7 +1881,7 @@ static LRESULT WINAPI EmuMsgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lPar case WM_CLOSE: CxbxReleaseCursor(); DestroyWindow(hWnd); - CxbxKrnlShutDown(); + CxbxrShutDown(); break; case WM_SETFOCUS: @@ -2455,7 +2242,7 @@ static void CreateDefaultD3D9Device DEBUG_D3DRESULT(hr, "IDirect3D::CreateDeviceEx"); if(FAILED(hr)) - CxbxrKrnlAbort("IDirect3D::CreateDeviceEx failed"); + CxbxrAbort("IDirect3D::CreateDeviceEx failed"); // Which texture formats does this device support? DetermineSupportedD3DFormats(); @@ -2772,7 +2559,7 @@ ConvertedIndexBuffer& CxbxUpdateActiveIndexBuffer if (CacheEntry.pHostIndexBuffer == nullptr) { CacheEntry.pHostIndexBuffer = CxbxCreateIndexBuffer(RequiredIndexCount); if (!CacheEntry.pHostIndexBuffer) - CxbxrKrnlAbort("CxbxUpdateActiveIndexBuffer: IndexBuffer Create Failed!"); + CxbxrAbort("CxbxUpdateActiveIndexBuffer: IndexBuffer Create Failed!"); } // TODO : Speeds this up, perhaps by hashing less often, and/or by @@ -2791,7 +2578,7 @@ ConvertedIndexBuffer& CxbxUpdateActiveIndexBuffer HRESULT hRet = CacheEntry.pHostIndexBuffer->Lock(0, /*entire SizeToLock=*/0, (D3DLockData **)&pHostIndexBufferData, D3DLOCK_DISCARD); DEBUG_D3DRESULT(hRet, "CacheEntry.pHostIndexBuffer->Lock"); if (pHostIndexBufferData == nullptr) { - CxbxrKrnlAbort("CxbxUpdateActiveIndexBuffer: Could not lock index buffer!"); + CxbxrAbort("CxbxUpdateActiveIndexBuffer: Could not lock index buffer!"); } // Determine highest and lowest index in use : @@ -2815,7 +2602,7 @@ ConvertedIndexBuffer& CxbxUpdateActiveIndexBuffer DEBUG_D3DRESULT(hRet, "g_pD3DDevice->SetIndices"); if (FAILED(hRet)) - CxbxrKrnlAbort("CxbxUpdateActiveIndexBuffer: SetIndices Failed!"); + CxbxrAbort("CxbxUpdateActiveIndexBuffer: SetIndices Failed!"); return CacheEntry; } @@ -2828,13 +2615,13 @@ void UpdateHostBackBufferDesc() 0, D3DBACKBUFFER_TYPE_MONO, &pCurrentHostBackBuffer); if (hRet != D3D_OK) { - CxbxrKrnlAbort("Unable to get host backbuffer surface"); + CxbxrAbort("Unable to get host backbuffer surface"); } hRet = pCurrentHostBackBuffer->GetDesc(&g_HostBackBufferDesc); if (hRet != D3D_OK) { pCurrentHostBackBuffer->Release(); - CxbxrKrnlAbort("Unable to determine host backbuffer dimensions"); + CxbxrAbort("Unable to determine host backbuffer dimensions"); } pCurrentHostBackBuffer->Release(); @@ -3008,11 +2795,11 @@ void Direct3D_CreateDevice_Start CxbxVertexShaderSetFlags(); if (!XboxRenderStates.Init()) { - CxbxrKrnlAbort("Failed to init XboxRenderStates"); + CxbxrAbort("Failed to init XboxRenderStates"); } if (!XboxTextureStates.Init(&XboxRenderStates)) { - CxbxrKrnlAbort("Failed to init XboxTextureStates"); + CxbxrAbort("Failed to init XboxTextureStates"); } SetXboxMultiSampleType(pPresentationParameters->MultiSampleType); @@ -3066,7 +2853,7 @@ void Direct3D_CreateDevice_End // At this point, g_pXbox_BackBufferSurface should now point to a valid render target // if it still doesn't, we cannot continue without crashing at draw time if (g_pXbox_BackBufferSurface == xbox::zeroptr) { - CxbxrKrnlAbort("Unable to determine default Xbox backbuffer"); + CxbxrAbort("Unable to determine default Xbox backbuffer"); } // Set the backbuffer as the initial rendertarget @@ -4023,7 +3810,7 @@ xbox::X_D3DSurface* CxbxrImpl_GetBackBuffer2 DEBUG_D3DRESULT(hRet, "g_pD3DDevice->GetBackBuffer"); if (FAILED(hRet)) - CxbxrKrnlAbort("Unable to retrieve back buffer"); + CxbxrAbort("Unable to retrieve back buffer"); SetHostSurface(pXboxBackBuffer, pCurrentHostBackBuffer); // No iTextureStage! @@ -4053,7 +3840,7 @@ xbox::X_D3DSurface* CxbxrImpl_GetBackBuffer2 // Now pXboxBackbuffer points to the requested Xbox backbuffer if (pXboxBackBuffer == nullptr) { - CxbxrKrnlAbort("D3DDevice_GetBackBuffer2: Could not get Xbox backbuffer"); + CxbxrAbort("D3DDevice_GetBackBuffer2: Could not get Xbox backbuffer"); } @@ -5789,7 +5576,7 @@ void CreateHostResource(xbox::X_D3DResource *pResource, DWORD D3DUsage, int iTex PCFormat = D3DFMT_A8R8G8B8; } else { // Otherwise, use a best matching format - /*CxbxrKrnlAbort*/EmuLog(LOG_LEVEL::WARNING, "Encountered a completely incompatible %s format!", ResourceTypeName); + /*CxbxrAbort*/EmuLog(LOG_LEVEL::WARNING, "Encountered a completely incompatible %s format!", ResourceTypeName); PCFormat = EmuXB2PC_D3DFormat(X_Format); } } @@ -5917,7 +5704,7 @@ void CreateHostResource(xbox::X_D3DResource *pResource, DWORD D3DUsage, int iTex // If the fallback failed, show an error and exit execution. if (hRet != D3D_OK) { // We cannot safely continue in this state. - CxbxrKrnlAbort("CreateImageSurface Failed!\n\nError: %s\nDesc: %s", + CxbxrAbort("CreateImageSurface Failed!\n\nError: %s\nDesc: %s", DXGetErrorString(hRet), DXGetErrorDescription(hRet)); } @@ -5985,7 +5772,7 @@ void CreateHostResource(xbox::X_D3DResource *pResource, DWORD D3DUsage, int iTex if (hRet != D3D_OK) { - CxbxrKrnlAbort("CreateTexture Failed!\n\n" + CxbxrAbort("CreateTexture Failed!\n\n" "Error: 0x%X\nFormat: %d\nDimensions: %dx%d", hRet, PCFormat, hostWidth, hostHeight); } @@ -6011,7 +5798,7 @@ void CreateHostResource(xbox::X_D3DResource *pResource, DWORD D3DUsage, int iTex } if (hRet != D3D_OK) { - CxbxrKrnlAbort("CreateVolumeTexture Failed!\n\nError: %s\nDesc: %s", + CxbxrAbort("CreateVolumeTexture Failed!\n\nError: %s\nDesc: %s", DXGetErrorString(hRet), DXGetErrorDescription(hRet)); } @@ -6040,7 +5827,7 @@ void CreateHostResource(xbox::X_D3DResource *pResource, DWORD D3DUsage, int iTex } if (hRet != D3D_OK) { - CxbxrKrnlAbort("CreateCubeTexture Failed!\n\nError: \nDesc: "/*, + CxbxrAbort("CreateCubeTexture Failed!\n\nError: \nDesc: "/*, DXGetErrorString(hRet), DXGetErrorDescription(hRet)*/); } @@ -6170,7 +5957,7 @@ void CreateHostResource(xbox::X_D3DResource *pResource, DWORD D3DUsage, int iTex pDst, dwDstRowPitch, dwDstSlicePitch, pxMipDepth,//used pxMipDepth here because in 3D mip map the 3rd dimension also shrinked to 1/2 at each mip level. iTextureStage)) { - CxbxrKrnlAbort("Unhandled conversion!"); + CxbxrAbort("Unhandled conversion!"); } } } @@ -6598,7 +6385,7 @@ void UpdateFixedFunctionVertexShaderState() auto hRet = g_pD3DDevice->SetVertexShaderConstantF(0, (float*)&ffShaderState, fixedFunctionStateSize); if (FAILED(hRet)) { - CxbxrKrnlAbort("Failed to write fixed-function HLSL state"); + CxbxrAbort("Failed to write fixed-function HLSL state"); } } @@ -7208,14 +6995,14 @@ void CxbxAssureQuadListD3DIndexBuffer(UINT NrOfQuadIndices) // Create a new native index buffer of the above determined size : g_pQuadToTriangleHostIndexBuffer = CxbxCreateIndexBuffer(NrOfTriangleIndices); if (g_pQuadToTriangleHostIndexBuffer == nullptr) - CxbxrKrnlAbort("CxbxAssureQuadListD3DIndexBuffer : IndexBuffer Create Failed!"); + CxbxrAbort("CxbxAssureQuadListD3DIndexBuffer : IndexBuffer Create Failed!"); // Put quadlist-to-triangle-list index mappings into this buffer : INDEX16* pHostIndexBufferData = nullptr; hRet = g_pQuadToTriangleHostIndexBuffer->Lock(0, /*entire SizeToLock=*/0, (D3DLockData **)&pHostIndexBufferData, D3DLOCK_DISCARD); DEBUG_D3DRESULT(hRet, "g_pQuadToTriangleHostIndexBuffer->Lock"); if (pHostIndexBufferData == nullptr) - CxbxrKrnlAbort("CxbxAssureQuadListD3DIndexBuffer : Could not lock index buffer!"); + CxbxrAbort("CxbxAssureQuadListD3DIndexBuffer : Could not lock index buffer!"); memcpy(pHostIndexBufferData, CxbxAssureQuadListIndexData(NrOfQuadIndices), NrOfTriangleIndices * sizeof(INDEX16)); @@ -7227,7 +7014,7 @@ void CxbxAssureQuadListD3DIndexBuffer(UINT NrOfQuadIndices) DEBUG_D3DRESULT(hRet, "g_pD3DDevice->SetIndices"); if (FAILED(hRet)) - CxbxrKrnlAbort("CxbxAssureQuadListD3DIndexBuffer : SetIndices Failed!"); // +DxbxD3DErrorString(hRet)); + CxbxrAbort("CxbxAssureQuadListD3DIndexBuffer : SetIndices Failed!"); // +DxbxD3DErrorString(hRet)); } // TODO : Move to own file @@ -7241,7 +7028,7 @@ void CxbxDrawIndexedClosingLine(INDEX16 LowIndex, INDEX16 HighIndex) if (g_pClosingLineLoopHostIndexBuffer == nullptr) { g_pClosingLineLoopHostIndexBuffer = CxbxCreateIndexBuffer(VERTICES_PER_LINE); if (g_pClosingLineLoopHostIndexBuffer == nullptr) - CxbxrKrnlAbort("Unable to create g_pClosingLineLoopHostIndexBuffer for D3DPT_LINELOOP emulation"); + CxbxrAbort("Unable to create g_pClosingLineLoopHostIndexBuffer for D3DPT_LINELOOP emulation"); } INDEX16 *pCxbxClosingLineLoopIndexBufferData = nullptr; diff --git a/src/core/hle/D3D8/Direct3D9/Direct3D9.h b/src/core/hle/D3D8/Direct3D9/Direct3D9.h index 91b001154..36ed559d2 100644 --- a/src/core/hle/D3D8/Direct3D9/Direct3D9.h +++ b/src/core/hle/D3D8/Direct3D9/Direct3D9.h @@ -42,25 +42,6 @@ void LookupTrampolinesD3D(); // initialize render window extern void CxbxInitWindow(bool bFullInit); -extern void CxbxSetPixelContainerHeader -( - xbox::X_D3DPixelContainer* pPixelContainer, - DWORD Common, - UINT Width, - UINT Height, - UINT Levels, - xbox::X_D3DFORMAT Format, - UINT Dimensions, - UINT Pitch -); - -extern uint8_t *ConvertD3DTextureToARGB( - xbox::X_D3DPixelContainer *pXboxPixelContainer, - uint8_t *pSrc, - int *pWidth, int *pHeight, - int TextureStage = 0 -); - void CxbxUpdateNativeD3DResources(); void CxbxImpl_SetRenderTarget(xbox::X_D3DSurface* pRenderTarget, xbox::X_D3DSurface* pNewZStencil); diff --git a/src/core/hle/D3D8/Direct3D9/TextureStates.cpp b/src/core/hle/D3D8/Direct3D9/TextureStates.cpp index aa669c7ec..cd761472a 100644 --- a/src/core/hle/D3D8/Direct3D9/TextureStates.cpp +++ b/src/core/hle/D3D8/Direct3D9/TextureStates.cpp @@ -361,9 +361,9 @@ DWORD NormalizeValue(DWORD xboxState, DWORD value) { uint32_t XboxTextureStateConverter::Get(int textureStage, DWORD xboxState) { if (textureStage < 0 || textureStage > 3) - CxbxrKrnlAbort("Requested texture stage was out of range: %d", textureStage); + CxbxrAbort("Requested texture stage was out of range: %d", textureStage); if (xboxState < xbox::X_D3DTSS_FIRST || xboxState > xbox::X_D3DTSS_LAST) - CxbxrKrnlAbort("Requested texture state was out of range: %d", xboxState); + CxbxrAbort("Requested texture state was out of range: %d", xboxState); // Read the value of the current stage/state from the Xbox data structure DWORD rawValue = D3D__TextureState[(textureStage * xbox::X_D3DTS_STAGESIZE) + XboxTextureStateOffsets[xboxState]]; diff --git a/src/core/hle/D3D8/Direct3D9/VertexShader.cpp b/src/core/hle/D3D8/Direct3D9/VertexShader.cpp index d53da1599..5f0f23a28 100644 --- a/src/core/hle/D3D8/Direct3D9/VertexShader.cpp +++ b/src/core/hle/D3D8/Direct3D9/VertexShader.cpp @@ -4,6 +4,7 @@ #include "VertexShader.h" // EmuCompileVertexShader #include "core\kernel\init\CxbxKrnl.h" // implicit CxbxKrnl_Xbe used in LOG_TEST_CASE #include "core\kernel\support\Emu.h" // LOG_TEST_CASE (via Logging.h) +#include "common/FilePaths.hpp" // For szFilePath_CxbxReloaded_Exe #include #include // std::stringstream diff --git a/src/core/hle/D3D8/XbConvert.cpp b/src/core/hle/D3D8/XbConvert.cpp index 73c7f1572..60ee6244b 100644 --- a/src/core/hle/D3D8/XbConvert.cpp +++ b/src/core/hle/D3D8/XbConvert.cpp @@ -1047,7 +1047,7 @@ D3DFORMAT EmuXB2PC_D3DFormat(xbox::X_D3DFORMAT Format) case ((xbox::X_D3DFORMAT)0xffffffff): return D3DFMT_UNKNOWN; // TODO -oCXBX: Not sure if this counts as swizzled or not... default: - CxbxrKrnlAbort("EmuXB2PC_D3DFormat: Unknown Format (0x%.08X)", Format); + CxbxrAbort("EmuXB2PC_D3DFormat: Unknown Format (0x%.08X)", Format); } return D3DFMT_UNKNOWN; @@ -1056,8 +1056,8 @@ D3DFORMAT EmuXB2PC_D3DFormat(xbox::X_D3DFORMAT Format) xbox::X_D3DFORMAT EmuPC2XB_D3DFormat(D3DFORMAT Format, bool bPreferLinear) { xbox::X_D3DFORMAT result; - switch(Format) - { + switch(Format) + { case D3DFMT_YUY2: result = xbox::X_D3DFMT_YUY2; break; @@ -1129,10 +1129,10 @@ xbox::X_D3DFORMAT EmuPC2XB_D3DFormat(D3DFORMAT Format, bool bPreferLinear) result = xbox::X_D3DFMT_VERTEXDATA; break; default: - CxbxrKrnlAbort("EmuPC2XB_D3DFormat: Unknown Format (%d)", Format); - } + CxbxrAbort("EmuPC2XB_D3DFormat: Unknown Format (%d)", Format); + } - return result; + return result; } DWORD EmuXB2PC_D3DLock(DWORD Flags) @@ -1591,6 +1591,221 @@ Direct3D9 states unused : D3DRS_BLENDOPALPHA = 209 // Blending operation for the alpha channel when D3DRS_SEPARATEDESTALPHAENABLE is TRUE */ +static xbox::PVOID g_pXbox_Palette_Data[xbox::X_D3DTS_STAGECOUNT] = { xbox::zeroptr, xbox::zeroptr, xbox::zeroptr, xbox::zeroptr }; // cached palette pointer + +xbox::X_D3DFORMAT GetXboxPixelContainerFormat(const xbox::dword_xt XboxPixelContainer_Format) +{ + xbox::X_D3DFORMAT d3d_format = (xbox::X_D3DFORMAT)((XboxPixelContainer_Format & X_D3DFORMAT_FORMAT_MASK) >> X_D3DFORMAT_FORMAT_SHIFT); + return d3d_format; +} + +xbox::X_D3DFORMAT GetXboxPixelContainerFormat(const xbox::X_D3DPixelContainer* pXboxPixelContainer) +{ + // Don't pass in unassigned Xbox pixel container + assert(pXboxPixelContainer != xbox::zeroptr); + + return GetXboxPixelContainerFormat(pXboxPixelContainer->Format); +} + +void CxbxGetPixelContainerMeasures +( + xbox::X_D3DPixelContainer* pPixelContainer, + // TODO : Add X_D3DCUBEMAP_FACES argument + DWORD dwMipMapLevel, // unused - TODO : Use + UINT* pWidth, + UINT* pHeight, + UINT* pDepth, + UINT* pRowPitch, + UINT* pSlicePitch +) +{ + DWORD Size = pPixelContainer->Size; + xbox::X_D3DFORMAT X_Format = GetXboxPixelContainerFormat(pPixelContainer); + + if (Size != 0) + { + *pDepth = 1; + *pWidth = ((Size & X_D3DSIZE_WIDTH_MASK) /* >> X_D3DSIZE_WIDTH_SHIFT*/) + 1; + *pHeight = ((Size & X_D3DSIZE_HEIGHT_MASK) >> X_D3DSIZE_HEIGHT_SHIFT) + 1; + *pRowPitch = (((Size & X_D3DSIZE_PITCH_MASK) >> X_D3DSIZE_PITCH_SHIFT) + 1) * X_D3DTEXTURE_PITCH_ALIGNMENT; + } + else + { + DWORD l2w = (pPixelContainer->Format & X_D3DFORMAT_USIZE_MASK) >> X_D3DFORMAT_USIZE_SHIFT; + DWORD l2h = (pPixelContainer->Format & X_D3DFORMAT_VSIZE_MASK) >> X_D3DFORMAT_VSIZE_SHIFT; + DWORD l2d = (pPixelContainer->Format & X_D3DFORMAT_PSIZE_MASK) >> X_D3DFORMAT_PSIZE_SHIFT; + DWORD dwBPP = EmuXBFormatBitsPerPixel(X_Format); + + *pDepth = 1 << l2d; + *pHeight = 1 << l2h; + *pWidth = 1 << l2w; + *pRowPitch = (*pWidth) * dwBPP / 8; + } + + *pSlicePitch = (*pRowPitch) * (*pHeight); + + if (EmuXBFormatIsCompressed(X_Format)) { + *pRowPitch *= 4; + } +} + +bool ConvertD3DTextureToARGBBuffer( + xbox::X_D3DFORMAT X_Format, + uint8_t* pSrc, + int SrcWidth, int SrcHeight, int SrcRowPitch, int SrcSlicePitch, + uint8_t* pDst, int DstRowPitch, int DstSlicePitch, + unsigned int uiDepth , + int iTextureStage +) +{ + const FormatToARGBRow ConvertRowToARGB = EmuXBFormatComponentConverter(X_Format); + if (ConvertRowToARGB == nullptr) + return false; // Unhandled conversion + + uint8_t* unswizleBuffer = nullptr; + if (EmuXBFormatIsSwizzled(X_Format)) { + unswizleBuffer = (uint8_t*)malloc(SrcSlicePitch * uiDepth); // TODO : Reuse buffer when performance is important + // First we need to unswizzle the texture data + EmuUnswizzleBox( + pSrc, SrcWidth, SrcHeight, uiDepth, + EmuXBFormatBytesPerPixel(X_Format), + // Note : use src pitch on dest, because this is an intermediate step : + unswizleBuffer, SrcRowPitch, SrcSlicePitch + ); + // Convert colors from the unswizzled buffer + pSrc = unswizleBuffer; + } + + int AdditionalArgument; + if (X_Format == xbox::X_D3DFMT_P8) + AdditionalArgument = (int)g_pXbox_Palette_Data[iTextureStage]; + else + AdditionalArgument = DstRowPitch; + + if (EmuXBFormatIsCompressed(X_Format)) { + if (SrcWidth < 4 || SrcHeight < 4) { + // HACK: The compressed DXT conversion code currently writes more pixels than it should, which can cause a crash. + // This code will get hit when converting compressed texture mipmaps on hardware that somehow doesn't support DXT natively + // (or lied when Cxbx asked it if it does!) + EmuLog(LOG_LEVEL::WARNING, "Converting DXT textures smaller than a block is not currently implemented. Ignoring conversion!"); + return true; + } + + // All compressed formats (DXT1, DXT3 and DXT5) encode blocks of 4 pixels on 4 lines + SrcHeight = (SrcHeight + 3) / 4; + DstRowPitch *= 4; + } + + uint8_t* pSrcSlice = pSrc; + uint8_t* pDstSlice = pDst; + for (unsigned int z = 0; z < uiDepth; z++) { + uint8_t* pSrcRow = pSrcSlice; + uint8_t* pDstRow = pDstSlice; + for (int y = 0; y < SrcHeight; y++) { + *(int*)pDstRow = AdditionalArgument; // Dirty hack, to avoid an extra parameter to all conversion callbacks + ConvertRowToARGB(pSrcRow, pDstRow, SrcWidth); + pSrcRow += SrcRowPitch; + pDstRow += DstRowPitch; + } + + pSrcSlice += SrcSlicePitch; + pDstSlice += DstSlicePitch; + } + + if (unswizleBuffer) + free(unswizleBuffer); + + return true; +} + +// Called by WndMain::LoadGameLogo() to load game logo bitmap +uint8_t* ConvertD3DTextureToARGB( + xbox::X_D3DPixelContainer* pXboxPixelContainer, + uint8_t* pSrc, + int* pWidth, int* pHeight, + int TextureStage // default = 0 +) +{ + // Avoid allocating pDest when ConvertD3DTextureToARGBBuffer will fail anyway + xbox::X_D3DFORMAT X_Format = GetXboxPixelContainerFormat(pXboxPixelContainer); + const FormatToARGBRow ConvertRowToARGB = EmuXBFormatComponentConverter(X_Format); + if (ConvertRowToARGB == nullptr) + return nullptr; // Unhandled conversion + + unsigned int SrcDepth, SrcRowPitch, SrcSlicePitch; + CxbxGetPixelContainerMeasures( + pXboxPixelContainer, + 0, // dwMipMapLevel + (UINT*)pWidth, + (UINT*)pHeight, + &SrcDepth, + &SrcRowPitch, + &SrcSlicePitch + ); + + // Now we know ConvertD3DTextureToARGBBuffer will do it's thing, allocate the resulting buffer + int DstDepth = 1; // for now TODO : Use SrcDepth when supporting volume textures + int DstRowPitch = (*pWidth) * sizeof(DWORD); // = sizeof ARGB pixel. TODO : Is this correct? + int DstSlicePitch = DstRowPitch * (*pHeight); // TODO : Is this correct? + int DstSize = DstSlicePitch * DstDepth; + uint8_t* pDst = (uint8_t*)malloc(DstSize); + + // And convert the source towards that buffer + /*ignore result*/ConvertD3DTextureToARGBBuffer( + X_Format, + pSrc, *pWidth, *pHeight, SrcRowPitch, SrcSlicePitch, + pDst, DstRowPitch, DstSlicePitch, + DstDepth, + TextureStage); + + // NOTE : Caller must take ownership! + return pDst; +} + +void CxbxSetPixelContainerHeader +( + xbox::X_D3DPixelContainer* pPixelContainer, + DWORD Common, + UINT Width, + UINT Height, + UINT Levels, + xbox::X_D3DFORMAT Format, + UINT Dimensions, + UINT Pitch +) +{ + // Set X_D3DResource field(s) : + pPixelContainer->Common = Common; + // DON'T SET pPixelContainer->Data + // DON'T SET pPixelContainer->Lock + + // Are Width and Height both a power of two? + DWORD l2w; _BitScanReverse(&l2w, Width); // MSVC intrinsic; GCC has __builtin_clz + DWORD l2h; _BitScanReverse(&l2h, Height); + DWORD l2d = 0; // TODO : Set this via input argument + if (((1 << l2w) == Width) && ((1 << l2h) == Height)) { + Width = Height = Pitch = 1; // When setting Format, clear Size field + } + else { + l2w = l2h = l2d = 0; // When setting Size, clear D3DFORMAT_USIZE, VSIZE and PSIZE + } + + // Set X_D3DPixelContainer field(s) : + pPixelContainer->Format = 0 + | ((Dimensions << X_D3DFORMAT_DIMENSION_SHIFT) & X_D3DFORMAT_DIMENSION_MASK) + | (((DWORD)Format << X_D3DFORMAT_FORMAT_SHIFT) & X_D3DFORMAT_FORMAT_MASK) + | ((Levels << X_D3DFORMAT_MIPMAP_SHIFT) & X_D3DFORMAT_MIPMAP_MASK) + | ((l2w << X_D3DFORMAT_USIZE_SHIFT) & X_D3DFORMAT_USIZE_MASK) + | ((l2h << X_D3DFORMAT_VSIZE_SHIFT) & X_D3DFORMAT_VSIZE_MASK) + | ((l2d << X_D3DFORMAT_PSIZE_SHIFT) & X_D3DFORMAT_PSIZE_MASK) + ; + pPixelContainer->Size = 0 + | (((Width - 1) /*X_D3DSIZE_WIDTH_SHIFT*/) & X_D3DSIZE_WIDTH_MASK) + | (((Height - 1) << X_D3DSIZE_HEIGHT_SHIFT) & X_D3DSIZE_HEIGHT_MASK) + | (((Pitch - 1) << X_D3DSIZE_PITCH_SHIFT) & X_D3DSIZE_PITCH_MASK) + ; +} + #if 0 /* Generic swizzle function, usable for both x and y dimensions. When passing x, Max should be 2*height, and Shift should be 0 diff --git a/src/core/hle/D3D8/XbConvert.h b/src/core/hle/D3D8/XbConvert.h index c245f73de..80f42cc1a 100644 --- a/src/core/hle/D3D8/XbConvert.h +++ b/src/core/hle/D3D8/XbConvert.h @@ -25,6 +25,7 @@ #ifndef XBCONVERT_H #define XBCONVERT_H +#include "common/cxbxr.hpp" #include "core\kernel\init\CxbxKrnl.h" #include "core\hle\D3D8\XbD3D8Types.h" @@ -90,7 +91,7 @@ else if((uint32)State < 20) else if((uint32)State > 255) State = (D3DTRANSFORMSTATETYPE)(State - 250); else - CxbxrKrnlAbortEx(LOG_PREFIX_D3DCVT, "Unknown Transform State Type (%d)", State); + CxbxrAbortEx(LOG_PREFIX_D3DCVT, "Unknown Transform State Type (%d)", State); //*/ // convert from xbox to pc texture transform state types @@ -115,7 +116,7 @@ inline D3DTRANSFORMSTATETYPE EmuXB2PC_D3DTS(xbox::X_D3DTRANSFORMSTATETYPE State) return D3DTS_WORLDMATRIX(State - 256); } - CxbxrKrnlAbortEx(LOG_PREFIX_D3DCVT, "Unknown Transform State Type (%d)", State); + CxbxrAbortEx(LOG_PREFIX_D3DCVT, "Unknown Transform State Type (%d)", State); return (D3DTRANSFORMSTATETYPE)0; } @@ -1819,5 +1820,36 @@ RenderStateInfo; extern const RenderStateInfo& GetDxbxRenderStateInfo(int State); +extern xbox::X_D3DFORMAT GetXboxPixelContainerFormat(const xbox::dword_xt XboxPixelContainer_Format); + +extern xbox::X_D3DFORMAT GetXboxPixelContainerFormat(const xbox::X_D3DPixelContainer* pXboxPixelContainer); + +extern bool ConvertD3DTextureToARGBBuffer( + xbox::X_D3DFORMAT X_Format, + uint8_t* pSrc, + int SrcWidth, int SrcHeight, int SrcRowPitch, int SrcSlicePitch, + uint8_t* pDst, int DstRowPitch, int DstSlicePitch, + unsigned int uiDepth = 1, + int iTextureStage = 0 +); + +extern void CxbxSetPixelContainerHeader +( + xbox::X_D3DPixelContainer* pPixelContainer, + DWORD Common, + UINT Width, + UINT Height, + UINT Levels, + xbox::X_D3DFORMAT Format, + UINT Dimensions, + UINT Pitch +); + +extern uint8_t* ConvertD3DTextureToARGB( + xbox::X_D3DPixelContainer* pXboxPixelContainer, + uint8_t* pSrc, + int* pWidth, int* pHeight, + int TextureStage = 0 +); #endif diff --git a/src/core/hle/D3D8/XbPixelShader.cpp b/src/core/hle/D3D8/XbPixelShader.cpp index d9ebb1104..cff3aa896 100644 --- a/src/core/hle/D3D8/XbPixelShader.cpp +++ b/src/core/hle/D3D8/XbPixelShader.cpp @@ -43,9 +43,10 @@ #include "core\hle\D3D8\Direct3D9\PixelShader.h" // EmuCompilePixelShader #include "core\hle\D3D8\XbD3D8Logging.h" // For D3DErrorString() -#include "core\kernel\init\CxbxKrnl.h" // For CxbxrKrnlAbort() +#include "core\kernel\init\CxbxKrnl.h" // For CxbxrAbort() #include "util\hasher.h" #include "core\hle\D3D8\Direct3D9\FixedFunctionPixelShader.hlsli" +#include "common/FilePaths.hpp" // For szFilePath_CxbxReloaded_Exe #include // assert() #include @@ -941,7 +942,7 @@ IDirect3DPixelShader9* GetFixedFunctionShader() IDirect3DPixelShader9* pShader = nullptr; auto hRet = g_pD3DDevice->CreatePixelShader((DWORD*)pShaderBlob->GetBufferPointer(), &pShader); if (hRet != S_OK) - CxbxrKrnlAbort("Failed to compile fixed function pixel shader"); + CxbxrAbort("Failed to compile fixed function pixel shader"); pShaderBlob->Release(); // Insert the shader into the cache diff --git a/src/core/hle/D3D8/XbVertexBuffer.cpp b/src/core/hle/D3D8/XbVertexBuffer.cpp index 2ce7b99d2..284cd78ca 100644 --- a/src/core/hle/D3D8/XbVertexBuffer.cpp +++ b/src/core/hle/D3D8/XbVertexBuffer.cpp @@ -84,7 +84,7 @@ void CxbxPatchedStream::Activate(CxbxDrawContext *pDrawContext, UINT HostStreamN uiCachedHostVertexStride); //DEBUG_D3DRESULT(hRet, "g_pD3DDevice->SetStreamSource"); if (FAILED(hRet)) { - CxbxrKrnlAbort("Failed to set the type patched buffer as the new stream source!\n"); + CxbxrAbort("Failed to set the type patched buffer as the new stream source!\n"); // TODO : test-case : XDK Cartoon hits the above case when the vertex cache size is 0. } } @@ -244,7 +244,7 @@ void CxbxVertexBufferConverter::ConvertStream if (pDrawContext->pXboxVertexStreamZeroData != xbox::zeroptr) { // There should only be one stream (stream zero) in this case if (XboxStreamNumber != 0) { - CxbxrKrnlAbort("Trying to patch a Draw..UP with more than stream zero!"); + CxbxrAbort("Trying to patch a Draw..UP with more than stream zero!"); } pXboxVertexData = (uint8_t *)pDrawContext->pXboxVertexStreamZeroData; @@ -350,7 +350,7 @@ void CxbxVertexBufferConverter::ConvertStream pHostVertexData = (uint8_t*)malloc(dwHostVertexDataSize); if (pHostVertexData == nullptr) { - CxbxrKrnlAbort("Couldn't allocate the new stream zero buffer"); + CxbxrAbort("Couldn't allocate the new stream zero buffer"); } } else { HRESULT hRet = g_pD3DDevice->CreateVertexBuffer( @@ -363,14 +363,14 @@ void CxbxVertexBufferConverter::ConvertStream ); if (FAILED(hRet)) { - CxbxrKrnlAbort("Failed to create vertex buffer"); + CxbxrAbort("Failed to create vertex buffer"); } } // If we need to lock a host vertex buffer, do so now if (pHostVertexData == nullptr && pNewHostVertexBuffer != nullptr) { if (FAILED(pNewHostVertexBuffer->Lock(0, 0, (D3DLockData **)&pHostVertexData, D3DLOCK_DISCARD))) { - CxbxrKrnlAbort("Couldn't lock vertex buffer"); + CxbxrAbort("Couldn't lock vertex buffer"); } } @@ -609,7 +609,7 @@ void CxbxVertexBufferConverter::ConvertStream void CxbxVertexBufferConverter::Apply(CxbxDrawContext *pDrawContext) { if ((pDrawContext->XboxPrimitiveType < xbox::X_D3DPT_POINTLIST) || (pDrawContext->XboxPrimitiveType > xbox::X_D3DPT_POLYGON)) - CxbxrKrnlAbort("Unknown primitive type: 0x%.02X\n", pDrawContext->XboxPrimitiveType); + CxbxrAbort("Unknown primitive type: 0x%.02X\n", pDrawContext->XboxPrimitiveType); CxbxVertexDeclaration* pCxbxVertexDeclaration = CxbxGetVertexDeclaration(); diff --git a/src/core/hle/D3D8/XbVertexShader.cpp b/src/core/hle/D3D8/XbVertexShader.cpp index abdc1e162..7d836912d 100644 --- a/src/core/hle/D3D8/XbVertexShader.cpp +++ b/src/core/hle/D3D8/XbVertexShader.cpp @@ -574,7 +574,7 @@ namespace XboxVertexShaderDecoder } if (pShader->Instructions.size() >= VSH_MAX_INTERMEDIATE_COUNT) { - CxbxrKrnlAbort("Shader exceeds conversion buffer!"); + CxbxrAbort("Shader exceeds conversion buffer!"); } VSH_INTERMEDIATE_FORMAT intermediate; @@ -1161,14 +1161,14 @@ void CxbxUpdateHostVertexShader() EmuCompileFixedFunction(&pBlob); if (pBlob) { hRet = g_pD3DDevice->CreateVertexShader((DWORD*)pBlob->GetBufferPointer(), &ffHlsl); - if (FAILED(hRet)) CxbxrKrnlAbort("Failed to create fixed-function shader"); + if (FAILED(hRet)) CxbxrAbort("Failed to create fixed-function shader"); } } fixedFunctionShader = ffHlsl; } hRet = g_pD3DDevice->SetVertexShader(fixedFunctionShader); - if (FAILED(hRet)) CxbxrKrnlAbort("Failed to set fixed-function shader"); + if (FAILED(hRet)) CxbxrAbort("Failed to set fixed-function shader"); } else if (g_Xbox_VertexShaderMode == VertexShaderMode::Passthrough && g_bUsePassthroughHLSL) { if (passthroughshader == nullptr) { diff --git a/src/core/hle/DSOUND/DirectSound/DirectSound.cpp b/src/core/hle/DSOUND/DirectSound/DirectSound.cpp index d370ff706..f87daaad1 100644 --- a/src/core/hle/DSOUND/DirectSound/DirectSound.cpp +++ b/src/core/hle/DSOUND/DirectSound/DirectSound.cpp @@ -166,13 +166,13 @@ xbox::hresult_xt WINAPI xbox::EMUPATCH(DirectSoundCreate) } if (dsErrorMsg != nullptr) { - CxbxrKrnlAbort(dsErrorMsg, hRet); + CxbxrAbort(dsErrorMsg, hRet); } hRet = g_pDSound8->SetCooperativeLevel(GET_FRONT_WINDOW_HANDLE, DSSCL_PRIORITY); if (hRet != DS_OK) { - CxbxrKrnlAbort("g_pDSound8->SetCooperativeLevel Failed!"); + CxbxrAbort("g_pDSound8->SetCooperativeLevel Failed!"); } // clear sound buffer cache @@ -200,7 +200,7 @@ xbox::hresult_xt WINAPI xbox::EMUPATCH(DirectSoundCreate) hRet = g_pDSound8->CreateSoundBuffer(&bufferDesc, &g_pDSoundPrimaryBuffer, nullptr); if (hRet != DS_OK) { - CxbxrKrnlAbort("Creating primary buffer for DirectSound Failed!"); + CxbxrAbort("Creating primary buffer for DirectSound Failed!"); } /* Quote from MDSN "For the primary buffer, you must use the @@ -213,7 +213,7 @@ xbox::hresult_xt WINAPI xbox::EMUPATCH(DirectSoundCreate) hRet = g_pDSoundPrimaryBuffer->QueryInterface(IID_IDirectSound3DListener8, (LPVOID*)&g_pDSoundPrimary3DListener8); if (hRet != DS_OK) { - CxbxrKrnlAbort("Creating primary 3D Listener for DirectSound Failed!"); + CxbxrAbort("Creating primary 3D Listener for DirectSound Failed!"); } initialized = true; @@ -422,7 +422,7 @@ void StreamBufferAudio(xbox::XbHybridDSBuffer* pHybridBuffer, float msToCopy) { 0); if (hRet != 0) { - CxbxrKrnlAbort("DirectSoundBuffer Lock Failed!"); + CxbxrAbort("DirectSoundBuffer Lock Failed!"); } if (lplpvAudioPtr1 && pThis->X_BufferCache != nullptr) { @@ -449,7 +449,7 @@ void StreamBufferAudio(xbox::XbHybridDSBuffer* pHybridBuffer, float msToCopy) { HRESULT hRet = dsb->Unlock(lplpvAudioPtr1, lplpvAudioBytes1, lplpvAudioPtr2, lplpvAudioBytes2); if (hRet != DS_OK) { - CxbxrKrnlAbort("DirectSoundBuffer Unlock Failed!"); + CxbxrAbort("DirectSoundBuffer Unlock Failed!"); } } } diff --git a/src/core/hle/DSOUND/DirectSound/DirectSoundBuffer.cpp b/src/core/hle/DSOUND/DirectSound/DirectSoundBuffer.cpp index 5952b77cc..8a4383049 100644 --- a/src/core/hle/DSOUND/DirectSound/DirectSoundBuffer.cpp +++ b/src/core/hle/DSOUND/DirectSound/DirectSoundBuffer.cpp @@ -174,7 +174,7 @@ xbox::hresult_xt WINAPI xbox::EMUPATCH(DirectSoundCreateBuffer) hRet = xbox::EMUPATCH(DirectSoundCreate)(nullptr, &g_pDSound8, nullptr); if (hRet != DS_OK) { - CxbxrKrnlAbort("Unable to initialize DirectSound!"); + CxbxrAbort("Unable to initialize DirectSound!"); } } @@ -239,7 +239,7 @@ xbox::hresult_xt WINAPI xbox::EMUPATCH(DirectSoundCreateBuffer) EmuLog(LOG_LEVEL::WARNING, output.str().c_str()); output.str(""); output << static_cast(hRet); - CxbxrKrnlAbort("DSB: DSoundBufferCreate error: %s", output.str().c_str()); + CxbxrAbort("DSB: DSoundBufferCreate error: %s", output.str().c_str()); } else { if (pdsbd->dwFlags & DSBCAPS_CTRL3D) { @@ -584,7 +584,7 @@ xbox::hresult_xt WINAPI xbox::EMUPATCH(IDirectSoundBuffer_Play) pThis->X_lock.dwLockBytes2); if (dwFlags & ~(X_DSBPLAY_LOOPING | X_DSBPLAY_FROMSTART | X_DSBPLAY_SYNCHPLAYBACK)) { - CxbxrKrnlAbort("Unsupported Playing Flags"); + CxbxrAbort("Unsupported Playing Flags"); } pThis->EmuPlayFlags = dwFlags; diff --git a/src/core/hle/DSOUND/DirectSound/DirectSoundInline.hpp b/src/core/hle/DSOUND/DirectSound/DirectSoundInline.hpp index 1b4aad730..1371749d1 100644 --- a/src/core/hle/DSOUND/DirectSound/DirectSoundInline.hpp +++ b/src/core/hle/DSOUND/DirectSound/DirectSoundInline.hpp @@ -274,7 +274,7 @@ static inline void GeneratePCMFormat( } if (DSBufferDesc.lpwfxFormat == nullptr) { - CxbxrKrnlAbort("Unable to allocate DSBufferDesc.Xb_lpwfxFormat"); + CxbxrAbort("Unable to allocate DSBufferDesc.Xb_lpwfxFormat"); } if (Xb_lpwfxFormat != xbox::zeroptr) { @@ -358,7 +358,7 @@ static inline void DSoundGenericUnlock( HRESULT hRet = pDSBuffer->Unlock(Host_lock.pLockPtr1, Host_lock.dwLockBytes1, Host_lock.pLockPtr2, Host_lock.dwLockBytes2); if (hRet != DS_OK) { - CxbxrKrnlAbort("DirectSoundBuffer Unlock Failed!"); + CxbxrAbort("DirectSoundBuffer Unlock Failed!"); } Host_lock.pLockPtr1 = nullptr; @@ -485,7 +485,7 @@ static inline void DSoundBufferRelease( if (pDS3DBuffer != nullptr) { refCount = pDS3DBuffer->Release(); if (refCount > 0) { - CxbxrKrnlAbort("Nope, wasn't fully cleaned up."); + CxbxrAbort("Nope, wasn't fully cleaned up."); } } @@ -554,7 +554,7 @@ static inline void DSoundBufferResizeUpdate( hRet = pThis->EmuDirectSoundBuffer8->Lock(0, 0, &pThis->Host_lock.pLockPtr1, &pThis->Host_lock.dwLockBytes1, nullptr, nullptr, DSBLOCK_ENTIREBUFFER); if (hRet != DS_OK) { - CxbxrKrnlAbort("Unable to lock region buffer!"); + CxbxrAbort("Unable to lock region buffer!"); } DSoundGenericUnlock(pThis->EmuFlags, pThis->EmuDirectSoundBuffer8, @@ -629,7 +629,7 @@ static inline void DSoundBufferRegenWithNewFormat( HRESULT hRet = pDSBuffer->GetStatus(&dwStatus); if (hRet != DS_OK) { - CxbxrKrnlAbort("Unable to retrieve current status for replace DS buffer!"); + CxbxrAbort("Unable to retrieve current status for replace DS buffer!"); } pDSBuffer->Stop(); @@ -637,7 +637,7 @@ static inline void DSoundBufferRegenWithNewFormat( hRet = pDSBuffer->GetCurrentPosition(&dwPlayCursor, nullptr); if (hRet != DS_OK) { - CxbxrKrnlAbort("Unable to retrieve current position for replace DS buffer!"); + CxbxrAbort("Unable to retrieve current position for replace DS buffer!"); } // TODO: Untested if transfer buffer to new audio buffer is necessary. @@ -921,7 +921,7 @@ static inline HRESULT HybridDirectSoundBuffer_Play( { if (dwFlags & ~(X_DSBPLAY_LOOPING | X_DSBPLAY_FROMSTART | X_DSBPLAY_SYNCHPLAYBACK)) { - CxbxrKrnlAbort("Unsupported Playing Flags"); + CxbxrAbort("Unsupported Playing Flags"); } // rewind buffer if ((dwFlags & X_DSBPLAY_FROMSTART)) { diff --git a/src/core/hle/DSOUND/DirectSound/DirectSoundStream.cpp b/src/core/hle/DSOUND/DirectSound/DirectSoundStream.cpp index 9678f2cd1..402e6d2f2 100644 --- a/src/core/hle/DSOUND/DirectSound/DirectSoundStream.cpp +++ b/src/core/hle/DSOUND/DirectSound/DirectSoundStream.cpp @@ -222,7 +222,7 @@ xbox::hresult_xt WINAPI xbox::EMUPATCH(DirectSoundCreateStream) hRet = xbox::EMUPATCH(DirectSoundCreate)(nullptr, &g_pDSound8, nullptr); if (hRet != DS_OK) { - CxbxrKrnlAbort("Unable to initialize DirectSound!"); + CxbxrAbort("Unable to initialize DirectSound!"); } } @@ -299,7 +299,7 @@ xbox::hresult_xt WINAPI xbox::EMUPATCH(DirectSoundCreateStream) EmuLog(LOG_LEVEL::WARNING, output.str().c_str()); output.str(""); output << static_cast(hRet); - CxbxrKrnlAbort("DSS: DSoundBufferCreate error: %s", output.str().c_str()); + CxbxrAbort("DSS: DSoundBufferCreate error: %s", output.str().c_str()); } else { if (DSBufferDesc.dwFlags & DSBCAPS_CTRL3D) { diff --git a/src/core/hle/Intercept.cpp b/src/core/hle/Intercept.cpp index 9d5062a1c..aff13632f 100644 --- a/src/core/hle/Intercept.cpp +++ b/src/core/hle/Intercept.cpp @@ -44,6 +44,7 @@ #include "Intercept.hpp" #include "Patches.hpp" #include "common\util\hasher.h" +#include "common/FilePaths.hpp" #include #include @@ -191,7 +192,7 @@ void CDECL EmuOutputMessage(xb_output_message mFlag, break; } case XB_OUTPUT_MESSAGE_ERROR: { - CxbxrKrnlAbort("%s", message); + CxbxrAbort("%s", message); break; } case XB_OUTPUT_MESSAGE_DEBUG: @@ -383,7 +384,7 @@ void EmuHLEIntercept(Xbe::Header *pXbeHeader) // Make sure the Symbol Cache directory exists std::string cachePath = g_DataFilePath + "\\SymbolCache\\"; if (!std::filesystem::exists(cachePath) && !std::filesystem::create_directory(cachePath)) { - CxbxrKrnlAbort("Couldn't create Cxbx-Reloaded SymbolCache folder!"); + CxbxrAbort("Couldn't create Cxbx-Reloaded SymbolCache folder!"); } // Hash the loaded XBE's header, use it as a filename diff --git a/src/core/hle/XAPI/Xapi.cpp b/src/core/hle/XAPI/Xapi.cpp index 82a360e97..cc93ce34c 100644 --- a/src/core/hle/XAPI/Xapi.cpp +++ b/src/core/hle/XAPI/Xapi.cpp @@ -27,14 +27,14 @@ #define LOG_PREFIX CXBXR_MODULE::XAPI - - #include +#include "core\hle\XAPI\Xapi.h" +#include "common/cxbxr.hpp" + #include "common\input\SdlJoystick.h" #include "common\input\InputManager.h" #include #include "common\input\LibusbDevice.h" // include this after Shlwapi.h or else it causes an error -#include "core\kernel\init\CxbxKrnl.h" #include "Logging.h" #include "core\kernel\support\Emu.h" #include "core\kernel\exports\EmuKrnl.h" // For DefaultLaunchDataPage @@ -45,7 +45,6 @@ #include "core\hle\Intercept.hpp" #include "Windef.h" #include -#include "core\hle\XAPI\Xapi.h" #include @@ -60,16 +59,14 @@ std::atomic g_bIsDevicesEmulating = false; // Protects access to xpp types std::atomic g_bXppGuard = false; -// Allocate enough memory for the max number of devices we can support simultaneously -// 4 duke / S / sbc / arcade joystick / lightgun (mutually exclusive) + 8 memory units -DeviceState g_devs[MAX_DEVS]; - xbox::ulong_xt g_Mounted_MUs = 0; xbox::char_xt g_AltLett_MU = 0; xbox::ulong_xt *g_XapiMountedMUs = &g_Mounted_MUs; xbox::char_xt *g_XapiAltLett_MU = &g_AltLett_MU; std::recursive_mutex g_MuLock; +#ifdef CXBXR_EMU + // Declare trampolines #define XB_TRAMPOLINES(XB_MACRO) \ XB_MACRO(xbox::dword_xt, WINAPI, XUnmountAlternateTitleA, (xbox::char_xt) ); \ @@ -84,6 +81,7 @@ void LookupTrampolinesXAPI() #undef XB_TRAMPOLINES +#endif static inline xbox::char_xt MuPort2Lett(xbox::dword_xt port, xbox::dword_xt slot) { @@ -211,11 +209,13 @@ void ConstructHleInputDevice(DeviceState *dev, DeviceState *upstream, int type, { g_bIsDevicesEmulating = true; +#ifdef CXBXR_EMU if (g_bIsChihiro) { // Don't emulate XID devices during Chihiro Emulation g_bIsDevicesEmulating = false; return; } +#endif // Set up common device state int port_num, slot; @@ -394,6 +394,9 @@ void DestructHleInputDevice(DeviceState *dev) EmuLogEx(CXBXR_MODULE::INPSYS, LOG_LEVEL::INFO, "Detached device %s from port %s", GetInputDeviceName(to_underlying(type)).c_str(), PortUserFormat(port).c_str()); } +// Patches/Functions below are mainly for emulation, we don't need them for GUI purpose. +#ifdef CXBXR_EMU + void SetupXboxDeviceTypes() { // If we don't yet have the offset to gDeviceType_Gamepad, work it out! @@ -415,7 +418,7 @@ void SetupXboxDeviceTypes() // Sanity check: Where all these device offsets within Xbox memory if ((deviceTableStartOffset >= g_SystemMaxMemory) || (deviceTableEndOffset >= g_SystemMaxMemory)) { - CxbxrKrnlAbort("DeviceTable Location is outside of Xbox Memory range"); + CxbxrAbort("DeviceTable Location is outside of Xbox Memory range"); } // Iterate through the table until we find gamepad @@ -1285,3 +1288,5 @@ xbox::void_xt WINAPI xbox::EMUPATCH(OutputDebugStringA) LOG_FUNC_ONE_ARG(lpOutputString); printf("OutputDebugStringA: %s\n", lpOutputString); } + +#endif diff --git a/src/core/hle/XAPI/Xapi.h b/src/core/hle/XAPI/Xapi.h index b0a5c1ce4..e904e9bab 100644 --- a/src/core/hle/XAPI/Xapi.h +++ b/src/core/hle/XAPI/Xapi.h @@ -27,7 +27,8 @@ void LookupTrampolinesXAPI(); -#include "xbox_types.h" +#include +#include "core/kernel/common/xbox.h" namespace xbox { diff --git a/src/core/hle/XGRAPHIC/XGraphic.cpp b/src/core/hle/XGRAPHIC/XGraphic.cpp index eee2c68d8..621c2850f 100644 --- a/src/core/hle/XGRAPHIC/XGraphic.cpp +++ b/src/core/hle/XGRAPHIC/XGraphic.cpp @@ -31,7 +31,7 @@ #include "core\kernel\support\Emu.h" #include "common\Logging.h" -#include "core\kernel\init\CxbxKrnl.h" // For CxbxrKrnlAbort() +#include "core\kernel\init\CxbxKrnl.h" // For CxbxrAbort() #include "core\hle\XAPI\Xapi.h" // For EMUPATCH #include "core\hle\D3D8\XbD3D8Logging.h" // for log rendering of X_D3DFORMAT, etc. #include "core\hle\XGRAPHIC\XGraphic.h" @@ -84,7 +84,7 @@ xbox::void_xt WINAPI xbox::EMUPATCH(XGSwizzleRect) else { if(pPoint != NULL && (pPoint->x != 0 || pPoint->y != 0)) - CxbxrKrnlAbort("Temporarily unsupported swizzle (very easy fix)"); + CxbxrAbort("Temporarily unsupported swizzle (very easy fix)"); DWORD dwMaxY = Height; DWORD dwChunkSize = Width; @@ -150,7 +150,7 @@ xbox::void_xt WINAPI xbox::EMUPATCH(XGSwizzleBox) else { if(pPoint != NULL && (pPoint->u != 0 || pPoint->v != 0 || pPoint->w != 0)) - CxbxrKrnlAbort("Temporarily unsupported swizzle (very easy fix)"); + CxbxrAbort("Temporarily unsupported swizzle (very easy fix)"); DWORD dwMaxY = Height; DWORD dwMaxZ = Depth; @@ -232,10 +232,10 @@ xbox::void_xt WINAPI xbox::EMUPATCH(XGSetTextureHeader) LOG_FUNC_END; /*if( Data != 0 ) - CxbxrKrnlAbort("Data != 0 (XGSetTextureHeader)" ); + CxbxrAbort("Data != 0 (XGSetTextureHeader)" ); if( Pitch != 0 ) - CxbxrKrnlAbort("Pitch != 0 (XGSetTextureHeader)" );*/ + CxbxrAbort("Pitch != 0 (XGSetTextureHeader)" );*/ pTexture->Common = X_D3DCOMMON_TYPE_TEXTURE + 1; // Set refcount to 1 pTexture->Data = Data; diff --git a/src/core/kernel/exports/EmuKrnl.cpp b/src/core/kernel/exports/EmuKrnl.cpp index 361d06f7f..06a8e0e10 100644 --- a/src/core/kernel/exports/EmuKrnl.cpp +++ b/src/core/kernel/exports/EmuKrnl.cpp @@ -145,7 +145,7 @@ extern void ExecuteDpcQueue(); void KiUnexpectedInterrupt() { xbox::KeBugCheck(TRAP_CAUSE_UNKNOWN); // see - CxbxrKrnlAbort("Unexpected Software Interrupt!"); + CxbxrAbort("Unexpected Software Interrupt!"); } void CallSoftwareInterrupt(const xbox::KIRQL SoftwareIrql) diff --git a/src/core/kernel/exports/EmuKrnlEx.cpp b/src/core/kernel/exports/EmuKrnlEx.cpp index 869e7339d..f1ce7fa1e 100644 --- a/src/core/kernel/exports/EmuKrnlEx.cpp +++ b/src/core/kernel/exports/EmuKrnlEx.cpp @@ -41,7 +41,7 @@ namespace NtDll #include "core\kernel\support\EmuNtDll.h" // For NtDelayExecution(), etc. }; -#include "core\kernel\init\CxbxKrnl.h" // For CxbxrKrnlAbort +#include "core\kernel\init\CxbxKrnl.h" // For CxbxrAbort #include "core\kernel\support\Emu.h" // For EmuLog(LOG_LEVEL::WARNING, ) #include "EmuKrnl.h" // For InsertHeadList, InsertTailList, RemoveHeadList diff --git a/src/core/kernel/exports/EmuKrnlHal.cpp b/src/core/kernel/exports/EmuKrnlHal.cpp index 1a22e9499..6129dedcc 100644 --- a/src/core/kernel/exports/EmuKrnlHal.cpp +++ b/src/core/kernel/exports/EmuKrnlHal.cpp @@ -33,7 +33,7 @@ #include "Logging.h" // For LOG_FUNC() #include "EmuKrnl.h" // For InitializeListHead(), etc. #include "EmuKrnlLogging.h" -#include "core\kernel\init\CxbxKrnl.h" // For CxbxrKrnlAbort, and CxbxExec +#include "core\kernel\init\CxbxKrnl.h" // For CxbxrAbort, and CxbxExec #include "core\kernel\support\Emu.h" // For EmuLog(LOG_LEVEL::WARNING, ) #include "core\kernel\support\EmuFS.h" #include "EmuKrnl.h" @@ -483,7 +483,7 @@ XBSYSAPI EXPORTNUM(49) xbox::void_xt DECLSPEC_NORETURN NTAPI xbox::HalReturnToFi switch (Routine) { case ReturnFirmwareHalt: - CxbxrKrnlAbort("Emulated Xbox is halted"); + CxbxrAbort("Emulated Xbox is halted"); break; case ReturnFirmwareReboot: @@ -598,7 +598,7 @@ XBSYSAPI EXPORTNUM(49) xbox::void_xt DECLSPEC_NORETURN NTAPI xbox::HalReturnToFi LOG_UNIMPLEMENTED(); } - CxbxKrnlShutDown(is_reboot); + CxbxrShutDown(is_reboot); } // ****************************************************************** diff --git a/src/core/kernel/exports/EmuKrnlIo.cpp b/src/core/kernel/exports/EmuKrnlIo.cpp index 3b369aafd..173b3d591 100644 --- a/src/core/kernel/exports/EmuKrnlIo.cpp +++ b/src/core/kernel/exports/EmuKrnlIo.cpp @@ -32,7 +32,7 @@ #include // For IoCompletionObjectType, etc. #include "Logging.h" // For LOG_FUNC() #include "EmuKrnlLogging.h" -#include "core\kernel\init\CxbxKrnl.h" // For CxbxrKrnlAbort +#include "core\kernel\init\CxbxKrnl.h" // For CxbxrAbort #include "core\kernel\support\Emu.h" // For EmuLog(LOG_LEVEL::WARNING, ) #include "core\kernel\support\EmuFile.h" // For CxbxCreateSymbolicLink(), etc. #include "CxbxDebugger.h" diff --git a/src/core/kernel/exports/EmuKrnlKe.cpp b/src/core/kernel/exports/EmuKrnlKe.cpp index 2716750e1..ed271fb56 100644 --- a/src/core/kernel/exports/EmuKrnlKe.cpp +++ b/src/core/kernel/exports/EmuKrnlKe.cpp @@ -75,7 +75,7 @@ namespace NtDll #include "core\kernel\support\EmuNtDll.h" // For NtDelayExecution(), etc. }; -#include "core\kernel\init\CxbxKrnl.h" // For CxbxrKrnlAbort +#include "core\kernel\init\CxbxKrnl.h" // For CxbxrAbort #include "core\kernel\support\Emu.h" // For EmuLog(LOG_LEVEL::WARNING, ) #include "EmuKrnl.h" // For InitializeListHead(), etc. #include "EmuKrnlKe.h" @@ -615,7 +615,7 @@ XBSYSAPI EXPORTNUM(96) xbox::ntstatus_xt NTAPI xbox::KeBugCheckEx int result = MessageBoxA(g_hEmuWindow, buffer, "KeBugCheck", MB_YESNO | MB_ICONWARNING); if (result == IDNO) { - CxbxrKrnlAbort(NULL); + CxbxrAbort(NULL); } KeBugCheckIgnored = true; diff --git a/src/core/kernel/exports/EmuKrnlMm.cpp b/src/core/kernel/exports/EmuKrnlMm.cpp index 844e1ca2a..95aa15218 100644 --- a/src/core/kernel/exports/EmuKrnlMm.cpp +++ b/src/core/kernel/exports/EmuKrnlMm.cpp @@ -34,7 +34,7 @@ #include "Logging.h" // For LOG_FUNC() #include "EmuKrnl.h" // For DefaultLaunchDataPage #include "EmuKrnlLogging.h" -#include "core\kernel\init\CxbxKrnl.h" // For CxbxrKrnlAbort +#include "core\kernel\init\CxbxKrnl.h" // For CxbxrAbort #include "core\kernel\support\Emu.h" // For EmuLog(LOG_LEVEL::WARNING, ) #include "core\kernel\memory-manager\VMManager.h" #include "EmuShared.h" diff --git a/src/core/kernel/exports/EmuKrnlNt.cpp b/src/core/kernel/exports/EmuKrnlNt.cpp index 07c50b50f..bba59e853 100644 --- a/src/core/kernel/exports/EmuKrnlNt.cpp +++ b/src/core/kernel/exports/EmuKrnlNt.cpp @@ -40,7 +40,7 @@ namespace NtDll #include "core\kernel\support\EmuNtDll.h" }; -#include "core\kernel\init\CxbxKrnl.h" // For CxbxrKrnlAbort +#include "core\kernel\init\CxbxKrnl.h" // For CxbxrAbort #include "core\kernel\exports\EmuKrnlKe.h" #include "EmuKrnlKi.h" #include "core\kernel\support\Emu.h" // For EmuLog(LOG_LEVEL::WARNING, ) @@ -759,7 +759,7 @@ XBSYSAPI EXPORTNUM(197) xbox::ntstatus_xt NTAPI xbox::NtDuplicateObject } if (!X_NT_SUCCESS(status)) { - CxbxrKrnlAbort("NtDll::NtDuplicateObject failed to duplicate the handle 0x%.8X!", SourceHandle); + CxbxrAbort("NtDll::NtDuplicateObject failed to duplicate the handle 0x%.8X!", SourceHandle); } } @@ -1087,7 +1087,7 @@ XBSYSAPI EXPORTNUM(207) xbox::ntstatus_xt NTAPI xbox::NtQueryDirectoryFile NTSTATUS ret; if (FileInformationClass != FileDirectoryInformation) // Due to unicode->string conversion - CxbxrKrnlAbort("Unsupported FileInformationClass"); + CxbxrAbort("Unsupported FileInformationClass"); NtDll::UNICODE_STRING NtFileMask; diff --git a/src/core/kernel/exports/EmuKrnlOb.cpp b/src/core/kernel/exports/EmuKrnlOb.cpp index 72f544fe1..691ff9d21 100644 --- a/src/core/kernel/exports/EmuKrnlOb.cpp +++ b/src/core/kernel/exports/EmuKrnlOb.cpp @@ -38,7 +38,7 @@ #include // For ObDirectoryObjectType, etc. #include "Logging.h" // For LOG_FUNC() #include "EmuKrnlLogging.h" -#include "core\kernel\init\CxbxKrnl.h" // For CxbxrKrnlAbort +#include "core\kernel\init\CxbxKrnl.h" // For CxbxrAbort #include "EmuKrnl.h" // For OBJECT_TO_OBJECT_HEADER() #include "core\kernel\support\EmuFile.h" // For EmuNtSymbolicLinkObject, NtStatusToString(), etc. #include "core\kernel\support\NativeHandle.h" diff --git a/src/core/kernel/exports/EmuKrnlRtl.cpp b/src/core/kernel/exports/EmuKrnlRtl.cpp index dcb21cfb5..671cca6d5 100644 --- a/src/core/kernel/exports/EmuKrnlRtl.cpp +++ b/src/core/kernel/exports/EmuKrnlRtl.cpp @@ -40,7 +40,7 @@ namespace NtDll #include "core\kernel\support\EmuNtDll.h" }; -#include "core\kernel\init\CxbxKrnl.h" // For CxbxrKrnlAbort() +#include "core\kernel\init\CxbxKrnl.h" // For CxbxrAbort() #include "core\kernel\support\Emu.h" // For EmuLog(LOG_LEVEL::WARNING, ) #include @@ -752,7 +752,7 @@ XBSYSAPI EXPORTNUM(277) xbox::void_xt NTAPI xbox::RtlEnterCriticalSection ); if (!X_NT_SUCCESS(result)) { - CxbxrKrnlAbort("Waiting for event of a critical section returned %lx.", result); + CxbxrAbort("Waiting for event of a critical section returned %lx.", result); }; } CriticalSection->OwningThread = thread; diff --git a/src/core/kernel/exports/EmuKrnlXbox.cpp b/src/core/kernel/exports/EmuKrnlXbox.cpp index a3efffd23..12bd8a8e0 100644 --- a/src/core/kernel/exports/EmuKrnlXbox.cpp +++ b/src/core/kernel/exports/EmuKrnlXbox.cpp @@ -26,11 +26,7 @@ // * // ****************************************************************** -#define LOG_PREFIX CXBXR_MODULE::XBOX - - -#include // For XboxEEPROMKey, etc. -#include "Logging.h" +#include // For XboxEEPROMKey, etc. // Certificate Key // Not exported but used to generate per-title keys diff --git a/src/core/kernel/exports/EmuKrnlXe.cpp b/src/core/kernel/exports/EmuKrnlXe.cpp index e7e0258a0..44f97578c 100644 --- a/src/core/kernel/exports/EmuKrnlXe.cpp +++ b/src/core/kernel/exports/EmuKrnlXe.cpp @@ -30,11 +30,14 @@ #include // For XeImageFileName, etc. +#ifdef CXBXR_EMU #include "core\kernel\init\CxbxKrnl.h" // For CxbxKrnl_Xbe +#endif #include "Logging.h" // For LOG_FUNC() #include "EmuKrnlLogging.h" +#ifdef CXBXR_EMU #include "core\kernel\memory-manager\VMManager.h" - +#endif // ****************************************************************** // * 0x0146 - XeImageFileName // ****************************************************************** @@ -47,6 +50,8 @@ XBSYSAPI EXPORTNUM(326) xbox::OBJECT_STRING xbox::XeImageFileName = }; + +#ifdef CXBXR_EMU // ****************************************************************** // * 0x0147 - XeLoadSection() // ****************************************************************** @@ -161,6 +166,7 @@ XBSYSAPI EXPORTNUM(328) xbox::ntstatus_xt NTAPI xbox::XeUnloadSection RETURN(ret); } +#endif // ****************************************************************** // * 0x0163 - XePublicKeyData diff --git a/src/core/kernel/init/CxbxKrnl.cpp b/src/core/kernel/init/CxbxKrnl.cpp index ee3b485ca..fe97b968e 100644 --- a/src/core/kernel/init/CxbxKrnl.cpp +++ b/src/core/kernel/init/CxbxKrnl.cpp @@ -51,7 +51,6 @@ #include "core\hle\JVS\JVS.h" // For JVS_Init #endif #include "core\hle\Intercept.hpp" -#include "ReservedMemory.h" // For virtual_memory_placeholder #include "core\kernel\memory-manager\VMManager.h" #include "CxbxDebugger.h" #include "common/util/cliConfig.hpp" @@ -92,14 +91,10 @@ Xbe::Header *CxbxKrnl_XbeHeader = NULL; /*! indicates a debug kernel */ bool g_bIsDebugKernel = false; -HWND CxbxKrnl_hEmuParent = NULL; DebugMode CxbxrKrnl_DebugMode = DebugMode::DM_NONE; std::string CxbxrKrnl_DebugFileName = ""; Xbe::Certificate *g_pCertificate = NULL; -char szFilePath_CxbxReloaded_Exe[MAX_PATH] = { 0 }; -std::string g_DataFilePath; -char szFilePath_EEPROM_bin[MAX_PATH] = { 0 }; // Hybrid host/xbox path to the xbe. // A semicolon in the path indicates the Xbox mount point. // Replacing the ';' with '\' gives a regular host path. @@ -441,52 +436,6 @@ void ImportLibraries(XbeImportEntry *pImportDirectory) } } -bool CreateSettings() -{ - g_Settings = new Settings(); - if (g_Settings == nullptr) { - PopupError(nullptr, szSettings_alloc_error); - return false; - } - - if (!g_Settings->Init()) { - return false; - } - - log_get_settings(); - return true; -} - -bool HandleFirstLaunch() -{ - bool bFirstLaunch; - g_EmuShared->GetIsFirstLaunch(&bFirstLaunch); - - /* check if process is launch with elevated access then prompt for continue on or not. */ - if (!bFirstLaunch) { - if (!CreateSettings()) { - return false; - } - - // Wine will always run programs as administrator by default, it can be safely disregard. - // Since Wine doesn't use root permission. Unless user is running Wine as root. - bool bElevated = CxbxIsElevated(); - if (bElevated && !isWineEnv() && !g_Settings->m_core.allowAdminPrivilege) { - PopupReturn ret = PopupWarningEx(nullptr, PopupButtons::YesNo, PopupReturn::No, - "Cxbx-Reloaded has detected that it has been launched with Administrator rights.\n" - "\nThis is dangerous, as a maliciously modified Xbox titles could take control of your system.\n" - "\nAre you sure you want to continue?"); - if (ret != PopupReturn::Yes) { - return false; - } - } - - g_EmuShared->SetIsFirstLaunch(true); - } - - return true; -} - FILE* CxbxrKrnlSetupVerboseLog(int BootFlags) { std::string tempStr; @@ -565,7 +514,7 @@ static void CxbxrKrnlSyncGUI() if (mbRet == PopupReturn::Retry) { continue; } - CxbxKrnlShutDown(); + CxbxrShutDown(); } break; } while (true); @@ -579,7 +528,7 @@ static void CxbxrKrnlSetupMemorySystem(int BootFlags, unsigned emulate_system, u blocks_reserved_t blocks_reserved_gui = { 0 }; // Reserve console system's memory ranges before start initialize. if (!ReserveAddressRanges(emulate_system, blocks_reserved_gui)) { - CxbxrKrnlAbort("Failed to reserve required memory ranges!", GetLastError()); + CxbxrAbort("Failed to reserve required memory ranges!", GetLastError()); } // Initialize the memory manager g_VMManager.Initialize(emulate_system, BootFlags, blocks_reserved_gui); @@ -648,20 +597,20 @@ static bool CxbxrKrnlXbeSystemSelector(int BootFlags, unsigned& reserved_systems std::string chihiroMediaBoardRom = g_DataFilePath + "/EmuDisk/" + MediaBoardRomFile; if (!std::filesystem::exists(chihiroMediaBoardRom)) { - CxbxrKrnlAbort("Chihiro Media Board ROM (fpr21042_m29w160et.bin) could not be found"); + CxbxrAbort("Chihiro Media Board ROM (fpr21042_m29w160et.bin) could not be found"); } // Open a handle to the mediaboard rom FILE* fpRom = fopen(chihiroMediaBoardRom.c_str(), "rb"); if (fpRom == nullptr) { - CxbxrKrnlAbort("Chihiro Media Board ROM (fpr21042_m29w160et.bin) could not opened for read"); + CxbxrAbort("Chihiro Media Board ROM (fpr21042_m29w160et.bin) could not opened for read"); } // Verify the size of media board rom fseek(fpRom, 0, SEEK_END); auto length = ftell(fpRom); if (length != 2 * ONE_MB) { - CxbxrKrnlAbort("Chihiro Media Board ROM (fpr21042_m29w160et.bin) has an invalid size"); + CxbxrAbort("Chihiro Media Board ROM (fpr21042_m29w160et.bin) has an invalid size"); } fseek(fpRom, 0, SEEK_SET); @@ -674,14 +623,14 @@ static bool CxbxrKrnlXbeSystemSelector(int BootFlags, unsigned& reserved_systems FILE* fpSegaBootOld = fopen(chihiroSegaBootOld.c_str(), "wb"); FILE* fpSegaBootNew = fopen(chihiroSegaBootNew.c_str(), "wb"); if (fpSegaBootNew == nullptr || fpSegaBootOld == nullptr) { - CxbxrKrnlAbort("Could not open SEGABOOT for writing"); + CxbxrAbort("Could not open SEGABOOT for writing"); } // Extract SEGABOOT (Old) void* buffer = malloc(ONE_MB); if (buffer == nullptr) { - CxbxrKrnlAbort("Could not allocate buffer for SEGABOOT"); + CxbxrAbort("Could not allocate buffer for SEGABOOT"); } @@ -704,7 +653,7 @@ static bool CxbxrKrnlXbeSystemSelector(int BootFlags, unsigned& reserved_systems // Launch Segaboot CxbxLaunchNewXbe(chihiroSegaBootNew); - CxbxKrnlShutDown(true); + CxbxrShutDown(true); } #endif // Chihiro wip block @@ -712,7 +661,7 @@ static bool CxbxrKrnlXbeSystemSelector(int BootFlags, unsigned& reserved_systems CxbxKrnl_Xbe = new Xbe(xbePath.c_str(), false); // TODO : Instead of using the Xbe class, port Dxbx _ReadXbeBlock() if (CxbxKrnl_Xbe->HasFatalError()) { - CxbxrKrnlAbort(CxbxKrnl_Xbe->GetError().c_str()); + CxbxrAbort(CxbxKrnl_Xbe->GetError().c_str()); return false; } @@ -770,7 +719,7 @@ static bool CxbxrKrnlXbeSystemSelector(int BootFlags, unsigned& reserved_systems EmuLogInit(LOG_LEVEL::INFO, "Host's compatible system types: %2X", reserved_systems); // If the system to emulate isn't supported on host, enforce failure. if (!isSystemFlagSupport(reserved_systems, emulate_system)) { - CxbxrKrnlAbort("Unable to emulate system type due to host is not able to reserve required memory ranges."); + CxbxrAbort("Unable to emulate system type due to host is not able to reserve required memory ranges."); return false; } // Clear emulation system from reserved systems so all unneeded memory ranges can be freed. @@ -795,7 +744,7 @@ static bool CxbxrKrnlXbeSystemSelector(int BootFlags, unsigned& reserved_systems } #else if (g_bIsChihiro) { - CxbxrKrnlAbort("Emulating Chihiro mode does not work yet. Please use different title to emulate."); + CxbxrAbort("Emulating Chihiro mode does not work yet. Please use different title to emulate."); } #endif @@ -835,7 +784,7 @@ static size_t CxbxrKrnlGetRelativePath(std::filesystem::path& get_relative_path) // Then we must obey the current directory it asked for. if (lastFind != std::string::npos) { if (relative_path.find(';', lastFind + 1) != std::string::npos) { - CxbxrKrnlAbortEx(LOG_PREFIX_INIT, "Cannot contain multiple of ; symbol."); + CxbxrAbortEx(LOG_PREFIX_INIT, "Cannot contain multiple of ; symbol."); } relative_path = relative_path.substr(0, lastFind); } @@ -939,15 +888,6 @@ static bool CxbxrKrnlPrepareXbeMap() return false; // TODO : Halt(0); } -#ifndef CXBXR_EMU - // verify virtual_memory_placeholder is located at 0x00011000 - if ((UINT_PTR)(&(virtual_memory_placeholder[0])) != (XBE_IMAGE_BASE + CXBX_BASE_OF_CODE)) - { - PopupFatal(nullptr, "virtual_memory_placeholder is not loaded to base address 0x00011000 (which is a requirement for Xbox emulation)"); - return false; // TODO : Halt(0); - } -#endif - // Create a safe copy of the complete EXE header: DWORD ExeHeaderSize = ExeOptionalHeader->SizeOfHeaders; // Should end up as 0x400 NewDosHeader = (PIMAGE_DOS_HEADER)VirtualAlloc(nullptr, ExeHeaderSize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); @@ -1021,7 +961,7 @@ void CxbxKrnlEmulate(unsigned int reserved_systems, blocks_reserved_t blocks_res // and capture any crash from this point and beyond. Useful for capture live crash and generate crash report. g_ExceptionManager = new ExceptionManager(); - // Set current process handle in order for CxbxKrnlShutDown to work properly. + // Set current process handle in order for CxbxrShutDown to work properly. g_CurrentProcessHandle = GetCurrentProcess(); // OpenProcess(PROCESS_ALL_ACCESS, FALSE, GetCurrentProcessId()); // First of all, check if the EmuShared version matches the emu version and abort otherwise @@ -1030,7 +970,7 @@ void CxbxKrnlEmulate(unsigned int reserved_systems, blocks_reserved_t blocks_res if (std::strncmp(GitVersionEmuShared, GetGitVersionStr(), GetGitVersionLength()) != 0) { PopupError(nullptr, "Mismatch detected between EmuShared and cxbx.exe/cxbxr-emu.dll, aborting." "\n\nPlease extract all contents from zip file and do not mix with older/newer builds."); - CxbxKrnlShutDown(); + CxbxrShutDown(); return; } @@ -1111,13 +1051,11 @@ void CxbxKrnlEmulate(unsigned int reserved_systems, blocks_reserved_t blocks_res } if (dwExitCode != EXIT_SUCCESS) {// Stop emulation - CxbxKrnlShutDown(); + CxbxrShutDown(); } /* Must be called after CxbxrInitFilePaths and previous kernel process shutdown. */ - if (!CxbxLockFilePath()) { - return; - } + CxbxrLockFilePath(); FILE* krnlLog = CxbxrKrnlSetupVerboseLog(BootFlags); @@ -1417,7 +1355,7 @@ static void CxbxrKrnlInitHacks() // CxbxInitWindow because that function creates the xbox EmuUpdateTickCount thread EmuGenerateFS(xbox::zeroptr, Host2XbStackBaseReserved, Host2XbStackSizeReserved); if (!xbox::ObInitSystem()) { - CxbxrKrnlAbortEx(LOG_PREFIX_INIT, "Unable to intialize ObInitSystem."); + CxbxrAbortEx(LOG_PREFIX_INIT, "Unable to intialize ObInitSystem."); } xbox::PsInitSystem(); xbox::KiInitSystem(); @@ -1540,7 +1478,7 @@ static void CxbxrKrnlInitHacks() } };*/ -[[noreturn]] void CxbxrKrnlAbortEx(CXBXR_MODULE cxbxr_module, const char *szErrorMessage, ...) +[[noreturn]] void CxbxrAbortEx(CXBXR_MODULE cxbxr_module, const char *szErrorMessage, ...) { g_bEmuException = true; @@ -1570,7 +1508,7 @@ static void CxbxrKrnlInitHacks() freopen("nul", "w", stdout); } - CxbxKrnlShutDown(); + CxbxrShutDown(); } void CxbxrKrnlSuspendThreads() @@ -1619,7 +1557,7 @@ void CxbxrKrnlSuspendThreads() } } -void CxbxKrnlShutDown(bool is_reboot) +void CxbxrShutDown(bool is_reboot) { if (!is_reboot) { // Clear all kernel boot flags. These (together with the shared memory) persist until Cxbx-Reloaded is closed otherwise. @@ -1656,7 +1594,7 @@ void CxbxKrnlShutDown(bool is_reboot) // Shutdown the memory manager g_VMManager.Shutdown(); - CxbxUnlockFilePath(); + CxbxrUnlockFilePath(); if (CxbxKrnl_hEmuParent != NULL && !is_reboot) { SendMessage(CxbxKrnl_hEmuParent, WM_PARENTNOTIFY, WM_DESTROY, 0); @@ -1699,13 +1637,13 @@ void CxbxKrnlPrintUEM(ULONG ErrorCode) xbox::ExSaveNonVolatileSetting(xbox::XC_MAX_ALL, Type, &Eeprom, sizeof(Eeprom)); } else { - CxbxrKrnlAbort("Could not display the fatal error screen"); + CxbxrAbort("Could not display the fatal error screen"); } if (g_bIsChihiro) { // The Chihiro doesn't display the UEM - CxbxrKrnlAbort("The running Chihiro xbe has encountered a fatal error and needs to close"); + CxbxrAbort("The running Chihiro xbe has encountered a fatal error and needs to close"); } g_CxbxFatalErrorCode = ErrorCode; @@ -1759,5 +1697,5 @@ void CxbxPrintUEMInfo(ULONG ErrorCode) void CxbxKrnlPanic() { - CxbxrKrnlAbort("Kernel Panic!"); + CxbxrAbort("Kernel Panic!"); } diff --git a/src/core/kernel/init/CxbxKrnl.h b/src/core/kernel/init/CxbxKrnl.h index 2de3a0e27..0a1a46fc4 100644 --- a/src/core/kernel/init/CxbxKrnl.h +++ b/src/core/kernel/init/CxbxKrnl.h @@ -26,6 +26,7 @@ #define CXBXKRNL_H #include "Cxbx.h" +#include "common/cxbxr.hpp" #include "common\AddressRanges.h" #include "common/ReserveAddressRanges.h" #include "common\xbe\Xbe.h" @@ -139,21 +140,9 @@ extern Xbe::Certificate *g_pCertificate; extern bool g_bIsDebugKernel; -bool CreateSettings(); - -bool HandleFirstLaunch(); - /*! Cxbx Kernel Entry Point */ void CxbxKrnlEmulate(unsigned int system, blocks_reserved_t blocks_reserved); -/*! cleanup emulation */ -[[noreturn]] void CxbxrKrnlAbortEx(CXBXR_MODULE cxbxr_module, const char *szErrorMessage, ...); - -#define CxbxrKrnlAbort(fmt, ...) CxbxrKrnlAbortEx(LOG_PREFIX, fmt, ##__VA_ARGS__) - -/*! terminate gracefully the emulation */ -[[noreturn]] void CxbxKrnlShutDown(bool is_reboot = false); - /*! display the fatal error message*/ void CxbxKrnlPrintUEM(ULONG ErrorCode); @@ -168,10 +157,6 @@ void CxbxKrnlNoFunc(); void CxbxInitPerformanceCounters(); // Implemented in EmuKrnlKe.cpp -void CxbxrInitFilePaths(); - -bool CxbxIsElevated(); - /*! kernel thunk table */ extern uint32_t CxbxKrnl_KernelThunkTable[379]; @@ -196,17 +181,12 @@ extern Xbe *CxbxKrnl_Xbe; extern HWND CxbxKrnl_hEmuParent; /*! file paths */ -extern char szFilePath_CxbxReloaded_Exe[MAX_PATH]; -extern std::string g_DataFilePath; -extern char szFilePath_EEPROM_bin[MAX_PATH]; extern char szFilePath_Xbe[xbox::max_path*2]; #ifdef __cplusplus } #endif -std::optional CxbxExec(bool useDebugger, HANDLE *hProcess, bool requestHandleProcess); - // Returns the last Win32 error, in string format. Returns an empty string if there is no error. extern std::string CxbxGetLastErrorString(char * lpszFunction); diff --git a/src/core/kernel/memory-manager/PoolManager.cpp b/src/core/kernel/memory-manager/PoolManager.cpp index e0c727843..212ab0b62 100644 --- a/src/core/kernel/memory-manager/PoolManager.cpp +++ b/src/core/kernel/memory-manager/PoolManager.cpp @@ -259,7 +259,7 @@ void PoolManager::DeallocatePool(VAddr addr) assert((Entry->PoolType & POOL_TYPE_MASK) != 0); if (!IS_POOL_HEADER_MARKED_ALLOCATED(Entry)) { - CxbxrKrnlAbort("Pool at address 0x%X is already free!", addr); + CxbxrAbort("Pool at address 0x%X is already free!", addr); } MARK_POOL_HEADER_FREED(Entry); diff --git a/src/core/kernel/memory-manager/VMManager.cpp b/src/core/kernel/memory-manager/VMManager.cpp index cf5979666..284119375 100644 --- a/src/core/kernel/memory-manager/VMManager.cpp +++ b/src/core/kernel/memory-manager/VMManager.cpp @@ -104,7 +104,7 @@ void VMManager::Initialize(unsigned int SystemType, int BootFlags, blocks_reserv for (int i = 0; i < 64; i++) { LPVOID ret = VirtualAlloc((LPVOID)(PAGE_TABLES_BASE + i * m_AllocationGranularity), m_AllocationGranularity, MEM_COMMIT, PAGE_READWRITE); if (ret != (LPVOID)(PAGE_TABLES_BASE + i * KiB(64))) { - CxbxrKrnlAbort("VirtualAlloc failed to commit the memory for the page tables. The error was 0x%08X", GetLastError()); + CxbxrAbort("VirtualAlloc failed to commit the memory for the page tables. The error was 0x%08X", GetLastError()); } } @@ -293,14 +293,14 @@ void VMManager::InitializeSystemAllocations() void VMManager::GetPersistentMemory() { if (m_PersistentMemoryHandle != nullptr) { - CxbxrKrnlAbort("Persistent memory is already opened!"); + CxbxrAbort("Persistent memory is already opened!"); return; } std::string persisted_mem_sid = str_persistent_memory_s + std::to_string(cli_config::GetSessionID()); m_PersistentMemoryHandle = OpenFileMapping(FILE_MAP_READ, FALSE, persisted_mem_sid.c_str()); if (m_PersistentMemoryHandle == nullptr) { - CxbxrKrnlAbort("Couldn't open persistent memory! OpenFileMapping failed with error 0x%08X", GetLastError()); + CxbxrAbort("Couldn't open persistent memory! OpenFileMapping failed with error 0x%08X", GetLastError()); return; } } @@ -308,13 +308,13 @@ void VMManager::GetPersistentMemory() void VMManager::RestorePersistentMemory() { if (m_PersistentMemoryHandle == nullptr) { - CxbxrKrnlAbort("Persistent memory is not open!"); + CxbxrAbort("Persistent memory is not open!"); return; } PersistedMemory* persisted_mem = (PersistedMemory*)MapViewOfFile(m_PersistentMemoryHandle, FILE_MAP_READ, 0, 0, 0); if (persisted_mem == nullptr) { - CxbxrKrnlAbort("Couldn't restore persistent memory! MapViewOfFile failed with error 0x%08X", GetLastError()); + CxbxrAbort("Couldn't restore persistent memory! MapViewOfFile failed with error 0x%08X", GetLastError()); return; } @@ -457,12 +457,12 @@ void VMManager::SavePersistentMemory() std::string persistent_mem_sid = str_persistent_memory_s + std::to_string(cli_config::GetSessionID()); m_PersistentMemoryHandle = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, num_persisted_ptes * PAGE_SIZE + num_persisted_ptes * 4 * 2 + sizeof(PersistedMemory), persistent_mem_sid.c_str()); if (m_PersistentMemoryHandle == NULL) { - CxbxrKrnlAbort("Couldn't persist memory! CreateFileMapping failed with error 0x%08X", GetLastError()); + CxbxrAbort("Couldn't persist memory! CreateFileMapping failed with error 0x%08X", GetLastError()); return; } addr = MapViewOfFile(m_PersistentMemoryHandle, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0); if (addr == nullptr) { - CxbxrKrnlAbort("Couldn't persist memory! MapViewOfFile failed with error 0x%08X", GetLastError()); + CxbxrAbort("Couldn't persist memory! MapViewOfFile failed with error 0x%08X", GetLastError()); return; } diff --git a/src/core/kernel/support/Emu.cpp b/src/core/kernel/support/Emu.cpp index 01b919af2..0c11fa848 100644 --- a/src/core/kernel/support/Emu.cpp +++ b/src/core/kernel/support/Emu.cpp @@ -45,7 +45,6 @@ CRITICAL_SECTION dbgCritical; // Global Variable(s) volatile thread_local bool g_bEmuException = false; static thread_local bool bOverrideEmuException; -volatile bool g_bPrintfOn = true; bool g_DisablePixelShaders = false; bool g_UseAllCores = false; bool g_SkipRdtscPatching = false; @@ -58,33 +57,6 @@ std::atomic_int64_t HostSystemTimeDelta(0); // Static Function(s) static int ExitException(LPEXCEPTION_POINTERS e); -std::string FormatTitleId(uint32_t title_id) -{ - std::stringstream ss; - - // If the Title ID prefix is a printable character, parse it - // This shows the correct game serial number for retail titles! - // EG: MS-001 for 1st tile published by MS, EA-002 for 2nd title by EA, etc - // Some special Xbes (Dashboard, XDK Samples) use non-alphanumeric serials - // We fall back to Hex for those - // ergo720: we cannot use isalnum() here because it will treat chars in the range -1 - 255 as valid ascii chars which can - // lead to unicode characters being printed in the title (e.g.: dashboard uses 0xFE and 0xFF) - uint8_t pTitleId1 = (title_id >> 24) & 0xFF; - uint8_t pTitleId2 = (title_id >> 16) & 0xFF; - - if ((pTitleId1 < 65 || pTitleId1 > 90) || (pTitleId2 < 65 || pTitleId2 > 90)) { - // Prefix was non-printable, so we need to print a hex reprentation of the entire title_id - ss << std::setfill('0') << std::setw(8) << std::hex << std::uppercase << title_id; - return ss.str(); - } - - ss << pTitleId1 << pTitleId2; - ss << "-"; - ss << std::setfill('0') << std::setw(3) << std::dec << (title_id & 0x0000FFFF); - - return ss.str(); -} - std::string EIPToString(xbox::addr_xt EIP) { char buffer[256]; diff --git a/src/core/kernel/support/EmuFile.cpp b/src/core/kernel/support/EmuFile.cpp index 4bab36358..3f79a18a8 100644 --- a/src/core/kernel/support/EmuFile.cpp +++ b/src/core/kernel/support/EmuFile.cpp @@ -26,6 +26,7 @@ // ****************************************************************** #define LOG_PREFIX CXBXR_MODULE::FILE +#define LOG_PREFIX_INIT CXBXR_MODULE::INIT #include "EmuFile.h" #include @@ -43,6 +44,8 @@ #include "common/util/cliConfig.hpp" #include "common/CxbxDebugger.h" #include "EmuShared.h" +#include "common/FilePaths.hpp" +#include "common/cxbxr.hpp" #include @@ -50,8 +53,6 @@ HANDLE g_hCurDir_hack = NULL; // HACK: We should not be depending on this variable. Instead, we should fix/implement Ob/Io objects such as IoCreateDevice. HANDLE g_DiskBasePathHandle; -std::string g_DiskBasePath; -std::string g_MuBasePath; // Default Xbox Partition Table #define PE_PARTFLAGS_IN_USE 0x80000000 @@ -98,7 +99,7 @@ io_mu_metadata::io_mu_metadata(const std::wstring_view root_path) : m_root_path( std::wstring path = m_root_path + static_cast(L'F' + i) + L".bin"; std::fstream fs(path, std::ios_base::in | std::ios_base::out | std::ios_base::binary); if (!fs.is_open()) { - CxbxrKrnlAbort("%s: could not open MU bin file at \"%ls\"!", __func__, path.c_str()); + CxbxrAbort("%s: could not open MU bin file at \"%ls\"!", __func__, path.c_str()); } fs.seekg(0); fs.read(m_buff[i], sizeof(FATX_SUPERBLOCK)); @@ -209,7 +210,7 @@ void CxbxCreatePartitionHeaderFile(std::string filename, bool partition0 = false { HANDLE hf = CreateFile(filename.c_str(), GENERIC_WRITE, 0, 0, CREATE_ALWAYS, 0, 0); if (!hf) { - CxbxrKrnlAbort("CxbxCreatePartitionHeaderFile Failed\nUnable to create file: %s (%s)", filename.c_str()); + CxbxrAbort("CxbxCreatePartitionHeaderFile Failed\nUnable to create file: %s (%s)", filename.c_str()); return; } @@ -229,7 +230,7 @@ XboxPartitionTable CxbxGetPartitionTable() XboxPartitionTable table; FILE* fp = fopen((g_DiskBasePath + "Partition0.bin").c_str(), "rb"); if (fp == nullptr) { - CxbxrKrnlAbort("CxbxGetPartitionTable Failed:\nUnable to open file: %s", (g_DiskBasePath + "Partition0.bin").c_str()); + CxbxrAbort("CxbxGetPartitionTable Failed:\nUnable to open file: %s", (g_DiskBasePath + "Partition0.bin").c_str()); } fread(&table, sizeof(XboxPartitionTable), 1, fp); @@ -267,7 +268,7 @@ std::wstring CxbxGetFinalPathNameByHandle(HANDLE hFile) DWORD size = GetFinalPathNameByHandleW(hFile, path.data(), INITIAL_BUF_SIZE, VOLUME_NAME_DOS); if (size == 0) { - CxbxrKrnlAbort("CxbxGetPartitionNumberFromHandle Failed:\nUnable to determine path for HANDLE 0x%08X", hFile); + CxbxrAbort("CxbxGetPartitionNumberFromHandle Failed:\nUnable to determine path for HANDLE 0x%08X", hFile); } // If the function fails because lpszFilePath is too small to hold the string plus the terminating null character, @@ -581,7 +582,7 @@ NTSTATUS CxbxConvertFilePath( RelativePath.erase(0, 5); // Remove '$HOME' } else - CxbxrKrnlAbort(("Unsupported path macro : " + OriginalPath).c_str()); + CxbxrAbort(("Unsupported path macro : " + OriginalPath).c_str()); } // Check if the path starts with a relative path indicator : else if (RelativePath[0] == '.') {// "4x4 Evo 2" needs this @@ -933,7 +934,7 @@ NTSTATUS EmuNtSymbolicLinkObject::Init(std::string aSymbolicLinkName, std::strin if (RootDirectoryHandle == INVALID_HANDLE_VALUE) { result = STATUS_DEVICE_DOES_NOT_EXIST; // TODO : Is this the correct error? - CxbxrKrnlAbort((std::string("Could not map ") + HostSymbolicLinkPath).c_str()); + CxbxrAbort((std::string("Could not map ") + HostSymbolicLinkPath).c_str()); } else { @@ -1316,7 +1317,7 @@ void CxbxLaunchNewXbe(const std::string& XbePath) { std::string cliCommands; if (!cli_config::GenCMD(cliCommands)) { - CxbxrKrnlAbort("Could not launch %s", XbePath.c_str()); + CxbxrAbort("Could not launch %s", XbePath.c_str()); } CxbxDebugger::ReportNewTarget(cliCommands.c_str()); @@ -1325,9 +1326,9 @@ void CxbxLaunchNewXbe(const std::string& XbePath) { } else { - if (const auto &err = CxbxExec(false, nullptr, false)) + if (const auto &err = CxbxrExec(false, nullptr, false)) { - CxbxrKrnlAbort("Could not launch %s\n\nThe reason was: %s", XbePath.c_str(), err->c_str()); + CxbxrAbort("Could not launch %s\n\nThe reason was: %s", XbePath.c_str(), err->c_str()); } } diff --git a/src/core/kernel/support/NativeHandle.cpp b/src/core/kernel/support/NativeHandle.cpp index b0be69a45..9474c52ba 100644 --- a/src/core/kernel/support/NativeHandle.cpp +++ b/src/core/kernel/support/NativeHandle.cpp @@ -61,7 +61,7 @@ void RegisterXboxHandle(xbox::HANDLE xhandle, HANDLE nhandle) // If we reach here, it means that we could not insert the handle after more than two seconds of trying. This probably means // that we have forgotten to call RemoveXboxHandle on the old handle, or the other thread is waiting/deadlocked, so this is a bug - CxbxrKrnlAbortEx(CXBXR_MODULE::CXBXR, "Failed to register new xbox handle after more than two seconds!"); + CxbxrAbortEx(CXBXR_MODULE::CXBXR, "Failed to register new xbox handle after more than two seconds!"); } } diff --git a/src/devices/SMCDevice.cpp b/src/devices/SMCDevice.cpp index f4ff7b169..7dbfb8eaf 100644 --- a/src/devices/SMCDevice.cpp +++ b/src/devices/SMCDevice.cpp @@ -153,7 +153,7 @@ void SMCDevice::WriteByte(uint8_t command, uint8_t value) switch (value) { case SMC_RESET_ASSERT_RESET: return; // TODO case SMC_RESET_ASSERT_POWERCYCLE: return; // TODO - case SMC_RESET_ASSERT_SHUTDOWN: CxbxKrnlShutDown(); return; // Power off, terminating the emulation + case SMC_RESET_ASSERT_SHUTDOWN: CxbxrShutDown(); return; // Power off, terminating the emulation } //case SMC_COMMAND_POWER_FAN_MODE: // 0x05 // power fan mode(0 = automatic; 1 = custom speed from reg 0x06) //case SMC_COMMAND_POWER_FAN_REGISTER: // 0x06 // Set custom power fan speed (0-50) diff --git a/src/devices/usb/OHCI.cpp b/src/devices/usb/OHCI.cpp index 0a5976c5f..875aae5d1 100644 --- a/src/devices/usb/OHCI.cpp +++ b/src/devices/usb/OHCI.cpp @@ -335,7 +335,7 @@ void OHCI::OHCI_FrameBoundaryWorker() if (!m_Registers.HcDoneHead) { // From the OHCI standard: "This is set to zero whenever HC writes the content of this // register to HCCA. It also sets the WritebackDoneHead of HcInterruptStatus." - CxbxrKrnlAbort("HcDoneHead is zero but WritebackDoneHead interrupt is not set!\n"); + CxbxrAbort("HcDoneHead is zero but WritebackDoneHead interrupt is not set!\n"); } if (m_Registers.HcInterrupt & m_Registers.HcInterruptStatus) { @@ -372,7 +372,7 @@ void OHCI::OHCI_FrameBoundaryWorker() void OHCI::OHCI_FatalError() { // According to the standard, an OHCI will stop operating, and set itself into error state - // (which can be queried by MMIO). Instead of calling directly CxbxrKrnlAbort, we let the + // (which can be queried by MMIO). Instead of calling directly CxbxrAbort, we let the // HCD know the problem so that it can try to solve it OHCI_SetInterrupt(OHCI_INTR_UE); diff --git a/src/devices/usb/USBDevice.cpp b/src/devices/usb/USBDevice.cpp index 4073cece0..00597fbee 100644 --- a/src/devices/usb/USBDevice.cpp +++ b/src/devices/usb/USBDevice.cpp @@ -486,7 +486,7 @@ void USBDevice::USB_PacketCopy(USBPacket* p, void* ptr, size_t bytes) IoVecFromBuffer(iov->IoVecStruct, iov->IoVecNumber, p->ActualLength, ptr, bytes); break; default: - CxbxrKrnlAbort("%s has an invalid pid: %x\n", __func__, p->Pid); + CxbxrAbort("%s has an invalid pid: %x\n", __func__, p->Pid); } p->ActualLength += bytes; } diff --git a/src/devices/video/nv2a.cpp b/src/devices/video/nv2a.cpp index ab1da9d7c..6c0e62aa0 100644 --- a/src/devices/video/nv2a.cpp +++ b/src/devices/video/nv2a.cpp @@ -1137,7 +1137,7 @@ void CxbxReserveNV2AMemory(NV2AState *d) for (int i = 0; i < 16; i++) { LPVOID ret = VirtualAlloc((LPVOID)(NV2A_ADDR + NV_PRAMIN_ADDR + i * 64 * ONE_KB), 64 * ONE_KB, MEM_COMMIT, PAGE_READWRITE); if (ret != (LPVOID)(NV2A_ADDR + NV_PRAMIN_ADDR + i * 64 * ONE_KB)) { - CxbxrKrnlAbort("VirtualAlloc failed to commit the memory for the nv2a pramin. The error was 0x%08X", GetLastError()); + CxbxrAbort("VirtualAlloc failed to commit the memory for the nv2a pramin. The error was 0x%08X", GetLastError()); } } diff --git a/src/gui/DlgEepromConfig.cpp b/src/gui/DlgEepromConfig.cpp index 17bc59d58..90eb987eb 100644 --- a/src/gui/DlgEepromConfig.cpp +++ b/src/gui/DlgEepromConfig.cpp @@ -30,9 +30,10 @@ #include #include // For memcpy #include "EmuEEPROM.h" // For EEPROMInfo, EEPROMInfos -#include "core\kernel\init\CxbxKrnl.h" +#include "core/kernel/support/EmuFile.h" #include "DlgEepromConfig.h" #include "resource/ResCxbx.h" +#include "common/FilePaths.hpp" #include "common/Logging.h" #include diff --git a/src/gui/WinMain.cpp b/src/gui/WinMain.cpp index 41b4b20a0..1e52033d1 100644 --- a/src/gui/WinMain.cpp +++ b/src/gui/WinMain.cpp @@ -29,8 +29,8 @@ #include "WndMain.h" +#include "common/cxbxr.hpp" #include "AddressRanges.h" // For VerifyWow64() -#include "VerifyAddressRanges.h" // For VerifyBaseAddr() #include "core\kernel\init\CxbxKrnl.h" #include "core\kernel\support\Emu.h" #include "EmuShared.h" @@ -38,6 +38,7 @@ #include #include "common/util/cliConverter.hpp" #include "common/util/cliConfig.hpp" +#include "common/FilePaths.hpp" // Enable Visual Styles @@ -58,14 +59,6 @@ int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine return EXIT_FAILURE; } -#ifndef CXBXR_EMU - /*! verify Cxbx.exe is loaded to base address 0x00010000 */ - if (!VerifyBaseAddr()) { - PopupError(nullptr, "Cxbx.exe is not loaded to base address 0x00010000, which is a requirement for Xbox emulation."); - return EXIT_FAILURE; - } -#endif - if (!cli_config::GenConfig(__argv, __argc)) { PopupError(nullptr, "Couldn't convert parsed command line!"); return EXIT_FAILURE; @@ -83,15 +76,9 @@ int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine } if (cli_config::hasKey("load")) { -#ifndef CXBXR_EMU - CxbxKrnlEmulate(0, nullptr); - EmuShared::Cleanup(); - return EXIT_SUCCESS; -#else PopupError(nullptr, "Emulation must be launched from cxbxr-ldr.exe!"); EmuShared::Cleanup(); return EXIT_FAILURE; -#endif } // If 2nd GUI executable is launched, load settings file for GUI for editable support. diff --git a/src/gui/WndMain.cpp b/src/gui/WndMain.cpp index f9e489e42..3aec49882 100644 --- a/src/gui/WndMain.cpp +++ b/src/gui/WndMain.cpp @@ -29,6 +29,8 @@ #define LOG_PREFIX CXBXR_MODULE::GUI +#include "common/cxbxr.hpp" // for CxbxrExec + #include "Logging.h" #include "WndMain.h" #include "DlgAbout.h" @@ -45,8 +47,8 @@ #include "common\Settings.hpp" #include "common/util/cliConfig.hpp" #include "common/win32/WineEnv.h" +#include "common/xbe/XbePrinter.h" // for FormatTitleId -#include "core\kernel\init\CxbxKrnl.h" // For CxbxExec #include "resource/ResCxbx.h" #include "CxbxVersion.h" #include "Shlwapi.h" @@ -1225,12 +1227,6 @@ LRESULT CALLBACK WndMain::WndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lP } break; #endif - case ID_USELOADEREXEC: - { - g_Settings->m_core.bUseLoaderExec = !g_Settings->m_core.bUseLoaderExec; - RefreshMenus(); - } - break; case ID_EMULATION_START: if (m_Xbe != nullptr) @@ -1693,9 +1689,6 @@ void WndMain::RefreshMenus() //chk_flag = (g_Settings->m_core.FlagsLLE & LLE_USB) ? MF_CHECKED : MF_UNCHECKED; // Reenable this when LLE USB actually works //CheckMenuItem(settings_menu, ID_EMULATION_LLE_USB, chk_flag); - chk_flag = g_Settings->m_core.bUseLoaderExec ? MF_CHECKED : MF_UNCHECKED; - CheckMenuItem(settings_menu, ID_USELOADEREXEC, chk_flag); - chk_flag = (g_Settings->m_hacks.DisablePixelShaders) ? MF_CHECKED : MF_UNCHECKED; CheckMenuItem(settings_menu, ID_HACKS_DISABLEPIXELSHADERS, chk_flag); @@ -1853,8 +1846,6 @@ void WndMain::UpdateRecentFiles() } } -extern std::string FormatTitleId(uint32_t title_id); - void WndMain::UpdateCaption() { char AsciiTitle[MAX_PATH]; @@ -2233,10 +2224,8 @@ void WndMain::StartEmulation(HWND hwndParent, DebuggerState LocalDebuggerState / char szExeFileName[MAX_PATH]; GetModuleFileName(GetModuleHandle(nullptr), szExeFileName, MAX_PATH); - if (g_Settings->m_core.bUseLoaderExec) { - PathRemoveFileSpec(szExeFileName); - PathAppend(szExeFileName, "\\cxbxr-ldr.exe"); - } + PathRemoveFileSpec(szExeFileName); + PathAppend(szExeFileName, "\\cxbxr-ldr.exe"); bool AttachLocalDebugger = (LocalDebuggerState == debuggerOn); g_EmuShared->SetDebuggingFlag(AttachLocalDebugger); @@ -2260,7 +2249,7 @@ void WndMain::StartEmulation(HWND hwndParent, DebuggerState LocalDebuggerState / // Check then close existing debugger monitor. DebuggerMonitorClose(); - if (CxbxExec(true, &m_hDebuggerProc, true)) { + if (CxbxrExec(true, &m_hDebuggerProc, true)) { PopupError(m_hwnd, "Failed to start emulation with the debugger.\n\nYou will need to build CxbxDebugger manually."); printf("WndMain: %s debugger shell failed.\n", m_Xbe->m_szAsciiTitle); @@ -2273,7 +2262,7 @@ void WndMain::StartEmulation(HWND hwndParent, DebuggerState LocalDebuggerState / } else { - if (const auto &err = CxbxExec(false, nullptr, false)) { + if (const auto &err = CxbxrExec(false, nullptr, false)) { PopupError(m_hwnd, err->c_str()); printf("WndMain: %s shell failed.\n", m_Xbe->m_szAsciiTitle); @@ -2318,8 +2307,6 @@ void WndMain::StopEmulation() // wrapper function to call CrashMonitor DWORD WndMain::CrashMonitorWrapper(LPVOID lpParam) { - CxbxSetThreadName("Cxbx Crash Monitor"); - Crash_Manager_Data* pCMD = (Crash_Manager_Data*)lpParam; static_cast(pCMD->pWndMain)->m_iIsEmulating++; // Multi-xbe boots usage check static_cast(pCMD->pWndMain)->CrashMonitor(pCMD->dwChildProcID); @@ -2377,7 +2364,6 @@ void WndMain::CrashMonitor(DWORD dwChildProcID) // monitor for Debugger to close then set as "available" (For limit to 1 debugger per Cxbx GUI.) DWORD WndMain::DebuggerMonitor(LPVOID lpVoid) { - CxbxSetThreadName("Cxbx Debugger Monitor"); WndMain* pThis = static_cast(lpVoid); if (pThis->m_hDebuggerProc != nullptr) { diff --git a/src/gui/resource/Cxbx.rc b/src/gui/resource/Cxbx.rc index f879eca1c..56b95e61e 100644 --- a/src/gui/resource/Cxbx.rc +++ b/src/gui/resource/Cxbx.rc @@ -792,7 +792,6 @@ BEGIN MENUITEM "Disable Pixel Shaders", ID_HACKS_DISABLEPIXELSHADERS,MFT_STRING,MFS_ENABLED MENUITEM "Skip rdtsc patching", ID_HACKS_SKIPRDTSCPATCHING,MFT_STRING,MFS_ENABLED END - MENUITEM "Use Loader Executable", ID_USELOADEREXEC,MFT_STRING,MFS_ENABLED MENUITEM "Ignore Invalid Xbe Signature", ID_SETTINGS_IGNOREINVALIDXBESIG,MFT_STRING,MFS_ENABLED MENUITEM "Ignore Invalid Xbe Sections", ID_SETTINGS_IGNOREINVALIDXBESEC,MFT_STRING,MFS_ENABLED MENUITEM "Allow Admin Privilege", ID_SETTINGS_ALLOWADMINPRIVILEGE,MFT_STRING,MFS_ENABLED diff --git a/src/gui/resource/ResCxbx.h b/src/gui/resource/ResCxbx.h index 1613e0115..927737d14 100644 --- a/src/gui/resource/ResCxbx.h +++ b/src/gui/resource/ResCxbx.h @@ -351,9 +351,8 @@ #define ID_SETTINGS_CONFIG_NETWORK 40111 #define ID_SYNC_CONFIG_INPUT 40112 #define ID_SETTINGS_EXPERIMENTAL 40113 -#define ID_USELOADEREXEC 40114 -#define ID_SETTINGS_IGNOREINVALIDXBESIG 40115 -#define ID_SETTINGS_IGNOREINVALIDXBESEC 40116 +#define ID_SETTINGS_IGNOREINVALIDXBESIG 40114 +#define ID_SETTINGS_IGNOREINVALIDXBESEC 40115 #define IDC_STATIC -1 // Next default values for new objects @@ -361,7 +360,7 @@ #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 139 -#define _APS_NEXT_COMMAND_VALUE 40117 +#define _APS_NEXT_COMMAND_VALUE 40116 #define _APS_NEXT_CONTROL_VALUE 1308 #define _APS_NEXT_SYMED_VALUE 109 #endif diff --git a/src/loader/cxbxr-ldr.cpp b/src/loader/cxbxr-ldr.cpp index 06298b2af..51e2cdda9 100644 --- a/src/loader/cxbxr-ldr.cpp +++ b/src/loader/cxbxr-ldr.cpp @@ -47,6 +47,8 @@ // and the executable doesn't contain any data that we refer too once we entered the emulation DLL, // this will be all right. The only bit of data I transfer over, is on the stack, but the stack // (of the initial thread) resides far outside of the reserved range, so that's all right too. +// Note : Old setup is removed in this commit, see git blame to look at src/common/ReservedMemory.h file. +// Which was used in cxbx.exe project. unsigned char virtual_memory_placeholder[VM_PLACEHOLDER_SIZE] = { 0 }; // = { OPCODE_NOP_90 }; // Note : This executable is meant to be as tiny as humanly possible. From 8b0b016aecbc79bbc06f429f196306cb112e542d Mon Sep 17 00:00:00 2001 From: RadWolfie Date: Wed, 13 Apr 2022 10:19:51 -0500 Subject: [PATCH 2/3] more cleanup --- CMakeLists.txt | 1 + src/common/ReserveAddressRanges.cpp | 6 - src/common/cxbxr.cpp | 40 ++++++- src/core/kernel/init/CxbxKrnl.cpp | 110 +------------------ src/core/kernel/memory-manager/VMManager.cpp | 4 - 5 files changed, 42 insertions(+), 119 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index ff2451ce3..141d77afb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -89,6 +89,7 @@ file (GLOB CXBXR_HEADER_COMMON "${CXBXR_ROOT_DIR}/src/common/xbe/XbePrinter.h" "${CXBXR_ROOT_DIR}/src/common/xbox/Logging.hpp" "${CXBXR_ROOT_DIR}/src/common/xbox/Types.hpp" + "${CXBXR_ROOT_DIR}/src/common/xbox_types.h" "${CXBXR_ROOT_DIR}/src/common/xdvdfs-tools/buffered_io.h" "${CXBXR_ROOT_DIR}/src/common/xdvdfs-tools/xdvdfs.h" "${CXBXR_ROOT_DIR}/src/core/hle/D3D8/XbConvert.h" diff --git a/src/common/ReserveAddressRanges.cpp b/src/common/ReserveAddressRanges.cpp index a4639522b..0a54b3d29 100644 --- a/src/common/ReserveAddressRanges.cpp +++ b/src/common/ReserveAddressRanges.cpp @@ -319,12 +319,6 @@ bool isSystemFlagSupport(unsigned int reserved_systems, unsigned int assign_syst if (reserved_systems & assign_system) { return true; } -// TODO: Once host's standalone emulation is remove from GUI, remove below as well. -#ifndef CXBXR_EMU - if (reserved_systems == 0) { - return true; - } -#endif return false; } diff --git a/src/common/cxbxr.cpp b/src/common/cxbxr.cpp index 7ae51cac1..c82364da3 100644 --- a/src/common/cxbxr.cpp +++ b/src/common/cxbxr.cpp @@ -24,6 +24,14 @@ // ****************************************************************** #define LOG_PREFIX CXBXR_MODULE::FILE +#ifdef CXBXR_EMU +#include "core/kernel/support/EmuFile.h" // For g_io_mu_metadata +#include "common/Timer.h" // For Timer_Shutdown +#include "core/common/video/RenderBase.hpp" // For g_renderbase +#include "core/kernel/memory-manager/VMManager.h" +extern void CxbxrKrnlSuspendThreads(); +#endif + #include "cxbxr.hpp" #include "EmuShared.h" @@ -81,7 +89,6 @@ bool HandleFirstLaunch() return true; } -#ifndef CXBXR_EMU [[noreturn]] void CxbxrShutDown(bool is_reboot) { if (!is_reboot) { @@ -97,6 +104,36 @@ bool HandleFirstLaunch() // Shutdown the input device manager g_InputDeviceManager.Shutdown(); +#ifdef CXBXR_EMU + // This is very important process to prevent false positive report and allow IDEs to continue debug multiple reboots. + CxbxrKrnlSuspendThreads(); + + if (g_io_mu_metadata) { + delete g_io_mu_metadata; + g_io_mu_metadata = nullptr; + } + + // Shutdown the render manager + if (g_renderbase != nullptr) { + g_renderbase->Shutdown(); + g_renderbase = nullptr; + } + + // NOTE: Require to be after g_renderbase's shutdown process. + // Next thing we need to do is shutdown our timer threads. + Timer_Shutdown(); + + // NOTE: Must be last step of shutdown process and before CxbxUnlockFilePath call! + // Shutdown the memory manager + g_VMManager.Shutdown(); + + CxbxrUnlockFilePath(); + + if (CxbxKrnl_hEmuParent != NULL && !is_reboot) { + SendMessage(CxbxKrnl_hEmuParent, WM_PARENTNOTIFY, WM_DESTROY, 0); + } +#endif + EmuShared::Cleanup(); TerminateProcess(GetCurrentProcess(), 0); @@ -132,4 +169,3 @@ bool HandleFirstLaunch() CxbxrShutDown(); } -#endif diff --git a/src/core/kernel/init/CxbxKrnl.cpp b/src/core/kernel/init/CxbxKrnl.cpp index fe97b968e..88093c0b7 100644 --- a/src/core/kernel/init/CxbxKrnl.cpp +++ b/src/core/kernel/init/CxbxKrnl.cpp @@ -30,16 +30,12 @@ #include -#include "gui/resource/ResCxbx.h" -#include "core\kernel\init\CxbxKrnl.h" #include "common\xbdm\CxbxXbdm.h" // For Cxbx_LibXbdmThunkTable -#include "CxbxVersion.h" -#include "core\kernel\support\Emu.h" #include "core/kernel/support/PatchRdtsc.hpp" -#include "devices\x86\EmuX86.h" +#include "devices\x86\EmuX86.h" // For EmuX86_Init #include "core\kernel\support\EmuFile.h" #include "core\kernel\support\EmuFS.h" // EmuInitFS -#include "EmuEEPROM.h" // For CxbxRestoreEEPROM, EEPROM, XboxFactoryGameRegion +#include "EmuEEPROM.h" // For CxbxRestoreEEPROM, EEPROM #include "core\kernel\exports\EmuKrnl.h" #include "core\kernel\exports\EmuKrnlKi.h" #include "core\kernel\exports\EmuKrnlKe.h" @@ -58,19 +54,16 @@ #include "common/ReserveAddressRanges.h" #include "common/xbox/Types.hpp" #include "common/win32/WineEnv.h" -#include "core/common/video/RenderBase.hpp" #include #include -#include // For time() #include // For std::ostringstream #include "devices\EEPROMDevice.h" // For g_EEPROM #include "devices\Xbox.h" // For InitXboxHardware() #include "devices\LED.h" // For LED::Sequence -#include "devices\SMCDevice.h" // For SMC Access #include "common\crypto\EmuSha.h" // For the SHA1 functions -#include "Timer.h" // For Timer_Init +#include "common/Timer.h" // For Timer_Init #include "common\input\InputManager.h" // For the InputDeviceManager #include "core/kernel/support/NativeHandle.h" #include "common/win32/Util.h" // for WinError2Str @@ -523,21 +516,10 @@ static void CxbxrKrnlSyncGUI() static void CxbxrKrnlSetupMemorySystem(int BootFlags, unsigned emulate_system, unsigned reserved_systems, blocks_reserved_t blocks_reserved) { -#ifndef CXBXR_EMU - // Only for GUI executable with emulation code. - blocks_reserved_t blocks_reserved_gui = { 0 }; - // Reserve console system's memory ranges before start initialize. - if (!ReserveAddressRanges(emulate_system, blocks_reserved_gui)) { - CxbxrAbort("Failed to reserve required memory ranges!", GetLastError()); - } - // Initialize the memory manager - g_VMManager.Initialize(emulate_system, BootFlags, blocks_reserved_gui); -#else // Release unnecessary memory ranges to allow console/host to use those memory ranges. FreeAddressRanges(emulate_system, reserved_systems, blocks_reserved); // Initialize the memory manager g_VMManager.Initialize(emulate_system, BootFlags, blocks_reserved); -#endif // Commit the memory used by the xbe header size_t HeaderSize = CxbxKrnl_Xbe->m_Header.dwSizeofHeaders; @@ -1478,39 +1460,6 @@ static void CxbxrKrnlInitHacks() } };*/ -[[noreturn]] void CxbxrAbortEx(CXBXR_MODULE cxbxr_module, const char *szErrorMessage, ...) -{ - g_bEmuException = true; - - // print out error message (if exists) - if(szErrorMessage != NULL) - { - char szBuffer2[1024]; - va_list argp; - - va_start(argp, szErrorMessage); - vsprintf(szBuffer2, szErrorMessage, argp); - va_end(argp); - - (void)PopupCustomEx(nullptr, cxbxr_module, LOG_LEVEL::FATAL, PopupIcon::Error, PopupButtons::Ok, PopupReturn::Ok, "Received Fatal Message:\n\n* %s\n", szBuffer2); // Will also EmuLogEx - } - - EmuLogInit(LOG_LEVEL::INFO, "MAIN: Terminating Process"); - fflush(stdout); - - // cleanup debug output - { - FreeConsole(); - - char buffer[16]; - - if(GetConsoleTitle(buffer, 16) != NULL) - freopen("nul", "w", stdout); - } - - CxbxrShutDown(); -} - void CxbxrKrnlSuspendThreads() { xbox::PLIST_ENTRY ThreadListEntry = KiUniqueProcess.ThreadListHead.Flink; @@ -1557,59 +1506,6 @@ void CxbxrKrnlSuspendThreads() } } -void CxbxrShutDown(bool is_reboot) -{ - if (!is_reboot) { - // Clear all kernel boot flags. These (together with the shared memory) persist until Cxbx-Reloaded is closed otherwise. - int BootFlags = 0; - g_EmuShared->SetBootFlags(&BootFlags); - } - - // NOTE: This causes a hang when exiting while NV2A is processing - // This is okay for now: It won't leak memory or resources since TerminateProcess will free everything - // delete g_NV2A; // TODO : g_pXbox - - // Shutdown the input device manager - g_InputDeviceManager.Shutdown(); - - if (g_io_mu_metadata) { - delete g_io_mu_metadata; - g_io_mu_metadata = nullptr; - } - - // Shutdown the render manager - if (g_renderbase != nullptr) { - g_renderbase->Shutdown(); - g_renderbase = nullptr; - } - - // This is very important process to prevent false positive report and allow IDEs to continue debug multiple reboots. - CxbxrKrnlSuspendThreads(); - - // NOTE: Require to be after g_renderbase's shutdown process. - // Next thing we need to do is shutdown our timer threads. - Timer_Shutdown(); - - // NOTE: Must be last step of shutdown process and before CxbxUnlockFilePath call! - // Shutdown the memory manager - g_VMManager.Shutdown(); - - CxbxrUnlockFilePath(); - - if (CxbxKrnl_hEmuParent != NULL && !is_reboot) { - SendMessage(CxbxKrnl_hEmuParent, WM_PARENTNOTIFY, WM_DESTROY, 0); - } - - EmuShared::Cleanup(); - - if (g_ExceptionManager) { - delete g_ExceptionManager; - g_ExceptionManager = nullptr; - } - - TerminateProcess(g_CurrentProcessHandle, 0); -} - void CxbxKrnlPrintUEM(ULONG ErrorCode) { xbox::dword_xt Type; diff --git a/src/core/kernel/memory-manager/VMManager.cpp b/src/core/kernel/memory-manager/VMManager.cpp index 284119375..93bd7c3b5 100644 --- a/src/core/kernel/memory-manager/VMManager.cpp +++ b/src/core/kernel/memory-manager/VMManager.cpp @@ -42,10 +42,6 @@ #include "core\kernel\exports\EmuKrnl.h" // For InitializeListHead(), etc. #include "common/util/cliConfig.hpp" // For GetSessionID #include -// Temporary usage for need ReserveAddressRanges func with cxbx.exe's emulation. -#ifndef CXBXR_EMU -#include "common/ReserveAddressRanges.h" -#endif constexpr char str_persistent_memory_s[] = "PersistentMemory-s"; From 23488ad22b348a209f548b50afe12dd696ed7a65 Mon Sep 17 00:00:00 2001 From: RadWolfie Date: Mon, 25 Apr 2022 04:49:22 -0500 Subject: [PATCH 3/3] review remark --- src/common/Settings.cpp | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/src/common/Settings.cpp b/src/common/Settings.cpp index 9e7ce069f..55d720b81 100644 --- a/src/common/Settings.cpp +++ b/src/common/Settings.cpp @@ -52,7 +52,12 @@ static_assert(false, "Please implement support for cross-platform's user profile uint16_t g_LibVersion_D3D8 = 0; uint16_t g_LibVersion_DSOUND = 0; -// NOTE: Update settings_version when add/edit/delete setting's structure. +// NOTE: Update settings_version when conversion to setting's structure is required. +// UPDATE: When settings are removed, use "if (use false && settings_version < {next_version}) {" statement +// until existing settings require replacement or conversion. next_version input is a hardcode number. +// Settings version 10 and later should consider as not backward compatible. +// TODO: Add read-only state when using an older build and add a notification for will not be able save to file. +// The sooner we do this, the better before version upgrade. /////////////////////////// // * History: // * 2: (RadWolfie), initial version @@ -96,7 +101,6 @@ static struct { const char* AllowAdminPrivilege = "AllowAdminPrivilege"; const char* LoggedModules = "LoggedModules"; const char* LogLevel = "LogLevel"; - const char* LoaderExecutable = "LoaderExecutable"; const char* LogPopupTestCase = "LogPopupTestCase"; } sect_core_keys; @@ -1023,4 +1027,9 @@ void Settings::RemoveLegacyConfigs(unsigned int CurrentRevision) if(CurrentRevision < 9) { m_si.Delete(section_video, "HardwareYUV", true); } + + // see settings_version for details. + if(false && CurrentRevision < 10) { + m_si.Delete(section_core, "LoaderExecutable", true); + } }