From e12490c9c50aec62caca5930bec7ebf43cc55a33 Mon Sep 17 00:00:00 2001 From: RPG Hacker Date: Sat, 19 Sep 2026 23:43:19 +0200 Subject: [PATCH 01/11] Made it slightly easier to get debugging via VSCode working on Linux systems --- .gitignore | 6 +++++- UI/Program.cs | 8 +++----- UI/UI.csproj | 8 ++++++-- 3 files changed, 14 insertions(+), 8 deletions(-) diff --git a/.gitignore b/.gitignore index 757b3b25d2..9164dc9a7f 100644 --- a/.gitignore +++ b/.gitignore @@ -189,4 +189,8 @@ packages/* !Libretro/hakchi/bin TestHelper/* -UI/Dependencies.zip \ No newline at end of file +UI/Dependencies.zip + +# Visual Studio Code local files +.vscodecsdt/Runners/ +.vscode diff --git a/UI/Program.cs b/UI/Program.cs index b183edb21d..dd5965cc61 100644 --- a/UI/Program.cs +++ b/UI/Program.cs @@ -39,11 +39,9 @@ static Program() [STAThread] public static int Main(string[] args) { - if(!System.Diagnostics.Debugger.IsAttached) { - NativeLibrary.SetDllImportResolver(Assembly.GetExecutingAssembly(), DllImportResolver); - NativeLibrary.SetDllImportResolver(typeof(SkiaSharp.SKGraphics).Assembly, DllImportResolver); - NativeLibrary.SetDllImportResolver(typeof(HarfBuzzSharp.Blob).Assembly, DllImportResolver); - } + NativeLibrary.SetDllImportResolver(Assembly.GetExecutingAssembly(), DllImportResolver); + NativeLibrary.SetDllImportResolver(typeof(SkiaSharp.SKGraphics).Assembly, DllImportResolver); + NativeLibrary.SetDllImportResolver(typeof(HarfBuzzSharp.Blob).Assembly, DllImportResolver); if(args.Length >= 4 && args[0] == "--update") { UpdateHelper.AttemptUpdate(args[1], args[2], args[3], args.Contains("admin")); diff --git a/UI/UI.csproj b/UI/UI.csproj index 883aa462a9..5ee088ae77 100644 --- a/UI/UI.csproj +++ b/UI/UI.csproj @@ -2,7 +2,11 @@ WinExe net10.0 - win-x64 + linux-x64 + osx-x64 + win-x64 enable true Mesen @@ -33,7 +37,7 @@ true IL2026;IL2070;IL2075;IL2104;IL3050;IL3053 - + .. From d6ef3f6425ea5883c192624d93629ba3b7db155f Mon Sep 17 00:00:00 2001 From: RPG Hacker Date: Sat, 19 Sep 2026 23:46:08 +0200 Subject: [PATCH 02/11] Added support for tracing to a network socket + Added partial support for Diztinguish's specifc binary format, which allows hooking Mesen up to Diztinguish for live disassembling --- Core/Core.vcxproj | 2 + Core/Core.vcxproj.filters | 6 + Core/Debugger/BaseTraceLogger.h | 79 +++ Core/Debugger/Debugger.cpp | 2 + Core/Debugger/Debugger.h | 6 + Core/Debugger/ITraceLogger.h | 1 + Core/Debugger/TraceLogNetworkSocket.h | 540 ++++++++++++++++++ .../TraceLogger/SnesCpuTraceLogger.cpp | 99 ++++ .../Debugger/TraceLogger/SnesCpuTraceLogger.h | 52 ++ Core/Shared/SettingTypes.h | 7 + Core/Shared/TraceFormat.h | 9 + InteropDLL/DebugApiWrapper.cpp | 36 ++ .../ViewModels/TraceLoggerViewModel.cs | 1 + .../TraceConfigureNetworkSocketWindow.axaml | 79 +++ ...TraceConfigureNetworkSocketWindow.axaml.cs | 82 +++ UI/Debugger/Windows/TraceLoggerWindow.axaml | 25 +- .../Windows/TraceLoggerWindow.axaml.cs | 29 + ...workSocketWaitForConnectionWindow.axaml.cs | 72 +++ ...workSocketWaitForConnectionWindow.cs.axaml | 42 ++ UI/Interop/DebugApi.cs | 22 + UI/Localization/resources.en.xml | 24 + 21 files changed, 1207 insertions(+), 8 deletions(-) create mode 100644 Core/Debugger/TraceLogNetworkSocket.h create mode 100644 Core/Shared/TraceFormat.h create mode 100644 UI/Debugger/Windows/TraceConfigureNetworkSocketWindow.axaml create mode 100644 UI/Debugger/Windows/TraceConfigureNetworkSocketWindow.axaml.cs create mode 100644 UI/Debugger/Windows/TraceNetworkSocketWaitForConnectionWindow.axaml.cs create mode 100644 UI/Debugger/Windows/TraceNetworkSocketWaitForConnectionWindow.cs.axaml diff --git a/Core/Core.vcxproj b/Core/Core.vcxproj index 8e23268d8f..59c386da37 100644 --- a/Core/Core.vcxproj +++ b/Core/Core.vcxproj @@ -19,6 +19,7 @@ + @@ -30,6 +31,7 @@ + diff --git a/Core/Core.vcxproj.filters b/Core/Core.vcxproj.filters index 45f8b485e2..fd37a0a55d 100644 --- a/Core/Core.vcxproj.filters +++ b/Core/Core.vcxproj.filters @@ -3021,6 +3021,12 @@ Shared\Video + + Debugger + + + Shared + diff --git a/Core/Debugger/BaseTraceLogger.h b/Core/Debugger/BaseTraceLogger.h index a18b3cb304..28a56b2d8c 100644 --- a/Core/Debugger/BaseTraceLogger.h +++ b/Core/Debugger/BaseTraceLogger.h @@ -13,6 +13,7 @@ #include "Debugger/ITraceLogger.h" #include "Debugger/ExpressionEvaluator.h" #include "Debugger/TraceLogFileSaver.h" +#include "Debugger/TraceLogNetworkSocket.h" #include "Utilities/HexUtilities.h" #include "Shared/Emulator.h" #include "Shared/EmuSettings.h" @@ -150,6 +151,8 @@ class BaseTraceLogger : public ITraceLogger LabelManager* _labelManager; MemoryDumper* _memoryDumper; Debugger* _debugger; + NetworkLoggingOptions* _networkLoggingOptions; + bool _rowStateInitialized = false; CpuType _cpuType = CpuType::Snes; MemoryType _cpuMemoryType = MemoryType::SnesMemory; @@ -299,6 +302,26 @@ class BaseTraceLogger : public ITraceLogger _pendingLog = false; + bool needsToTrackRowState = _debugger->GetTraceLogNetworkSocket()->IsEnabled() && _networkLoggingOptions->UniqueRowsOnly; + if(needsToTrackRowState && !_rowStateInitialized) { + StartRowStateTracking(); + _rowStateInitialized = true; + } else if(!needsToTrackRowState && _rowStateInitialized) { + StopRowStateTracking(); + _rowStateInitialized = false; + } + + // Skipping rows is currently a network logging option and thus not used + // for file logging or tracing in general. However, that could very easily + // be changed if it's deemed useful for thos scenarios. + bool skipRow = needsToTrackRowState; + if(needsToTrackRowState) { + if(IsUniqueRow(cpuState, disassemblyInfo)) { + TrackRowState(cpuState, disassemblyInfo); + skipRow = false; + } + } + if(_debugger->GetTraceLogFileSaver()->IsEnabled()) { string row; row.reserve(300); @@ -314,6 +337,40 @@ class BaseTraceLogger : public ITraceLogger _debugger->GetTraceLogFileSaver()->Log(row); } + if(_debugger->GetTraceLogNetworkSocket()->IsEnabled()) { + if(!skipRow) { + switch(_networkLoggingOptions->TraceFormat) { + case TraceFormat::Text: { + // Unlike the log file saver, the log network socket does + // not get the PC automatically. There could be some + // tool waiting at the other end of the socket, expecting + // a very specific text format. It's probably best for end + // users to just use the [PC] specifier explicitly if needed. + string row; + row.reserve(300); + + ((TraceLoggerType*)this)->GetTraceRow(row, cpuState, _ppuState[_currentPos], disassemblyInfo); + // +1 for the null terminator. + _debugger->GetTraceLogNetworkSocket()->Log((const uint8_t*)row.c_str(), (int)row.length() + 1); + break; + } + + case TraceFormat::Diztinguish: + case TraceFormat::DiztinguishAbridged: { + vector data; + GetTraceData(&data, cpuState, disassemblyInfo, _networkLoggingOptions->TraceFormat); + + if (!data.empty()) { + _debugger->GetTraceLogNetworkSocket()->Log(&data.front(), (int)data.size()); + } + break; + } + } + } else { + _debugger->GetTraceLogNetworkSocket()->FlushOldBuffers(); + } + } + _currentPos = (_currentPos + 1) % ExecutionLogSize; } @@ -386,6 +443,27 @@ class BaseTraceLogger : public ITraceLogger virtual RowDataType GetFormatTagType(string& tag) = 0; + virtual void StartRowStateTracking() + { + } + + virtual void StopRowStateTracking() + { + } + + virtual bool IsUniqueRow(CpuStateType& cpuState, DisassemblyInfo& disassemblyInfo) + { + return true; + } + + virtual void TrackRowState(CpuStateType& cpuState, DisassemblyInfo& disassemblyInfo) + { + } + + virtual void GetTraceData(vector* target, CpuStateType& cpuState, DisassemblyInfo& disassemblyInfo, TraceFormat traceFormat) + { + } + void ProcessSharedTag(RowPart& rowPart, string& output, CpuStateType& cpuState, TraceLogPpuState& ppuState, DisassemblyInfo& disassemblyInfo) { switch(rowPart.DataType) { @@ -417,6 +495,7 @@ class BaseTraceLogger : public ITraceLogger _options = {}; _currentPos = 0; _pendingLog = false; + _networkLoggingOptions = debugger->GetNetworkLoggingOptions(); _disassemblyCache = new DisassemblyInfo[BaseTraceLogger::ExecutionLogSize]; _rowIds = new uint64_t[BaseTraceLogger::ExecutionLogSize]; diff --git a/Core/Debugger/Debugger.cpp b/Core/Debugger/Debugger.cpp index 96a60ff792..27719834c3 100644 --- a/Core/Debugger/Debugger.cpp +++ b/Core/Debugger/Debugger.cpp @@ -18,6 +18,7 @@ #include "Debugger/ExpressionEvaluator.h" #include "Debugger/BaseEventManager.h" #include "Debugger/TraceLogFileSaver.h" +#include "Debugger/TraceLogNetworkSocket.h" #include "Debugger/CdlManager.h" #include "Debugger/ITraceLogger.h" #include "SNES/SnesCpuTypes.h" @@ -78,6 +79,7 @@ Debugger::Debugger(Emulator* emu, IConsole* console) _memoryAccessCounter.reset(new MemoryAccessCounter(this)); _scriptManager.reset(new ScriptManager(this)); _traceLogSaver.reset(new TraceLogFileSaver()); + _traceLogNetworkSocket.reset(new TraceLogNetworkSocket()); _cdlManager.reset(new CdlManager(this, _disassembler.get())); //Use cpuTypes for iteration (ordered), not _cpuTypes (order is important for coprocessors, etc.) diff --git a/Core/Debugger/Debugger.h b/Core/Debugger/Debugger.h index 4c586d358f..2fe4c37481 100644 --- a/Core/Debugger/Debugger.h +++ b/Core/Debugger/Debugger.h @@ -35,6 +35,7 @@ class IAssembler; class IDebugger; class ITraceLogger; class TraceLogFileSaver; +class TraceLogNetworkSocket; class FrozenAddressManager; class ISerializable; @@ -75,6 +76,8 @@ class Debugger unique_ptr _cdlManager; unique_ptr _traceLogSaver; + unique_ptr _traceLogNetworkSocket; + NetworkLoggingOptions _networkLoggingOptions; SimpleLock _logLock; std::list _debuggerLog; @@ -188,6 +191,9 @@ class Debugger IDebugger* GetMainDebugger(); TraceLogFileSaver* GetTraceLogFileSaver() { return _traceLogSaver.get(); } + TraceLogNetworkSocket* GetTraceLogNetworkSocket() { return _traceLogNetworkSocket.get(); } + void SetNetworkLoggingOptions(const NetworkLoggingOptions& options) { _networkLoggingOptions = options; } + NetworkLoggingOptions* GetNetworkLoggingOptions() { return &_networkLoggingOptions; } MemoryDumper* GetMemoryDumper() { return _memoryDumper.get(); } MemoryAccessCounter* GetMemoryAccessCounter() { return _memoryAccessCounter.get(); } Disassembler* GetDisassembler() { return _disassembler.get(); } diff --git a/Core/Debugger/ITraceLogger.h b/Core/Debugger/ITraceLogger.h index 1ecd23275f..2c930e0147 100644 --- a/Core/Debugger/ITraceLogger.h +++ b/Core/Debugger/ITraceLogger.h @@ -1,6 +1,7 @@ #pragma once #include "pch.h" #include "Debugger/DebugTypes.h" +#include "Core/Shared/TraceFormat.h" struct TraceRow { diff --git a/Core/Debugger/TraceLogNetworkSocket.h b/Core/Debugger/TraceLogNetworkSocket.h new file mode 100644 index 0000000000..70634a7735 --- /dev/null +++ b/Core/Debugger/TraceLogNetworkSocket.h @@ -0,0 +1,540 @@ +#pragma once +#include "pch.h" + +#include "Utilities/Socket.h" +#include "Utilities/CRC32.h" +#include "Core/Shared/TraceFormat.h" +#include "Core/Shared/MessageManager.h" +#include "Utilities/CompressionHelper.h" + +#include +#include +#include +#include +#include + +class TraceLogNetworkSocket +{ +private: + enum class State + { + Uninitialized, + Initialized, + SocketCreated, + Listening, + Connected, + Logging, + }; + + // A simple explanation on logger's general functionality: + // - The main thread appends all traces to a ChunkSize-sized buffer from the logging + // queue when calling Log(). + // - Once the buffer is full, it is dequeued and pushed to the compression queue. + // - A second thread dequeues a buffer from the compression queue and zlib-compresses + // it into a CompressedChunkSize-sized buffer. + // - The original buffer is returned to the logging queue, and the compressed buffer + // pushed to the networking queue. + // - A third thread dequeues a buffer from the networking queue, sends it to all + // current connections, and pushes it back into the compression queue. + // Not much testing has been done to verify all of this is necessary for performance, + // but the original bsnes-plus implementation of this code as used by DiztinGUIsh + // functioned very similarly, and apparently it was the only way to achieve decent + // performance. However, I can imagine this could be improved further by switching + // from TCP to UDP for sending data, which should be fine for the kind of data + // we're sending here (especially when used for the purpose of disassembling ROMs). + // Though I won't be doing that until I know the networking thread is actually + // a bottleneck. + + static constexpr size_t ChunkSize = 1u * 1024u * 1024u; + static constexpr size_t CompressedChunkSize = (size_t)((float)ChunkSize * 1.2f); + static constexpr size_t ChunkCount = 10u; + + struct WorkItem + { + uint8_t* Buffer; + size_t Capacity; + size_t Size; + }; + + uint8_t* _logMemoryStart; + uint8_t* _compressionMemoryStart; + + WorkItem _currentLogItem; + uint64_t _lastLogTime; + std::queue _loggingQueue; + std::queue _compressionInputQueue; + std::queue _compressionOutputQueue; + std::queue _networkingQueue; + + // This bool is a (probably bad) attempt at preventing a race condition + // that can happen during shutdown because Log() and StopLogging() are + // called from different threads. Because Log() is a performance-critical + // function, I don't want to protect it with a mutex. + bool _insideLogFunction; + bool _compressionThreadQuitRequested; + bool _networkingThreadQuitRequested; + std::thread _compressionThread; + std::thread _networkingThread; + std::mutex _compressionInputMutex; + std::mutex _compressionOutputMutex; + + std::atomic _state = State::Uninitialized; + std::unique_ptr _socket = nullptr; + std::vector> _openConnections; + + struct ZlibCompressionHeader + { + // 0: uint8_t: Character 'Z' as a flag for compressed data. + // 1 - 4: uint32_t: Length of the uncompressed buffer, little-endian. + // 5 - 8: uint32_t: Length of the compressed buffer, little-endian. + uint8_t data[9u]; + }; + +public: + ~TraceLogNetworkSocket() + { + CloseSocket(); + } + + + bool OpenSocket(uint16_t port) + { + if (_state == State::Uninitialized) { + _logMemoryStart = new uint8_t[ChunkSize * ChunkCount]; + + if (_logMemoryStart == nullptr) { + return false; + } + + _compressionMemoryStart = new uint8_t[CompressedChunkSize * ChunkCount]; + + if (_compressionMemoryStart == nullptr) { + delete _logMemoryStart; + return false; + } + + _loggingQueue = std::queue(); + _compressionInputQueue = std::queue(); + _compressionOutputQueue = std::queue(); + _networkingQueue = std::queue(); + + for (size_t i = 0; i < ChunkCount; ++i) { + WorkItem workItem; + workItem.Buffer = _logMemoryStart + (i * ChunkSize); + workItem.Capacity = ChunkSize; + workItem.Size = 0u; + _loggingQueue.push(workItem); + } + + for (size_t i = 0; i < ChunkCount; ++i) { + WorkItem workItem; + workItem.Buffer = _compressionMemoryStart + (i * CompressedChunkSize); + workItem.Capacity = CompressedChunkSize; + workItem.Size = 0u; + _compressionOutputQueue.push(workItem); + } + + _state = State::Initialized; + } + + if (_state == State::Initialized) { + _socket = std::make_unique(); + + if (_socket->ConnectionError()) { + _socket.reset(nullptr); + CloseSocket(); + return false; + } + + _socket->Bind(port); + + if (_socket->ConnectionError()) { + _socket.reset(nullptr); + CloseSocket(); + return false; + } + + _state = State::SocketCreated; + } + + if (_state == State::SocketCreated) { + _socket->Listen(10); + + if (_socket->ConnectionError()) + { + CloseSocket(); + return false; + } + + _state = State::Listening; + } + + return true; + } + + void CloseSocket() + { + EndConnection(); + + if (_state == State::Listening) { + _state = State::SocketCreated; + } + + if (_state == State::SocketCreated) { + _socket->Close(); + _socket.reset(nullptr); + _state = State::Initialized; + } + + if (_state == State::Initialized) { + delete _logMemoryStart; + _logMemoryStart = nullptr; + + delete _compressionMemoryStart; + _compressionMemoryStart = nullptr; + + _loggingQueue = std::queue(); + _compressionInputQueue = std::queue(); + _compressionOutputQueue = std::queue(); + _networkingQueue = std::queue(); + + _state = State::Uninitialized; + } + } + + + bool BeginConnection() + { + if (_state == State::Listening) { + if (AcceptConnection()) { + _state = State::Connected; + return true; + } + } + + return false; + } + + void EndConnection() + { + StopLogging(); + + if (_state == State::Connected) { + for (std::unique_ptr& socket : _openConnections) { + socket->Close(); + } + + _openConnections.clear(); + _state = State::Listening; + } + } + + + bool StartLogging() + { + if (_state == State::Connected) { + _insideLogFunction = false; + + _compressionThreadQuitRequested = false; + _networkingThreadQuitRequested = false; + + _currentLogItem = _loggingQueue.front(); + _loggingQueue.pop(); + + _compressionThread = std::thread([this](){ RunCompression(); }); + _networkingThread = std::thread([this](){ RunNetworking(); }); + + _lastLogTime = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); + + _state = State::Logging; + } + + return true; + } + + void StopLogging() + { + if(_state == State::Logging) { + // In this particular case, because of a possible race condition with the Log() function + // we set the new state immediately and then spin-lock until the Log() function is done. + // This way we make sure it can't be called again while our shutdown is active. Adding + // a mutex here would probably be bad for performance, since Log() gets called thousands + // of times within a frame. + _state = State::Connected; + + while(_insideLogFunction) { + std::this_thread::sleep_for(5ms); + } + + { + std::lock_guard guard(_compressionInputMutex); + + if (_currentLogItem.Size > 0) + { + _compressionInputQueue.push(_currentLogItem); + } + else + { + _loggingQueue.push(_currentLogItem); + } + _currentLogItem.Buffer = nullptr; + } + + _compressionThreadQuitRequested = true; + _compressionThread.join(); + _networkingThreadQuitRequested = true; + _networkingThread.join(); + } + } + + + __forceinline bool IsEnabled() { return _state >= State::Logging; } + + + void Log(const uint8_t* data, int length) + { + _insideLogFunction = true; + + if(_state != State::Logging) { + _insideLogFunction = false; + return; + } + + _lastLogTime = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); + + if (_currentLogItem.Size + length > _currentLogItem.Capacity) { + if (_currentLogItem.Size == 0u) { + // If this log entry does not fit into our current buffer, + // yet the current buffer's size is still at 0, it means the + // log entry is larger than our full buffer size. There is + // absolutely no way this entry will ever fit into the buffer, + // so just discard it. Not much else we can do. + MessageManager::Log("[Network Socket] Discarding log entry of size " + std::to_string(length) + " because it exceeds the maximum buffer size."); + _insideLogFunction = false; + return; + } + + FlushCurrentWorkItem(); + } + + std::memcpy(_currentLogItem.Buffer + _currentLogItem.Size, data, length); + _currentLogItem.Size += length; + + _insideLogFunction = false; + } + + void FlushCurrentWorkItem() + { + { + std::lock_guard guard(_compressionInputMutex); + + _compressionInputQueue.push(_currentLogItem); + _currentLogItem.Buffer = nullptr; + + if (!_loggingQueue.empty()) + { + _currentLogItem = _loggingQueue.front(); + _loggingQueue.pop(); + } + } + + // In the unlikely case we ever run out of buffers, sleep until one becomes available. + while (_currentLogItem.Buffer == nullptr) { + std::this_thread::sleep_for(25ms); + + { + std::lock_guard guard(_compressionInputMutex); + + if (!_loggingQueue.empty()) { + _currentLogItem = _loggingQueue.front(); + _loggingQueue.pop(); + } + } + } + } + + void FlushOldBuffers() + { + if (_state != State::Logging) { + return; + } + + if (_currentLogItem.Size == 0u) { + return; + } + + uint64_t currentTime = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); + + if (currentTime - _lastLogTime >= 5000u) { + FlushCurrentWorkItem(); + } + } + + + void RunCompression() + { + while(!_compressionThreadQuitRequested) { + FlushCompressionQueue(); + std::this_thread::sleep_for(25ms); + } + + FlushCompressionQueue(); + } + + void FlushCompressionQueue() + { + WorkItem currentItem; + FetchNextCompressionItem(¤tItem); + + while (currentItem.Buffer != nullptr) { + WorkItem outputItem; + outputItem.Buffer = nullptr; + + while (outputItem.Buffer == nullptr) { + { + std::lock_guard guard(_compressionOutputMutex); + + if (!_compressionOutputQueue.empty()) + { + outputItem = _compressionOutputQueue.front(); + _compressionOutputQueue.pop(); + } + } + + if (outputItem.Buffer == nullptr) + { + std::this_thread::sleep_for(25ms); + } + } + + ZlibCompressionHeader header; + header.data[0] = 'Z'; + header.data[1] = (currentItem.Size >> 0) & 0xFF; + header.data[2] = (currentItem.Size >> 8) & 0xFF; + header.data[3] = (currentItem.Size >> 16) & 0xFF; + header.data[4] = (currentItem.Size >> 24) & 0xFF; + + outputItem.Size = 9; + + mz_ulong compressedSize = (mz_ulong)(outputItem.Capacity - outputItem.Size); + int z_result = compress(outputItem.Buffer + outputItem.Size, &compressedSize, currentItem.Buffer, (mz_ulong)currentItem.Size); + + { + std::lock_guard guard(_compressionInputMutex); + + currentItem.Size = 0u; + _loggingQueue.push(currentItem); + } + + if (z_result != Z_MEM_ERROR && z_result != Z_BUF_ERROR) { + outputItem.Size += compressedSize; + + header.data[5] = (compressedSize >> 0) & 0xFF; + header.data[6] = (compressedSize >> 8) & 0xFF; + header.data[7] = (compressedSize >> 16) & 0xFF; + header.data[8] = (compressedSize >> 24) & 0xFF; + + memcpy(outputItem.Buffer, &header, sizeof(header)); + + { + std::lock_guard guard(_compressionOutputMutex); + + _networkingQueue.push(outputItem); + } + } else { + // If there was some compression error, we just discard the result. + // The most likely cause is the output buffer being too small. + outputItem.Size = 0u; + + std::lock_guard guard(_compressionOutputMutex); + + _compressionOutputQueue.push(outputItem); + } + + FetchNextCompressionItem(¤tItem); + } + } + + void FetchNextCompressionItem(WorkItem* targetItem) + { + targetItem->Buffer = nullptr; + + std::lock_guard guard(_compressionInputMutex); + + if (!_compressionInputQueue.empty()) { + *targetItem = _compressionInputQueue.front(); + _compressionInputQueue.pop(); + } + } + + + void RunNetworking() + { + while(!_networkingThreadQuitRequested) { + FlushNetworkingQueue(); + std::this_thread::sleep_for(25ms); + } + + FlushNetworkingQueue(); + } + + void FlushNetworkingQueue() + { + WorkItem currentItem; + FetchNextNetworkingItem(¤tItem); + + while (currentItem.Buffer != nullptr) { + AcceptConnection(); + + for (auto it = _openConnections.begin(); it != _openConnections.end(); ) { + std::unique_ptr& socket = *it; + + socket->Send((char*)currentItem.Buffer, (int)currentItem.Size, 0u); + + // Erase a connection if it produced a connection error. Probably not much else + // we can do here. The "AcceptConnection()" above should hopefully re-establish + // the connection if desired. + if (socket->ConnectionError()) { + it = _openConnections.erase(it); + } else { + ++it; + } + } + + { + currentItem.Size = 0u; + + std::lock_guard guard(_compressionOutputMutex); + _compressionOutputQueue.push(currentItem); + } + + FetchNextNetworkingItem(¤tItem); + } + } + + void FetchNextNetworkingItem(WorkItem* targetItem) + { + targetItem->Buffer = nullptr; + + std::lock_guard guard(_compressionOutputMutex); + + if (!_networkingQueue.empty()) { + *targetItem = _networkingQueue.front(); + _networkingQueue.pop(); + } + } + + +private: + bool AcceptConnection() + { + unique_ptr socket = _socket->Accept(); + + if (socket->ConnectionError()) { + return false; + } + + _openConnections.push_back(std::move(socket)); + return true; + } +}; \ No newline at end of file diff --git a/Core/SNES/Debugger/TraceLogger/SnesCpuTraceLogger.cpp b/Core/SNES/Debugger/TraceLogger/SnesCpuTraceLogger.cpp index 27b09efeb0..6176b88a8c 100644 --- a/Core/SNES/Debugger/TraceLogger/SnesCpuTraceLogger.cpp +++ b/Core/SNES/Debugger/TraceLogger/SnesCpuTraceLogger.cpp @@ -34,6 +34,105 @@ RowDataType SnesCpuTraceLogger::GetFormatTagType(string& tag) } } +void SnesCpuTraceLogger::StartRowStateTracking() +{ + _uniqueRowBankRecords = new RomState; + memset(_uniqueRowBankRecords, 0, sizeof(RomState)); +} + +void SnesCpuTraceLogger::StopRowStateTracking() +{ + for(size_t i = 0u; i < BankCount; ++i) { + if(_uniqueRowBankRecords->BankStates[i] != nullptr) { + delete _uniqueRowBankRecords->BankStates[i]; + } + } + + delete _uniqueRowBankRecords; +} + +bool SnesCpuTraceLogger::IsUniqueRow(SnesCpuState& cpuState, DisassemblyInfo& disassemblyInfo) +{ + uint32_t pc = GetProgramCounter(cpuState); + uint8_t bank = (uint8_t)(pc >> 16); + uint16_t bankOffset = (uint16_t)pc; + + // Make sure to only call this function after StartRowStateTracking(). + assert(_uniqueRowBankRecords != nullptr); + + RelevantCpuStateSetter rowState; + rowState.PackedState = 0u; + rowState.State.D = cpuState.D; + rowState.State.K = cpuState.K; + rowState.State.DBR = cpuState.DBR; + rowState.State.PS = cpuState.PS; + rowState.State.EmulationMode = cpuState.EmulationMode; + + return (_uniqueRowBankRecords->BankStates[bank] == nullptr + || _uniqueRowBankRecords->BankStates[bank]->RowStates[bankOffset].UniqueCpuStates.find(rowState.PackedState) == _uniqueRowBankRecords->BankStates[bank]->RowStates[bankOffset].UniqueCpuStates.cend()); +} + +void SnesCpuTraceLogger::TrackRowState(SnesCpuState& cpuState, DisassemblyInfo& disassemblyInfo) +{ + uint32_t pc = GetProgramCounter(cpuState); + uint8_t bank = (uint8_t)(pc >> 16); + uint16_t bankOffset = (uint16_t)pc; + + RelevantCpuStateSetter rowState; + rowState.PackedState = 0u; + rowState.State.D = cpuState.D; + rowState.State.K = cpuState.K; + rowState.State.DBR = cpuState.DBR; + rowState.State.PS = cpuState.PS; + rowState.State.EmulationMode = cpuState.EmulationMode; + + if(_uniqueRowBankRecords->BankStates[bank] == nullptr) { + _uniqueRowBankRecords->BankStates[bank] = new BankState; + } + + _uniqueRowBankRecords->BankStates[bank]->RowStates[bankOffset].UniqueCpuStates.insert(rowState.PackedState); +} + +void SnesCpuTraceLogger::GetTraceData(vector* target, SnesCpuState& cpuState, DisassemblyInfo& disassemblyInfo, TraceFormat traceFormat) +{ + switch(traceFormat) { + case TraceFormat::Text: + // Should never be called - handled in BaseTraceLogger. + break; + case TraceFormat::Diztinguish: + target->push_back(0xEF); + break; + case TraceFormat::DiztinguishAbridged: + target->push_back(0xEE); + break; + } + + uint32_t pc = GetProgramCounter(cpuState); + + if(traceFormat == TraceFormat::Diztinguish || traceFormat == TraceFormat::DiztinguishAbridged) { + size_t sizeIndex = target->size(); + target->push_back(0xFF); // Stub - we'll fill this out later. + + target->push_back((pc >> 0) & 0xFF); + target->push_back((pc >> 8) & 0xFF); + target->push_back((pc >> 16) & 0xFF); + + target->push_back(disassemblyInfo.GetOpSize()); + + target->push_back((cpuState.D >> 0) & 0xFF); + target->push_back((cpuState.D >> 8) & 0xFF); + + target->push_back(cpuState.DBR); + target->push_back(cpuState.PS); + + if (traceFormat == TraceFormat::Diztinguish) { + // TODO + } + + (*target)[sizeIndex] = (uint8_t)(target->size() - sizeIndex - 1u); + } +} + void SnesCpuTraceLogger::GetTraceRow(string& output, SnesCpuState& cpuState, TraceLogPpuState& ppuState, DisassemblyInfo& disassemblyInfo) { constexpr char activeStatusLetters[8] = { 'N', 'V', 'M', 'X', 'D', 'I', 'Z', 'C' }; diff --git a/Core/SNES/Debugger/TraceLogger/SnesCpuTraceLogger.h b/Core/SNES/Debugger/TraceLogger/SnesCpuTraceLogger.h index c0a85cd7fe..72c9e3dbd6 100644 --- a/Core/SNES/Debugger/TraceLogger/SnesCpuTraceLogger.h +++ b/Core/SNES/Debugger/TraceLogger/SnesCpuTraceLogger.h @@ -3,6 +3,9 @@ #include "Debugger/BaseTraceLogger.h" #include "SNES/SnesCpuTypes.h" +#include +#include + class DisassemblyInfo; class Debugger; class SnesPpu; @@ -14,8 +17,57 @@ class SnesCpuTraceLogger : public BaseTraceLogger= sizeof(State)); + }; + + struct RowState + { + std::set UniqueCpuStates; + }; + + struct BankState + { + RowState RowStates[BankSize]; + }; + + struct RomState + { + // Allocated dynamically to avoid allocating memory that isn't needed. + BankState* BankStates[BankCount]; + }; + + // Maybe this one doesn't absolutely need dynamic allocation, since it only contains + // 256 pointers, so roughly 2 KB of memory. But whatever. + RomState* _uniqueRowBankRecords; + protected: RowDataType GetFormatTagType(string& tag) override; + void StartRowStateTracking() override; + void StopRowStateTracking() override; + bool IsUniqueRow(SnesCpuState& cpuState, DisassemblyInfo& disassemblyInfo) override; + void TrackRowState(SnesCpuState& cpuState, DisassemblyInfo& disassemblyInfo) override; + void GetTraceData(vector* target, SnesCpuState& cpuState, DisassemblyInfo& disassemblyInfo, TraceFormat traceFormat) override; public: SnesCpuTraceLogger(Debugger* debugger, IDebugger* cpuDebugger, CpuType cpuType, SnesPpu* ppu, SnesMemoryManager* memoryManager); diff --git a/Core/Shared/SettingTypes.h b/Core/Shared/SettingTypes.h index a3eec39ddd..c548e13533 100644 --- a/Core/Shared/SettingTypes.h +++ b/Core/Shared/SettingTypes.h @@ -1,5 +1,6 @@ #pragma once #include "pch.h" +#include "TraceFormat.h" #include enum class EmulationFlags @@ -1147,3 +1148,9 @@ enum class DebuggerFlags GbaDebuggerEnabled = (1 << 11), WsDebuggerEnabled = (1 << 12), }; + +struct NetworkLoggingOptions +{ + TraceFormat TraceFormat; + bool UniqueRowsOnly; +}; diff --git a/Core/Shared/TraceFormat.h b/Core/Shared/TraceFormat.h new file mode 100644 index 0000000000..f3ecf51d28 --- /dev/null +++ b/Core/Shared/TraceFormat.h @@ -0,0 +1,9 @@ +#pragma once +#include "pch.h" + +enum class TraceFormat : uint8_t +{ + Text = 0, + Diztinguish = 1, + DiztinguishAbridged = 2, +}; \ No newline at end of file diff --git a/InteropDLL/DebugApiWrapper.cpp b/InteropDLL/DebugApiWrapper.cpp index b6434ae734..30cdac0e91 100644 --- a/InteropDLL/DebugApiWrapper.cpp +++ b/InteropDLL/DebugApiWrapper.cpp @@ -21,6 +21,7 @@ #include "Core/Debugger/BaseEventManager.h" #include "Core/Debugger/ITraceLogger.h" #include "Core/Debugger/TraceLogFileSaver.h" +#include "Core/Debugger/TraceLogNetworkSocket.h" #include "Core/Debugger/FrozenAddressManager.h" #include "Core/Gameboy/GbTypes.h" #include "Utilities/StringUtilities.h" @@ -111,6 +112,11 @@ extern "C" WithToolVoid(GetTraceLogger(type), SetOptions(options)); } + DllExport void __stdcall SetNetworkLoggingOptions(NetworkLoggingOptions options) + { + WithDebugger(void, SetNetworkLoggingOptions(options)); + } + DllExport uint32_t __stdcall GetExecutionTrace(TraceRow output[], uint32_t startOffset, uint32_t lineCount) { return WithDebugger(uint32_t, GetExecutionTrace(output, startOffset, lineCount)); @@ -131,6 +137,36 @@ extern "C" WithDebugger(void, GetTraceLogFileSaver()->StopLogging()); } + DllExport bool __stdcall OpenNetworkLogSocket(uint16_t port) + { + return WithDebugger(bool, GetTraceLogNetworkSocket()->OpenSocket(port)); + } + + DllExport void __stdcall CloseNetworkLogSocket() + { + WithDebugger(void, GetTraceLogNetworkSocket()->CloseSocket()); + } + + DllExport bool __stdcall BeginNetworkLogConnection() + { + return WithDebugger(bool, GetTraceLogNetworkSocket()->BeginConnection()); + } + + DllExport void __stdcall EndNetworkLogConnection() + { + WithDebugger(void, GetTraceLogNetworkSocket()->EndConnection()); + } + + DllExport bool __stdcall StartNetworkLogLogging() + { + return WithDebugger(bool, GetTraceLogNetworkSocket()->StartLogging()); + } + + DllExport void __stdcall StopNetworkLogLogging() + { + WithDebugger(void, GetTraceLogNetworkSocket()->StopLogging()); + } + DllExport void __stdcall SetBreakpoints(Breakpoint breakpoints[], uint32_t length) { WithDebugger(void, SetBreakpoints(breakpoints, length)); diff --git a/UI/Debugger/ViewModels/TraceLoggerViewModel.cs b/UI/Debugger/ViewModels/TraceLoggerViewModel.cs index a58385a43f..b39f1ede48 100644 --- a/UI/Debugger/ViewModels/TraceLoggerViewModel.cs +++ b/UI/Debugger/ViewModels/TraceLoggerViewModel.cs @@ -32,6 +32,7 @@ public partial class TraceLoggerViewModel : DisposableViewModel, ISelectableMode [ObservableProperty] public partial int MinScrollPosition { get; set; } = 0; [ObservableProperty] public partial int MaxScrollPosition { get; set; } = DebugApi.TraceLogBufferSize; [ObservableProperty] public partial bool IsLoggingToFile { get; set; } = false; + [ObservableProperty] public partial bool IsLoggingToNetworkSocket { get; set; } = false; [ObservableProperty] public partial List Tabs { get; set; } = new(); [ObservableProperty] public partial TraceLoggerOptionTab SelectedTab { get; set; } = null!; diff --git a/UI/Debugger/Windows/TraceConfigureNetworkSocketWindow.axaml b/UI/Debugger/Windows/TraceConfigureNetworkSocketWindow.axaml new file mode 100644 index 0000000000..a163b0293f --- /dev/null +++ b/UI/Debugger/Windows/TraceConfigureNetworkSocketWindow.axaml @@ -0,0 +1,79 @@ + + + + + + + + + + + + + + + + + +