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/Core/Core.vcxproj b/Core/Core.vcxproj index 8e23268d8f..25fa0f1492 100644 --- a/Core/Core.vcxproj +++ b/Core/Core.vcxproj @@ -30,6 +30,7 @@ + @@ -451,7 +452,9 @@ - + + + diff --git a/Core/Core.vcxproj.filters b/Core/Core.vcxproj.filters index 45f8b485e2..1c91931a6b 100644 --- a/Core/Core.vcxproj.filters +++ b/Core/Core.vcxproj.filters @@ -163,7 +163,13 @@ Debugger - + + Debugger + + + Debugger + + Debugger @@ -3021,6 +3027,9 @@ Shared\Video + + Shared + diff --git a/Core/Debugger/BaseTraceLogger.h b/Core/Debugger/BaseTraceLogger.h index a18b3cb304..ec122519ca 100644 --- a/Core/Debugger/BaseTraceLogger.h +++ b/Core/Debugger/BaseTraceLogger.h @@ -12,7 +12,8 @@ #include "Debugger/DebugBreakHelper.h" #include "Debugger/ITraceLogger.h" #include "Debugger/ExpressionEvaluator.h" -#include "Debugger/TraceLogFileSaver.h" +#include "Debugger/TraceLogOutputFile.h" +#include "Debugger/TraceLogOutputNetworkSocket.h" #include "Utilities/HexUtilities.h" #include "Shared/Emulator.h" #include "Shared/EmuSettings.h" @@ -150,6 +151,7 @@ class BaseTraceLogger : public ITraceLogger LabelManager* _labelManager; MemoryDumper* _memoryDumper; Debugger* _debugger; + bool _rowStateInitialized = false; CpuType _cpuType = CpuType::Snes; MemoryType _cpuMemoryType = MemoryType::SnesMemory; @@ -170,6 +172,11 @@ class BaseTraceLogger : public ITraceLogger unique_ptr _expEvaluator; ExpressionData _conditionData; + bool _anyLoggingActive; + std::queue _disassemblyInfoQueuedForLogging; + std::queue _cpuStateQueuedForLogging; + std::queue _ppuStateQueuedForLogging; + void WriteByteCode(DisassemblyInfo& info, RowPart& rowPart, string& output) { string byteCode; @@ -297,23 +304,14 @@ class BaseTraceLogger : public ITraceLogger _rowIds[_currentPos] = ITraceLogger::NextRowId; ITraceLogger::NextRowId++; - _pendingLog = false; - - if(_debugger->GetTraceLogFileSaver()->IsEnabled()) { - string row; - row.reserve(300); - - //Display PC - RowPart rowPart = {}; - rowPart.DisplayInHex = true; - rowPart.MinWidth = DebugUtilities::GetProgramCounterSize(_cpuType); - WriteIntValue(row, ((TraceLoggerType*)this)->GetProgramCounter(cpuState), rowPart); - row += " "; - - ((TraceLoggerType*)this)->GetTraceRow(row, cpuState, _ppuState[_currentPos], disassemblyInfo); - _debugger->GetTraceLogFileSaver()->Log(row); + if(_anyLoggingActive) { + _disassemblyInfoQueuedForLogging.push(disassemblyInfo); + _cpuStateQueuedForLogging.push(cpuState); + _ppuStateQueuedForLogging.push(_ppuState[_currentPos]); } + _pendingLog = false; + _currentPos = (_currentPos + 1) % ExecutionLogSize; } @@ -386,6 +384,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, TraceLogOutput::OutputFormat traceFormat) + { + } + void ProcessSharedTag(RowPart& rowPart, string& output, CpuStateType& cpuState, TraceLogPpuState& ppuState, DisassemblyInfo& disassemblyInfo) { switch(rowPart.DataType) { @@ -478,6 +497,110 @@ class BaseTraceLogger : public ITraceLogger } } + void ProcessEndOfFrame() + { + TraceLoggerType* selfDerived = ((TraceLoggerType*)this); + TraceLogOutput* logOutput = nullptr; + + { + TraceLogOutputFile* fileLogger = _debugger->GetTraceLogOutputFile(); + TraceLogOutputNetworkSocket* networkLogger = _debugger->GetTraceLogOutputNetworkSocket(); + + if(fileLogger->IsEnabled()) { + logOutput = fileLogger; + } else if(networkLogger->IsEnabled()) { + logOutput = networkLogger; + } + } + + if(logOutput != nullptr) { + _anyLoggingActive = true; + + bool needsToTrackRowState = logOutput->GetUniqueRowsOnly(); + + if(needsToTrackRowState && !_rowStateInitialized) { + StartRowStateTracking(); + _rowStateInitialized = true; + } + + if(!_cpuStateQueuedForLogging.empty()) { + logOutput->UpdateLastLogTimestamp(); + } else { + logOutput->FlushOldBuffers(); + return; + } + + string rowText; + rowText.reserve(300); + + vector rowData; + rowData.reserve(50); + + while(!_cpuStateQueuedForLogging.empty()) { + DisassemblyInfo disassemblyInfo = _disassemblyInfoQueuedForLogging.front(); + CpuStateType cpuState = _cpuStateQueuedForLogging.front(); + TraceLogPpuState ppuState = _ppuStateQueuedForLogging.front(); + _disassemblyInfoQueuedForLogging.pop(); + _cpuStateQueuedForLogging.pop(); + _ppuStateQueuedForLogging.pop(); + + bool skipRow = needsToTrackRowState; + if(needsToTrackRowState) { + if(IsUniqueRow(cpuState, disassemblyInfo)) { + TrackRowState(cpuState, disassemblyInfo); + skipRow = false; + } + } + + if(!skipRow) { + switch(logOutput->GetOutputFormat()) { + case TraceLogOutput::OutputFormat::Text: { + rowText.clear(); + + if(logOutput->GetIncludeImplictPC()) { + RowPart rowPart = {}; + rowPart.DisplayInHex = true; + rowPart.MinWidth = DebugUtilities::GetProgramCounterSize(_cpuType); + WriteIntValue(rowText, selfDerived->GetProgramCounter(cpuState), rowPart); + rowText += " "; + } + + selfDerived->GetTraceRow(rowText, cpuState, ppuState, disassemblyInfo); + rowText += '\n'; + logOutput->Log((const uint8_t*)rowText.c_str(), (int)rowText.length()); + break; + } + + case TraceLogOutput::OutputFormat::Diztinguish: + case TraceLogOutput::OutputFormat::DiztinguishAbridged: { + rowData.clear(); + GetTraceData(&rowData, cpuState, disassemblyInfo, logOutput->GetOutputFormat()); + + if(!rowData.empty()) { + logOutput->Log(&rowData.front(), (int)rowData.size()); + } + break; + } + } + } + } + } else { + // These should always have the same size, so just the first check should be good enough. + if(_cpuStateQueuedForLogging.size() > 0 /*|| _ppuStateQueuedForLogging.size() > 0 || _disassemblyInfoQueuedForLogging.size() > 0*/) { + _disassemblyInfoQueuedForLogging = std::queue(); + _cpuStateQueuedForLogging = std::queue(); + _ppuStateQueuedForLogging = std::queue(); + } + + if(_rowStateInitialized) { + StopRowStateTracking(); + _rowStateInitialized = false; + } + + _anyLoggingActive = false; + } + } + void SetOptions(TraceLoggerOptions options) override { DebugBreakHelper helper(_debugger); diff --git a/Core/Debugger/Debugger.cpp b/Core/Debugger/Debugger.cpp index 96a60ff792..07886601d6 100644 --- a/Core/Debugger/Debugger.cpp +++ b/Core/Debugger/Debugger.cpp @@ -17,7 +17,8 @@ #include "Debugger/Profiler.h" #include "Debugger/ExpressionEvaluator.h" #include "Debugger/BaseEventManager.h" -#include "Debugger/TraceLogFileSaver.h" +#include "Debugger/TraceLogOutputFile.h" +#include "Debugger/TraceLogOutputNetworkSocket.h" #include "Debugger/CdlManager.h" #include "Debugger/ITraceLogger.h" #include "SNES/SnesCpuTypes.h" @@ -77,7 +78,8 @@ Debugger::Debugger(Emulator* emu, IConsole* console) _disassemblySearch.reset(new DisassemblySearch(_disassembler.get(), _labelManager.get())); _memoryAccessCounter.reset(new MemoryAccessCounter(this)); _scriptManager.reset(new ScriptManager(this)); - _traceLogSaver.reset(new TraceLogFileSaver()); + _traceLogOutputFile.reset(new TraceLogOutputFile()); + _traceLogOutputNetworkSocket.reset(new TraceLogOutputNetworkSocket()); _cdlManager.reset(new CdlManager(this, _disassembler.get())); //Use cpuTypes for iteration (ordered), not _cpuTypes (order is important for coprocessors, etc.) @@ -648,6 +650,15 @@ void Debugger::ProcessEvent(EventType type, std::optional cpuTypeOpt) } } +void Debugger::ProcessEndOfFrame() +{ + for(int i = 0; i <= (int)DebugUtilities::GetLastCpuType(); i++) { + if(_debuggers[i].Debugger) { + _debuggers[i].Debugger->ProcessEndOfFrame(); + } + } +} + template void Debugger::ProcessScripts(uint32_t addr, T& value, MemoryOperationType opType) { diff --git a/Core/Debugger/Debugger.h b/Core/Debugger/Debugger.h index 4c586d358f..6fc22d7f03 100644 --- a/Core/Debugger/Debugger.h +++ b/Core/Debugger/Debugger.h @@ -34,7 +34,8 @@ class BaseEventManager; class IAssembler; class IDebugger; class ITraceLogger; -class TraceLogFileSaver; +class TraceLogOutputFile; +class TraceLogOutputNetworkSocket; class FrozenAddressManager; class ISerializable; @@ -74,7 +75,8 @@ class Debugger unique_ptr _labelManager; unique_ptr _cdlManager; - unique_ptr _traceLogSaver; + unique_ptr _traceLogOutputFile; + unique_ptr _traceLogOutputNetworkSocket; SimpleLock _logLock; std::list _debuggerLog; @@ -125,6 +127,7 @@ class Debugger void InternalProcessInterrupt(CpuType cpuType, IDebugger& dbg, StepRequest& stepRequest, AddressInfo& src, uint32_t srcAddr, AddressInfo& dest, uint32_t destAddr, AddressInfo& ret, uint32_t retAddr, uint32_t retSp, bool forNmi); void ProcessEvent(EventType type, std::optional cpuType); + void ProcessEndOfFrame(); void ProcessConfigChange(); @@ -187,7 +190,8 @@ class Debugger IDebugger* GetCpuDebugger(CpuType cpuType); IDebugger* GetMainDebugger(); - TraceLogFileSaver* GetTraceLogFileSaver() { return _traceLogSaver.get(); } + TraceLogOutputFile* GetTraceLogOutputFile() { return _traceLogOutputFile.get(); } + TraceLogOutputNetworkSocket* GetTraceLogOutputNetworkSocket() { return _traceLogOutputNetworkSocket.get(); } MemoryDumper* GetMemoryDumper() { return _memoryDumper.get(); } MemoryAccessCounter* GetMemoryAccessCounter() { return _memoryAccessCounter.get(); } Disassembler* GetDisassembler() { return _disassembler.get(); } diff --git a/Core/Debugger/IDebugger.h b/Core/Debugger/IDebugger.h index b9e81ae196..db4e3e0a49 100644 --- a/Core/Debugger/IDebugger.h +++ b/Core/Debugger/IDebugger.h @@ -52,6 +52,8 @@ class IDebugger virtual void Reset() = 0; virtual void Run() = 0; + virtual void ProcessEndOfFrame() {} + virtual void Init() {} virtual void ProcessConfigChange() {} diff --git a/Core/Debugger/TraceLogFileSaver.h b/Core/Debugger/TraceLogFileSaver.h deleted file mode 100644 index c37b1647c1..0000000000 --- a/Core/Debugger/TraceLogFileSaver.h +++ /dev/null @@ -1,48 +0,0 @@ -#pragma once -#include "pch.h" - -class TraceLogFileSaver -{ -private: - bool _enabled = false; - string _outputFilepath; - string _outputBuffer; - ofstream _outputFile; - -public: - ~TraceLogFileSaver() - { - StopLogging(); - } - - void StartLogging(string filename) - { - _outputBuffer.clear(); - _outputFile.open(filename, ios::out | ios::binary); - _enabled = true; - } - - void StopLogging() - { - if(_enabled) { - _enabled = false; - if(_outputFile) { - if(!_outputBuffer.empty()) { - _outputFile << _outputBuffer; - } - _outputFile.close(); - } - } - } - - __forceinline bool IsEnabled() { return _enabled; } - - void Log(string& log) - { - _outputBuffer += log + '\n'; - if(_outputBuffer.size() > 32768) { - _outputFile << _outputBuffer; - _outputBuffer.clear(); - } - } -}; \ No newline at end of file diff --git a/Core/Debugger/TraceLogOutput.h b/Core/Debugger/TraceLogOutput.h new file mode 100644 index 0000000000..306a32913e --- /dev/null +++ b/Core/Debugger/TraceLogOutput.h @@ -0,0 +1,486 @@ +#pragma once +#include "pch.h" + +#include "Core/Shared/MessageManager.h" +#include "Utilities/CompressionHelper.h" + +#include +#include +#include +#include +#include + +class TraceLogOutput +{ +public: + enum class CompressionType : uint8_t + { + None = 0, + DiztinguishZlib = 1, + }; + + enum class OutputFormat : uint8_t + { + Text = 0, + Diztinguish = 1, + DiztinguishAbridged = 2, + + }; + + struct Settings + { + uint32_t ChunkSize; + uint32_t ChunkCount; + bool BatchLogData; + bool UniqueRowsOnly; + bool IncludeImplicitPC; + CompressionType CompressionType; + OutputFormat Format; + }; + + bool GetUniqueRowsOnly() const + { + return _sharedSettings.UniqueRowsOnly; + } + + bool GetIncludeImplictPC() const + { + return _sharedSettings.IncludeImplicitPC; + } + + OutputFormat GetOutputFormat() const + { + return _sharedSettings.Format; + } + + __forceinline bool IsEnabled() { return _threadsRunning; } + + void Log(const uint8_t* data, int length) + { + _insideLogFunction = true; + + if(!_threadsRunning) { + _insideLogFunction = false; + return; + } + + 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("[Trace Log Output] 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; + + if(!_sharedSettings.BatchLogData) { + FlushCurrentWorkItem(); + } + + _insideLogFunction = false; + } + + void UpdateLastLogTimestamp() + { + if(_threadsRunning) { + return; + } + + _lastLogTime = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); + } + + void FlushOldBuffers() + { + if(_threadsRunning) { + 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(); + } + } + +protected: + Settings _sharedSettings; + + // A simple explanation of the general functionality here: + // - The main thread appends all traces to a ChunkSize-sized buffer from the logging + // queue when calling Log(). + // - Once the buffer is full (or, depending on the setting, immediately), that buffer + // is dequeued and pushed into the compression queue. + // - A second thread dequeues a buffer from the compression queue and compresses it + // into a CompressedChunkSize-sized buffer using the compression of choice. + // - The original buffer is returned to the logging queue, and the compressed buffer + // pushed to the send queue. + // - A third thread dequeues a buffer from the send queue, write it to the configured + // target output stream, and pushes it back into the compression queue. + // Ultimately, the goal of all this complexity is to improve performance by moving as + // much work as possible onto secondary threads so that the main thread spends as little + // time as possible on the logging functionality. + + struct WorkItem + { + uint8_t* Buffer; + size_t Capacity; + size_t Size; + + WorkItem() + { + Buffer = nullptr; + Capacity = 0u; + Size = 0u; + } + }; + + bool _threadsRunning = false; + + uint8_t* _logMemoryStart = nullptr; + uint8_t* _compressionMemoryStart = nullptr; + + WorkItem _currentLogItem; + uint64_t _lastLogTime = 0u; + std::queue _loggingQueue; + std::queue _compressionInputQueue; + std::queue _compressionOutputQueue; + std::queue _sendQueue; + + // 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. + volatile bool _insideLogFunction = false; + bool _compressionThreadQuitRequested = false; + bool _sendThreadQuitRequested = false; + std::thread _compressionThread; + std::thread _sendThread; + std::mutex _compressionInputMutex; + std::mutex _compressionOutputMutex; + + struct DiztinguishZlibCompressionHeader + { + // 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]; + }; + + bool AllocateBuffers() + { + // Just a wild guess as to how much memory the compressed data will need at most. + // In the average, most likely case, the compressed buffer will need a lot less + // memory than the input buffers, but this should prepare us for the worst case + // without needing to constantly reallocate memory. + const size_t CompressedChunkSize = (size_t)((float)_sharedSettings.ChunkSize * 1.3f); + + _logMemoryStart = new uint8_t[_sharedSettings.ChunkSize * _sharedSettings.ChunkCount]; + + if(_logMemoryStart == nullptr) { + return false; + } + + _compressionMemoryStart = new uint8_t[CompressedChunkSize * _sharedSettings.ChunkCount]; + + if(_compressionMemoryStart == nullptr) { + delete _logMemoryStart; + return false; + } + + _loggingQueue = std::queue(); + _compressionInputQueue = std::queue(); + _compressionOutputQueue = std::queue(); + _sendQueue = std::queue(); + + for(size_t i = 0; i < _sharedSettings.ChunkCount; ++i) { + WorkItem workItem; + workItem.Buffer = _logMemoryStart + (i * _sharedSettings.ChunkSize); + workItem.Capacity = _sharedSettings.ChunkSize; + workItem.Size = 0u; + _loggingQueue.push(workItem); + } + + for(size_t i = 0; i < _sharedSettings.ChunkCount; ++i) { + WorkItem workItem; + workItem.Buffer = _compressionMemoryStart + (i * CompressedChunkSize); + workItem.Capacity = CompressedChunkSize; + workItem.Size = 0u; + _compressionOutputQueue.push(workItem); + } + + return true; + } + + void FreeBuffers() + { + if(_compressionMemoryStart != nullptr) { + delete _compressionMemoryStart; + _compressionMemoryStart = nullptr; + } + + if(_logMemoryStart != nullptr) { + delete _logMemoryStart; + _logMemoryStart = nullptr; + } + } + + void StartThreads() + { + if(_threadsRunning) { + return; + } + + _insideLogFunction = false; + + _compressionThreadQuitRequested = false; + _sendThreadQuitRequested = false; + + _currentLogItem = _loggingQueue.front(); + _loggingQueue.pop(); + + _compressionThread = std::thread([this]() { RunCompression(); }); + _sendThread = std::thread([this]() { RunSend(); }); + + _lastLogTime = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); + + _threadsRunning = true; + } + + void StopThreads() + { + if(!_threadsRunning) { + return; + } + + // Because of a possible race condition with the Log() function, we set the flag right + // here at the start of the function 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. + _threadsRunning = false; + + 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(); + _sendThreadQuitRequested = true; + _sendThread.join(); + } + + 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 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); + } + } + + switch(_sharedSettings.CompressionType) { + case CompressionType::None: + memcpy(outputItem.Buffer, currentItem.Buffer, currentItem.Size); + outputItem.Size = currentItem.Size; + + { + std::lock_guard guard(_compressionInputMutex); + + currentItem.Size = 0u; + _loggingQueue.push(currentItem); + } + + { + std::lock_guard guard(_compressionOutputMutex); + + _sendQueue.push(outputItem); + } + + break; + + case CompressionType::DiztinguishZlib: { + DiztinguishZlibCompressionHeader 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); + + _sendQueue.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); + } + break; + } + } + + FetchNextCompressionItem(¤tItem); + } + } + + void FetchNextCompressionItem(WorkItem* targetItem) + { + targetItem->Buffer = nullptr; + + std::lock_guard guard(_compressionInputMutex); + + if(!_compressionInputQueue.empty()) { + *targetItem = _compressionInputQueue.front(); + _compressionInputQueue.pop(); + } + } + + void RunSend() + { + while(!_sendThreadQuitRequested) { + FlushSendQueue(); + std::this_thread::sleep_for(25ms); + } + + FlushSendQueue(); + } + + void FlushSendQueue() + { + WorkItem currentItem; + FetchNextSendItem(¤tItem); + + while(currentItem.Buffer != nullptr) { + FlushItemToStream(currentItem); + + { + currentItem.Size = 0u; + + std::lock_guard guard(_compressionOutputMutex); + _compressionOutputQueue.push(currentItem); + } + + FetchNextSendItem(¤tItem); + } + } + + void FetchNextSendItem(WorkItem* targetItem) + { + targetItem->Buffer = nullptr; + + std::lock_guard guard(_compressionOutputMutex); + + if(!_sendQueue.empty()) { + *targetItem = _sendQueue.front(); + _sendQueue.pop(); + } + } + + virtual void FlushItemToStream(const WorkItem& item) {} +}; \ No newline at end of file diff --git a/Core/Debugger/TraceLogOutputFile.h b/Core/Debugger/TraceLogOutputFile.h new file mode 100644 index 0000000000..9b5c661d2a --- /dev/null +++ b/Core/Debugger/TraceLogOutputFile.h @@ -0,0 +1,72 @@ +#pragma once +#include "pch.h" +#include "TraceLogOutput.h" + +class TraceLogOutputFile : public TraceLogOutput +{ +public: + struct Settings + { + // This is coming directly from C# code. I don't know + // how long this memory is guaranteed to be valid, which + // might be a problem if we ever want to access the filename + // after copying the struct over. + const char* FileName; + bool NativeNewLines; + }; + +private: + Settings _selfSettings; + + ofstream _outputFile; + +public: + virtual ~TraceLogOutputFile() + { + StopLogging(); + } + + bool StartLogging(const Settings& selfSettings, const TraceLogOutput::Settings& sharedSettings) + { + _selfSettings = selfSettings; + _sharedSettings = sharedSettings; + + std::ios_base::openmode openMode = ios::out; + + if(_sharedSettings.Format != OutputFormat::Text || !_selfSettings.NativeNewLines) { + openMode |= ios::binary; + } + + _outputFile.open(_selfSettings.FileName, openMode); + + if(!_outputFile.is_open()) { + return false; + } + + if(!AllocateBuffers()) { + _outputFile.close(); + return false; + } + + StartThreads(); + + return true; + } + + void StopLogging() + { + if(!IsEnabled()) { + return; + } + + StopThreads(); + FreeBuffers(); + + _outputFile.close(); + } + + void FlushItemToStream(const WorkItem& item) override + { + _outputFile.write((const char*)item.Buffer, item.Size); + } +}; \ No newline at end of file diff --git a/Core/Debugger/TraceLogOutputNetworkSocket.h b/Core/Debugger/TraceLogOutputNetworkSocket.h new file mode 100644 index 0000000000..1411a50c24 --- /dev/null +++ b/Core/Debugger/TraceLogOutputNetworkSocket.h @@ -0,0 +1,195 @@ +#pragma once +#include "pch.h" +#include "TraceLogOutput.h" + +#include "Utilities/Socket.h" +#include "Core/Shared/MessageManager.h" +#include "Utilities/CompressionHelper.h" + +#include +#include +#include +#include +#include + +class TraceLogOutputNetworkSocket : public TraceLogOutput +{ +public: + struct Settings + { + uint16_t ConnectionPort; + }; + +private: + enum class State + { + Uninitialized, + Initialized, + SocketCreated, + Listening, + Connected, + Logging, + }; + + Settings _selfSettings; + + std::atomic _state = State::Uninitialized; + std::unique_ptr _socket = nullptr; + std::vector> _openConnections; + +public: + virtual ~TraceLogOutputNetworkSocket() + { + CloseSocket(); + } + + bool OpenSocket(const Settings& selfSettings, const TraceLogOutput::Settings& sharedSettings) + { + if(_state == State::Uninitialized) { + _selfSettings = selfSettings; + _sharedSettings = sharedSettings; + + if(!AllocateBuffers()) { + return false; + } + + _state = State::Initialized; + } + + if(_state == State::Initialized) { + _socket = std::make_unique(); + + if(_socket->ConnectionError()) { + _socket.reset(nullptr); + CloseSocket(); + return false; + } + + _socket->Bind(_selfSettings.ConnectionPort); + + 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) { + FreeBuffers(); + + _loggingQueue = std::queue(); + _compressionInputQueue = std::queue(); + _compressionOutputQueue = std::queue(); + _sendQueue = 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) { + StartThreads(); + _state = State::Logging; + } + + return true; + } + + void StopLogging() + { + if(_state == State::Logging) { + StopThreads(); + _state = State::Connected; + } + } + +protected: + void FlushItemToStream(const WorkItem& item) override + { + AcceptConnection(); + + for(auto it = _openConnections.begin(); it != _openConnections.end();) { + std::unique_ptr& socket = *it; + + socket->Send((char*)item.Buffer, (int)item.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; + } + } + } + + 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/GBA/Debugger/GbaDebugger.cpp b/Core/GBA/Debugger/GbaDebugger.cpp index cfc2386e53..e8249d983f 100644 --- a/Core/GBA/Debugger/GbaDebugger.cpp +++ b/Core/GBA/Debugger/GbaDebugger.cpp @@ -250,6 +250,13 @@ void GbaDebugger::Step(int32_t stepCount, StepType type) _step.reset(new StepRequest(step)); } +void GbaDebugger::ProcessEndOfFrame() +{ + if(_traceLogger->IsEnabled()) { + _traceLogger->ProcessEndOfFrame(); + } +} + StepBackConfig GbaDebugger::GetStepBackConfig() { return { diff --git a/Core/GBA/Debugger/GbaDebugger.h b/Core/GBA/Debugger/GbaDebugger.h index 70edfc9be8..1bab57b828 100644 --- a/Core/GBA/Debugger/GbaDebugger.h +++ b/Core/GBA/Debugger/GbaDebugger.h @@ -71,6 +71,8 @@ class GbaDebugger final : public IDebugger void Step(int32_t stepCount, StepType type) override; StepBackConfig GetStepBackConfig() override; + void ProcessEndOfFrame() override; + void DrawPartialFrame() override; bool SaveRomToDisk(string filename, bool saveAsIps, CdlStripOption stripOption); diff --git a/Core/Gameboy/Debugger/GbDebugger.cpp b/Core/Gameboy/Debugger/GbDebugger.cpp index 718ba3193f..8e3527a467 100644 --- a/Core/Gameboy/Debugger/GbDebugger.cpp +++ b/Core/Gameboy/Debugger/GbDebugger.cpp @@ -260,6 +260,13 @@ void GbDebugger::Step(int32_t stepCount, StepType type) _step.reset(new StepRequest(step)); } +void GbDebugger::ProcessEndOfFrame() +{ + if(_traceLogger->IsEnabled()) { + _traceLogger->ProcessEndOfFrame(); + } +} + StepBackConfig GbDebugger::GetStepBackConfig() { return { diff --git a/Core/Gameboy/Debugger/GbDebugger.h b/Core/Gameboy/Debugger/GbDebugger.h index 13c8d72d6a..87113b3113 100644 --- a/Core/Gameboy/Debugger/GbDebugger.h +++ b/Core/Gameboy/Debugger/GbDebugger.h @@ -70,6 +70,8 @@ class GbDebugger final : public IDebugger void Step(int32_t stepCount, StepType type) override; StepBackConfig GetStepBackConfig() override; + void ProcessEndOfFrame() override; + void DrawPartialFrame() override; bool SaveRomToDisk(string filename, bool saveAsIps, CdlStripOption stripOption); diff --git a/Core/NES/Debugger/NesDebugger.cpp b/Core/NES/Debugger/NesDebugger.cpp index c6a88b5304..a4523ed347 100644 --- a/Core/NES/Debugger/NesDebugger.cpp +++ b/Core/NES/Debugger/NesDebugger.cpp @@ -283,6 +283,13 @@ void NesDebugger::Step(int32_t stepCount, StepType type) _step.reset(new StepRequest(step)); } +void NesDebugger::ProcessEndOfFrame() +{ + if(_traceLogger->IsEnabled()) { + _traceLogger->ProcessEndOfFrame(); + } +} + StepBackConfig NesDebugger::GetStepBackConfig() { return { diff --git a/Core/NES/Debugger/NesDebugger.h b/Core/NES/Debugger/NesDebugger.h index 299b9c0779..03e1e42d2e 100644 --- a/Core/NES/Debugger/NesDebugger.h +++ b/Core/NES/Debugger/NesDebugger.h @@ -85,6 +85,8 @@ class NesDebugger final : public IDebugger void Step(int32_t stepCount, StepType type) override; StepBackConfig GetStepBackConfig() override; + void ProcessEndOfFrame() override; + void DrawPartialFrame() override; DebuggerFeatures GetSupportedFeatures() override; diff --git a/Core/PCE/Debugger/PceDebugger.cpp b/Core/PCE/Debugger/PceDebugger.cpp index 568f75a3f9..c87f885e8e 100644 --- a/Core/PCE/Debugger/PceDebugger.cpp +++ b/Core/PCE/Debugger/PceDebugger.cpp @@ -267,6 +267,13 @@ void PceDebugger::Step(int32_t stepCount, StepType type) _step.reset(new StepRequest(step)); } +void PceDebugger::ProcessEndOfFrame() +{ + if(_traceLogger->IsEnabled()) { + _traceLogger->ProcessEndOfFrame(); + } +} + StepBackConfig PceDebugger::GetStepBackConfig() { return { diff --git a/Core/PCE/Debugger/PceDebugger.h b/Core/PCE/Debugger/PceDebugger.h index 937e506c27..6c8adbb6e8 100644 --- a/Core/PCE/Debugger/PceDebugger.h +++ b/Core/PCE/Debugger/PceDebugger.h @@ -85,6 +85,8 @@ class PceDebugger final : public IDebugger void Step(int32_t stepCount, StepType type) override; StepBackConfig GetStepBackConfig() override; + void ProcessEndOfFrame() override; + void DrawPartialFrame() override; DebuggerFeatures GetSupportedFeatures() override; diff --git a/Core/SMS/Debugger/SmsDebugger.cpp b/Core/SMS/Debugger/SmsDebugger.cpp index 6e9cd3ef6f..2abddef4b3 100644 --- a/Core/SMS/Debugger/SmsDebugger.cpp +++ b/Core/SMS/Debugger/SmsDebugger.cpp @@ -248,6 +248,13 @@ void SmsDebugger::Step(int32_t stepCount, StepType type) _step.reset(new StepRequest(step)); } +void SmsDebugger::ProcessEndOfFrame() +{ + if(_traceLogger->IsEnabled()) { + _traceLogger->ProcessEndOfFrame(); + } +} + StepBackConfig SmsDebugger::GetStepBackConfig() { return { diff --git a/Core/SMS/Debugger/SmsDebugger.h b/Core/SMS/Debugger/SmsDebugger.h index 11318a62a9..00d5e7dfe0 100644 --- a/Core/SMS/Debugger/SmsDebugger.h +++ b/Core/SMS/Debugger/SmsDebugger.h @@ -76,6 +76,8 @@ class SmsDebugger final : public IDebugger void Step(int32_t stepCount, StepType type) override; StepBackConfig GetStepBackConfig() override; + void ProcessEndOfFrame() override; + void DrawPartialFrame() override; bool SaveRomToDisk(string filename, bool saveAsIps, CdlStripOption stripOption); diff --git a/Core/SNES/Debugger/Cx4Debugger.cpp b/Core/SNES/Debugger/Cx4Debugger.cpp index e21e64fda9..3fd540552a 100644 --- a/Core/SNES/Debugger/Cx4Debugger.cpp +++ b/Core/SNES/Debugger/Cx4Debugger.cpp @@ -167,6 +167,13 @@ void Cx4Debugger::Step(int32_t stepCount, StepType type) _step.reset(new StepRequest(step)); } +void Cx4Debugger::ProcessEndOfFrame() +{ + if(_traceLogger->IsEnabled()) { + _traceLogger->ProcessEndOfFrame(); + } +} + void Cx4Debugger::SetProgramCounter(uint32_t addr, bool updateDebuggerOnly) { Cx4State& state = _cx4->GetState(); diff --git a/Core/SNES/Debugger/Cx4Debugger.h b/Core/SNES/Debugger/Cx4Debugger.h index 481ae3212f..0e893baf4d 100644 --- a/Core/SNES/Debugger/Cx4Debugger.h +++ b/Core/SNES/Debugger/Cx4Debugger.h @@ -46,6 +46,8 @@ class Cx4Debugger final : public IDebugger void Run() override; void Step(int32_t stepCount, StepType type) override; + void ProcessEndOfFrame() override; + void SetProgramCounter(uint32_t addr, bool updateDebuggerOnly = false) override; uint32_t GetProgramCounter(bool getInstPc) override; uint64_t GetCpuCycleCount(bool forProfiler) override; diff --git a/Core/SNES/Debugger/GsuDebugger.cpp b/Core/SNES/Debugger/GsuDebugger.cpp index cf66743b1d..3c287370b7 100644 --- a/Core/SNES/Debugger/GsuDebugger.cpp +++ b/Core/SNES/Debugger/GsuDebugger.cpp @@ -143,6 +143,13 @@ void GsuDebugger::Step(int32_t stepCount, StepType type) _step.reset(new StepRequest(step)); } +void GsuDebugger::ProcessEndOfFrame() +{ + if(_traceLogger->IsEnabled()) { + _traceLogger->ProcessEndOfFrame(); + } +} + void GsuDebugger::SetProgramCounter(uint32_t addr, bool updateDebuggerOnly) { if(!updateDebuggerOnly) { diff --git a/Core/SNES/Debugger/GsuDebugger.h b/Core/SNES/Debugger/GsuDebugger.h index ca65da46f4..3dd9831f96 100644 --- a/Core/SNES/Debugger/GsuDebugger.h +++ b/Core/SNES/Debugger/GsuDebugger.h @@ -44,6 +44,8 @@ class GsuDebugger final : public IDebugger void Run() override; void Step(int32_t stepCount, StepType type) override; + void ProcessEndOfFrame() override; + void SetProgramCounter(uint32_t addr, bool updateDebuggerOnly = false) override; uint32_t GetProgramCounter(bool getInstPc) override; uint64_t GetCpuCycleCount(bool forProfiler) override; diff --git a/Core/SNES/Debugger/NecDspDebugger.cpp b/Core/SNES/Debugger/NecDspDebugger.cpp index ad559c8eb1..91bce1d854 100644 --- a/Core/SNES/Debugger/NecDspDebugger.cpp +++ b/Core/SNES/Debugger/NecDspDebugger.cpp @@ -152,6 +152,13 @@ void NecDspDebugger::Step(int32_t stepCount, StepType type) _step.reset(new StepRequest(step)); } +void NecDspDebugger::ProcessEndOfFrame() +{ + if(_traceLogger->IsEnabled()) { + _traceLogger->ProcessEndOfFrame(); + } +} + DebuggerFeatures NecDspDebugger::GetSupportedFeatures() { DebuggerFeatures features = {}; diff --git a/Core/SNES/Debugger/NecDspDebugger.h b/Core/SNES/Debugger/NecDspDebugger.h index 778b6db3f7..1e52bf6aa4 100644 --- a/Core/SNES/Debugger/NecDspDebugger.h +++ b/Core/SNES/Debugger/NecDspDebugger.h @@ -44,6 +44,8 @@ class NecDspDebugger final : public IDebugger void Run() override; void Step(int32_t stepCount, StepType type) override; + void ProcessEndOfFrame() override; + DebuggerFeatures GetSupportedFeatures() override; void SetProgramCounter(uint32_t addr, bool updateDebuggerOnly = false) override; uint32_t GetProgramCounter(bool getInstPc) override; diff --git a/Core/SNES/Debugger/SnesDebugger.cpp b/Core/SNES/Debugger/SnesDebugger.cpp index 9189d58981..991d6a1063 100644 --- a/Core/SNES/Debugger/SnesDebugger.cpp +++ b/Core/SNES/Debugger/SnesDebugger.cpp @@ -354,6 +354,13 @@ void SnesDebugger::Step(int32_t stepCount, StepType type) _step.reset(new StepRequest(step)); } +void SnesDebugger::ProcessEndOfFrame() +{ + if(_traceLogger->IsEnabled()) { + _traceLogger->ProcessEndOfFrame(); + } +} + StepBackConfig SnesDebugger::GetStepBackConfig() { if(_cpuType == CpuType::Snes) { diff --git a/Core/SNES/Debugger/SnesDebugger.h b/Core/SNES/Debugger/SnesDebugger.h index e21437de40..cb99017265 100644 --- a/Core/SNES/Debugger/SnesDebugger.h +++ b/Core/SNES/Debugger/SnesDebugger.h @@ -103,6 +103,8 @@ class SnesDebugger final : public IDebugger void Step(int32_t stepCount, StepType type) override; StepBackConfig GetStepBackConfig() override; + void ProcessEndOfFrame() override; + void DrawPartialFrame() override; DebuggerFeatures GetSupportedFeatures() override; diff --git a/Core/SNES/Debugger/SpcDebugger.cpp b/Core/SNES/Debugger/SpcDebugger.cpp index 99aca7e2d6..6e0b77cfc9 100644 --- a/Core/SNES/Debugger/SpcDebugger.cpp +++ b/Core/SNES/Debugger/SpcDebugger.cpp @@ -212,6 +212,13 @@ void SpcDebugger::Step(int32_t stepCount, StepType type) _step.reset(new StepRequest(step)); } +void SpcDebugger::ProcessEndOfFrame() +{ + if(_traceLogger->IsEnabled()) { + _traceLogger->ProcessEndOfFrame(); + } +} + DebuggerFeatures SpcDebugger::GetSupportedFeatures() { DebuggerFeatures features = {}; diff --git a/Core/SNES/Debugger/SpcDebugger.h b/Core/SNES/Debugger/SpcDebugger.h index 8209a98f12..51c4399cf0 100644 --- a/Core/SNES/Debugger/SpcDebugger.h +++ b/Core/SNES/Debugger/SpcDebugger.h @@ -56,6 +56,8 @@ class SpcDebugger final : public IDebugger void Run() override; void Step(int32_t stepCount, StepType type) override; + void ProcessEndOfFrame() override; + DebuggerFeatures GetSupportedFeatures() override; void SetProgramCounter(uint32_t addr, bool updateDebuggerOnly = false) override; uint32_t GetProgramCounter(bool getInstPc) override; diff --git a/Core/SNES/Debugger/St018Debugger.cpp b/Core/SNES/Debugger/St018Debugger.cpp index f5a95775a8..9705547663 100644 --- a/Core/SNES/Debugger/St018Debugger.cpp +++ b/Core/SNES/Debugger/St018Debugger.cpp @@ -185,6 +185,13 @@ void St018Debugger::Step(int32_t stepCount, StepType type) _step.reset(new StepRequest(step)); } +void St018Debugger::ProcessEndOfFrame() +{ + if(_traceLogger->IsEnabled()) { + _traceLogger->ProcessEndOfFrame(); + } +} + void St018Debugger::ProcessCallStackUpdates(AddressInfo& destAddr, uint32_t destPc) { if(GbaDisUtils::IsJumpToSub(_prevOpCode, _prevFlags) && destPc != _prevProgramCounter + GbaDisUtils::GetOpSize(_prevOpCode, _prevFlags)) { diff --git a/Core/SNES/Debugger/St018Debugger.h b/Core/SNES/Debugger/St018Debugger.h index 48f495d089..2fecb63527 100644 --- a/Core/SNES/Debugger/St018Debugger.h +++ b/Core/SNES/Debugger/St018Debugger.h @@ -56,6 +56,8 @@ class St018Debugger final : public IDebugger void Run() override; void Step(int32_t stepCount, StepType type) override; + void ProcessEndOfFrame() override; + void SetProgramCounter(uint32_t addr, bool updateDebuggerOnly = false) override; uint32_t GetProgramCounter(bool getInstPc) override; uint64_t GetCpuCycleCount(bool forProfiler = false) override; diff --git a/Core/SNES/Debugger/TraceLogger/SnesCpuTraceLogger.cpp b/Core/SNES/Debugger/TraceLogger/SnesCpuTraceLogger.cpp index 27b09efeb0..1be2f65dce 100644 --- a/Core/SNES/Debugger/TraceLogger/SnesCpuTraceLogger.cpp +++ b/Core/SNES/Debugger/TraceLogger/SnesCpuTraceLogger.cpp @@ -34,6 +34,123 @@ 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]; + _uniqueRowBankRecords->BankStates[i] = nullptr; + } + } + + 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, TraceLogOutput::OutputFormat traceFormat) +{ + switch(traceFormat) { + case TraceLogOutput::OutputFormat::Text: + // Should never be called - handled in BaseTraceLogger. + break; + case TraceLogOutput::OutputFormat::Diztinguish: + target->push_back(0xEF); + break; + case TraceLogOutput::OutputFormat::DiztinguishAbridged: + target->push_back(0xEE); + break; + } + + uint32_t pc = GetProgramCounter(cpuState); + + if(traceFormat == TraceLogOutput::OutputFormat::Diztinguish || traceFormat == TraceLogOutput::OutputFormat::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 == TraceLogOutput::OutputFormat::Diztinguish) { + uint8_t* byteCode = disassemblyInfo.GetByteCode(); + target->push_back(byteCode[0u]); + target->push_back(byteCode[1u]); + target->push_back(byteCode[2u]); + target->push_back(byteCode[3u]); + + target->push_back((cpuState.A >> 0) & 0xFF); + target->push_back((cpuState.A >> 8) & 0xFF); + + target->push_back((cpuState.X >> 0) & 0xFF); + target->push_back((cpuState.X >> 8) & 0xFF); + + target->push_back((cpuState.Y >> 0) & 0xFF); + target->push_back((cpuState.Y >> 8) & 0xFF); + + target->push_back((cpuState.SP >> 0) & 0xFF); + target->push_back((cpuState.SP >> 8) & 0xFF); + + target->push_back((uint8_t)cpuState.EmulationMode); + } + + (*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..97231e3a73 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, TraceLogOutput::OutputFormat traceFormat) override; public: SnesCpuTraceLogger(Debugger* debugger, IDebugger* cpuDebugger, CpuType cpuType, SnesPpu* ppu, SnesMemoryManager* memoryManager); diff --git a/Core/Shared/Emulator.cpp b/Core/Shared/Emulator.cpp index 754bc271e5..da2c08785a 100644 --- a/Core/Shared/Emulator.cpp +++ b/Core/Shared/Emulator.cpp @@ -304,6 +304,11 @@ void Emulator::ProcessEndOfFrame() _console->GetControlManager()->ProcessEndOfFrame(); } + + if(_internalDebugger) { + _internalDebugger->ProcessEndOfFrame(); + } + _frameRunning = false; } diff --git a/Core/WS/Debugger/WsDebugger.cpp b/Core/WS/Debugger/WsDebugger.cpp index 04df942303..43113f4d2d 100644 --- a/Core/WS/Debugger/WsDebugger.cpp +++ b/Core/WS/Debugger/WsDebugger.cpp @@ -279,6 +279,13 @@ void WsDebugger::Step(int32_t stepCount, StepType type) _step.reset(new StepRequest(step)); } +void WsDebugger::ProcessEndOfFrame() +{ + if(_traceLogger->IsEnabled()) { + _traceLogger->ProcessEndOfFrame(); + } +} + StepBackConfig WsDebugger::GetStepBackConfig() { return { diff --git a/Core/WS/Debugger/WsDebugger.h b/Core/WS/Debugger/WsDebugger.h index d7e941761f..58f7060712 100644 --- a/Core/WS/Debugger/WsDebugger.h +++ b/Core/WS/Debugger/WsDebugger.h @@ -77,6 +77,8 @@ class WsDebugger final : public IDebugger void Step(int32_t stepCount, StepType type) override; StepBackConfig GetStepBackConfig() override; + void ProcessEndOfFrame() override; + void DrawPartialFrame() override; bool SaveRomToDisk(string filename, bool saveAsIps, CdlStripOption stripOption); diff --git a/InteropDLL/DebugApiWrapper.cpp b/InteropDLL/DebugApiWrapper.cpp index b6434ae734..9ed968308d 100644 --- a/InteropDLL/DebugApiWrapper.cpp +++ b/InteropDLL/DebugApiWrapper.cpp @@ -20,7 +20,8 @@ #include "Core/Debugger/IAssembler.h" #include "Core/Debugger/BaseEventManager.h" #include "Core/Debugger/ITraceLogger.h" -#include "Core/Debugger/TraceLogFileSaver.h" +#include "Core/Debugger/TraceLogOutputFile.h" +#include "Core/Debugger/TraceLogOutputNetworkSocket.h" #include "Core/Debugger/FrozenAddressManager.h" #include "Core/Gameboy/GbTypes.h" #include "Utilities/StringUtilities.h" @@ -121,14 +122,44 @@ extern "C" WithDebugger(void, ClearExecutionTrace()); } - DllExport void __stdcall StartLogTraceToFile(const char* filename) + DllExport bool __stdcall StartLogTraceToFile(TraceLogOutputFile::Settings selfSettings, TraceLogOutput::Settings sharedSettings) { - WithDebugger(void, GetTraceLogFileSaver()->StartLogging(filename)); + return WithDebugger(bool, GetTraceLogOutputFile()->StartLogging(selfSettings, sharedSettings)); } DllExport void __stdcall StopLogTraceToFile() { - WithDebugger(void, GetTraceLogFileSaver()->StopLogging()); + WithDebugger(void, GetTraceLogOutputFile()->StopLogging()); + } + + DllExport bool __stdcall OpenNetworkLogSocket(TraceLogOutputNetworkSocket::Settings selfSettings, TraceLogOutput::Settings sharedSettings) + { + return WithDebugger(bool, GetTraceLogOutputNetworkSocket()->OpenSocket(selfSettings, sharedSettings)); + } + + DllExport void __stdcall CloseNetworkLogSocket() + { + WithDebugger(void, GetTraceLogOutputNetworkSocket()->CloseSocket()); + } + + DllExport bool __stdcall BeginNetworkLogConnection() + { + return WithDebugger(bool, GetTraceLogOutputNetworkSocket()->BeginConnection()); + } + + DllExport void __stdcall EndNetworkLogConnection() + { + WithDebugger(void, GetTraceLogOutputNetworkSocket()->EndConnection()); + } + + DllExport bool __stdcall StartNetworkLogLogging() + { + return WithDebugger(bool, GetTraceLogOutputNetworkSocket()->StartLogging()); + } + + DllExport void __stdcall StopNetworkLogLogging() + { + WithDebugger(void, GetTraceLogOutputNetworkSocket()->StopLogging()); } DllExport void __stdcall SetBreakpoints(Breakpoint breakpoints[], uint32_t length) diff --git a/UI/Config/Debugger/TraceLogOutputConfig.cs b/UI/Config/Debugger/TraceLogOutputConfig.cs new file mode 100644 index 0000000000..852f072329 --- /dev/null +++ b/UI/Config/Debugger/TraceLogOutputConfig.cs @@ -0,0 +1,108 @@ +using CommunityToolkit.Mvvm.ComponentModel; +using Mesen.Interop; +using Mesen.ViewModels; +using System; +using System.Diagnostics.CodeAnalysis; + +namespace Mesen.Config +{ + public enum TraceLogOutputTarget + { + File, + NetworkSocket, + }; + + public enum TraceLogOutputCompressionType : byte + { + None = 0, + [RestrictToPlatforms(CpuType.Snes, CpuType.Sa1)] + DiztinguishZlib = 1, + }; + + public enum TraceLogOutputFormat : byte + { + Text = 0, + [RestrictToPlatforms(CpuType.Snes, CpuType.Sa1)] + Diztinguish = 1, + [RestrictToPlatforms(CpuType.Snes, CpuType.Sa1)] + DiztinguishAbridged = 2, + } + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] + public partial class TraceLogOutputCpuDependentConfig : BaseConfig + { + [ObservableProperty] public partial TraceLogOutputCompressionType CompressionType { get; set; } = TraceLogOutputCompressionType.None; + [ObservableProperty] public partial TraceLogOutputFormat Format { get; set; } = TraceLogOutputFormat.Text; + }; + + public partial class TraceLogOutputSharedConfig : BaseConfig + { + [ObservableProperty] public partial uint ChunkSize { get; set; } = 1 * 1024 * 1024; + [ObservableProperty] public partial uint ChunkCount { get; set; } = 10; + [ObservableProperty] public partial bool BatchLogData { get; set; } = true; + + [RestrictToPlatforms(CpuType.Snes, CpuType.Sa1)] + [ObservableProperty] public partial bool UniqueRowsOnly { get; set; } = false; + [ObservableProperty] public partial bool IncludeImplicitPC { get; set; } = true; + + // I copied this from TraceLoggerConfig.cs. + // Is that really the best way to do things? + [ObservableProperty] public partial TraceLogOutputCpuDependentConfig SnesConfig { get; set; } = new(); + [ObservableProperty] public partial TraceLogOutputCpuDependentConfig SpcConfig { get; set; } = new(); + [ObservableProperty] public partial TraceLogOutputCpuDependentConfig NecDspConfig { get; set; } = new(); + [ObservableProperty] public partial TraceLogOutputCpuDependentConfig Sa1Config { get; set; } = new(); + [ObservableProperty] public partial TraceLogOutputCpuDependentConfig GsuConfig { get; set; } = new(); + [ObservableProperty] public partial TraceLogOutputCpuDependentConfig Cx4Config { get; set; } = new(); + [ObservableProperty] public partial TraceLogOutputCpuDependentConfig St018Config { get; set; } = new(); + [ObservableProperty] public partial TraceLogOutputCpuDependentConfig GbConfig { get; set; } = new(); + [ObservableProperty] public partial TraceLogOutputCpuDependentConfig NesConfig { get; set; } = new(); + [ObservableProperty] public partial TraceLogOutputCpuDependentConfig PceConfig { get; set; } = new(); + [ObservableProperty] public partial TraceLogOutputCpuDependentConfig SmsConfig { get; set; } = new(); + [ObservableProperty] public partial TraceLogOutputCpuDependentConfig GbaConfig { get; set; } = new(); + [ObservableProperty] public partial TraceLogOutputCpuDependentConfig WsConfig { get; set; } = new(); + + // Feels slightly evil, but is the easiest way we can bind these settings to Avalonia... + [ObservableProperty] public partial CpuType LastUsedCpuType { get; set; } = CpuType.Snes; + public TraceLogOutputCpuDependentConfig CpuDependentConfig { get => GetCpuConfig(LastUsedCpuType); } + + public TraceLogOutputCpuDependentConfig GetCpuConfig(CpuType type) + { + return type switch { + CpuType.Snes => SnesConfig, + CpuType.Spc => SpcConfig, + CpuType.NecDsp => NecDspConfig, + CpuType.Sa1 => Sa1Config, + CpuType.Gsu => GsuConfig, + CpuType.Cx4 => Cx4Config, + CpuType.St018 => St018Config, + CpuType.Gameboy => GbConfig, + CpuType.Nes => NesConfig, + CpuType.Pce => PceConfig, + CpuType.Sms => SmsConfig, + CpuType.Gba => GbaConfig, + CpuType.Ws => WsConfig, + _ => throw new NotImplementedException("Unsupport cpu type") + }; + } + }; + + public partial class TraceLogOutputFileConfig : BaseConfig + { + [ObservableProperty] public partial string FileName { get; set; } = ""; + [ObservableProperty] public partial bool NativeNewLines { get; set; } = true; + }; + + public partial class TraceLogOutputNetworkSocketConfig : BaseConfig + { + [ObservableProperty] public partial ushort ConnectionPort { get; set; } = 27015; + }; + + public partial class TraceLogOutputConfig : BaseWindowConfig + { + [ObservableProperty] public partial TraceLogOutputTarget OutputTarget { get; set; } = TraceLogOutputTarget.File; + [ObservableProperty] public partial bool ShowAdvancedSettings { get; set; } = false; + [ObservableProperty] public partial TraceLogOutputSharedConfig SharedConfig { get; set; } = new(); + [ObservableProperty] public partial TraceLogOutputFileConfig FileConfig { get; set; } = new(); + [ObservableProperty] public partial TraceLogOutputNetworkSocketConfig SocketConfig { get; set; } = new(); + } +} diff --git a/UI/Config/Debugger/TraceLoggerConfig.cs b/UI/Config/Debugger/TraceLoggerConfig.cs index c5c94620ea..c1e1ff353b 100644 --- a/UI/Config/Debugger/TraceLoggerConfig.cs +++ b/UI/Config/Debugger/TraceLoggerConfig.cs @@ -35,6 +35,8 @@ public partial class TraceLoggerConfig : BaseWindowConfig [ObservableProperty] public partial TraceLoggerCpuConfig GbaConfig { get; set; } = new(); [ObservableProperty] public partial TraceLoggerCpuConfig WsConfig { get; set; } = new(); + [ObservableProperty] public partial TraceLogOutputConfig OutputConfig { get; set; } = new(); + public TraceLoggerConfig() { } diff --git a/UI/Config/PlatformAttributes.cs b/UI/Config/PlatformAttributes.cs new file mode 100644 index 0000000000..bb49e34957 --- /dev/null +++ b/UI/Config/PlatformAttributes.cs @@ -0,0 +1,15 @@ +using System; +using Mesen.Interop; + +namespace Mesen.Config +{ + public class RestrictToPlatformsAttribute : Attribute + { + public CpuType[] SupportedCpuTypes { get; set; } + + public RestrictToPlatformsAttribute(params CpuType[] supportedCpuTypes) + { + this.SupportedCpuTypes = supportedCpuTypes; + } + } +} diff --git a/UI/Debugger/ViewModels/TraceLogOutputConfigurationViewModel.cs b/UI/Debugger/ViewModels/TraceLogOutputConfigurationViewModel.cs new file mode 100644 index 0000000000..4f86c63090 --- /dev/null +++ b/UI/Debugger/ViewModels/TraceLogOutputConfigurationViewModel.cs @@ -0,0 +1,161 @@ +using Avalonia.Data; +using Avalonia.Data.Converters; +using CommunityToolkit.Mvvm.ComponentModel; +using Mesen.Config; +using Mesen.Interop; +using Mesen.Utilities; +using Mesen.ViewModels; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Reflection; + +namespace Mesen.Debugger.ViewModels +{ + public class RestrictToPlatformValueConverter : IMultiValueConverter + { + public object? Convert(IList values, Type targetType, object? parameter, CultureInfo culture) + { + if(values.Count == 2 + && values[0] is object propertyOwner + && values[1] is CpuType cpuType + && parameter is string propertyName) { + if(typeof(bool).IsAssignableTo(targetType) && propertyOwner != null) { + return IsPropertyAllowedOnPlatform(propertyOwner, propertyName, cpuType); + } + } + + return new BindingNotification(new InvalidCastException(), BindingErrorType.Error); + } + + private bool IsPropertyAllowedOnPlatform(object propertyOwner, string propertyName, CpuType cpuType) + { + Type ownerType = propertyOwner.GetType(); + + // This here stinks quite a bit. This is only here to silence a warning on GetProperty(). + // This could be solved differently, but this here feels like the least invasive solution. + if(ownerType == typeof(TraceLogOutputCpuDependentConfig)) { + ownerType = typeof(TraceLogOutputCpuDependentConfig); + } else if(ownerType == typeof(TraceLogOutputSharedConfig)) { + ownerType = typeof(TraceLogOutputSharedConfig); + } else if(ownerType == typeof(TraceLogOutputFileConfig)) { + ownerType = typeof(TraceLogOutputFileConfig); + } else if(ownerType == typeof(TraceLogOutputNetworkSocketConfig)) { + ownerType = typeof(TraceLogOutputNetworkSocketConfig); + } else if(ownerType == typeof(TraceLogOutputConfig)) { + ownerType = typeof(TraceLogOutputConfig); + } else { + return true; + } + + PropertyInfo? propertyInfo = ownerType.GetProperty(propertyName); + + if(propertyInfo == null) { + return false; + } + + RestrictToPlatformsAttribute? resrictAttribute = (RestrictToPlatformsAttribute?)Attribute.GetCustomAttribute(propertyInfo, typeof(RestrictToPlatformsAttribute)); + + if(resrictAttribute != null) { + foreach(var allowedCpuType in resrictAttribute.SupportedCpuTypes) { + if(allowedCpuType == cpuType) { + return true; + } + } + + return false; + } + + return true; + } + } + + public partial class TraceLogOutputConfigurationViewModel : DisposableViewModel + { + public TraceLogOutputConfig Config { get; } + + public Enum[] AvailableFormats { get; private set; } = []; + public Enum[] AvailableCompressionTypes { get; private set; } = []; + + [ObservableProperty] public partial bool IsUsingTextFormat { get; set; } = true; + + [Obsolete("For designer only")] + public TraceLogOutputConfigurationViewModel() : this(CpuType.Snes, new()) + { + } + + public TraceLogOutputConfigurationViewModel(CpuType cpuType, TraceLogOutputConfig config) + { + Config = config; + Config.SharedConfig.LastUsedCpuType = cpuType; + + AvailableFormats = FilterEnumByPlatform(cpuType).ToArray(); + AvailableCompressionTypes = FilterEnumByPlatform(cpuType).ToArray(); + + UpdateUsingTextFormat(); + + AddDisposable(ReactiveHelper.RegisterRecursiveObserver(Config, OnOptionsChanged)); + } + + // This could be useful in other places as well, so maybe it should move to another location later. + private static List FilterEnumByPlatform< + [DynamicallyAccessedMembers( + DynamicallyAccessedMemberTypes.PublicConstructors | + DynamicallyAccessedMemberTypes.PublicMethods | + DynamicallyAccessedMemberTypes.PublicFields | + DynamicallyAccessedMemberTypes.PublicNestedTypes | + DynamicallyAccessedMemberTypes.PublicProperties | + DynamicallyAccessedMemberTypes.PublicEvents)] T + >(CpuType cpuType) where T : struct, Enum + { + Type enumType = typeof(T); + T[] values = Enum.GetValues(); + + List result = new(); + + foreach(T value in values) { + var memInfo = enumType.GetMember(value.ToString()); + object[] attributes = memInfo[0].GetCustomAttributes(typeof(RestrictToPlatformsAttribute), false); + + bool exclude = false; + + foreach(var attribute in attributes) { + if(attribute is RestrictToPlatformsAttribute resrictAttribute) { + exclude = true; + + foreach(var allowedCpuType in resrictAttribute.SupportedCpuTypes) { + if(allowedCpuType == cpuType) { + exclude = false; + break; + } + } + } + } + + if(!exclude) { + result.Add(value); + } + } + + return result; + } + + + public void UpdateUsingTextFormat() + { + IsUsingTextFormat = !Config.ShowAdvancedSettings || Config.SharedConfig.CpuDependentConfig.Format == TraceLogOutputFormat.Text; + } + + public void UpdateOptions() + { + UpdateUsingTextFormat(); + } + + private void OnOptionsChanged(object? sender, PropertyChangedEventArgs e) + { + UpdateOptions(); + } + } +} diff --git a/UI/Debugger/ViewModels/TraceLoggerViewModel.cs b/UI/Debugger/ViewModels/TraceLoggerViewModel.cs index a58385a43f..e3b611dc85 100644 --- a/UI/Debugger/ViewModels/TraceLoggerViewModel.cs +++ b/UI/Debugger/ViewModels/TraceLoggerViewModel.cs @@ -31,7 +31,7 @@ public partial class TraceLoggerViewModel : DisposableViewModel, ISelectableMode [ObservableProperty] public partial int ScrollPosition { get; set; } = 0; [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 IsLoggingToStream { get; set; } = false; [ObservableProperty] public partial List Tabs { get; set; } = new(); [ObservableProperty] public partial TraceLoggerOptionTab SelectedTab { get; set; } = null!; @@ -86,8 +86,8 @@ public TraceLoggerViewModel() AddDisposable(this.ObserveProp(nameof(MinScrollPosition), UpdateScrollPosition)); AddDisposable(this.ObserveProp(nameof(MaxScrollPosition), UpdateScrollPosition)); - AddDisposable(this.ObserveProp(nameof(IsLoggingToFile), () => { - AllowOpenTraceFile = !IsLoggingToFile && TraceFile != null; + AddDisposable(this.ObserveProp(nameof(IsLoggingToStream), () => { + AllowOpenTraceFile = !IsLoggingToStream && TraceFile != null; })); AddDisposable(this.ObserveProp([nameof(SelectionStart), nameof(SelectionEnd), nameof(SelectedRow), nameof(SelectionAnchor)], () => { diff --git a/UI/Debugger/Windows/TraceLogOutputConfigurationWindow.axaml b/UI/Debugger/Windows/TraceLogOutputConfigurationWindow.axaml new file mode 100644 index 0000000000..f94f119d02 --- /dev/null +++ b/UI/Debugger/Windows/TraceLogOutputConfigurationWindow.axaml @@ -0,0 +1,237 @@ + + + + + + + + + + + + + + + + +