From a2f4c83c90d34eb9e72d780169985709494f540d Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Wed, 26 Dec 2012 20:15:31 -0800 Subject: [PATCH 01/29] Initial state saving for kernelObjects. --- Core/HLE/sceKernel.cpp | 35 +++++++++++++++++++++++++++++++++++ Core/HLE/sceKernel.h | 12 ++++++++---- 2 files changed, 43 insertions(+), 4 deletions(-) diff --git a/Core/HLE/sceKernel.cpp b/Core/HLE/sceKernel.cpp index 27d8464fb4..1883e7b64b 100644 --- a/Core/HLE/sceKernel.cpp +++ b/Core/HLE/sceKernel.cpp @@ -136,6 +136,18 @@ void __KernelShutdown() kernelRunning = false; } +void __KernelDoState(PointerWrap &p) +{ + kernelObjects.DoState(p); + p.DoMarker("KernelObjects"); + // TODO + // kernelObjects + // modules + // core timing + // memstick + // filesystem +} + bool __KernelIsRunning() { return kernelRunning; } @@ -304,6 +316,29 @@ int KernelObjectPool::GetCount() return count; } +void KernelObjectPool::DoState(PointerWrap &p) +{ + int _maxCount = maxCount; + p.Do(_maxCount); + p.DoArray(occupied, maxCount); + for (int i = 0; i < maxCount; ++i) + { + if (!occupied[i]) + continue; + + KernelObject *t = pool[i]; + if (!t) + { + // TODO: Pass down error? + ERROR_LOG(HLE, "Unable to save state: inconsistent kernel object pool."); + return; + } + + t->DoState(p); + } + p.DoMarker("KernelObjectPool"); +} + void sceKernelIcacheInvalidateAll() { DEBUG_LOG(CPU, "Icache invalidated - should clear JIT someday"); diff --git a/Core/HLE/sceKernel.h b/Core/HLE/sceKernel.h index bf5d609c10..cfb1c1cfcb 100644 --- a/Core/HLE/sceKernel.h +++ b/Core/HLE/sceKernel.h @@ -18,6 +18,7 @@ #pragma once #include "../../Globals.h" +#include "../../Common/ChunkFile.h" #include enum @@ -263,6 +264,7 @@ struct SceKernelLoadExecParam void __KernelInit(); void __KernelShutdown(); +void __KernelDoState(PointerWrap &p); bool __KernelIsRunning(); bool __KernelLoadExec(const char *filename, SceKernelLoadExecParam *param); @@ -311,9 +313,11 @@ public: // Implement this in all subclasses: // static u32 GetMissingErrorCode() - // Future - // void Serialize(ChunkFile) - // void DeSerialize(ChunkFile) + virtual void DoState(PointerWrap &p) + { + // TODO + //_dbg_assert_msg_(HLE, false, "Bad kernel object"); + } }; @@ -325,7 +329,7 @@ public: // Allocates a UID within the range and inserts the object into the map. SceUID Create(KernelObject *obj, int rangeBottom = 16, int rangeTop = 0x7fffffff); - // TODO: How will we ever save/restore this pool? + void DoState(PointerWrap &p); template u32 Destroy(SceUID handle) From 991243fffdcdfb618fec755748bee08bbf8551f1 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Wed, 26 Dec 2012 20:34:10 -0800 Subject: [PATCH 02/29] Add basic DoState() to tertiary kernel objects. --- Core/HLE/sceKernel.h | 3 +-- Core/HLE/sceKernelAlarm.cpp | 26 +++++++++++++++++++++----- Core/HLE/sceKernelEventFlag.cpp | 7 +++++++ Core/HLE/sceKernelMbx.cpp | 7 +++++++ Core/HLE/sceKernelMsgPipe.cpp | 19 ++++++++++++++----- Core/HLE/sceKernelMutex.cpp | 16 ++++++++++++++++ Core/HLE/sceKernelSemaphore.cpp | 7 +++++++ Core/HLE/sceKernelVTimer.cpp | 12 ++++++++++++ 8 files changed, 85 insertions(+), 12 deletions(-) diff --git a/Core/HLE/sceKernel.h b/Core/HLE/sceKernel.h index cfb1c1cfcb..9ae451eb8e 100644 --- a/Core/HLE/sceKernel.h +++ b/Core/HLE/sceKernel.h @@ -315,8 +315,7 @@ public: virtual void DoState(PointerWrap &p) { - // TODO - //_dbg_assert_msg_(HLE, false, "Bad kernel object"); + _dbg_assert_msg_(HLE, false, "Unable to save state: bad kernel object."); } }; diff --git a/Core/HLE/sceKernelAlarm.cpp b/Core/HLE/sceKernelAlarm.cpp index 4e378b2a49..3a26a7788b 100644 --- a/Core/HLE/sceKernelAlarm.cpp +++ b/Core/HLE/sceKernelAlarm.cpp @@ -37,6 +37,13 @@ struct Alarm : public KernelObject const char *GetTypeName() {return "Alarm";} static u32 GetMissingErrorCode() { return SCE_KERNEL_ERROR_UNKNOWN_ALMID; } int GetIDType() const { return SCE_KERNEL_TMID_Alarm; } + + virtual void DoState(PointerWrap &p) + { + p.Do(alm); + p.DoMarker("Alarm"); + } + NativeAlarm alm; }; @@ -47,7 +54,7 @@ class AlarmIntrHandler : public SubIntrHandler public: AlarmIntrHandler(Alarm *alarm) { - this->alarm = alarm; + alarmID = alarm->GetUID(); handlerAddress = alarm->alm.handlerPtr; enabled = true; } @@ -56,26 +63,35 @@ public: { SubIntrHandler::copyArgsToCPU(pend); - currentMIPS->r[MIPS_REG_A0] = alarm->alm.commonPtr; + u32 error; + Alarm *alarm = kernelObjects.Get(alarmID, error); + if (alarm) + currentMIPS->r[MIPS_REG_A0] = alarm->alm.commonPtr; + else + ERROR_LOG(HLE, "sceKernelAlarm: Unable to send interrupt args: alarm deleted?"); } virtual void handleResult(int result) { // A non-zero result means to reschedule. if (result > 0) + { + u32 error; + Alarm *alarm = kernelObjects.Get(alarmID, error); __KernelScheduleAlarm(alarm, (u64) usToCycles(result)); + } else { if (result < 0) WARN_LOG(HLE, "Alarm requested reschedule for negative value %u, ignoring", (unsigned) result); // Delete the alarm if it's not rescheduled. - __ReleaseSubInterruptHandler(PSP_SYSTIMER0_INTR, alarm->GetUID()); - kernelObjects.Destroy(alarm->GetUID()); + kernelObjects.Destroy(alarmID); + __ReleaseSubInterruptHandler(PSP_SYSTIMER0_INTR, alarmID); } } - Alarm *alarm; + SceUID alarmID; }; static int alarmTimer = 0; diff --git a/Core/HLE/sceKernelEventFlag.cpp b/Core/HLE/sceKernelEventFlag.cpp index a28c06c0d6..5a2c625117 100644 --- a/Core/HLE/sceKernelEventFlag.cpp +++ b/Core/HLE/sceKernelEventFlag.cpp @@ -63,6 +63,13 @@ public: } int GetIDType() const { return SCE_KERNEL_TMID_EventFlag; } + virtual void DoState(PointerWrap &p) + { + p.Do(nef); + p.Do(waitingThreads); + p.DoMarker("EventFlag"); + } + NativeEventFlag nef; std::vector waitingThreads; }; diff --git a/Core/HLE/sceKernelMbx.cpp b/Core/HLE/sceKernelMbx.cpp index c8c758a215..080226870e 100644 --- a/Core/HLE/sceKernelMbx.cpp +++ b/Core/HLE/sceKernelMbx.cpp @@ -153,6 +153,13 @@ struct Mbx : public KernelObject return 0; } + virtual void DoState(PointerWrap &p) + { + p.Do(nmb); + p.Do(waitingThreads); + p.DoMarker("Mbx"); + } + NativeMbx nmb; std::vector waitingThreads; diff --git a/Core/HLE/sceKernelMsgPipe.cpp b/Core/HLE/sceKernelMsgPipe.cpp index 1521d5f188..e98786f366 100644 --- a/Core/HLE/sceKernelMsgPipe.cpp +++ b/Core/HLE/sceKernelMsgPipe.cpp @@ -56,11 +56,6 @@ struct MsgPipe : public KernelObject static u32 GetMissingErrorCode() { return SCE_KERNEL_ERROR_UNKNOWN_MPPID; } int GetIDType() const { return SCE_KERNEL_TMID_Mpipe; } - NativeMsgPipe nmp; - - std::vector sendWaitingThreads; - std::vector receiveWaitingThreads; - void AddWaitingThread(std::vector &list, SceUID id, u32 addr, u32 size, int waitMode, u32 transferredBytesAddr, bool usePrio) { MsgPipeWaitingThread thread = { id, addr, size, size, waitMode, transferredBytesAddr }; @@ -150,6 +145,20 @@ struct MsgPipe : public KernelObject } } + virtual void DoState(PointerWrap &p) + { + p.Do(nmp); + p.Do(sendWaitingThreads); + p.Do(receiveWaitingThreads); + p.DoArray(buffer, nmp.bufSize); + p.DoMarker("MsgPipe"); + } + + NativeMsgPipe nmp; + + std::vector sendWaitingThreads; + std::vector receiveWaitingThreads; + u8 *buffer; }; diff --git a/Core/HLE/sceKernelMutex.cpp b/Core/HLE/sceKernelMutex.cpp index e3d048e545..b5a78afdfe 100644 --- a/Core/HLE/sceKernelMutex.cpp +++ b/Core/HLE/sceKernelMutex.cpp @@ -62,6 +62,14 @@ struct Mutex : public KernelObject const char *GetTypeName() {return "Mutex";} static u32 GetMissingErrorCode() { return PSP_MUTEX_ERROR_NO_SUCH_MUTEX; } int GetIDType() const { return SCE_KERNEL_TMID_Mutex; } + + virtual void DoState(PointerWrap &p) + { + p.Do(nm); + p.Do(waitingThreads); + p.DoMarker("Mutex"); + } + NativeMutex nm; std::vector waitingThreads; }; @@ -103,6 +111,14 @@ struct LwMutex : public KernelObject const char *GetTypeName() {return "LwMutex";} static u32 GetMissingErrorCode() { return PSP_LWMUTEX_ERROR_NO_SUCH_LWMUTEX; } int GetIDType() const { return SCE_KERNEL_TMID_LwMutex; } + + virtual void DoState(PointerWrap &p) + { + p.Do(nm); + p.Do(waitingThreads); + p.DoMarker("LwMutex"); + } + NativeLwMutex nm; std::vector waitingThreads; }; diff --git a/Core/HLE/sceKernelSemaphore.cpp b/Core/HLE/sceKernelSemaphore.cpp index 2fd575d0d4..54c30ae831 100644 --- a/Core/HLE/sceKernelSemaphore.cpp +++ b/Core/HLE/sceKernelSemaphore.cpp @@ -57,6 +57,13 @@ struct Semaphore : public KernelObject static u32 GetMissingErrorCode() { return SCE_KERNEL_ERROR_UNKNOWN_SEMID; } int GetIDType() const { return SCE_KERNEL_TMID_Semaphore; } + virtual void DoState(PointerWrap &p) + { + p.Do(ns); + p.Do(waitingThreads); + p.DoMarker("Semaphore"); + } + NativeSemaphore ns; std::vector waitingThreads; }; diff --git a/Core/HLE/sceKernelVTimer.cpp b/Core/HLE/sceKernelVTimer.cpp index 299e47fd6b..ad3d383141 100644 --- a/Core/HLE/sceKernelVTimer.cpp +++ b/Core/HLE/sceKernelVTimer.cpp @@ -30,6 +30,18 @@ struct VTimer : public KernelObject static u32 GetMissingErrorCode() { return SCE_KERNEL_ERROR_UNKNOWN_VTID; } int GetIDType() const { return SCE_KERNEL_TMID_VTimer; } + virtual void DoState(PointerWrap &p) + { + p.Do(size); + p.Do(name); + p.Do(startTime); + p.Do(running); + p.Do(handler); + p.Do(handlerTime); + p.Do(argument); + p.DoMarker("VTimer"); + } + SceSize size; char name[KERNELOBJECT_MAX_NAME_LENGTH+1]; u64 startTime; From d9efdf548b9f244413108395abf6618b59c68177 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Wed, 26 Dec 2012 21:07:29 -0800 Subject: [PATCH 03/29] Add basic state for the memory kernel objects. Not the actual memory partitions quite yet. --- Common/ChunkFile.h | 22 +++++++++++++++++++++- Core/HLE/sceKernelMemory.cpp | 34 ++++++++++++++++++++++++++++++---- Core/Util/BlockAllocator.cpp | 10 ++++++++++ Core/Util/BlockAllocator.h | 5 ++++- 4 files changed, 65 insertions(+), 6 deletions(-) diff --git a/Common/ChunkFile.h b/Common/ChunkFile.h index 7228365ccd..83270c32ac 100644 --- a/Common/ChunkFile.h +++ b/Common/ChunkFile.h @@ -31,6 +31,7 @@ #include #include #include +#include #include "Common.h" #include "FileUtil.h" @@ -133,7 +134,26 @@ public: for(i = 0; i < deq_size; i++) DoVoid(&x[i],sizeof(T)); } - + + // Store STL lists. + template + void Do(std::list &x) + { + T dv; + Do(x, dv); + } + + template + void Do(std::list &x, T &default_val) + { + u32 list_size = (u32)x.size(); + x.resize(list_size, default_val); + + typename std::list::iterator itr, end; + for (itr = x.begin(), end = x.end(); itr != end; ++itr) + Do(*itr); + } + // Store strings. void Do(std::string &x) { diff --git a/Core/HLE/sceKernelMemory.cpp b/Core/HLE/sceKernelMemory.cpp index 0b5a3c49b7..2b06e0108a 100644 --- a/Core/HLE/sceKernelMemory.cpp +++ b/Core/HLE/sceKernelMemory.cpp @@ -59,9 +59,6 @@ struct FPL : KernelObject const char *GetTypeName() {return "FPL";} static u32 GetMissingErrorCode() { return SCE_KERNEL_ERROR_UNKNOWN_FPLID; } int GetIDType() const { return SCE_KERNEL_TMID_Fpl; } - NativeFPL nf; - bool *blocks; - u32 address; int findFreeBlock() { for (int i = 0; i < nf.numBlocks; i++) { @@ -85,6 +82,18 @@ struct FPL : KernelObject } return false; } + + virtual void DoState(PointerWrap &p) + { + p.Do(nf); + p.DoArray(blocks, nf.numBlocks); + p.Do(address); + p.DoMarker("FPL"); + } + + NativeFPL nf; + bool *blocks; + u32 address; }; struct SceKernelVplInfo @@ -103,9 +112,18 @@ struct VPL : KernelObject const char *GetTypeName() {return "VPL";} static u32 GetMissingErrorCode() { return SCE_KERNEL_ERROR_UNKNOWN_VPLID; } int GetIDType() const { return SCE_KERNEL_TMID_Vpl; } + + virtual void DoState(PointerWrap &p) + { + p.Do(nv); + p.Do(size); + p.Do(address); + alloc.DoState(p); + p.DoMarker("VPL"); + } + SceKernelVplInfo nv; u32 size; - bool *freeBlocks; u32 address; BlockAllocator alloc; }; @@ -364,6 +382,14 @@ public: } bool IsValid() {return address != (u32)-1;} BlockAllocator *alloc; + + virtual void DoState(PointerWrap &p) + { + p.Do(address); + p.Do(name); + p.DoMarker("PMB"); + } + u32 address; char name[32]; }; diff --git a/Core/Util/BlockAllocator.cpp b/Core/Util/BlockAllocator.cpp index 27183cbff8..66cc8484e7 100644 --- a/Core/Util/BlockAllocator.cpp +++ b/Core/Util/BlockAllocator.cpp @@ -297,3 +297,13 @@ u32 BlockAllocator::GetTotalFreeBytes() } return sum; } + +void BlockAllocator::DoState(PointerWrap &p) +{ + Block default_value(0, 0, false); + p.Do(blocks, default_value); + p.Do(rangeStart_); + p.Do(rangeSize_); + p.Do(grain_); + p.DoMarker("BlockAllocator"); +} diff --git a/Core/Util/BlockAllocator.h b/Core/Util/BlockAllocator.h index 7ed26d3fc6..dc75a8292e 100644 --- a/Core/Util/BlockAllocator.h +++ b/Core/Util/BlockAllocator.h @@ -2,6 +2,7 @@ #pragma once #include "../../Globals.h" +#include "../../Common/ChunkFile.h" #include #include @@ -22,7 +23,7 @@ public: void ListBlocks(); - // WARNING: size can be modified upwards! + // WARNING: size can be modified upwards! u32 Alloc(u32 &size, bool fromTop = false, const char *tag = 0); u32 AllocAt(u32 position, u32 size, const char *tag = 0); @@ -42,6 +43,8 @@ public: u32 GetLargestFreeBlockSize(); u32 GetTotalFreeBytes(); + void DoState(PointerWrap &p); + private: void CheckBlocks(); From 595759ef78f0ea320335b67c5340fac87c5246ec Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Wed, 26 Dec 2012 22:45:19 -0800 Subject: [PATCH 04/29] Implement a factory for kernel objects. Couldn't think of a better way to do this, maybe there's some fancy one I don't know about. Also finished up a couple left over kernel objects. Maybe a quarter the way there? --- Common/ChunkFile.h | 37 +++++++++++++++++++ Core/FileSystems/FileSystem.h | 15 ++++++++ Core/HLE/sceIo.cpp | 34 ++++++++++++++++- Core/HLE/sceIo.h | 3 ++ Core/HLE/sceKernel.cpp | 65 +++++++++++++++++++++++++++++---- Core/HLE/sceKernel.h | 8 ++++ Core/HLE/sceKernelAlarm.cpp | 6 +++ Core/HLE/sceKernelAlarm.h | 1 + Core/HLE/sceKernelEventFlag.cpp | 6 +++ Core/HLE/sceKernelEventFlag.h | 1 + Core/HLE/sceKernelMbx.cpp | 5 +++ Core/HLE/sceKernelMbx.h | 1 + Core/HLE/sceKernelMemory.cpp | 31 +++++++++++++--- Core/HLE/sceKernelMemory.h | 4 ++ Core/HLE/sceKernelModule.cpp | 16 +++++++- Core/HLE/sceKernelModule.h | 2 + Core/HLE/sceKernelMsgPipe.cpp | 5 +++ Core/HLE/sceKernelMsgPipe.h | 4 +- Core/HLE/sceKernelMutex.cpp | 10 +++++ Core/HLE/sceKernelMutex.h | 2 + Core/HLE/sceKernelSemaphore.cpp | 5 +++ Core/HLE/sceKernelSemaphore.h | 1 + Core/HLE/sceKernelThread.cpp | 50 +++++++++++++++++++++++++ Core/HLE/sceKernelThread.h | 2 + Core/HLE/sceKernelVTimer.cpp | 5 +++ Core/HLE/sceKernelVTimer.h | 2 + 26 files changed, 304 insertions(+), 17 deletions(-) diff --git a/Common/ChunkFile.h b/Common/ChunkFile.h index 83270c32ac..00d8593000 100644 --- a/Common/ChunkFile.h +++ b/Common/ChunkFile.h @@ -32,6 +32,7 @@ #include #include #include +#include #include "Common.h" #include "FileUtil.h" @@ -147,6 +148,7 @@ public: void Do(std::list &x, T &default_val) { u32 list_size = (u32)x.size(); + Do(list_size); x.resize(list_size, default_val); typename std::list::iterator itr, end; @@ -154,6 +156,41 @@ public: Do(*itr); } + // Store STL sets. + template + void Do(std::set &x) + { + unsigned int number = (unsigned int)x.size(); + Do(number); + + switch (mode) + { + case MODE_READ: + { + x.clear(); + while (number-- > 0) + { + T it; + Do(it); + x.insert(it); + } + } + break; + case MODE_WRITE: + case MODE_MEASURE: + case MODE_VERIFY: + { + typename std::set::iterator itr = x.begin(); + while (number-- > 0) + Do(*itr++); + } + break; + + default: + ERROR_LOG(COMMON, "Savestate error: invalid mode %d.", mode); + } + } + // Store strings. void Do(std::string &x) { diff --git a/Core/FileSystems/FileSystem.h b/Core/FileSystems/FileSystem.h index ab1c1e48d2..d14854803e 100644 --- a/Core/FileSystems/FileSystem.h +++ b/Core/FileSystems/FileSystem.h @@ -18,6 +18,7 @@ #pragma once #include "../../Globals.h" +#include "../../Common/ChunkFile.h" #include enum FileAccess @@ -56,6 +57,20 @@ struct PSPFileInfo PSPFileInfo() : size(0), access(0), exists(false), type(FILETYPE_NORMAL), isOnSectorSystem(false), startSector(0), numSectors(0) {} + void DoState(PointerWrap &p) + { + p.Do(name); + p.Do(size); + p.Do(access); + p.Do(exists); + p.Do(type); + p.Do(mtime); + p.Do(isOnSectorSystem); + p.Do(startSector); + p.Do(numSectors); + p.DoMarker("PSPFileInfo"); + } + std::string name; s64 size; u32 access; //unix 777 diff --git a/Core/HLE/sceIo.cpp b/Core/HLE/sceIo.cpp index 2523539a0a..801b4bf917 100644 --- a/Core/HLE/sceIo.cpp +++ b/Core/HLE/sceIo.cpp @@ -137,7 +137,18 @@ public: sprintf(ptr, "Seekpos: %08x", (u32)pspFileSystem.GetSeekPos(handle)); } static u32 GetMissingErrorCode() { return SCE_KERNEL_ERROR_BADF; } - int GetIDType() const { return 0; } + int GetIDType() const { return PPSSPP_KERNEL_TMID_File; } + + virtual void DoState(PointerWrap &p) { + p.Do(fullpath); + p.Do(handle); + p.Do(callbackID); + p.Do(callbackArg); + p.Do(asyncResult); + p.Do(pendingAsyncResult); + p.Do(sectorBlockMode); + p.DoMarker("File"); + } std::string fullpath; u32 handle; @@ -836,7 +847,18 @@ public: const char *GetName() {return name.c_str();} const char *GetTypeName() {return "DirListing";} static u32 GetMissingErrorCode() { return SCE_KERNEL_ERROR_BADF; } - int GetIDType() const { return 0; } + int GetIDType() const { return PPSSPP_KERNEL_TMID_DirList; } + + virtual void DoState(PointerWrap &p) { + p.Do(name); + + // TODO: Is this the right way for it to wake up? + size_t count = listing.size(); + for (size_t i = 0; i < count; ++i) { + listing[i].DoState(p); + } + p.DoMarker("DirListing"); + } std::string name; std::vector listing; @@ -920,6 +942,14 @@ u32 sceIoIoctl(u32 id, u32 cmd, u32 indataPtr, u32 inlen, u32 outdataPtr, u32 ou return 0; } +KernelObject *__KernelFileNodeObject() { + return new FileNode; +} + +KernelObject *__KernelDirListingObject() { + return new DirListing; +} + const HLEFunction IoFileMgrForUser[] = { { 0xb29ddf9c, &WrapU_C, "sceIoDopen" }, { 0xe3eb004c, &WrapU_IU, "sceIoDread" }, diff --git a/Core/HLE/sceIo.h b/Core/HLE/sceIo.h index 907fd6046b..8015bd93d9 100644 --- a/Core/HLE/sceIo.h +++ b/Core/HLE/sceIo.h @@ -19,9 +19,12 @@ #include #include "HLE.h" +#include "sceKernel.h" void __IoInit(); void __IoShutdown(); +KernelObject *__KernelFileNodeObject(); +KernelObject *__KernelDirListingObject(); void Register_IoFileMgrForUser(); void Register_StdioForUser(); diff --git a/Core/HLE/sceKernel.cpp b/Core/HLE/sceKernel.cpp index 1883e7b64b..947d6d3a48 100644 --- a/Core/HLE/sceKernel.cpp +++ b/Core/HLE/sceKernel.cpp @@ -320,25 +320,76 @@ void KernelObjectPool::DoState(PointerWrap &p) { int _maxCount = maxCount; p.Do(_maxCount); + + if (_maxCount != maxCount) + ERROR_LOG(HLE, "Unable to load state: different kernel object storage."); + + // Assumption: on load, we've already cleared. p.DoArray(occupied, maxCount); for (int i = 0; i < maxCount; ++i) { if (!occupied[i]) continue; - KernelObject *t = pool[i]; - if (!t) + int type; + if (p.mode == p.MODE_READ) { - // TODO: Pass down error? - ERROR_LOG(HLE, "Unable to save state: inconsistent kernel object pool."); - return; + p.Do(type); + pool[i] = CreateByIDType(type); } - - t->DoState(p); + else + { + type = pool[i]->GetIDType(); + p.Do(type); + } + pool[i]->DoState(p); } p.DoMarker("KernelObjectPool"); } +KernelObject *KernelObjectPool::CreateByIDType(int type) +{ + // Used for save states. This is ugly, but what other way is there? + switch (type) + { + case SCE_KERNEL_TMID_Alarm: + return __KernelAlarmObject(); + case SCE_KERNEL_TMID_EventFlag: + return __KernelEventFlagObject(); + case SCE_KERNEL_TMID_Mbox: + return __KernelMbxObject(); + case SCE_KERNEL_TMID_Fpl: + return __KernelMemoryFPLObject(); + case SCE_KERNEL_TMID_Vpl: + return __KernelMemoryVPLObject(); + case PPSSPP_KERNEL_TMID_PMB: + return __KernelMemoryPMBObject(); + case PPSSPP_KERNEL_TMID_Module: + return __KernelModuleObject(); + case SCE_KERNEL_TMID_Mpipe: + return __KernelMsgPipeObject(); + case SCE_KERNEL_TMID_Mutex: + return __KernelMutexObject(); + case SCE_KERNEL_TMID_LwMutex: + return __KernelLwMutexObject(); + case SCE_KERNEL_TMID_Semaphore: + return __KernelSemaphoreObject(); + case SCE_KERNEL_TMID_Callback: + return __KernelCallbackObject(); + case SCE_KERNEL_TMID_Thread: + return __KernelThreadObject(); + case SCE_KERNEL_TMID_VTimer: + return __KernelVTimerObject(); + case PPSSPP_KERNEL_TMID_File: + return __KernelFileNodeObject(); + case PPSSPP_KERNEL_TMID_DirList: + return __KernelDirListingObject(); + + default: + ERROR_LOG(COMMON, "Unable to load state: could not find object type %d.", type); + } +} + void sceKernelIcacheInvalidateAll() { DEBUG_LOG(CPU, "Icache invalidated - should clear JIT someday"); diff --git a/Core/HLE/sceKernel.h b/Core/HLE/sceKernel.h index 9ae451eb8e..90835442d1 100644 --- a/Core/HLE/sceKernel.h +++ b/Core/HLE/sceKernel.h @@ -224,6 +224,7 @@ enum SCE_KERNEL_ERROR_ERRORMAX = 0x8002044d, }; +// If you add to this, make sure to check KernelObjectPool::CreateByIDType(). enum TMIDPurpose { SCE_KERNEL_TMID_Thread = 1, @@ -243,6 +244,12 @@ enum TMIDPurpose SCE_KERNEL_TMID_DelayThread = 65, SCE_KERNEL_TMID_SuspendThread = 66, SCE_KERNEL_TMID_DormantThread = 67, + + // Not official, but need ids for save states. + PPSSPP_KERNEL_TMID_Module = 0x100001, + PPSSPP_KERNEL_TMID_PMB = 0x100002, + PPSSPP_KERNEL_TMID_File = 0x100003, + PPSSPP_KERNEL_TMID_DirList = 0x100004, }; typedef int SceUID; @@ -329,6 +336,7 @@ public: SceUID Create(KernelObject *obj, int rangeBottom = 16, int rangeTop = 0x7fffffff); void DoState(PointerWrap &p); + static KernelObject *CreateByIDType(int type); template u32 Destroy(SceUID handle) diff --git a/Core/HLE/sceKernelAlarm.cpp b/Core/HLE/sceKernelAlarm.cpp index 3a26a7788b..ea833860ec 100644 --- a/Core/HLE/sceKernelAlarm.cpp +++ b/Core/HLE/sceKernelAlarm.cpp @@ -111,6 +111,12 @@ void __KernelAlarmInit() alarmTimer = CoreTiming::RegisterEvent("Alarm", __KernelTriggerAlarm); } +KernelObject *__KernelAlarmObject() +{ + // Default object to load from state. + return new Alarm; +} + void __KernelScheduleAlarm(Alarm *alarm, u64 ticks) { alarm->alm.schedule = (CoreTiming::GetTicks() + ticks) / (u64) CoreTiming::GetClockFrequencyMHz(); diff --git a/Core/HLE/sceKernelAlarm.h b/Core/HLE/sceKernelAlarm.h index 09dd2e2f82..24cc866e37 100644 --- a/Core/HLE/sceKernelAlarm.h +++ b/Core/HLE/sceKernelAlarm.h @@ -23,3 +23,4 @@ int sceKernelCancelAlarm(SceUID uid); int sceKernelReferAlarmStatus(SceUID uid, u32 infoPtr); void __KernelAlarmInit(); +KernelObject *__KernelAlarmObject(); diff --git a/Core/HLE/sceKernelEventFlag.cpp b/Core/HLE/sceKernelEventFlag.cpp index 5a2c625117..f0e5e16034 100644 --- a/Core/HLE/sceKernelEventFlag.cpp +++ b/Core/HLE/sceKernelEventFlag.cpp @@ -104,6 +104,12 @@ void __KernelEventFlagInit() eventFlagWaitTimer = CoreTiming::RegisterEvent("EventFlagTimeout", &__KernelEventFlagTimeout); } +KernelObject *__KernelEventFlagObject() +{ + // Default object to load from state. + return new EventFlag; +} + bool __KernelEventFlagMatches(u32 *pattern, u32 bits, u8 wait, u32 outAddr) { if ((wait & PSP_EVENT_WAITOR) diff --git a/Core/HLE/sceKernelEventFlag.h b/Core/HLE/sceKernelEventFlag.h index 4243b8d897..2eb1c659ba 100644 --- a/Core/HLE/sceKernelEventFlag.h +++ b/Core/HLE/sceKernelEventFlag.h @@ -28,3 +28,4 @@ u32 sceKernelReferEventFlagStatus(SceUID id, u32 statusPtr); u32 sceKernelCancelEventFlag(SceUID uid, u32 pattern, u32 numWaitThreadsPtr); void __KernelEventFlagInit(); +KernelObject *__KernelEventFlagObject(); diff --git a/Core/HLE/sceKernelMbx.cpp b/Core/HLE/sceKernelMbx.cpp index 080226870e..3ae6ae4f04 100644 --- a/Core/HLE/sceKernelMbx.cpp +++ b/Core/HLE/sceKernelMbx.cpp @@ -170,6 +170,11 @@ void __KernelMbxInit() mbxWaitTimer = CoreTiming::RegisterEvent("MbxTimeout", &__KernelMbxTimeout); } +KernelObject *__KernelMbxObject() +{ + return new Mbx; +} + bool __KernelUnlockMbxForThread(Mbx *m, MbxWaitingThread &th, u32 &error, int result, bool &wokeThreads) { SceUID waitID = __KernelGetWaitID(th.first, WAITTYPE_MBX, error); diff --git a/Core/HLE/sceKernelMbx.h b/Core/HLE/sceKernelMbx.h index 7edf6309e9..b0fb25e952 100644 --- a/Core/HLE/sceKernelMbx.h +++ b/Core/HLE/sceKernelMbx.h @@ -34,3 +34,4 @@ int sceKernelCancelReceiveMbx(SceUID id, u32 numWaitingThreadsAddr); int sceKernelReferMbxStatus(SceUID id, u32 infoAddr); void __KernelMbxInit(); +KernelObject *__KernelMbxObject(); diff --git a/Core/HLE/sceKernelMemory.cpp b/Core/HLE/sceKernelMemory.cpp index 2b06e0108a..807e74a2e1 100644 --- a/Core/HLE/sceKernelMemory.cpp +++ b/Core/HLE/sceKernelMemory.cpp @@ -53,7 +53,7 @@ struct NativeFPL }; //FPL - Fixed Length Dynamic Memory Pool - every item has the same length -struct FPL : KernelObject +struct FPL : public KernelObject { const char *GetName() {return nf.name;} const char *GetTypeName() {return "FPL";} @@ -106,7 +106,7 @@ struct SceKernelVplInfo int numWaitThreads; }; -struct VPL : KernelObject +struct VPL : public KernelObject { const char *GetName() {return nv.name;} const char *GetTypeName() {return "VPL";} @@ -368,13 +368,18 @@ public: sprintf(ptr, "MemPart: %08x - %08x size: %08x", address, address + sz, sz); } static u32 GetMissingErrorCode() { return SCE_KERNEL_ERROR_UNKNOWN_MPPID; } /// ???? - int GetIDType() const { return 0; } + int GetIDType() const { return PPSSPP_KERNEL_TMID_PMB; } PartitionMemoryBlock(BlockAllocator *_alloc, u32 size, bool fromEnd) { alloc = _alloc; - address = alloc->Alloc(size, fromEnd, "PMB"); - alloc->ListBlocks(); + + // 0 is used for save states to wake up. + if (size != 0) + { + address = alloc->Alloc(size, fromEnd, "PMB"); + alloc->ListBlocks(); + } } ~PartitionMemoryBlock() { @@ -620,6 +625,22 @@ void sceKernelSetCompilerVersion(int version) flags_ |= SCE_KERNEL_HASCOMPILERVERSION; } +KernelObject *__KernelMemoryFPLObject() +{ + return new FPL; +} + +KernelObject *__KernelMemoryVPLObject() +{ + return new VPL; +} + +KernelObject *__KernelMemoryPMBObject() +{ + // TODO: We could theoretically handle kernelMemory too, but we don't support that now anyway. + return new PartitionMemoryBlock(&userMemory, 0, true); +} + // VPL = variable length memory pool diff --git a/Core/HLE/sceKernelMemory.h b/Core/HLE/sceKernelMemory.h index eaf2e23f4c..cc5334ae89 100644 --- a/Core/HLE/sceKernelMemory.h +++ b/Core/HLE/sceKernelMemory.h @@ -18,6 +18,7 @@ #pragma once #include "../Util/BlockAllocator.h" +#include "sceKernel.h" //todo: "real" memory block allocator, @@ -30,6 +31,9 @@ extern BlockAllocator kernelMemory; void __KernelMemoryInit(); void __KernelMemoryShutdown(); +KernelObject *__KernelMemoryFPLObject(); +KernelObject *__KernelMemoryVPLObject(); +KernelObject *__KernelMemoryPMBObject(); void sceKernelCreateVpl(); void sceKernelDeleteVpl(); diff --git a/Core/HLE/sceKernelModule.cpp b/Core/HLE/sceKernelModule.cpp index a1b045bc9f..1f7b0c050c 100644 --- a/Core/HLE/sceKernelModule.cpp +++ b/Core/HLE/sceKernelModule.cpp @@ -117,13 +117,25 @@ public: nm.entry_addr); } static u32 GetMissingErrorCode() { return SCE_KERNEL_ERROR_UNKNOWN_MODULE; } - int GetIDType() const { return 0; } + int GetIDType() const { return PPSSPP_KERNEL_TMID_Module; } + + virtual void DoState(PointerWrap &p) + { + p.Do(nm); + p.Do(memoryBlockAddr); + p.DoMarker("Module"); + } NativeModule nm; u32 memoryBlockAddr; }; +KernelObject *__KernelModuleObject() +{ + return new Module; +} + ////////////////////////////////////////////////////////////////////////// // MODULES ////////////////////////////////////////////////////////////////////////// @@ -642,7 +654,7 @@ u32 sceKernelLoadModule(const char *name, u32 flags) class AfterModuleEntryCall : public Action { public: AfterModuleEntryCall() {} - Module *module_; + SceUID moduleID_; u32 retValAddr; virtual void run(); }; diff --git a/Core/HLE/sceKernelModule.h b/Core/HLE/sceKernelModule.h index 2652e1e55f..18e3d5f036 100644 --- a/Core/HLE/sceKernelModule.h +++ b/Core/HLE/sceKernelModule.h @@ -20,6 +20,8 @@ #include "sceKernel.h" #include "HLE.h" +KernelObject *__KernelModuleObject(); + u32 __KernelGetModuleGP(SceUID module); bool __KernelLoadExec(const char *filename, SceKernelLoadExecParam *param, std::string *error_string); diff --git a/Core/HLE/sceKernelMsgPipe.cpp b/Core/HLE/sceKernelMsgPipe.cpp index e98786f366..8d60cccf48 100644 --- a/Core/HLE/sceKernelMsgPipe.cpp +++ b/Core/HLE/sceKernelMsgPipe.cpp @@ -162,6 +162,11 @@ struct MsgPipe : public KernelObject u8 *buffer; }; +KernelObject *__KernelMsgPipeObject() +{ + return new MsgPipe; +} + void sceKernelCreateMsgPipe() { const char *name = Memory::GetCharPointer(PARAM(0)); diff --git a/Core/HLE/sceKernelMsgPipe.h b/Core/HLE/sceKernelMsgPipe.h index 0f262038b8..46f812f4ee 100644 --- a/Core/HLE/sceKernelMsgPipe.h +++ b/Core/HLE/sceKernelMsgPipe.h @@ -26,4 +26,6 @@ void sceKernelReceiveMsgPipe(); void sceKernelReceiveMsgPipeCB(); void sceKernelTryReceiveMsgPipe(); void sceKernelCancelMsgPipe(); -void sceKernelReferMsgPipeStatus(); \ No newline at end of file +void sceKernelReferMsgPipeStatus(); + +KernelObject *__KernelMsgPipeObject(); diff --git a/Core/HLE/sceKernelMutex.cpp b/Core/HLE/sceKernelMutex.cpp index b5a78afdfe..c0778031c7 100644 --- a/Core/HLE/sceKernelMutex.cpp +++ b/Core/HLE/sceKernelMutex.cpp @@ -137,6 +137,16 @@ void __KernelMutexInit() __KernelListenThreadEnd(&__KernelMutexThreadEnd); } +KernelObject *__KernelMutexObject() +{ + return new Mutex; +} + +KernelObject *__KernelLwMutexObject() +{ + return new LwMutex; +} + void __KernelMutexShutdown() { mutexHeldLocks.clear(); diff --git a/Core/HLE/sceKernelMutex.h b/Core/HLE/sceKernelMutex.h index de54371948..5db1f3b4d5 100644 --- a/Core/HLE/sceKernelMutex.h +++ b/Core/HLE/sceKernelMutex.h @@ -38,3 +38,5 @@ void __KernelMutexThreadEnd(SceUID thread); void __KernelMutexInit(); void __KernelMutexShutdown(); +KernelObject *__KernelMutexObject(); +KernelObject *__KernelLwMutexObject(); diff --git a/Core/HLE/sceKernelSemaphore.cpp b/Core/HLE/sceKernelSemaphore.cpp index 54c30ae831..0572a8d70d 100644 --- a/Core/HLE/sceKernelSemaphore.cpp +++ b/Core/HLE/sceKernelSemaphore.cpp @@ -75,6 +75,11 @@ void __KernelSemaInit() semaWaitTimer = CoreTiming::RegisterEvent("SemaphoreTimeout", &__KernelSemaTimeout); } +KernelObject *__KernelSemaphoreObject() +{ + return new Semaphore; +} + // Returns whether the thread should be removed. bool __KernelUnlockSemaForThread(Semaphore *s, SceUID threadID, u32 &error, int result, bool &wokeThreads) { diff --git a/Core/HLE/sceKernelSemaphore.h b/Core/HLE/sceKernelSemaphore.h index 9a8b9f2640..f816f97e41 100644 --- a/Core/HLE/sceKernelSemaphore.h +++ b/Core/HLE/sceKernelSemaphore.h @@ -29,3 +29,4 @@ int sceKernelWaitSemaCB(SceUID semaid, int signal, u32 timeoutPtr); void __KernelSemaTimeout(u64 userdata, int cycleslate); void __KernelSemaInit(); +KernelObject *__KernelSemaphoreObject(); diff --git a/Core/HLE/sceKernelThread.cpp b/Core/HLE/sceKernelThread.cpp index 8d03a17f8a..816c3f4a2c 100644 --- a/Core/HLE/sceKernelThread.cpp +++ b/Core/HLE/sceKernelThread.cpp @@ -113,6 +113,18 @@ public: static u32 GetMissingErrorCode() { return SCE_KERNEL_ERROR_UNKNOWN_CBID; } int GetIDType() const { return SCE_KERNEL_TMID_Callback; } + virtual void DoState(PointerWrap &p) + { + p.Do(nc); + p.Do(savedPC); + p.Do(savedRA); + p.Do(savedV0); + p.Do(savedV1); + p.Do(savedIdRegister); + p.Do(forceDelete); + p.DoMarker("Callback"); + } + NativeCallback nc; u32 savedPC; @@ -297,6 +309,34 @@ public: bool isWaiting() const { return (nt.status & THREADSTATUS_WAIT) != 0; } bool isSuspended() const { return (nt.status & THREADSTATUS_SUSPEND) != 0; } + virtual void DoState(PointerWrap &p) + { + p.Do(nt); + p.Do(waitInfo); + p.Do(sleeping); + p.Do(moduleId); + p.Do(isProcessingCallbacks); + p.Do(currentCallbackId); + p.Do(context); + + u32 numCallbacks = THREAD_CALLBACK_NUM_TYPES; + p.Do(numCallbacks); + if (numCallbacks != THREAD_CALLBACK_NUM_TYPES) + ERROR_LOG(HLE, "Unable to load state: different kernel object storage."); + + for (size_t i = 0; i < THREAD_CALLBACK_NUM_TYPES; ++i) + { + std::set::iterator it, end; + p.Do(registeredCallbacks[i]); + p.Do(readyCallbacks[i]); + } + + p.Do(pendingMipsCalls); + p.Do(stackBlock); + + p.DoMarker("Thread"); + } + NativeThread nt; ThreadWaitInfo waitInfo; @@ -409,6 +449,16 @@ void __KernelThreadingInit() __KernelListenThreadEnd(__KernelCancelWakeup); } +KernelObject *__KernelThreadObject() +{ + return new Thread; +} + +KernelObject *__KernelCallbackObject() +{ + return new Callback; +} + void __KernelListenThreadEnd(ThreadCallback callback) { threadEndListeners.push_back(callback); diff --git a/Core/HLE/sceKernelThread.h b/Core/HLE/sceKernelThread.h index 913511fe65..d11a33c17c 100644 --- a/Core/HLE/sceKernelThread.h +++ b/Core/HLE/sceKernelThread.h @@ -98,6 +98,8 @@ struct ThreadContext void __KernelThreadingInit(); void __KernelThreadingShutdown(); +KernelObject *__KernelThreadObject(); +KernelObject *__KernelCallbackObject(); void __KernelScheduleWakeup(int usFromNow, int threadnumber); SceUID __KernelGetCurThread(); diff --git a/Core/HLE/sceKernelVTimer.cpp b/Core/HLE/sceKernelVTimer.cpp index ad3d383141..35174f34f1 100644 --- a/Core/HLE/sceKernelVTimer.cpp +++ b/Core/HLE/sceKernelVTimer.cpp @@ -51,6 +51,11 @@ struct VTimer : public KernelObject u32 argument; }; +KernelObject *__KernelVTimerObject() +{ + return new VTimer; +} + void sceKernelCreateVTimer() { DEBUG_LOG(HLE,"sceKernelCreateVTimer"); diff --git a/Core/HLE/sceKernelVTimer.h b/Core/HLE/sceKernelVTimer.h index 260341b214..3597dfeb18 100644 --- a/Core/HLE/sceKernelVTimer.h +++ b/Core/HLE/sceKernelVTimer.h @@ -23,3 +23,5 @@ void sceKernelSetVTimerHandler(); // TODO void _sceKernelReturnFromTimerHandler(); + +KernelObject *__KernelVTimerObject(); From d6d3688c8c6d3119178b335661fb5a89ad650a6b Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Wed, 26 Dec 2012 22:50:45 -0800 Subject: [PATCH 05/29] Fix a warning if loading wrong version / etc. --- Core/HLE/sceKernel.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Core/HLE/sceKernel.cpp b/Core/HLE/sceKernel.cpp index 947d6d3a48..9ef1122e45 100644 --- a/Core/HLE/sceKernel.cpp +++ b/Core/HLE/sceKernel.cpp @@ -336,6 +336,10 @@ void KernelObjectPool::DoState(PointerWrap &p) { p.Do(type); pool[i] = CreateByIDType(type); + + // Already logged an error. + if (pool[i] == NULL) + return; } else { @@ -387,6 +391,7 @@ KernelObject *KernelObjectPool::CreateByIDType(int type) default: ERROR_LOG(COMMON, "Unable to load state: could not find object type %d.", type); + return NULL; } } From abeaaa91057abb78e3ad0e581d9e868755721128 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Thu, 27 Dec 2012 10:34:22 -0800 Subject: [PATCH 06/29] Add Verify() method to quickly test states work. --- CMakeLists.txt | 2 ++ Common/ChunkFile.h | 24 ++++++++++++++++++++ Core/Core.vcxproj | 2 ++ Core/Core.vcxproj.filters | 6 +++++ Core/HLE/sceKernel.cpp | 1 - Core/SaveState.cpp | 46 +++++++++++++++++++++++++++++++++++++++ Core/SaveState.h | 33 ++++++++++++++++++++++++++++ Qt/Core.pro | 2 ++ android/jni/Android.mk | 1 + 9 files changed, 116 insertions(+), 1 deletion(-) create mode 100644 Core/SaveState.cpp create mode 100644 Core/SaveState.h diff --git a/CMakeLists.txt b/CMakeLists.txt index caaee30936..5fd1b01c88 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -765,6 +765,8 @@ add_library(${CoreLibName} ${CoreLinkType} Core/PSPLoaders.h Core/PSPMixer.cpp Core/PSPMixer.h + Core/SaveState.cpp + Core/SaveState.h Core/System.cpp Core/System.h Core/Util/BlockAllocator.cpp diff --git a/Common/ChunkFile.h b/Common/ChunkFile.h index 00d8593000..eda388211e 100644 --- a/Common/ChunkFile.h +++ b/Common/ChunkFile.h @@ -428,6 +428,30 @@ public: return true; } + template + static bool Verify(T& _class) + { + u8 *ptr = 0; + + // Step 1: Measure the space required. + PointerWrap p(&ptr, PointerWrap::MODE_MEASURE); + _class.DoState(p); + size_t const sz = (size_t)ptr; + std::vector buffer(sz); + + // Step 2: Dump the state. + ptr = &buffer[0]; + p.SetMode(PointerWrap::MODE_WRITE); + _class.DoState(p); + + // Step 3: Verify the state. + ptr = &buffer[0]; + p.SetMode(PointerWrap::MODE_VERIFY); + _class.DoState(p); + + return true; + } + private: struct SChunkHeader { diff --git a/Core/Core.vcxproj b/Core/Core.vcxproj index f10562449e..089671dfb9 100644 --- a/Core/Core.vcxproj +++ b/Core/Core.vcxproj @@ -253,6 +253,7 @@ + @@ -371,6 +372,7 @@ + diff --git a/Core/Core.vcxproj.filters b/Core/Core.vcxproj.filters index 0784ba189c..d6bf753d66 100644 --- a/Core/Core.vcxproj.filters +++ b/Core/Core.vcxproj.filters @@ -348,6 +348,9 @@ HLE\Libraries + + Core + @@ -641,6 +644,9 @@ HLE\Libraries + + Core + diff --git a/Core/HLE/sceKernel.cpp b/Core/HLE/sceKernel.cpp index 9ef1122e45..da528027eb 100644 --- a/Core/HLE/sceKernel.cpp +++ b/Core/HLE/sceKernel.cpp @@ -141,7 +141,6 @@ void __KernelDoState(PointerWrap &p) kernelObjects.DoState(p); p.DoMarker("KernelObjects"); // TODO - // kernelObjects // modules // core timing // memstick diff --git a/Core/SaveState.cpp b/Core/SaveState.cpp new file mode 100644 index 0000000000..bbf0e2328d --- /dev/null +++ b/Core/SaveState.cpp @@ -0,0 +1,46 @@ +// Copyright (c) 2012- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#include "SaveState.h" +#include "MemMap.h" +#include "HLE/sceKernel.h" + +// TODO: Need a way to schedule via CoreTiming and actually run then. + +bool SaveState::Load(std::string &filename) +{ + SaveState state; + return CChunkFileReader::Load(filename, REVISION, state); +} + +bool SaveState::Save(std::string &filename) +{ + SaveState state; + return CChunkFileReader::Save(filename, REVISION, state); +} + +bool SaveState::Verify() +{ + SaveState state; + return CChunkFileReader::Verify(state); +} + +void SaveState::DoState(PointerWrap &p) +{ + Memory::DoState(p); + __KernelDoState(p); +} \ No newline at end of file diff --git a/Core/SaveState.h b/Core/SaveState.h new file mode 100644 index 0000000000..f0edfcf921 --- /dev/null +++ b/Core/SaveState.h @@ -0,0 +1,33 @@ +// Copyright (c) 2012- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#include "../Common/ChunkFile.h" + +struct SaveState +{ + // TODO: Better place for this? + static const int REVISION = 1; + + // Load the specified file into the current state. + static bool Load(std::string &filename); + // Save the current state to the specified file. + static bool Save(std::string &filename); + // For testing / automated tests. Runs a save state verification pass. + static bool Verify(); + + void DoState(PointerWrap &p); +}; \ No newline at end of file diff --git a/Qt/Core.pro b/Qt/Core.pro index 2a14f42b01..6c2cada922 100755 --- a/Qt/Core.pro +++ b/Qt/Core.pro @@ -121,6 +121,7 @@ SOURCES += ../Core/CPU.cpp \ # Core ../Core/MemMapFunctions.cpp \ ../Core/PSPLoaders.cpp \ ../Core/PSPMixer.cpp \ + ../Core/SaveState.cpp \ ../Core/System.cpp \ ../Core/Util/BlockAllocator.cpp \ ../Core/Util/PPGeDraw.cpp \ @@ -227,6 +228,7 @@ HEADERS += ../Core/CPU.h \ ../Core/MemMap.h \ ../Core/PSPLoaders.h \ ../Core/PSPMixer.h \ + ../Core/SaveState.h \ ../Core/System.h \ ../Core/Util/BlockAllocator.h \ ../Core/Util/PPGeDraw.h \ diff --git a/android/jni/Android.mk b/android/jni/Android.mk index 409fffe706..22887307ff 100644 --- a/android/jni/Android.mk +++ b/android/jni/Android.mk @@ -95,6 +95,7 @@ LOCAL_SRC_FILES := \ $(SRC)/Core/PSPLoaders.cpp \ $(SRC)/Core/MemMap.cpp \ $(SRC)/Core/MemMapFunctions.cpp \ + $(SRC)/Core/SaveState.cpp \ $(SRC)/Core/System.cpp \ $(SRC)/Core/PSPMixer.cpp \ $(SRC)/Core/Debugger/Breakpoints.cpp \ From 2197d9698960201de02cd23657fcd02899c56ea1 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Thu, 27 Dec 2012 11:28:12 -0800 Subject: [PATCH 07/29] Run save state operations at next Advance(). Should take some question marks out of things. --- Core/HLE/HLE.h | 4 -- Core/HLE/sceKernel.cpp | 2 + Core/SaveState.cpp | 146 ++++++++++++++++++++++++++++++++++------- Core/SaveState.h | 24 ++++--- 4 files changed, 139 insertions(+), 37 deletions(-) diff --git a/Core/HLE/HLE.h b/Core/HLE/HLE.h index fb0eefa1be..09d5fc75cd 100644 --- a/Core/HLE/HLE.h +++ b/Core/HLE/HLE.h @@ -94,7 +94,3 @@ void WriteSyscall(const char *module, u32 nib, u32 address); void CallSyscall(u32 op); void ResolveSyscall(const char *moduleName, u32 nib, u32 address); -// Need to be able to save entire kernel state -int GetStateSize(); -void SaveState(u8 *ptr); -void LoadState(const u8 *ptr); diff --git a/Core/HLE/sceKernel.cpp b/Core/HLE/sceKernel.cpp index da528027eb..20f3af0997 100644 --- a/Core/HLE/sceKernel.cpp +++ b/Core/HLE/sceKernel.cpp @@ -24,6 +24,7 @@ #include "../FileSystems/MetaFileSystem.h" #include "../PSPLoaders.h" #include "../../Core/CoreTiming.h" +#include "../../Core/SaveState.h" #include "../../Core/System.h" #include "../../GPU/GPUInterface.h" #include "../../GPU/GPUState.h" @@ -77,6 +78,7 @@ void __KernelInit() return; } + SaveState::Init(); __KernelMemoryInit(); __KernelThreadingInit(); __KernelMutexInit(); diff --git a/Core/SaveState.cpp b/Core/SaveState.cpp index bbf0e2328d..43d181bb9b 100644 --- a/Core/SaveState.cpp +++ b/Core/SaveState.cpp @@ -15,32 +15,130 @@ // Official git repository and contact information can be found at // https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. +#include "../Common/StdMutex.h" +#include + #include "SaveState.h" -#include "MemMap.h" +#include "CoreTiming.h" #include "HLE/sceKernel.h" +#include "MemMap.h" -// TODO: Need a way to schedule via CoreTiming and actually run then. - -bool SaveState::Load(std::string &filename) +namespace SaveState { - SaveState state; - return CChunkFileReader::Load(filename, REVISION, state); + struct SaveStart + { + void DoState(PointerWrap &p); + }; + + enum OperationType + { + SAVESTATE_SAVE, + SAVESTATE_LOAD, + SAVESTATE_VERIFY, + }; + + struct Operation + { + Operation(OperationType t, std::string &f, Callback cb) + : type(t), filename(f), callback(cb) + { + } + + OperationType type; + std::string filename; + Callback callback; + }; + + static int timer; + static std::vector pending; + static std::recursive_mutex mutex; + + // This is where the magic happens. + void SaveStart::DoState(PointerWrap &p) + { + // This save state even saves its own state. + p.Do(timer); + p.DoMarker("SaveState"); + + Memory::DoState(p); + __KernelDoState(p); + } + + void Enqueue(SaveState::Operation op) + { + std::lock_guard guard(mutex); + pending.push_back(op); + + // Don't actually run it until next CoreTiming::Advance(). + // It's possible there might be a duplicate but it won't hurt us. + // TODO: If paused, just run, don't wait? + CoreTiming::ScheduleEvent_Threadsafe(0, timer); + } + + void Load(std::string &filename, Callback callback) + { + Enqueue(Operation(SAVESTATE_LOAD, filename, callback)); + } + + void Save(std::string &filename, Callback callback) + { + Enqueue(Operation(SAVESTATE_SAVE, filename, callback)); + } + + void Verify(Callback callback) + { + Enqueue(Operation(SAVESTATE_VERIFY, std::string(""), callback)); + } + + std::vector Flush() + { + std::lock_guard guard(mutex); + std::vector copy = pending; + pending.clear(); + + return copy; + } + + void Process(u64 userdata, int cyclesLate) + { + std::vector operations = Flush(); + SaveStart state; + + for (size_t i = 0, n = operations.size(); i < n; ++i) + { + Operation &op = operations[i]; + bool result; + + switch (op.type) + { + case SAVESTATE_LOAD: + INFO_LOG(COMMON, "Loading state from %s", op.filename.c_str()); + result = CChunkFileReader::Load(op.filename, REVISION, state); + break; + + case SAVESTATE_SAVE: + INFO_LOG(COMMON, "Saving state to %s", op.filename.c_str()); + result = CChunkFileReader::Save(op.filename, REVISION, state); + break; + + case SAVESTATE_VERIFY: + INFO_LOG(COMMON, "Verifying save state system"); + result = CChunkFileReader::Verify(state); + break; + + default: + ERROR_LOG(COMMON, "Savestate failure: unknown operation type %d", op.type); + result = false; + break; + } + + if (op.callback != NULL) + op.callback(result); + } + } + + void Init() + { + timer = CoreTiming::RegisterEvent("SaveState", Process); + } } - -bool SaveState::Save(std::string &filename) -{ - SaveState state; - return CChunkFileReader::Save(filename, REVISION, state); -} - -bool SaveState::Verify() -{ - SaveState state; - return CChunkFileReader::Verify(state); -} - -void SaveState::DoState(PointerWrap &p) -{ - Memory::DoState(p); - __KernelDoState(p); -} \ No newline at end of file diff --git a/Core/SaveState.h b/Core/SaveState.h index f0edfcf921..411ad2f88c 100644 --- a/Core/SaveState.h +++ b/Core/SaveState.h @@ -16,18 +16,24 @@ // https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. #include "../Common/ChunkFile.h" +#include -struct SaveState +namespace SaveState { + typedef void (*Callback)(bool status); + // TODO: Better place for this? - static const int REVISION = 1; + const int REVISION = 1; - // Load the specified file into the current state. - static bool Load(std::string &filename); - // Save the current state to the specified file. - static bool Save(std::string &filename); - // For testing / automated tests. Runs a save state verification pass. - static bool Verify(); + void Init(); - void DoState(PointerWrap &p); + // Load the specified file into the current state (async.) + // Warning: callback will be called on a different thread. + void Load(std::string &filename, Callback callback = NULL); + // Save the current state to the specified file (async.) + // Warning: callback will be called on a different thread. + void Save(std::string &filename, Callback callback = NULL); + // For testing / automated tests. Runs a save state verification pass (async.) + // Warning: callback will be called on a different thread. + void Verify(Callback callback = NULL); }; \ No newline at end of file From 570e8c812bde68baa4f704282c534b7dd3d890c0 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Thu, 27 Dec 2012 11:32:34 -0800 Subject: [PATCH 08/29] Also handle save states while paused. --- Core/SaveState.cpp | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/Core/SaveState.cpp b/Core/SaveState.cpp index 43d181bb9b..5e2ac11242 100644 --- a/Core/SaveState.cpp +++ b/Core/SaveState.cpp @@ -19,6 +19,7 @@ #include #include "SaveState.h" +#include "Core.h" #include "CoreTiming.h" #include "HLE/sceKernel.h" #include "MemMap.h" @@ -64,6 +65,8 @@ namespace SaveState __KernelDoState(p); } + void Process(u64 userdata, int cyclesLate); + void Enqueue(SaveState::Operation op) { std::lock_guard guard(mutex); @@ -71,8 +74,13 @@ namespace SaveState // Don't actually run it until next CoreTiming::Advance(). // It's possible there might be a duplicate but it won't hurt us. - // TODO: If paused, just run, don't wait? - CoreTiming::ScheduleEvent_Threadsafe(0, timer); + if (Core_IsStepping()) + { + // Warning: this may run on a different thread. + Process(0, 0); + } + else + CoreTiming::ScheduleEvent_Threadsafe(0, timer); } void Load(std::string &filename, Callback callback) From fbe4fd396e40c691da26a33feabb27dfad78d866 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Thu, 27 Dec 2012 11:58:15 -0800 Subject: [PATCH 09/29] Add a mechanism to restore event callback ptrs. Ugh, more duplicates. Maybe can find a good way to refactor. --- Core/CoreTiming.cpp | 24 ++++++++++++++++++++---- Core/CoreTiming.h | 2 ++ Core/HW/MemoryStick.cpp | 7 +++++++ Core/HW/MemoryStick.h | 2 ++ Core/SaveState.cpp | 6 ++++++ 5 files changed, 37 insertions(+), 4 deletions(-) diff --git a/Core/CoreTiming.cpp b/Core/CoreTiming.cpp index b5d40610dd..b1999015f9 100644 --- a/Core/CoreTiming.cpp +++ b/Core/CoreTiming.cpp @@ -36,6 +36,11 @@ namespace CoreTiming struct EventType { + EventType() {} + + EventType(TimedCallback cb, const char *n) + : callback(cb), name(n) {} + TimedCallback callback; const char *name; }; @@ -125,13 +130,24 @@ void FreeTsEvent(Event* ev) int RegisterEvent(const char *name, TimedCallback callback) { - EventType type; - type.name = name; - type.callback = callback; - event_types.push_back(type); + event_types.push_back(EventType(callback, name)); return (int)event_types.size() - 1; } +void AntiCrashCallback(u64 userdata, int cyclesLate) +{ + ERROR_LOG(CPU, "Savestate broken: an unregistered event was called."); + Core_Halt("invalid timing events"); +} + +void RestoreEvent(int event_type, const char *name, TimedCallback callback) +{ + if (event_type >= event_types.size()) + event_types.resize(event_type + 1, EventType(AntiCrashCallback, "INVALID EVENT")); + + event_types[event_type] = EventType(callback, name); +} + void UnregisterAllEvents() { if (first) diff --git a/Core/CoreTiming.h b/Core/CoreTiming.h index f8883d9b35..c3ec4bc1b3 100644 --- a/Core/CoreTiming.h +++ b/Core/CoreTiming.h @@ -78,6 +78,8 @@ namespace CoreTiming // Returns the event_type identifier. int RegisterEvent(const char *name, TimedCallback callback); + // For save states. + void RestoreEvent(int event_type, const char *name, TimedCallback callback); void UnregisterAllEvents(); // userdata MAY NOT CONTAIN POINTERS. userdata might get written and reloaded from disk, diff --git a/Core/HW/MemoryStick.cpp b/Core/HW/MemoryStick.cpp index 4d83e4783c..b2a746b0af 100644 --- a/Core/HW/MemoryStick.cpp +++ b/Core/HW/MemoryStick.cpp @@ -4,6 +4,13 @@ static MemStickState memStickState = PSP_MEMORYSTICK_STATE_DRIVER_READY; static MemStickFatState memStickFatState = PSP_FAT_MEMORYSTICK_STATE_ASSIGNED; +void MemoryStick_DoState(PointerWrap &p) +{ + p.Do(memStickState); + p.Do(memStickFatState); + p.DoMarker("MemoryStick"); +} + MemStickState MemoryStick_State() { return memStickState; diff --git a/Core/HW/MemoryStick.h b/Core/HW/MemoryStick.h index 1ccd9b64fa..fbd42b827b 100644 --- a/Core/HW/MemoryStick.h +++ b/Core/HW/MemoryStick.h @@ -1,4 +1,5 @@ #include "../../Globals.h" +#include "../../Common/ChunkFile.h" // mscmhc0 states enum MemStickState { @@ -14,6 +15,7 @@ enum MemStickFatState { PSP_FAT_MEMORYSTICK_STATE_ASSIGNED = 1, }; +void MemoryStick_DoState(PointerWrap &p); MemStickState MemoryStick_State(); MemStickFatState MemoryStick_FatState(); diff --git a/Core/SaveState.cpp b/Core/SaveState.cpp index 5e2ac11242..ce70a40df0 100644 --- a/Core/SaveState.cpp +++ b/Core/SaveState.cpp @@ -22,6 +22,7 @@ #include "Core.h" #include "CoreTiming.h" #include "HLE/sceKernel.h" +#include "HW/MemoryStick.h" #include "MemMap.h" namespace SaveState @@ -57,11 +58,16 @@ namespace SaveState // This is where the magic happens. void SaveStart::DoState(PointerWrap &p) { + // Gotta do CoreTiming first since we'll restore into it. + // TODO CoreTiming + // This save state even saves its own state. p.Do(timer); + CoreTiming::RestoreEvent(timer, "SaveState", Process); p.DoMarker("SaveState"); Memory::DoState(p); + MemoryStick_DoState(p); __KernelDoState(p); } From 91d727a65a338e34ed051cfaa6af7c32ea2dcdac Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Thu, 27 Dec 2012 13:08:58 -0800 Subject: [PATCH 10/29] Add CoreTiming to save states. I hope DoLinkedList works, seems like it should. --- Core/CoreTiming.cpp | 36 ++++++++++++++++++++++++++++-------- Core/CoreTiming.h | 6 +++++- Core/SaveState.cpp | 8 ++++---- 3 files changed, 37 insertions(+), 13 deletions(-) diff --git a/Core/CoreTiming.cpp b/Core/CoreTiming.cpp index b1999015f9..31b9bbb0ad 100644 --- a/Core/CoreTiming.cpp +++ b/Core/CoreTiming.cpp @@ -24,6 +24,7 @@ #include "CoreTiming.h" #include "Core.h" #include "HLE/sceKernelThread.h" +#include "../Common/ChunkFile.h" int CPU_HZ = 222000000; @@ -55,12 +56,6 @@ struct BaseEvent // Event *next; }; -template -struct LinkedListItem : public T -{ - LinkedListItem *next; -}; - typedef LinkedListItem Event; Event *first; @@ -79,6 +74,7 @@ s64 idledCycles; static std::recursive_mutex externalEventSection; +// Warning: not included in save state. void (*advanceCallback)(int cyclesExecuted) = NULL; void SetClockFrequencyMHz(int cpuMhz) @@ -140,9 +136,9 @@ void AntiCrashCallback(u64 userdata, int cyclesLate) Core_Halt("invalid timing events"); } -void RestoreEvent(int event_type, const char *name, TimedCallback callback) +void RestoreRegisterEvent(int event_type, const char *name, TimedCallback callback) { - if (event_type >= event_types.size()) + if (event_type >= (int) event_types.size()) event_types.resize(event_type + 1, EventType(AntiCrashCallback, "INVALID EVENT")); event_types[event_type] = EventType(callback, name); @@ -311,6 +307,7 @@ u64 UnscheduleEvent(int event_type, u64 userdata) return result; } +// Warning: not included in save state. void RegisterAdvanceCallback(void (*callback)(int cyclesExecuted)) { advanceCallback = callback; @@ -546,4 +543,27 @@ std::string GetScheduledEventsSummary() return text; } +void Event_DoState(PointerWrap &p, BaseEvent *ev) +{ + p.Do(*ev); +} + +void DoState(PointerWrap &p) +{ + size_t n = event_types.size(); + p.Do(n); + // These (should) be filled in later by the modules. + event_types.resize(n, EventType(AntiCrashCallback, "INVALID EVENT")); + + p.DoLinkedList(first, (Event **) NULL); + p.DoLinkedList(tsFirst, &tsLast); + + p.Do(CPU_HZ); + p.Do(downcount); + p.Do(slicelength); + p.Do(globalTimer); + p.Do(idledCycles); + p.DoMarker("CoreTiming"); +} + } // namespace diff --git a/Core/CoreTiming.h b/Core/CoreTiming.h index c3ec4bc1b3..e5aa8f8772 100644 --- a/Core/CoreTiming.h +++ b/Core/CoreTiming.h @@ -32,6 +32,7 @@ // ScheduleEvent(periodInCycles - cyclesLate, callback, "whatever") #include "../Globals.h" +#include "../Common/ChunkFile.h" #include @@ -79,7 +80,7 @@ namespace CoreTiming // Returns the event_type identifier. int RegisterEvent(const char *name, TimedCallback callback); // For save states. - void RestoreEvent(int event_type, const char *name, TimedCallback callback); + void RestoreRegisterEvent(int event_type, const char *name, TimedCallback callback); void UnregisterAllEvents(); // userdata MAY NOT CONTAIN POINTERS. userdata might get written and reloaded from disk, @@ -105,10 +106,13 @@ namespace CoreTiming void LogPendingEvents(); + // Warning: not included in save states. void RegisterAdvanceCallback(void (*callback)(int cyclesExecuted)); std::string GetScheduledEventsSummary(); + void DoState(PointerWrap &p); + void SetClockFrequencyMHz(int cpuMhz); int GetClockFrequencyMHz(); extern int downcount; diff --git a/Core/SaveState.cpp b/Core/SaveState.cpp index ce70a40df0..bbf8717b9f 100644 --- a/Core/SaveState.cpp +++ b/Core/SaveState.cpp @@ -55,15 +55,17 @@ namespace SaveState static std::vector pending; static std::recursive_mutex mutex; + void Process(u64 userdata, int cyclesLate); + // This is where the magic happens. void SaveStart::DoState(PointerWrap &p) { // Gotta do CoreTiming first since we'll restore into it. - // TODO CoreTiming + CoreTiming::DoState(p); // This save state even saves its own state. p.Do(timer); - CoreTiming::RestoreEvent(timer, "SaveState", Process); + CoreTiming::RestoreRegisterEvent(timer, "SaveState", Process); p.DoMarker("SaveState"); Memory::DoState(p); @@ -71,8 +73,6 @@ namespace SaveState __KernelDoState(p); } - void Process(u64 userdata, int cyclesLate); - void Enqueue(SaveState::Operation op) { std::lock_guard guard(mutex); From 3ed2045f6b312102db2bb63069fbd7d353df0ec7 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Thu, 27 Dec 2012 14:21:39 -0800 Subject: [PATCH 11/29] Add state saving to tertiary kernel modules. --- Common/ChunkFile.h | 37 +++++++++++++++++++++++++++++++++ Core/HLE/sceKernel.cpp | 21 +++++++++++-------- Core/HLE/sceKernelAlarm.cpp | 7 +++++++ Core/HLE/sceKernelAlarm.h | 1 + Core/HLE/sceKernelEventFlag.cpp | 9 +++++++- Core/HLE/sceKernelEventFlag.h | 1 + Core/HLE/sceKernelMbx.cpp | 9 +++++++- Core/HLE/sceKernelMbx.h | 1 + Core/HLE/sceKernelMemory.cpp | 7 +++++++ Core/HLE/sceKernelMemory.h | 1 + Core/HLE/sceKernelModule.cpp | 6 ++++++ Core/HLE/sceKernelModule.h | 1 + Core/HLE/sceKernelMutex.cpp | 14 +++++++++++-- Core/HLE/sceKernelMutex.h | 1 + Core/HLE/sceKernelSemaphore.cpp | 9 +++++++- Core/HLE/sceKernelSemaphore.h | 1 + 16 files changed, 112 insertions(+), 14 deletions(-) diff --git a/Common/ChunkFile.h b/Common/ChunkFile.h index eda388211e..c6dd5d6de0 100644 --- a/Common/ChunkFile.h +++ b/Common/ChunkFile.h @@ -114,6 +114,43 @@ public: } } + template + void Do(std::multimap &x) + { + unsigned int number = (unsigned int)x.size(); + Do(number); + switch (mode) { + case MODE_READ: + { + x.clear(); + while (number > 0) + { + K first; + Do(first); + T second; + Do(second); + x.insert(std::make_pair(first, second)); + --number; + } + } + break; + case MODE_WRITE: + case MODE_MEASURE: + case MODE_VERIFY: + { + typename std::multimap::iterator itr = x.begin(); + while (number > 0) + { + Do(itr->first); + Do(itr->second); + --number; + ++itr; + } + } + break; + } + } + // Store vectors. template void Do(std::vector &x) diff --git a/Core/HLE/sceKernel.cpp b/Core/HLE/sceKernel.cpp index 20f3af0997..67f6b073db 100644 --- a/Core/HLE/sceKernel.cpp +++ b/Core/HLE/sceKernel.cpp @@ -59,8 +59,6 @@ #include "../Util/PPGeDraw.h" -extern MetaFileSystem pspFileSystem; - /* 17: [MIPS32 R4K 00000000 ]: Loader: Type: 1 Vaddr: 00000000 Filesz: 2856816 Memsz: 2856816 18: [MIPS32 R4K 00000000 ]: Loader: Loadable Segment Copied to 0898dab0, size 002b9770 @@ -69,6 +67,7 @@ extern MetaFileSystem pspFileSystem; */ static bool kernelRunning = false; +KernelObjectPool kernelObjects; void __KernelInit() { @@ -140,13 +139,19 @@ void __KernelShutdown() void __KernelDoState(PointerWrap &p) { + p.Do(kernelRunning); kernelObjects.DoState(p); p.DoMarker("KernelObjects"); - // TODO - // modules - // core timing - // memstick - // filesystem + + // TODO: Put these in the correct order... + __KernelAlarmDoState(p); + __KernelEventFlagDoState(p); + __KernelMbxDoState(p); + __KernelMemoryDoState(p); + __KernelModuleDoState(p); + __KernelMutexDoState(p); + __KernelSemaDoState(p); + // TODO: more modules } bool __KernelIsRunning() { @@ -232,8 +237,6 @@ void sceKernelDcacheWritebackInvalidateAll() gpu->InvalidateCache(0, -1); } -KernelObjectPool kernelObjects; - KernelObjectPool::KernelObjectPool() { memset(occupied, 0, sizeof(bool)*maxCount); diff --git a/Core/HLE/sceKernelAlarm.cpp b/Core/HLE/sceKernelAlarm.cpp index ea833860ec..baf4ddbf38 100644 --- a/Core/HLE/sceKernelAlarm.cpp +++ b/Core/HLE/sceKernelAlarm.cpp @@ -111,6 +111,13 @@ void __KernelAlarmInit() alarmTimer = CoreTiming::RegisterEvent("Alarm", __KernelTriggerAlarm); } +void __KernelAlarmDoState(PointerWrap &p) +{ + p.Do(alarmTimer); + CoreTiming::RestoreRegisterEvent(alarmTimer, "Alarm", __KernelTriggerAlarm); + p.DoMarker("sceKernelAlarm"); +} + KernelObject *__KernelAlarmObject() { // Default object to load from state. diff --git a/Core/HLE/sceKernelAlarm.h b/Core/HLE/sceKernelAlarm.h index 24cc866e37..4b286eb87a 100644 --- a/Core/HLE/sceKernelAlarm.h +++ b/Core/HLE/sceKernelAlarm.h @@ -23,4 +23,5 @@ int sceKernelCancelAlarm(SceUID uid); int sceKernelReferAlarmStatus(SceUID uid, u32 infoPtr); void __KernelAlarmInit(); +void __KernelAlarmDoState(PointerWrap &p); KernelObject *__KernelAlarmObject(); diff --git a/Core/HLE/sceKernelEventFlag.cpp b/Core/HLE/sceKernelEventFlag.cpp index f0e5e16034..80471c4c4d 100644 --- a/Core/HLE/sceKernelEventFlag.cpp +++ b/Core/HLE/sceKernelEventFlag.cpp @@ -101,7 +101,14 @@ int eventFlagWaitTimer = 0; void __KernelEventFlagInit() { - eventFlagWaitTimer = CoreTiming::RegisterEvent("EventFlagTimeout", &__KernelEventFlagTimeout); + eventFlagWaitTimer = CoreTiming::RegisterEvent("EventFlagTimeout", __KernelEventFlagTimeout); +} + +void __KernelEventFlagDoState(PointerWrap &p) +{ + p.Do(eventFlagWaitTimer); + CoreTiming::RestoreRegisterEvent(eventFlagWaitTimer, "EventFlagTimeout", __KernelEventFlagTimeout); + p.DoMarker("sceKernelEventFlag"); } KernelObject *__KernelEventFlagObject() diff --git a/Core/HLE/sceKernelEventFlag.h b/Core/HLE/sceKernelEventFlag.h index 2eb1c659ba..151efa25f7 100644 --- a/Core/HLE/sceKernelEventFlag.h +++ b/Core/HLE/sceKernelEventFlag.h @@ -28,4 +28,5 @@ u32 sceKernelReferEventFlagStatus(SceUID id, u32 statusPtr); u32 sceKernelCancelEventFlag(SceUID uid, u32 pattern, u32 numWaitThreadsPtr); void __KernelEventFlagInit(); +void __KernelEventFlagDoState(PointerWrap &p); KernelObject *__KernelEventFlagObject(); diff --git a/Core/HLE/sceKernelMbx.cpp b/Core/HLE/sceKernelMbx.cpp index 3ae6ae4f04..34aea59532 100644 --- a/Core/HLE/sceKernelMbx.cpp +++ b/Core/HLE/sceKernelMbx.cpp @@ -167,7 +167,14 @@ struct Mbx : public KernelObject void __KernelMbxInit() { - mbxWaitTimer = CoreTiming::RegisterEvent("MbxTimeout", &__KernelMbxTimeout); + mbxWaitTimer = CoreTiming::RegisterEvent("MbxTimeout", __KernelMbxTimeout); +} + +void __KernelMbxDoState(PointerWrap &p) +{ + p.Do(mbxWaitTimer); + CoreTiming::RestoreRegisterEvent(mbxWaitTimer, "MbxTimeout", __KernelMbxTimeout); + p.DoMarker("sceKernelMbx"); } KernelObject *__KernelMbxObject() diff --git a/Core/HLE/sceKernelMbx.h b/Core/HLE/sceKernelMbx.h index b0fb25e952..c171461a8f 100644 --- a/Core/HLE/sceKernelMbx.h +++ b/Core/HLE/sceKernelMbx.h @@ -34,4 +34,5 @@ int sceKernelCancelReceiveMbx(SceUID id, u32 numWaitingThreadsAddr); int sceKernelReferMbxStatus(SceUID id, u32 infoAddr); void __KernelMbxInit(); +void __KernelMbxDoState(PointerWrap &p); KernelObject *__KernelMbxObject(); diff --git a/Core/HLE/sceKernelMemory.cpp b/Core/HLE/sceKernelMemory.cpp index 807e74a2e1..97ce91136b 100644 --- a/Core/HLE/sceKernelMemory.cpp +++ b/Core/HLE/sceKernelMemory.cpp @@ -135,6 +135,13 @@ void __KernelMemoryInit() INFO_LOG(HLE, "Kernel and user memory pools initialized"); } +void __KernelMemoryDoState(PointerWrap &p) +{ + kernelMemory.DoState(p); + userMemory.DoState(p); + p.DoMarker("sceKernelMemory"); +} + void __KernelMemoryShutdown() { INFO_LOG(HLE,"Shutting down user memory pool: "); diff --git a/Core/HLE/sceKernelMemory.h b/Core/HLE/sceKernelMemory.h index cc5334ae89..0b6602d756 100644 --- a/Core/HLE/sceKernelMemory.h +++ b/Core/HLE/sceKernelMemory.h @@ -30,6 +30,7 @@ extern BlockAllocator userMemory; extern BlockAllocator kernelMemory; void __KernelMemoryInit(); +void __KernelMemoryDoState(PointerWrap &p); void __KernelMemoryShutdown(); KernelObject *__KernelMemoryFPLObject(); KernelObject *__KernelMemoryVPLObject(); diff --git a/Core/HLE/sceKernelModule.cpp b/Core/HLE/sceKernelModule.cpp index 1f7b0c050c..d35e5d5138 100644 --- a/Core/HLE/sceKernelModule.cpp +++ b/Core/HLE/sceKernelModule.cpp @@ -172,6 +172,12 @@ static SceUID mainModuleID; // hack // STATE END ////////////////////////////////////////////////////////////////////////// +void __KernelModuleDoState(PointerWrap &p) +{ + p.Do(mainModuleID); + p.DoMarker("sceKernelModule"); +} + Module *__KernelLoadELFFromPtr(const u8 *ptr, u32 loadAddress, std::string *error_string) { Module *module = new Module; diff --git a/Core/HLE/sceKernelModule.h b/Core/HLE/sceKernelModule.h index 18e3d5f036..732bd43173 100644 --- a/Core/HLE/sceKernelModule.h +++ b/Core/HLE/sceKernelModule.h @@ -21,6 +21,7 @@ #include "HLE.h" KernelObject *__KernelModuleObject(); +void __KernelModuleDoState(PointerWrap &p); u32 __KernelGetModuleGP(SceUID module); bool __KernelLoadExec(const char *filename, SceKernelLoadExecParam *param, std::string *error_string); diff --git a/Core/HLE/sceKernelMutex.cpp b/Core/HLE/sceKernelMutex.cpp index c0778031c7..a6243fff08 100644 --- a/Core/HLE/sceKernelMutex.cpp +++ b/Core/HLE/sceKernelMutex.cpp @@ -131,12 +131,22 @@ static MutexMap mutexHeldLocks; void __KernelMutexInit() { - mutexWaitTimer = CoreTiming::RegisterEvent("MutexTimeout", &__KernelMutexTimeout); - lwMutexWaitTimer = CoreTiming::RegisterEvent("LwMutexTimeout", &__KernelLwMutexTimeout); + mutexWaitTimer = CoreTiming::RegisterEvent("MutexTimeout", __KernelMutexTimeout); + lwMutexWaitTimer = CoreTiming::RegisterEvent("LwMutexTimeout", __KernelLwMutexTimeout); __KernelListenThreadEnd(&__KernelMutexThreadEnd); } +void __KernelMutexDoState(PointerWrap &p) +{ + p.Do(mutexWaitTimer); + CoreTiming::RestoreRegisterEvent(mutexWaitTimer, "MutexTimeout", __KernelMutexTimeout); + p.Do(lwMutexWaitTimer); + CoreTiming::RestoreRegisterEvent(lwMutexWaitTimer, "LwMutexTimeout", __KernelLwMutexTimeout); + p.Do(mutexHeldLocks); + p.DoMarker("sceKernelMutex"); +} + KernelObject *__KernelMutexObject() { return new Mutex; diff --git a/Core/HLE/sceKernelMutex.h b/Core/HLE/sceKernelMutex.h index 5db1f3b4d5..18eeb4fafb 100644 --- a/Core/HLE/sceKernelMutex.h +++ b/Core/HLE/sceKernelMutex.h @@ -37,6 +37,7 @@ void __KernelLwMutexTimeout(u64 userdata, int cyclesLate); void __KernelMutexThreadEnd(SceUID thread); void __KernelMutexInit(); +void __KernelMutexDoState(PointerWrap &p); void __KernelMutexShutdown(); KernelObject *__KernelMutexObject(); KernelObject *__KernelLwMutexObject(); diff --git a/Core/HLE/sceKernelSemaphore.cpp b/Core/HLE/sceKernelSemaphore.cpp index 0572a8d70d..6e213ff31d 100644 --- a/Core/HLE/sceKernelSemaphore.cpp +++ b/Core/HLE/sceKernelSemaphore.cpp @@ -72,7 +72,14 @@ static int semaWaitTimer = 0; void __KernelSemaInit() { - semaWaitTimer = CoreTiming::RegisterEvent("SemaphoreTimeout", &__KernelSemaTimeout); + semaWaitTimer = CoreTiming::RegisterEvent("SemaphoreTimeout", __KernelSemaTimeout); +} + +void __KernelSemaDoState(PointerWrap &p) +{ + p.Do(semaWaitTimer); + CoreTiming::RestoreRegisterEvent(semaWaitTimer, "SemaphoreTimeout", __KernelSemaTimeout); + p.DoMarker("sceKernelSema"); } KernelObject *__KernelSemaphoreObject() diff --git a/Core/HLE/sceKernelSemaphore.h b/Core/HLE/sceKernelSemaphore.h index f816f97e41..14df34cbed 100644 --- a/Core/HLE/sceKernelSemaphore.h +++ b/Core/HLE/sceKernelSemaphore.h @@ -29,4 +29,5 @@ int sceKernelWaitSemaCB(SceUID semaid, int signal, u32 timeoutPtr); void __KernelSemaTimeout(u64 userdata, int cycleslate); void __KernelSemaInit(); +void __KernelSemaDoState(PointerWrap &p); KernelObject *__KernelSemaphoreObject(); From db787d266d557c87ea02d27faebca95c61818ff2 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Thu, 27 Dec 2012 15:56:46 -0800 Subject: [PATCH 12/29] Require interrupt handlers to be registered. This allows it to be save stated sanely. --- Core/HLE/sceKernel.cpp | 19 ++-- Core/HLE/sceKernelAlarm.cpp | 26 +++++- Core/HLE/sceKernelInterrupt.cpp | 159 +++++++++++++++++++++++++------- Core/HLE/sceKernelInterrupt.h | 42 +++++---- 4 files changed, 183 insertions(+), 63 deletions(-) diff --git a/Core/HLE/sceKernel.cpp b/Core/HLE/sceKernel.cpp index 67f6b073db..76e690465c 100644 --- a/Core/HLE/sceKernel.cpp +++ b/Core/HLE/sceKernel.cpp @@ -78,18 +78,18 @@ void __KernelInit() } SaveState::Init(); + __InterruptsInit(); __KernelMemoryInit(); __KernelThreadingInit(); - __KernelMutexInit(); - __KernelSemaInit(); __KernelAlarmInit(); __KernelEventFlagInit(); __KernelMbxInit(); + __KernelMutexInit(); + __KernelSemaInit(); __IoInit(); __AudioInit(); __SasInit(); __DisplayInit(); - __InterruptsInit(); __GeInit(); __PowerInit(); __UtilityInit(); @@ -126,10 +126,10 @@ void __KernelShutdown() __DisplayShutdown(); __AudioShutdown(); __IoShutdown(); - __InterruptsShutdown(); __KernelMutexShutdown(); __KernelThreadingShutdown(); __KernelMemoryShutdown(); + __InterruptsShutdown(); CoreTiming::ClearPendingEvents(); CoreTiming::UnregisterAllEvents(); @@ -144,14 +144,17 @@ void __KernelDoState(PointerWrap &p) p.DoMarker("KernelObjects"); // TODO: Put these in the correct order... + __InterruptsDoState(p); + __KernelMemoryDoState(p); + // TODO: __KernelThreadingDoState(p); __KernelAlarmDoState(p); __KernelEventFlagDoState(p); __KernelMbxDoState(p); - __KernelMemoryDoState(p); __KernelModuleDoState(p); __KernelMutexDoState(p); __KernelSemaDoState(p); - // TODO: more modules + // TODO: non-kernel modules + // TODO: PPGe } bool __KernelIsRunning() { @@ -328,7 +331,9 @@ void KernelObjectPool::DoState(PointerWrap &p) if (_maxCount != maxCount) ERROR_LOG(HLE, "Unable to load state: different kernel object storage."); - // Assumption: on load, we've already cleared. + if (p.mode == p.MODE_READ) + kernelObjects.Clear(); + p.DoArray(occupied, maxCount); for (int i = 0; i < maxCount; ++i) { diff --git a/Core/HLE/sceKernelAlarm.cpp b/Core/HLE/sceKernelAlarm.cpp index baf4ddbf38..bb29e077e6 100644 --- a/Core/HLE/sceKernelAlarm.cpp +++ b/Core/HLE/sceKernelAlarm.cpp @@ -52,7 +52,12 @@ void __KernelScheduleAlarm(Alarm *alarm, u64 ticks); class AlarmIntrHandler : public SubIntrHandler { public: - AlarmIntrHandler(Alarm *alarm) + static SubIntrHandler *Create() + { + return new AlarmIntrHandler(); + } + + void setAlarm(Alarm *alarm) { alarmID = alarm->GetUID(); handlerAddress = alarm->alm.handlerPtr; @@ -87,10 +92,17 @@ public: // Delete the alarm if it's not rescheduled. kernelObjects.Destroy(alarmID); - __ReleaseSubInterruptHandler(PSP_SYSTIMER0_INTR, alarmID); + __ReleaseSubIntrHandler(PSP_SYSTIMER0_INTR, alarmID); } } + virtual void DoState(PointerWrap &p) + { + SubIntrHandler::DoState(p); + p.Do(alarmID); + p.DoMarker("AlarmIntrHandler"); + } + SceUID alarmID; }; @@ -109,6 +121,7 @@ void __KernelTriggerAlarm(u64 userdata, int cyclesLate) void __KernelAlarmInit() { alarmTimer = CoreTiming::RegisterEvent("Alarm", __KernelTriggerAlarm); + __RegisterSubIntrCreator(PSP_SYSTIMER0_INTR, AlarmIntrHandler::Create); } void __KernelAlarmDoState(PointerWrap &p) @@ -142,10 +155,15 @@ SceUID __KernelSetAlarm(u64 ticks, u32 handlerPtr, u32 commonPtr) alarm->alm.handlerPtr = handlerPtr; alarm->alm.commonPtr = commonPtr; - u32 error = __RegisterSubInterruptHandler(PSP_SYSTIMER0_INTR, uid, new AlarmIntrHandler(alarm)); + u32 error; + AlarmIntrHandler *handler = (AlarmIntrHandler *) __RegisterSubIntrHandler(PSP_SYSTIMER0_INTR, uid, error); if (error != 0) + { + kernelObjects.Destroy(uid); return error; + } + handler->setAlarm(alarm); __KernelScheduleAlarm(alarm, ticks); return uid; } @@ -174,7 +192,7 @@ int sceKernelCancelAlarm(SceUID uid) DEBUG_LOG(HLE, "sceKernelCancelAlarm(%08x)", uid); CoreTiming::UnscheduleEvent(alarmTimer, uid); - __ReleaseSubInterruptHandler(PSP_SYSTIMER0_INTR, uid); + __ReleaseSubIntrHandler(PSP_SYSTIMER0_INTR, uid); return kernelObjects.Destroy(uid); } diff --git a/Core/HLE/sceKernelInterrupt.cpp b/Core/HLE/sceKernelInterrupt.cpp index bc00c82254..445546f349 100644 --- a/Core/HLE/sceKernelInterrupt.cpp +++ b/Core/HLE/sceKernelInterrupt.cpp @@ -28,11 +28,6 @@ #include "sceKernelInterrupt.h" #include "sceKernelMutex.h" -struct Interrupt -{ - PSPInterrupt intno; -}; - void __DisableInterrupts(); void __EnableInterrupts(); bool __InterruptsEnabled(); @@ -92,9 +87,21 @@ void sceKernelCpuResumeIntrWithSync(u32 enable) class IntrHandler { public: - void add(int subIntrNum, SubIntrHandler *handler) + IntrHandler() + : subIntrCreator(NULL) { + } + + SubIntrHandler *add(int subIntrNum) + { + SubIntrHandler *handler; + if (subIntrCreator != NULL) + handler = subIntrCreator(); + else + handler = new SubIntrHandler(); + subIntrHandlers[subIntrNum] = handler; + return handler; } void remove(int subIntrNum) { @@ -113,8 +120,7 @@ public: if (has(subIntrNum)) return subIntrHandlers[subIntrNum]; else - return 0; - // what to do, what to do... + return NULL; } void clear() { @@ -146,7 +152,49 @@ public: } } + void setCreator(SubIntrCreator creator) + { + subIntrCreator = creator; + } + + void DoState(PointerWrap &p) + { + // We assume that the same creator has already been registered. + bool hasCreator = subIntrCreator != NULL; + p.Do(hasCreator); + if (hasCreator != (subIntrCreator != NULL)) + { + ERROR_LOG(HLE, "Savestate failure: incompatible sub interrupt handler."); + return; + } + + size_t n = subIntrHandlers.size(); + p.Do(n); + + if (p.mode == p.MODE_READ) + { + clear(); + for (size_t i = 0; i < n; ++i) + { + int subIntrNum; + p.Do(subIntrNum); + SubIntrHandler *handler = add(subIntrNum); + handler->DoState(p); + } + } + else + { + std::map::iterator it, end; + for (it = subIntrHandlers.begin(), end = subIntrHandlers.end(); it != end; ++it) + { + p.Do(it->first); + it->second->DoState(p); + } + } + } + private: + SubIntrCreator subIntrCreator; std::map subIntrHandlers; }; @@ -157,6 +205,13 @@ public: void restore(); void clear(); + void DoState(PointerWrap &p) + { + p.Do(insideInterrupt); + p.Do(savedCpu); + p.DoMarker("InterruptState"); + } + bool insideInterrupt; ThreadContext savedCpu; // Action afterInterruptAction; @@ -181,6 +236,25 @@ void __InterruptsInit() intState.clear(); } +void __InterruptsDoState(PointerWrap &p) +{ + int numInterrupts = PSP_NUMBER_INTERRUPTS; + p.Do(numInterrupts); + if (numInterrupts != PSP_NUMBER_INTERRUPTS) + { + ERROR_LOG(HLE, "Savestate failure: wrong number of interrupts, can't load."); + return; + } + + intState.DoState(p); + for (int i = 0; i < PSP_NUMBER_INTERRUPTS; ++i) + intrHandlers[i].DoState(p); + p.Do(pendingInterrupts, PendingInterrupt(0, 0)); + p.Do(interruptsEnabled); + p.Do(inInterrupt); + p.DoMarker("sceKernelInterrupt"); +} + void __InterruptsShutdown() { for (int i = 0; i < PSP_NUMBER_INTERRUPTS; ++i) @@ -238,25 +312,16 @@ void SubIntrHandler::queueUp() { if (!enabled) return; - PendingInterrupt pend; - pend.handler = this; - pend.hasArg = false; - pend.intr = intrNumber; - pend.subintr = number; - pendingInterrupts.push_back(pend); + + pendingInterrupts.push_back(PendingInterrupt(intrNumber, number)); }; void SubIntrHandler::queueUpWithArg(int arg) { if (!enabled) return; - PendingInterrupt pend; - pend.handler = this; - pend.arg = arg; - pend.hasArg = true; - pend.intr = intrNumber; - pend.subintr = number; - pendingInterrupts.push_back(pend); + + pendingInterrupts.push_back(PendingInterrupt(intrNumber, number, arg)); } void SubIntrHandler::copyArgsToCPU(const PendingInterrupt &pend) @@ -278,6 +343,7 @@ bool __RunOnePendingInterrupt() return false; } // Can easily prioritize between different kinds of interrupts if necessary. +retry: if (pendingInterrupts.size()) { // If we came from CoreTiming::Advance(), we might've come from a waiting thread's callback. @@ -285,8 +351,16 @@ bool __RunOnePendingInterrupt() __KernelSwitchOffThread("interrupt"); PendingInterrupt pend = pendingInterrupts.front(); + SubIntrHandler *handler = intrHandlers[pend.intr].get(pend.subintr); + if (handler == NULL) + { + WARN_LOG(HLE, "Ignoring interrupt, already been released."); + pendingInterrupts.pop_front(); + goto retry; + } + intState.save(); - pend.handler->copyArgsToCPU(pend); + handler->copyArgsToCPU(pend); currentMIPS->r[MIPS_REG_RA] = __KernelInterruptReturnAddress(); inInterrupt = true; @@ -340,7 +414,12 @@ void __KernelReturnFromInterrupt() // This is what we just ran. PendingInterrupt pend = pendingInterrupts.front(); pendingInterrupts.pop_front(); - pend.handler->handleResult(currentMIPS->r[MIPS_REG_V0]); + + SubIntrHandler *handler = intrHandlers[pend.intr].get(pend.subintr); + if (handler != NULL) + handler->handleResult(currentMIPS->r[MIPS_REG_V0]); + else + ERROR_LOG(HLE, "Interrupt released itself? Should not happen."); // Restore context after running the interrupt. intState.restore(); @@ -351,15 +430,21 @@ void __KernelReturnFromInterrupt() __KernelReSchedule("return from interrupt"); } -u32 __RegisterSubInterruptHandler(u32 intrNumber, u32 subIntrNumber, SubIntrHandler *subIntrHandler) +void __RegisterSubIntrCreator(u32 intrNumber, SubIntrCreator creator) { - subIntrHandler->number = subIntrNumber; - subIntrHandler->intrNumber = intrNumber; - intrHandlers[intrNumber].add(subIntrNumber, subIntrHandler); - return 0; + intrHandlers[intrNumber].setCreator(creator); } -u32 __ReleaseSubInterruptHandler(u32 intrNumber, u32 subIntrNumber) +SubIntrHandler *__RegisterSubIntrHandler(u32 intrNumber, u32 subIntrNumber, u32 &error) +{ + SubIntrHandler *subIntrHandler = intrHandlers[intrNumber].add(subIntrNumber); + subIntrHandler->number = subIntrNumber; + subIntrHandler->intrNumber = intrNumber; + error = 0; + return subIntrHandler; +} + +u32 __ReleaseSubIntrHandler(u32 intrNumber, u32 subIntrNumber) { if (!intrHandlers[intrNumber].has(subIntrNumber)) return -1; @@ -383,11 +468,15 @@ u32 sceKernelRegisterSubIntrHandler(u32 intrNumber, u32 subIntrNumber, u32 handl if (intrNumber >= PSP_NUMBER_INTERRUPTS) return -1; - SubIntrHandler *subIntrHandler = new SubIntrHandler(); - subIntrHandler->enabled = false; - subIntrHandler->handlerAddress = handler; - subIntrHandler->handlerArg = handlerArg; - return __RegisterSubInterruptHandler(intrNumber, subIntrNumber, subIntrHandler); + u32 error; + SubIntrHandler *subIntrHandler = __RegisterSubIntrHandler(intrNumber, subIntrNumber, error); + if (subIntrHandler) + { + subIntrHandler->enabled = false; + subIntrHandler->handlerAddress = handler; + subIntrHandler->handlerArg = handlerArg; + } + return error; } u32 sceKernelReleaseSubIntrHandler(u32 intrNumber, u32 subIntrNumber) @@ -397,7 +486,7 @@ u32 sceKernelReleaseSubIntrHandler(u32 intrNumber, u32 subIntrNumber) if (intrNumber >= PSP_NUMBER_INTERRUPTS) return -1; - return __ReleaseSubInterruptHandler(intrNumber, subIntrNumber); + return __ReleaseSubIntrHandler(intrNumber, subIntrNumber); } u32 sceKernelEnableSubIntr(u32 intrNumber, u32 subIntrNumber) diff --git a/Core/HLE/sceKernelInterrupt.h b/Core/HLE/sceKernelInterrupt.h index af57d6f3f4..3a298b955b 100644 --- a/Core/HLE/sceKernelInterrupt.h +++ b/Core/HLE/sceKernelInterrupt.h @@ -17,6 +17,8 @@ #pragma once +#include "../../Common/ChunkFile.h" + enum PSPInterrupt { PSP_GPIO_INTR = 4, PSP_ATA_INTR = 5, @@ -63,36 +65,38 @@ enum PSPInterruptTriggerType { PSP_INTR_ONLY_IF_ENABLED = 0x2, }; -class AllegrexInterruptHandler; - struct PendingInterrupt { - AllegrexInterruptHandler *handler; + PendingInterrupt(int intr_, int subintr_) + : intr(intr_), subintr(subintr_), hasArg(false) {} + PendingInterrupt(int intr_, int subintr_, int arg_) + : intr(intr_), subintr(subintr_), hasArg(true), arg(arg_) {} + int arg; bool hasArg; int intr; int subintr; }; - -class AllegrexInterruptHandler -{ -public: - virtual ~AllegrexInterruptHandler() {} - virtual void copyArgsToCPU(const PendingInterrupt &pend) = 0; - virtual void queueUp() = 0; - virtual void queueUpWithArg(int arg) = 0; - virtual void handleResult(int result) = 0; -}; - -class SubIntrHandler : public AllegrexInterruptHandler +class SubIntrHandler { public: SubIntrHandler() {} + virtual ~SubIntrHandler() {} virtual void queueUp(); virtual void queueUpWithArg(int arg); virtual void copyArgsToCPU(const PendingInterrupt &pend); virtual void handleResult(int result) {} + virtual void DoState(PointerWrap &p) + { + p.Do(enabled); + p.Do(intrNumber); + p.Do(number); + p.Do(handlerAddress); + p.Do(handlerArg); + p.DoMarker("SubIntrHandler"); + } + bool enabled; int intrNumber; int number; @@ -100,16 +104,20 @@ public: u32 handlerArg; }; +typedef SubIntrHandler *(*SubIntrCreator)(); + bool __IsInInterrupt(); void __InterruptsInit(); +void __InterruptsDoState(PointerWrap &p); void __InterruptsShutdown(); void __TriggerInterrupt(int type, PSPInterrupt intno, int subInterrupts = -1); void __TriggerInterruptWithArg(int type, PSPInterrupt intno, int subintr, int arg); // For GE "callbacks" bool __RunOnePendingInterrupt(); void __KernelReturnFromInterrupt(); -u32 __RegisterSubInterruptHandler(u32 intrNumber, u32 subIntrNumber, SubIntrHandler *subIntrHandler); -u32 __ReleaseSubInterruptHandler(u32 intrNumber, u32 subIntrNumber); +void __RegisterSubIntrCreator(u32 intrNumber, SubIntrCreator creator); +SubIntrHandler *__RegisterSubIntrHandler(u32 intrNumber, u32 subIntrNumber, u32 &error); +u32 __ReleaseSubIntrHandler(u32 intrNumber, u32 subIntrNumber); u32 sceKernelRegisterSubIntrHandler(u32 intrNumber, u32 subIntrNumber, u32 handler, u32 handlerArg); u32 sceKernelReleaseSubIntrHandler(u32 intrNumber, u32 subIntrNumber); From f5dd7f03e8baca183f460072a70bb5ba6ed9586c Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Thu, 27 Dec 2012 17:43:44 -0800 Subject: [PATCH 13/29] Change threadqueue and currentThread to be SceUIDs. hmm, kind of a big change. Tried to add some checks to be safe. --- Core/HLE/sceKernelThread.cpp | 228 ++++++++++++++++++++++------------- 1 file changed, 141 insertions(+), 87 deletions(-) diff --git a/Core/HLE/sceKernelThread.cpp b/Core/HLE/sceKernelThread.cpp index 816c3f4a2c..66a9172675 100644 --- a/Core/HLE/sceKernelThread.cpp +++ b/Core/HLE/sceKernelThread.cpp @@ -368,12 +368,12 @@ bool __KernelCheckThreadCallbacks(Thread *thread, bool force); //STATE BEGIN ////////////////////////////////////////////////////////////////////////// int g_inCbCount = 0; -Thread *currentThread; +SceUID currentThread; u32 idleThreadHackAddr; u32 threadReturnHackAddr; u32 cbReturnHackAddr; u32 intReturnHackAddr; -std::vector threadqueue; //Change to SceUID +std::vector threadqueue; std::vector threadEndListeners; SceUID threadIdleID[2]; @@ -395,7 +395,11 @@ SceUID curModule; // TODO: Should move to this wrapper so we can keep the current thread as a SceUID instead // of a dangerous raw pointer. Thread *__GetCurrentThread() { - return currentThread; + u32 error; + if (currentThread != 0) + return kernelObjects.Get(currentThread, error); + else + return NULL; } u32 __KernelMipsCallReturnAddress() @@ -492,7 +496,7 @@ bool __KernelSwitchOffThread(const char *reason) if (!reason) reason = "switch off thread"; - SceUID threadID = currentThread->GetUID(); + SceUID threadID = currentThread; if (threadID != threadIdleID[0] && threadID != threadIdleID[1]) { @@ -666,7 +670,7 @@ u32 sceKernelGetThreadmanIdList(u32 type, u32 readBufPtr, u32 readBufSize, u32 i for (size_t i = 0; i < std::min((size_t)readBufSize, threadqueue.size()); i++) { - Memory::Write_U32(threadqueue[i]->GetUID(), readBufPtr + i * 4); + Memory::Write_U32(threadqueue[i], readBufPtr + i * 4); } Memory::Write_U32(threadqueue.size(), idCountPtr); return 0; @@ -762,10 +766,11 @@ bool __KernelTriggerWait(WaitType type, int id, bool useRetVal, int retVal, bool { bool doneAnything = false; - for (std::vector::iterator iter = threadqueue.begin(); iter != threadqueue.end(); iter++) + u32 error; + for (std::vector::iterator iter = threadqueue.begin(); iter != threadqueue.end(); iter++) { - Thread *t = *iter; - if (t->isWaitingFor(type, id)) + Thread *t = kernelObjects.Get(*iter, error); + if (t && t->isWaitingFor(type, id)) { // This thread was waiting for the triggered object. t->resumeFromWait(); @@ -805,12 +810,13 @@ void __KernelWaitCurThread(WaitType type, SceUID waitID, u32 waitValue, u32 time if (g_inCbCount > 0) WARN_LOG(HLE, "UNTESTED - waiting within a callback, probably bad mojo."); - currentThread->nt.waitID = waitID; - currentThread->nt.waitType = type; - __KernelChangeThreadState(currentThread, THREADSTATUS_WAIT); - currentThread->nt.numReleases++; - currentThread->waitInfo.waitValue = waitValue; - currentThread->waitInfo.timeoutPtr = timeoutPtr; + Thread *thread = __GetCurrentThread(); + thread->nt.waitID = waitID; + thread->nt.waitType = type; + __KernelChangeThreadState(thread, THREADSTATUS_WAIT); + thread->nt.numReleases++; + thread->waitInfo.waitValue = waitValue; + thread->waitInfo.timeoutPtr = timeoutPtr; // TODO: Remove this once all callers are cleaned up. RETURN(0); //pretend all went OK @@ -843,7 +849,7 @@ void __KernelRemoveFromThreadQueue(Thread *t) { for (size_t i = 0; i < threadqueue.size(); i++) { - if (threadqueue[i] == t) + if (threadqueue[i] == t->GetUID()) { DEBUG_LOG(HLE, "Deleted thread %p (%i) from thread queue", t, t->GetUID()); threadqueue.erase(threadqueue.begin() + i); @@ -869,12 +875,13 @@ Thread *__KernelNextThread() { } } + u32 error; for (size_t i = 0; i < threadqueue.size(); i++) { next = (next + 1) % threadqueue.size(); - Thread *t = threadqueue[next]; - if (t->nt.currentPriority < prio) + Thread *t = kernelObjects.Get(threadqueue[next], error); + if (t && t->nt.currentPriority < prio) { if (t->nt.status & THREADSTATUS_READY) { @@ -885,7 +892,7 @@ Thread *__KernelNextThread() { } if (bestthread != -1) - return threadqueue[bestthread]; + return kernelObjects.Get(threadqueue[bestthread], error); else return 0; } @@ -933,14 +940,14 @@ retry: void __KernelReSchedule(bool doCallbacks, const char *reason) { - Thread *thread = currentThread; + Thread *thread = __GetCurrentThread(); if (doCallbacks) { if (thread) thread->isProcessingCallbacks = doCallbacks; } __KernelReSchedule(reason); - if (doCallbacks && thread != NULL && thread == currentThread) { + if (doCallbacks && thread != NULL && thread->GetUID() == currentThread) { if (thread->isRunning()) { thread->isProcessingCallbacks = false; } @@ -1020,7 +1027,7 @@ Thread *__KernelCreateThread(SceUID &id, SceUID moduleId, const char *name, u32 Thread *t = new Thread; id = kernelObjects.Create(t); - threadqueue.push_back(t); + threadqueue.push_back(id); memset(&t->nt, 0xCD, sizeof(t->nt)); @@ -1052,13 +1059,15 @@ void __KernelSetupRootThread(SceUID moduleID, int args, const char *argp, int pr curModule = moduleID; //grab mips regs SceUID id; - currentThread = __KernelCreateThread(id, moduleID, "root", currentMIPS->pc, prio, stacksize, attr); - __KernelResetThread(currentThread); - currentThread->nt.status = THREADSTATUS_READY; // do not schedule + Thread *thread = __KernelCreateThread(id, moduleID, "root", currentMIPS->pc, prio, stacksize, attr); + __KernelResetThread(thread); - strcpy(currentThread->nt.name, "root"); + currentThread = id; + thread->nt.status = THREADSTATUS_READY; // do not schedule - __KernelLoadContext(¤tThread->context); + strcpy(thread->nt.name, "root"); + + __KernelLoadContext(&thread->context); mipsr4k.r[MIPS_REG_A0] = args; mipsr4k.r[MIPS_REG_SP] -= 256; u32 location = mipsr4k.r[MIPS_REG_SP]; @@ -1082,7 +1091,7 @@ int sceKernelCreateThread(const char *threadName, u32 entry, u32 prio, int stack // int sceKernelStartThread(SceUID threadToStartID, SceSize argSize, void *argBlock) int sceKernelStartThread(SceUID threadToStartID, u32 argSize, u32 argBlockPtr) { - if (threadToStartID != currentThread->GetUID()) + if (threadToStartID != currentThread) { u32 error; Thread *startThread = kernelObjects.Get(threadToStartID, error); @@ -1144,7 +1153,7 @@ void sceKernelGetThreadStackFreeSize() INFO_LOG(HLE,"sceKernelGetThreadStackFreeSize(%i)", threadID); if (threadID == 0) - thread = currentThread; + thread = __GetCurrentThread(); else { u32 error; @@ -1172,15 +1181,18 @@ void sceKernelGetThreadStackFreeSize() // Internal function void __KernelReturnFromThread() { - INFO_LOG(HLE,"__KernelReturnFromThread : %s", currentThread->GetName()); + Thread *thread = __GetCurrentThread(); + _dbg_assert_msg_(HLE, thread != NULL, "Returned from a NULL thread."); + + INFO_LOG(HLE,"__KernelReturnFromThread : %s", thread->GetName()); // TEMPORARY HACK: kill the stack of the root thread early: - if (!strcmp(currentThread->GetName(), "root")) { - currentThread->FreeStack(); + if (!strcmp(thread->GetName(), "root")) { + thread->FreeStack(); } - currentThread->nt.exitStatus = currentThread->context.r[2]; - currentThread->nt.status = THREADSTATUS_DORMANT; - __KernelFireThreadEnd(currentThread); + thread->nt.exitStatus = thread->context.r[2]; + thread->nt.status = THREADSTATUS_DORMANT; + __KernelFireThreadEnd(thread); // TODO: Need to remove the thread from any ready queues. @@ -1194,10 +1206,13 @@ void __KernelReturnFromThread() void sceKernelExitThread() { + Thread *thread = __GetCurrentThread(); + _dbg_assert_msg_(HLE, thread != NULL, "Exited from a NULL thread."); + ERROR_LOG(HLE,"sceKernelExitThread FAKED"); - currentThread->nt.status = THREADSTATUS_DORMANT; - currentThread->nt.exitStatus = PARAM(0); - __KernelFireThreadEnd(currentThread); + thread->nt.status = THREADSTATUS_DORMANT; + thread->nt.exitStatus = PARAM(0); + __KernelFireThreadEnd(thread); //Find threads that waited for me // Wake them @@ -1209,15 +1224,18 @@ void sceKernelExitThread() void _sceKernelExitThread() { + Thread *thread = __GetCurrentThread(); + _dbg_assert_msg_(HLE, thread != NULL, "_Exited from a NULL thread."); + ERROR_LOG(HLE,"_sceKernelExitThread FAKED"); - currentThread->nt.status = THREADSTATUS_DORMANT; - currentThread->nt.exitStatus = PARAM(0); - __KernelFireThreadEnd(currentThread); + thread->nt.status = THREADSTATUS_DORMANT; + thread->nt.exitStatus = PARAM(0); + __KernelFireThreadEnd(thread); //Find threads that waited for this one // Wake them if (!__KernelTriggerWait(WAITTYPE_THREADEND, __KernelGetCurThread())) - hleReSchedule("exit-deleted thread"); + hleReSchedule("_exit thread"); // The stack will be deallocated when the thread is deleted. } @@ -1230,11 +1248,11 @@ void sceKernelExitDeleteThread() if (t) { INFO_LOG(HLE,"sceKernelExitDeleteThread()"); - currentThread->nt.status = THREADSTATUS_DORMANT; - currentThread->nt.exitStatus = PARAM(0); - __KernelFireThreadEnd(currentThread); + t->nt.status = THREADSTATUS_DORMANT; + t->nt.exitStatus = PARAM(0); + __KernelFireThreadEnd(t); //userMemory.Free(currentThread->stackBlock); - currentThread->stackBlock = 0; + t->stackBlock = 0; __KernelRemoveFromThreadQueue(t); currentThread = 0; @@ -1274,7 +1292,7 @@ void sceKernelRotateThreadReadyQueue() int sceKernelDeleteThread(int threadHandle) { - if (threadHandle != currentThread->GetUID()) + if (threadHandle != currentThread) { //TODO: remove from threadqueue! DEBUG_LOG(HLE,"sceKernelDeleteThread(%i)",threadHandle); @@ -1299,14 +1317,14 @@ int sceKernelDeleteThread(int threadHandle) } else { - ERROR_LOG(HLE, "Thread \"%s\" tries to delete itself! :(",currentThread->GetName()); + ERROR_LOG(HLE, "Thread \"%s\" tries to delete itself! :(", __GetCurrentThread() ? __GetCurrentThread()->GetName() : "NULL"); return -1; } } int sceKernelTerminateDeleteThread(int threadno) { - if (threadno != currentThread->GetUID()) + if (threadno != currentThread) { //TODO: remove from threadqueue! INFO_LOG(HLE, "sceKernelTerminateDeleteThread(%i)", threadno); @@ -1315,18 +1333,19 @@ int sceKernelTerminateDeleteThread(int threadno) if (!__KernelTriggerWait(WAITTYPE_THREADEND, threadno)) hleReSchedule("termdeletethread"); + // TODO: Why not delete? return 0; //kernelObjects.Destroy(threadno)); } else { - ERROR_LOG(HLE, "Thread \"%s\" trying to delete itself! :(", currentThread->GetName()); + ERROR_LOG(HLE, "Thread \"%s\" trying to delete itself! :(", __GetCurrentThread() ? __GetCurrentThread()->GetName() : "NULL"); return -1; } } int sceKernelTerminateThread(u32 threadID) { - if (threadID != currentThread->GetUID()) + if (threadID != currentThread) { INFO_LOG(HLE, "sceKernelTerminateThread(%i)", threadID); @@ -1343,25 +1362,28 @@ int sceKernelTerminateThread(u32 threadID) } else { - ERROR_LOG(HLE, "Thread \"%s\" trying to delete itself! :(", currentThread->GetName()); + ERROR_LOG(HLE, "Thread \"%s\" trying to delete itself! :(", __GetCurrentThread() ? __GetCurrentThread()->GetName() : "NULL"); return -1; } } SceUID __KernelGetCurThread() { - return currentThread->GetUID(); + return currentThread; } SceUID __KernelGetCurThreadModuleId() { - return currentThread->moduleId; + Thread *t = __GetCurrentThread(); + if (t) + return t->moduleId; + return 0; } void sceKernelGetThreadId() { - u32 retVal = currentThread->GetUID(); + u32 retVal = currentThread; DEBUG_LOG(HLE,"%i = sceKernelGetThreadId()", retVal); RETURN(retVal); } @@ -1378,14 +1400,18 @@ void sceKernelChangeCurrentThreadAttr() int clearAttr = PARAM(0); int setAttr = PARAM(1); DEBUG_LOG(HLE,"0 = sceKernelChangeCurrentThreadAttr(clear = %08x, set = %08x", clearAttr, setAttr); - currentThread->nt.attr = (currentThread->nt.attr & ~clearAttr) | setAttr; + Thread *t = __GetCurrentThread(); + if (t) + t->nt.attr = (t->nt.attr & ~clearAttr) | setAttr; + else + ERROR_LOG(HLE, "%s(): No current thread?", __FUNCTION__); RETURN(0); } void sceKernelChangeThreadPriority() { int id = PARAM(0); - if (id == 0) id = currentThread->GetUID(); //special + if (id == 0) id = currentThread; //special u32 error; Thread *thread = kernelObjects.Get(id, error); @@ -1476,9 +1502,16 @@ void sceKernelCancelWakeupThread() } static void __KernelSleepThread(bool doCallbacks) { - DEBUG_LOG(HLE,"sceKernelSleepThread() - wakeupCount decremented to %i", currentThread->nt.wakeupCount); - if (currentThread->nt.wakeupCount > 0) { - currentThread->nt.wakeupCount--; + Thread *thread = __GetCurrentThread(); + if (!thread) + { + ERROR_LOG(HLE, "sceKernelSleepThread*(): bad current thread"); + return; + } + + DEBUG_LOG(HLE,"sceKernelSleepThread() - wakeupCount decremented to %i", thread->nt.wakeupCount); + if (thread->nt.wakeupCount > 0) { + thread->nt.wakeupCount--; RETURN(0); } else { RETURN(0); @@ -1679,7 +1712,7 @@ void ActionAfterMipsCall::run() { ActionAfterMipsCall *Thread::getRunningCallbackAction() { - if (this == currentThread && g_inCbCount > 0) + if (this->GetUID() == currentThread && g_inCbCount > 0) { MipsCall *call = mipsCalls.get(this->currentCallbackId); ActionAfterMipsCall *action; @@ -1700,7 +1733,7 @@ ActionAfterMipsCall *Thread::getRunningCallbackAction() void Thread::setReturnValue(u32 retval) { - if (this == currentThread) { + if (this->GetUID() == currentThread) { if (g_inCbCount) { int callId = this->currentCallbackId; MipsCall *call = mipsCalls.get(callId); @@ -1790,23 +1823,25 @@ void __KernelSwitchContext(Thread *target, const char *reason) u32 oldPC = 0; u32 oldUID = 0; const char *oldName = "(none)"; - if (currentThread) // It might just have been deleted. + + Thread *cur = __GetCurrentThread(); + if (cur) // It might just have been deleted. { - __KernelSaveContext(¤tThread->context); + __KernelSaveContext(&cur->context); oldPC = currentMIPS->pc; - oldUID = currentThread->GetUID(); - oldName = currentThread->GetName(); + oldUID = cur->GetUID(); + oldName = cur->GetName(); } - currentThread = target; - __KernelLoadContext(¤tThread->context); + currentThread = target->GetUID(); + __KernelLoadContext(&target->context); DEBUG_LOG(HLE,"Context switched: %s -> %s (%s) (%i - pc: %08x -> %i - pc: %08x)", - oldName, currentThread->GetName(), + oldName, target->GetName(), reason, - oldUID, oldPC, currentThread->GetUID(), currentMIPS->pc); + oldUID, oldPC, target->GetUID(), currentMIPS->pc); // No longer waiting. - currentThread->nt.waitType = WAITTYPE_NONE; - currentThread->nt.waitID = 0; + target->nt.waitType = WAITTYPE_NONE; + target->nt.waitID = 0; __KernelExecutePendingMipsCalls(true); } @@ -1815,7 +1850,7 @@ void __KernelChangeThreadState(Thread *thread, ThreadStatus newStatus) { if (!thread || thread->nt.status == newStatus) return; - if (!dispatchEnabled && thread == currentThread && newStatus != THREADSTATUS_RUNNING) { + if (!dispatchEnabled && thread == __GetCurrentThread() && newStatus != THREADSTATUS_RUNNING) { ERROR_LOG(HLE, "Dispatching suspended, not changing thread state"); return; } @@ -1871,9 +1906,9 @@ void __KernelCallAddress(Thread *thread, u32 entryPoint, Action *afterAction, bo int callId = mipsCalls.add(call); bool called = false; - if (!thread || thread == currentThread) { + if (!thread || thread == __GetCurrentThread()) { if (__CanExecuteCallbackNow(thread)) { - thread = currentThread; + thread = __GetCurrentThread(); __KernelChangeThreadState(thread, THREADSTATUS_RUNNING); __KernelExecuteMipsCallOnCurrentThread(callId, reschedAfter); called = true; @@ -1892,8 +1927,15 @@ void __KernelCallAddress(Thread *thread, u32 entryPoint, Action *afterAction, bo void __KernelExecuteMipsCallOnCurrentThread(int callId, bool reschedAfter) { + Thread *cur = __GetCurrentThread(); + if (cur == NULL) + { + ERROR_LOG(HLE, "__KernelExecuteMipsCallOnCurrentThread(): Bad current thread"); + return; + } + if (g_inCbCount > 0) { - WARN_LOG(HLE, "__KernelExecuteMipsCallOnCurrentThread: Already in a callback!"); + WARN_LOG(HLE, "__KernelExecuteMipsCallOnCurrentThread(): Already in a callback!"); } DEBUG_LOG(HLE, "Executing mipscall %i", callId); MipsCall *call = mipsCalls.get(callId); @@ -1904,7 +1946,7 @@ void __KernelExecuteMipsCallOnCurrentThread(int callId, bool reschedAfter) call->savedV0 = currentMIPS->r[MIPS_REG_V0]; call->savedV1 = currentMIPS->r[MIPS_REG_V1]; call->savedIdRegister = currentMIPS->r[MIPS_REG_CALL_ID]; - call->savedId = currentThread->currentCallbackId; + call->savedId = cur->currentCallbackId; call->returnVoid = false; call->reschedAfter = reschedAfter; @@ -1914,7 +1956,7 @@ void __KernelExecuteMipsCallOnCurrentThread(int callId, bool reschedAfter) // We put this two places in case the game overwrites it. // We may want it later to "inject" return values. currentMIPS->r[MIPS_REG_CALL_ID] = callId; - currentThread->currentCallbackId = callId; + cur->currentCallbackId = callId; for (int i = 0; i < call->numArgs; i++) { currentMIPS->r[MIPS_REG_A0 + i] = call->args[i]; } @@ -1924,7 +1966,14 @@ void __KernelExecuteMipsCallOnCurrentThread(int callId, bool reschedAfter) void __KernelReturnFromMipsCall() { - int callId = currentThread->currentCallbackId; + Thread *cur = __GetCurrentThread(); + if (cur == NULL) + { + ERROR_LOG(HLE, "__KernelReturnFromMipsCall(): Bad current thread"); + return; + } + + int callId = cur->currentCallbackId; if (currentMIPS->r[MIPS_REG_CALL_ID] != callId) WARN_LOG(HLE, "__KernelReturnFromMipsCall(): s0 is %08x != %08x", currentMIPS->r[MIPS_REG_CALL_ID], callId); @@ -1943,16 +1992,16 @@ void __KernelReturnFromMipsCall() currentMIPS->r[MIPS_REG_V0] = call->savedV0; currentMIPS->r[MIPS_REG_V1] = call->savedV1; currentMIPS->r[MIPS_REG_CALL_ID] = call->savedIdRegister; - currentThread->currentCallbackId = call->savedId; + cur->currentCallbackId = call->savedId; g_inCbCount--; // yeah! back in the real world, let's keep going. Should we process more callbacks? - __KernelCheckThreadCallbacks(currentThread, !call->reschedAfter); + __KernelCheckThreadCallbacks(cur, !call->reschedAfter); if (!__KernelExecutePendingMipsCalls(call->reschedAfter)) { // Sometimes, we want to stay on the thread. - int threadReady = currentThread->nt.status & (THREADSTATUS_READY | THREADSTATUS_RUNNING); + int threadReady = cur->nt.status & (THREADSTATUS_READY | THREADSTATUS_RUNNING); if (call->reschedAfter || threadReady == 0) __KernelReSchedule("return from callback"); } @@ -2062,13 +2111,14 @@ bool __KernelCheckThreadCallbacks(Thread *thread, bool force) // Checks for callbacks on all threads bool __KernelCheckCallbacks() { // SceUID currentThread = __KernelGetCurThread(); - // currentThread->isProcessingCallbacks = true; + // __GetCurrentThread()->isProcessingCallbacks = true; // do { bool processed = false; - for (std::vector::iterator iter = threadqueue.begin(); iter != threadqueue.end(); iter++) { - Thread *thread = *iter; - if (__KernelCheckThreadCallbacks(thread, false)) { + u32 error; + for (std::vector::iterator iter = threadqueue.begin(); iter != threadqueue.end(); iter++) { + Thread *thread = kernelObjects.Get(*iter, error); + if (thread && __KernelCheckThreadCallbacks(thread, false)) { processed = true; } } @@ -2153,8 +2203,12 @@ void __KernelNotifyCallback(RegisteredCallbackType type, SceUID cbId, int notify // TODO: If cbId == -1, notify the callback ID on all threads that have it. u32 __KernelNotifyCallbackType(RegisteredCallbackType type, SceUID cbId, int notifyArg) { - for (std::vector::iterator iter = threadqueue.begin(); iter != threadqueue.end(); iter++) { - Thread *t = *iter; + u32 error; + for (std::vector::iterator iter = threadqueue.begin(); iter != threadqueue.end(); iter++) { + Thread *t = kernelObjects.Get(*iter, error); + if (!t) + continue; + for (std::set::iterator citer = t->registeredCallbacks[type].begin(); citer != t->registeredCallbacks[type].end(); citer++) { if (cbId == -1 || cbId == *citer) { __KernelNotifyCallback(type, *citer, notifyArg); From a8c9c31e167433e091a04571605fe0f196c43f12 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Thu, 27 Dec 2012 19:30:36 -0800 Subject: [PATCH 14/29] Add a registry for actions so they can be stated. Also add late loaders to ensure things are hooked up properly. --- Common/Action.h | 3 + Core/HLE/sceKernel.cpp | 6 +- Core/HLE/sceKernelInterrupt.cpp | 10 +- Core/HLE/sceKernelInterrupt.h | 1 + Core/HLE/sceKernelModule.cpp | 40 ++++-- Core/HLE/sceKernelThread.cpp | 222 +++++++++++++++++++++++++++++--- Core/HLE/sceKernelThread.h | 10 +- 7 files changed, 257 insertions(+), 35 deletions(-) diff --git a/Common/Action.h b/Common/Action.h index dbe7fb3759..ae3524b923 100644 --- a/Common/Action.h +++ b/Common/Action.h @@ -1,6 +1,7 @@ #pragma once #include +#include "ChunkFile.h" // Sometimes you want to set something to happen later, without that later place really needing // to know about all the things that might happen. That's when you use an Action, and add it @@ -17,4 +18,6 @@ class Action public: virtual ~Action() {} virtual void run() = 0; + virtual void DoState(PointerWrap &p) = 0; + int actionTypeID; }; diff --git a/Core/HLE/sceKernel.cpp b/Core/HLE/sceKernel.cpp index 76e690465c..3e18b4c6b8 100644 --- a/Core/HLE/sceKernel.cpp +++ b/Core/HLE/sceKernel.cpp @@ -143,10 +143,9 @@ void __KernelDoState(PointerWrap &p) kernelObjects.DoState(p); p.DoMarker("KernelObjects"); - // TODO: Put these in the correct order... __InterruptsDoState(p); __KernelMemoryDoState(p); - // TODO: __KernelThreadingDoState(p); + __KernelThreadingDoState(p); __KernelAlarmDoState(p); __KernelEventFlagDoState(p); __KernelMbxDoState(p); @@ -155,6 +154,9 @@ void __KernelDoState(PointerWrap &p) __KernelSemaDoState(p); // TODO: non-kernel modules // TODO: PPGe + + __InterruptsDoStateLate(p); + __KernelThreadingDoStateLate(p); } bool __KernelIsRunning() { diff --git a/Core/HLE/sceKernelInterrupt.cpp b/Core/HLE/sceKernelInterrupt.cpp index 445546f349..ecb1bef957 100644 --- a/Core/HLE/sceKernelInterrupt.cpp +++ b/Core/HLE/sceKernelInterrupt.cpp @@ -247,14 +247,20 @@ void __InterruptsDoState(PointerWrap &p) } intState.DoState(p); - for (int i = 0; i < PSP_NUMBER_INTERRUPTS; ++i) - intrHandlers[i].DoState(p); p.Do(pendingInterrupts, PendingInterrupt(0, 0)); p.Do(interruptsEnabled); p.Do(inInterrupt); p.DoMarker("sceKernelInterrupt"); } +void __InterruptsDoStateLate(PointerWrap &p) +{ + // We do these later to ensure the handlers have been registered. + for (int i = 0; i < PSP_NUMBER_INTERRUPTS; ++i) + intrHandlers[i].DoState(p); + p.DoMarker("sceKernelInterrupt Late"); +} + void __InterruptsShutdown() { for (int i = 0; i < PSP_NUMBER_INTERRUPTS; ++i) diff --git a/Core/HLE/sceKernelInterrupt.h b/Core/HLE/sceKernelInterrupt.h index 3a298b955b..6b60a7870f 100644 --- a/Core/HLE/sceKernelInterrupt.h +++ b/Core/HLE/sceKernelInterrupt.h @@ -109,6 +109,7 @@ typedef SubIntrHandler *(*SubIntrCreator)(); bool __IsInInterrupt(); void __InterruptsInit(); void __InterruptsDoState(PointerWrap &p); +void __InterruptsDoStateLate(PointerWrap &p); void __InterruptsShutdown(); void __TriggerInterrupt(int type, PSPInterrupt intno, int subInterrupts = -1); void __TriggerInterruptWithArg(int type, PSPInterrupt intno, int subintr, int arg); // For GE "callbacks" diff --git a/Core/HLE/sceKernelModule.cpp b/Core/HLE/sceKernelModule.cpp index d35e5d5138..701b51297c 100644 --- a/Core/HLE/sceKernelModule.cpp +++ b/Core/HLE/sceKernelModule.cpp @@ -136,6 +136,25 @@ KernelObject *__KernelModuleObject() return new Module; } +class AfterModuleEntryCall : public Action { +public: + AfterModuleEntryCall() {} + SceUID moduleID_; + u32 retValAddr; + virtual void run(); + virtual void DoState(PointerWrap &p) { + p.Do(moduleID_); + p.Do(retValAddr); + } + static Action *Create() { + return new AfterModuleEntryCall; + } +}; + +void AfterModuleEntryCall::run() { + Memory::Write_U32(retValAddr, currentMIPS->r[2]); +} + ////////////////////////////////////////////////////////////////////////// // MODULES ////////////////////////////////////////////////////////////////////////// @@ -168,13 +187,21 @@ struct SceKernelSMOption { ////////////////////////////////////////////////////////////////////////// // STATE BEGIN +static int actionAfterModule; static SceUID mainModuleID; // hack // STATE END ////////////////////////////////////////////////////////////////////////// +void __KernelModuleInit() +{ + actionAfterModule = __KernelRegisterActionType(AfterModuleEntryCall::Create); +} + void __KernelModuleDoState(PointerWrap &p) { p.Do(mainModuleID); + p.Do(actionAfterModule); + __KernelRestoreActionType(actionAfterModule, AfterModuleEntryCall::Create); p.DoMarker("sceKernelModule"); } @@ -533,6 +560,7 @@ bool __KernelLoadExec(const char *filename, SceKernelLoadExecParam *param, std:: if (__KernelIsRunning()) __KernelShutdown(); + __KernelModuleInit(); __KernelInit(); PSPFileInfo info = pspFileSystem.GetFileInfo(filename); @@ -657,18 +685,6 @@ u32 sceKernelLoadModule(const char *name, u32 flags) return module->GetUID(); } -class AfterModuleEntryCall : public Action { -public: - AfterModuleEntryCall() {} - SceUID moduleID_; - u32 retValAddr; - virtual void run(); -}; - -void AfterModuleEntryCall::run() { - Memory::Write_U32(retValAddr, currentMIPS->r[2]); -} - void sceKernelStartModule(u32 moduleId, u32 argsize, u32 argAddr, u32 returnValueAddr, u32 optionAddr) { ERROR_LOG(HLE,"UNIMPL sceKernelStartModule(%d,asize=%08x,aptr=%08x,retptr=%08x,%08x)", diff --git a/Core/HLE/sceKernelThread.cpp b/Core/HLE/sceKernelThread.cpp index 66a9172675..3743bb2a4b 100644 --- a/Core/HLE/sceKernelThread.cpp +++ b/Core/HLE/sceKernelThread.cpp @@ -193,13 +193,62 @@ public: return temp; } void clear() { + // TODO: Should this delete them? (it should probably just own them.) calls_.clear(); idGen_ = 0; } + int registerType(ActionCreator creator) { + types_.push_back(creator); + return types_.size() - 1; + } + + void restoreType(int actionType, ActionCreator creator) { + if (actionType >= (int) types_.size()) + types_.resize(actionType + 1, NULL); + types_[actionType] = creator; + } + + Action *createByType(int actionType) { + if (actionType < (int) types_.size() && types_[actionType] != NULL) { + Action *a = types_[actionType](); + a->actionTypeID = actionType; + return a; + } + return NULL; + } + + void DoState(PointerWrap &p) { + p.Do(idGen_); + + size_t n = (int) calls_.size(); + p.Do(n); + + if (p.mode == p.MODE_READ) { + // TODO: Delete them? + calls_.clear(); + for (size_t i = 0; i < n; ++i) { + int k; + p.Do(k); + // TODO: Presumably leaks? MipsCallManager may need to own these. + MipsCall *call = new MipsCall(); + call->DoState(p); + calls_[k] = call; + } + } else { + std::map::iterator it, end; + for (it = calls_.begin(), end = calls_.end(); it != end; ++it) { + p.Do(it->first); + it->second->DoState(p); + } + } + p.DoMarker("MipsCallManager"); + } + private: int genId() { return ++idGen_; } std::map calls_; + std::vector types_; int idGen_; }; @@ -207,7 +256,37 @@ class ActionAfterMipsCall : public Action { public: virtual void run(); - Thread *thread; + + static Action *Create() + { + return new ActionAfterMipsCall; + } + + virtual void DoState(PointerWrap &p) + { + p.Do(threadID); + p.Do(status); + p.Do(waitType); + p.Do(waitID); + p.Do(waitInfo); + p.Do(isProcessingCallbacks); + + p.DoMarker("ActionAfterMipsCall"); + + int chainedActionType = 0; + if (chainedAction != NULL) + chainedActionType = chainedAction->actionTypeID; + p.Do(chainedActionType); + + if (chainedActionType != 0) + { + if (p.mode == p.MODE_READ) + chainedAction = __KernelCreateAction(chainedActionType); + chainedAction->DoState(p); + } + } + + SceUID threadID; // Saved thread state int status; @@ -219,6 +298,31 @@ public: Action *chainedAction; }; +class ActionAfterCallback : public Action +{ +public: + ActionAfterCallback() {} + virtual void run(); + + static Action *Create() + { + return new ActionAfterCallback; + } + + void setCallback(SceUID cbId_) + { + cbId = cbId_; + } + + void DoState(PointerWrap &p) + { + p.Do(cbId); + p.DoMarker("ActionAfterCallback"); + } + + SceUID cbId; +}; + class Thread : public KernelObject { public: @@ -383,6 +487,8 @@ int eventScheduledWakeup; bool dispatchEnabled = true; MipsCallManager mipsCalls; +int actionAfterCallback; +int actionAfterMipsCall; // This seems nasty SceUID curModule; @@ -391,6 +497,50 @@ SceUID curModule; //STATE END ////////////////////////////////////////////////////////////////////////// +int __KernelRegisterActionType(ActionCreator creator) +{ + return mipsCalls.registerType(creator); +} + +void __KernelRestoreActionType(int actionType, ActionCreator creator) +{ + mipsCalls.restoreType(actionType, creator); +} + +Action *__KernelCreateAction(int actionType) +{ + return mipsCalls.createByType(actionType); +} + +void MipsCall::DoState(PointerWrap &p) +{ + p.Do(entryPoint); + p.Do(cbId); + p.DoArray(args, ARRAY_SIZE(args)); + p.Do(numArgs); + p.Do(savedIdRegister); + p.Do(savedRa); + p.Do(savedPc); + p.Do(savedV0); + p.Do(savedV1); + p.Do(returnVoid); + p.Do(tag); + p.Do(savedId); + p.Do(reschedAfter); + + p.DoMarker("MipsCall"); + + int actionTypeID = 0; + if (doAfter != NULL) + actionTypeID = doAfter->actionTypeID; + p.Do(actionTypeID); + if (actionTypeID != 0) + { + if (p.mode == p.MODE_READ) + doAfter = __KernelCreateAction(actionTypeID); + doAfter->DoState(p); + } +} // TODO: Should move to this wrapper so we can keep the current thread as a SceUID instead // of a dangerous raw pointer. @@ -443,6 +593,8 @@ void __KernelThreadingInit() WriteSyscall("FakeSysCalls", NID_INTERRUPTRETURN, intReturnHackAddr); eventScheduledWakeup = CoreTiming::RegisterEvent("ScheduledWakeup", &hleScheduledWakeup); + actionAfterMipsCall = __KernelRegisterActionType(ActionAfterMipsCall::Create); + actionAfterCallback = __KernelRegisterActionType(ActionAfterCallback::Create); // Create the two idle threads, as well. With the absolute minimal possible priority. // 4096 stack size - don't know what the right value is. Hm, if callbacks are ever to run on these threads... @@ -453,6 +605,37 @@ void __KernelThreadingInit() __KernelListenThreadEnd(__KernelCancelWakeup); } +void __KernelThreadingDoState(PointerWrap &p) +{ + p.Do(g_inCbCount); + p.Do(idleThreadHackAddr); + p.Do(threadReturnHackAddr); + p.Do(cbReturnHackAddr); + p.Do(intReturnHackAddr); + + p.Do(currentThread); + p.Do(threadqueue); + p.DoArray(threadIdleID, ARRAY_SIZE(threadIdleID)); + p.Do(dispatchEnabled); + p.Do(curModule); + + p.Do(eventScheduledWakeup); + CoreTiming::RestoreRegisterEvent(eventScheduledWakeup, "ScheduledWakeup", &hleScheduledWakeup); + p.Do(actionAfterMipsCall); + __KernelRestoreActionType(actionAfterMipsCall, ActionAfterMipsCall::Create); + p.Do(actionAfterCallback); + __KernelRestoreActionType(actionAfterCallback, ActionAfterCallback::Create); + + p.DoMarker("sceKernelThread"); +} + +void __KernelThreadingDoStateLate(PointerWrap &p) +{ + // We do this late to give modules time to register actions. + mipsCalls.DoState(p); + p.DoMarker("sceKernelThread Late"); +} + KernelObject *__KernelThreadObject() { return new Thread; @@ -1698,11 +1881,15 @@ void sceKernelReferCallbackStatus() } void ActionAfterMipsCall::run() { - thread->nt.status = status; - thread->nt.waitType = waitType; - thread->nt.waitID = waitID; - thread->waitInfo = waitInfo; - thread->isProcessingCallbacks = isProcessingCallbacks; + u32 error; + Thread *thread = kernelObjects.Get(threadID, error); + if (thread) { + thread->nt.status = status; + thread->nt.waitType = waitType; + thread->nt.waitID = waitID; + thread->waitInfo = waitInfo; + thread->isProcessingCallbacks = isProcessingCallbacks; + } if (chainedAction) { chainedAction->run(); @@ -1877,9 +2064,9 @@ bool __CanExecuteCallbackNow(Thread *thread) { void __KernelCallAddress(Thread *thread, u32 entryPoint, Action *afterAction, bool returnVoid, std::vector args, bool reschedAfter) { if (thread) { - ActionAfterMipsCall *after = new ActionAfterMipsCall(); + ActionAfterMipsCall *after = (ActionAfterMipsCall *) __KernelCreateAction(actionAfterMipsCall); after->chainedAction = afterAction; - after->thread = thread; + after->threadID = thread->GetUID(); after->status = thread->nt.status; after->waitType = thread->nt.waitType; after->waitID = thread->nt.waitID; @@ -1986,6 +2173,7 @@ void __KernelReturnFromMipsCall() // Should also save/restore wait state here. if (call->doAfter) call->doAfter->run(); + // TODO: Do we need to delete call->doAfter? currentMIPS->pc = call->savedPc; currentMIPS->r[MIPS_REG_RA] = call->savedRa; @@ -2005,6 +2193,8 @@ void __KernelReturnFromMipsCall() if (call->reschedAfter || threadReady == 0) __KernelReSchedule("return from callback"); } + + // TODO: Do we need to delete call? } bool __KernelExecutePendingMipsCalls(bool reschedAfter) @@ -2027,15 +2217,6 @@ bool __KernelExecutePendingMipsCalls(bool reschedAfter) return false; } - -class ActionAfterCallback : public Action -{ -public: - ActionAfterCallback(SceUID cbId_) : cbId(cbId_) {} - virtual void run(); - SceUID cbId; -}; - // Executes the callback, when it next is context switched to. void __KernelRunCallbackOnThread(SceUID cbId, Thread *thread, bool reschedAfter) { @@ -2060,7 +2241,12 @@ void __KernelRunCallbackOnThread(SceUID cbId, Thread *thread, bool reschedAfter) cb->nc.notifyCount = 0; cb->nc.notifyArg = 0; - Action *action = new ActionAfterCallback(cbId); + ActionAfterCallback *action = (ActionAfterCallback *) __KernelCreateAction(actionAfterCallback); + if (action != NULL) + action->setCallback(cbId); + else + ERROR_LOG(HLE, "Something went wrong creating a restore action for a callback."); + __KernelCallAddress(thread, cb->nc.entrypoint, action, false, args, reschedAfter); } diff --git a/Core/HLE/sceKernelThread.h b/Core/HLE/sceKernelThread.h index d11a33c17c..b63fe58312 100644 --- a/Core/HLE/sceKernelThread.h +++ b/Core/HLE/sceKernelThread.h @@ -97,6 +97,8 @@ struct ThreadContext // Internal API, used by implementations of kernel functions void __KernelThreadingInit(); +void __KernelThreadingDoState(PointerWrap &p); +void __KernelThreadingDoStateLate(PointerWrap &p); void __KernelThreadingShutdown(); KernelObject *__KernelThreadObject(); KernelObject *__KernelCallbackObject(); @@ -184,6 +186,10 @@ bool __KernelSwitchOffThread(const char *reason); // A call into game code. These can be pending on a thread. // Similar to Callback-s (NOT CallbackInfos) in JPCSP. class Action; +typedef Action *(*ActionCreator)(); +Action *__KernelCreateAction(int actionType); +int __KernelRegisterActionType(ActionCreator creator); +void __KernelRestoreActionType(int actionType, ActionCreator creator); struct MipsCall { u32 entryPoint; u32 cbId; @@ -196,9 +202,11 @@ struct MipsCall { u32 savedV0; u32 savedV1; bool returnVoid; - const char *tag; + std::string tag; u32 savedId; bool reschedAfter; + + void DoState(PointerWrap &p); }; enum ThreadStatus { From b81899876f04f6f30ff9150b538049adda789e97 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Thu, 27 Dec 2012 19:45:00 -0800 Subject: [PATCH 15/29] Don't leak MipsCall objects. --- Core/HLE/sceKernelThread.cpp | 31 +++++++++++++++++-------------- 1 file changed, 17 insertions(+), 14 deletions(-) diff --git a/Core/HLE/sceKernelThread.cpp b/Core/HLE/sceKernelThread.cpp index 3743bb2a4b..9cfecf7874 100644 --- a/Core/HLE/sceKernelThread.cpp +++ b/Core/HLE/sceKernelThread.cpp @@ -175,7 +175,6 @@ struct ThreadWaitInfo { }; // Owns outstanding MIPS calls and provides a way to get them by ID. -// TODO: MipsCall structs are kinda big, try to cut down on the copying by owning pointers instead. class MipsCallManager { public: MipsCallManager() : idGen_(0) {} @@ -193,23 +192,26 @@ public: return temp; } void clear() { - // TODO: Should this delete them? (it should probably just own them.) + std::map::iterator it, end; + for (it = calls_.begin(), end = calls_.end(); it != end; ++it) { + delete it->second; + } calls_.clear(); idGen_ = 0; } - int registerType(ActionCreator creator) { + int registerActionType(ActionCreator creator) { types_.push_back(creator); return types_.size() - 1; } - void restoreType(int actionType, ActionCreator creator) { + void restoreActionType(int actionType, ActionCreator creator) { if (actionType >= (int) types_.size()) types_.resize(actionType + 1, NULL); types_[actionType] = creator; } - Action *createByType(int actionType) { + Action *createActionByType(int actionType) { if (actionType < (int) types_.size() && types_[actionType] != NULL) { Action *a = types_[actionType](); a->actionTypeID = actionType; @@ -219,18 +221,15 @@ public: } void DoState(PointerWrap &p) { - p.Do(idGen_); size_t n = (int) calls_.size(); p.Do(n); if (p.mode == p.MODE_READ) { - // TODO: Delete them? - calls_.clear(); + clear(); for (size_t i = 0; i < n; ++i) { int k; p.Do(k); - // TODO: Presumably leaks? MipsCallManager may need to own these. MipsCall *call = new MipsCall(); call->DoState(p); calls_[k] = call; @@ -242,6 +241,8 @@ public: it->second->DoState(p); } } + + p.Do(idGen_); p.DoMarker("MipsCallManager"); } @@ -499,17 +500,17 @@ SceUID curModule; int __KernelRegisterActionType(ActionCreator creator) { - return mipsCalls.registerType(creator); + return mipsCalls.registerActionType(creator); } void __KernelRestoreActionType(int actionType, ActionCreator creator) { - mipsCalls.restoreType(actionType, creator); + mipsCalls.restoreActionType(actionType, creator); } Action *__KernelCreateAction(int actionType) { - return mipsCalls.createByType(actionType); + return mipsCalls.createActionByType(actionType); } void MipsCall::DoState(PointerWrap &p) @@ -2172,8 +2173,10 @@ void __KernelReturnFromMipsCall() // Should also save/restore wait state here. if (call->doAfter) + { call->doAfter->run(); - // TODO: Do we need to delete call->doAfter? + delete call->doAfter; + } currentMIPS->pc = call->savedPc; currentMIPS->r[MIPS_REG_RA] = call->savedRa; @@ -2194,7 +2197,7 @@ void __KernelReturnFromMipsCall() __KernelReSchedule("return from callback"); } - // TODO: Do we need to delete call? + delete call; } bool __KernelExecutePendingMipsCalls(bool reschedAfter) From e3e6f81dfa9f0156ea124927d205b9f824c93d9a Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Thu, 27 Dec 2012 20:33:10 -0800 Subject: [PATCH 16/29] Snapshot the CPU state as well. --- Core/MIPS/MIPS.cpp | 27 +++++++++++++++++++++++++++ Core/MIPS/MIPS.h | 8 ++++++++ Core/SaveState.cpp | 3 +++ 3 files changed, 38 insertions(+) diff --git a/Core/MIPS/MIPS.cpp b/Core/MIPS/MIPS.cpp index e4fa5549fe..d784419212 100644 --- a/Core/MIPS/MIPS.cpp +++ b/Core/MIPS/MIPS.cpp @@ -99,6 +99,33 @@ void MIPSState::Reset() rng.Init(0x1337); } +void MIPSState::DoState(PointerWrap &p) +{ + // Reset the jit if we're loading. + if (p.mode == p.MODE_READ) + Reset(); + + p.DoArray(r, sizeof(r) / sizeof(r[0])); + p.DoArray(f, sizeof(f) / sizeof(f[0])); + p.DoArray(v, sizeof(v) / sizeof(v[0])); + p.DoArray(vfpuCtrl, sizeof(vfpuCtrl) / sizeof(vfpuCtrl[0])); + p.DoArray(vfpuWriteMask, sizeof(vfpuWriteMask) / sizeof(vfpuWriteMask[0])); + p.Do(pc); + p.Do(nextPC); + p.Do(hi); + p.Do(lo); + p.Do(fpcond); + p.Do(fcr0); + p.Do(fcr31); + rng.DoState(p); + p.Do(inDelaySlot); + p.Do(llBit); + p.Do(cpuType); + p.Do(exceptions); + p.Do(debugCount); + p.DoMarker("MIPSState"); +} + void MIPSState::SetWriteMask(const bool wm[4]) { for (int i = 0; i < 4; i++) diff --git a/Core/MIPS/MIPS.h b/Core/MIPS/MIPS.h index cbab48edba..1e8bd29a6f 100644 --- a/Core/MIPS/MIPS.h +++ b/Core/MIPS/MIPS.h @@ -18,6 +18,7 @@ #pragma once #include "../../Globals.h" +#include "../../Common/ChunkFile.h" #include "../CPU.h" enum @@ -92,6 +93,12 @@ public: return (m_z << 16) + m_w; } + void DoState(PointerWrap &p) { + p.Do(m_w); + p.Do(m_z); + p.DoMarker("GMRng"); + } + private: u32 m_w; u32 m_z; @@ -104,6 +111,7 @@ public: ~MIPSState(); void Reset(); + void DoState(PointerWrap &p); u32 r[32]; float f[32]; diff --git a/Core/SaveState.cpp b/Core/SaveState.cpp index bbf8717b9f..69ba1a517c 100644 --- a/Core/SaveState.cpp +++ b/Core/SaveState.cpp @@ -24,6 +24,7 @@ #include "HLE/sceKernel.h" #include "HW/MemoryStick.h" #include "MemMap.h" +#include "MIPS/MIPS.h" namespace SaveState { @@ -70,7 +71,9 @@ namespace SaveState Memory::DoState(p); MemoryStick_DoState(p); + currentMIPS->DoState(p); __KernelDoState(p); + // TODO: filesystem, HLE? } void Enqueue(SaveState::Operation op) From 4b39e39455b3806c1fffb72aa016be3cf7dccda4 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Thu, 27 Dec 2012 22:14:31 -0800 Subject: [PATCH 17/29] Start save stating the filesystem state. Plus minor fixes and at least an attempt to make states the same on both 32 and 64 bit. --- Common/ChunkFile.h | 3 +- Core/CoreTiming.cpp | 2 +- Core/FileSystems/DirectoryFileSystem.cpp | 5 ++ Core/FileSystems/DirectoryFileSystem.h | 1 + Core/FileSystems/FileSystem.h | 2 + Core/FileSystems/ISOFileSystem.cpp | 70 ++++++++++++++++++++++++ Core/FileSystems/ISOFileSystem.h | 5 +- Core/FileSystems/MetaFileSystem.cpp | 19 +++++++ Core/FileSystems/MetaFileSystem.h | 2 + Core/HLE/HLE.cpp | 6 ++ Core/HLE/HLE.h | 1 + Core/HLE/sceIo.cpp | 6 +- Core/HLE/sceKernelInterrupt.cpp | 4 +- Core/HLE/sceKernelThread.cpp | 4 +- Core/SaveState.cpp | 5 +- 15 files changed, 125 insertions(+), 10 deletions(-) diff --git a/Common/ChunkFile.h b/Common/ChunkFile.h index c6dd5d6de0..f6e3f0a0ce 100644 --- a/Common/ChunkFile.h +++ b/Common/ChunkFile.h @@ -158,7 +158,8 @@ public: u32 vec_size = (u32)x.size(); Do(vec_size); x.resize(vec_size); - DoArray(&x[0], vec_size); + if (vec_size > 0) + DoArray(&x[0], vec_size); } // Store deques. diff --git a/Core/CoreTiming.cpp b/Core/CoreTiming.cpp index 31b9bbb0ad..504d28fb5b 100644 --- a/Core/CoreTiming.cpp +++ b/Core/CoreTiming.cpp @@ -550,7 +550,7 @@ void Event_DoState(PointerWrap &p, BaseEvent *ev) void DoState(PointerWrap &p) { - size_t n = event_types.size(); + int n = (int) event_types.size(); p.Do(n); // These (should) be filled in later by the modules. event_types.resize(n, EventType(AntiCrashCallback, "INVALID EVENT")); diff --git a/Core/FileSystems/DirectoryFileSystem.cpp b/Core/FileSystems/DirectoryFileSystem.cpp index 51dbcc7979..e57be86eb2 100644 --- a/Core/FileSystems/DirectoryFileSystem.cpp +++ b/Core/FileSystems/DirectoryFileSystem.cpp @@ -546,3 +546,8 @@ std::vector DirectoryFileSystem::GetDirListing(std::string path) { return myVector; } +void DirectoryFileSystem::DoState(PointerWrap &p) { + if (!entries.empty()) { + ERROR_LOG(FILESYS, "FIXME: Open files during savestate, could go badly."); + } +} diff --git a/Core/FileSystems/DirectoryFileSystem.h b/Core/FileSystems/DirectoryFileSystem.h index e3f4bf0acc..6cb334fc53 100644 --- a/Core/FileSystems/DirectoryFileSystem.h +++ b/Core/FileSystems/DirectoryFileSystem.h @@ -53,6 +53,7 @@ public: DirectoryFileSystem(IHandleAllocator *_hAlloc, std::string _basePath); ~DirectoryFileSystem(); + void DoState(PointerWrap &p); std::vector GetDirListing(std::string path); u32 OpenFile(std::string filename, FileAccess access); void CloseFile(u32 handle); diff --git a/Core/FileSystems/FileSystem.h b/Core/FileSystems/FileSystem.h index d14854803e..4d8670effd 100644 --- a/Core/FileSystems/FileSystem.h +++ b/Core/FileSystems/FileSystem.h @@ -90,6 +90,7 @@ class IFileSystem public: virtual ~IFileSystem() {} + virtual void DoState(PointerWrap &p) = 0; virtual std::vector GetDirListing(std::string path) = 0; virtual u32 OpenFile(std::string filename, FileAccess access) = 0; virtual void CloseFile(u32 handle) = 0; @@ -108,6 +109,7 @@ public: class EmptyFileSystem : public IFileSystem { public: + virtual void DoState(PointerWrap &p) {} std::vector GetDirListing(std::string path) {std::vector vec; return vec;} u32 OpenFile(std::string filename, FileAccess access) {return 0;} void CloseFile(u32 handle) {} diff --git a/Core/FileSystems/ISOFileSystem.cpp b/Core/FileSystems/ISOFileSystem.cpp index a7e7bf01f6..712a10e953 100644 --- a/Core/FileSystems/ISOFileSystem.cpp +++ b/Core/FileSystems/ISOFileSystem.cpp @@ -131,6 +131,7 @@ ISOFileSystem::ISOFileSystem(IHandleAllocator *_hAlloc, BlockDevice *_blockDevic entireISO.size = _blockDevice->GetNumBlocks() * _blockDevice->GetBlockSize(); entireISO.isBlockSectorMode = true; entireISO.flags = 0; + entireISO.parent = NULL; if (!memcmp(desc.cd001, "CD001", 5)) { @@ -142,6 +143,7 @@ ISOFileSystem::ISOFileSystem(IHandleAllocator *_hAlloc, BlockDevice *_blockDevic } treeroot = new TreeEntry; + treeroot->parent = NULL; u32 rootSector = desc.root.firstDataSectorLE; u32 rootSize = desc.root.dataLengthLE; @@ -211,6 +213,7 @@ nextblock: e->isDirectory = !isFile; e->flags = dir.flags; e->isBlockSectorMode = false; + e->parent = root; // Let's not excessively spam the log - I commented this line out. //DEBUG_LOG(FILESYS, "%s: %s %08x %08x %i", e->isDirectory?"D":"F", name, dir.firstDataSectorLE, e->startingPosition, e->startingPosition); @@ -540,3 +543,70 @@ std::vector ISOFileSystem::GetDirListing(std::string path) } return myVector; } + +std::string ISOFileSystem::EntryFullPath(TreeEntry *e) +{ + size_t fullLen = 0; + TreeEntry *cur = e; + while (cur != NULL && cur != treeroot) + { + // For the "/". + fullLen += 1 + cur->name.size(); + cur = cur->parent; + } + + std::string path; + path.resize(fullLen); + + cur = e; + while (cur != NULL && cur != treeroot) + { + path.replace(fullLen - cur->name.size(), cur->name.size(), cur->name); + path.replace(fullLen - cur->name.size() - 1, 1, "/"); + fullLen -= 1 + cur->name.size(); + cur = cur->parent; + } + + return path; +} + +void ISOFileSystem::DoState(PointerWrap &p) +{ + int n = (int) entries.size(); + p.Do(n); + + if (p.mode == p.MODE_READ) + { + entries.clear(); + for (int i = 0; i < n; ++i) + { + u32 fd; + p.Do(fd); + std::string path; + p.Do(path); + OpenFileEntry of; + of.file = path.empty() ? NULL : GetFromPath(path); + p.Do(of.seekPos); + p.Do(of.isRawSector); + p.Do(of.sectorStart); + p.Do(of.openSize); + entries[fd] = of; + } + } + else + { + for (EntryMap::iterator it = entries.begin(), end = entries.end(); it != end; ++it) + { + p.Do(it->first); + std::string path = ""; + if (it->second.file != NULL) + path = EntryFullPath(it->second.file); + p.Do(path); + p.Do(it->second.seekPos); + p.Do(it->second.isRawSector); + p.Do(it->second.sectorStart); + p.Do(it->second.openSize); + } + } + p.DoMarker("ISOFileSystem"); +} diff --git a/Core/FileSystems/ISOFileSystem.h b/Core/FileSystems/ISOFileSystem.h index 61f30016f1..96e88e0710 100644 --- a/Core/FileSystems/ISOFileSystem.h +++ b/Core/FileSystems/ISOFileSystem.h @@ -42,8 +42,9 @@ class ISOFileSystem : public IFileSystem u32 startingPosition; s64 size; bool isDirectory; - bool isBlockSectorMode; // "umd:" mode: all sizes and offsets are in 2048 byte chunks + bool isBlockSectorMode; // "umd:" mode: all sizes and offsets are in 2048 byte chunks + TreeEntry *parent; std::vector children; }; @@ -67,10 +68,12 @@ class ISOFileSystem : public IFileSystem void ReadDirectory(u32 startsector, u32 dirsize, TreeEntry *root); TreeEntry *GetFromPath(std::string path); + std::string EntryFullPath(TreeEntry *e); public: ISOFileSystem(IHandleAllocator *_hAlloc, BlockDevice *_blockDevice); ~ISOFileSystem(); + void DoState(PointerWrap &p); std::vector GetDirListing(std::string path); u32 OpenFile(std::string filename, FileAccess access); void CloseFile(u32 handle); diff --git a/Core/FileSystems/MetaFileSystem.cpp b/Core/FileSystems/MetaFileSystem.cpp index ed18b31a07..58ae33fae1 100644 --- a/Core/FileSystems/MetaFileSystem.cpp +++ b/Core/FileSystems/MetaFileSystem.cpp @@ -367,3 +367,22 @@ size_t MetaFileSystem::SeekFile(u32 handle, s32 position, FileMove type) return 0; } +void MetaFileSystem::DoState(PointerWrap &p) +{ + p.Do(current); + p.Do(currentDirectory); + + int n = (int) fileSystems.size(); + p.Do(n); + if (n != fileSystems.size()) + { + ERROR_LOG(FILESYS, "Savestate failure: number of filesystems doesn't match."); + return; + } + + for (int i = 0; i < n; ++i) + fileSystems[i].system->DoState(p); + + p.DoMarker("MetaFileSystem"); +} + diff --git a/Core/FileSystems/MetaFileSystem.h b/Core/FileSystems/MetaFileSystem.h index b0b63d9b97..7fd0a96db2 100644 --- a/Core/FileSystems/MetaFileSystem.h +++ b/Core/FileSystems/MetaFileSystem.h @@ -36,6 +36,8 @@ public: u32 GetNewHandle() {return current++;} void FreeHandle(u32 handle) {} + virtual void DoState(PointerWrap &p); + IFileSystem *GetHandleOwner(u32 handle); bool MapFilePath(const std::string &inpath, std::string &outpath, IFileSystem **system); diff --git a/Core/HLE/HLE.cpp b/Core/HLE/HLE.cpp index f58a2aca4f..7d5c426c49 100644 --- a/Core/HLE/HLE.cpp +++ b/Core/HLE/HLE.cpp @@ -58,6 +58,12 @@ void HLEInit() RegisterAllModules(); } +void HLEDoState(PointerWrap &p) +{ + p.Do(unresolvedSyscalls); + p.DoMarker("HLE"); +} + void HLEShutdown() { hleAfterSyscall = HLE_AFTER_NOTHING; diff --git a/Core/HLE/HLE.h b/Core/HLE/HLE.h index 09d5fc75cd..8ff39c328c 100644 --- a/Core/HLE/HLE.h +++ b/Core/HLE/HLE.h @@ -87,6 +87,7 @@ void hleRunInterrupts(); void hleDebugBreak(); void HLEInit(); +void HLEDoState(PointerWrap &p); void HLEShutdown(); u32 GetNibByName(const char *module, const char *function); u32 GetSyscallOp(const char *module, u32 nib); diff --git a/Core/HLE/sceIo.cpp b/Core/HLE/sceIo.cpp index 801b4bf917..70af694f7b 100644 --- a/Core/HLE/sceIo.cpp +++ b/Core/HLE/sceIo.cpp @@ -853,8 +853,10 @@ public: p.Do(name); // TODO: Is this the right way for it to wake up? - size_t count = listing.size(); - for (size_t i = 0; i < count; ++i) { + int count = listing.size(); + p.Do(count); + listing.resize(count); + for (int i = 0; i < count; ++i) { listing[i].DoState(p); } p.DoMarker("DirListing"); diff --git a/Core/HLE/sceKernelInterrupt.cpp b/Core/HLE/sceKernelInterrupt.cpp index ecb1bef957..7c8c9d2544 100644 --- a/Core/HLE/sceKernelInterrupt.cpp +++ b/Core/HLE/sceKernelInterrupt.cpp @@ -168,13 +168,13 @@ public: return; } - size_t n = subIntrHandlers.size(); + int n = (int) subIntrHandlers.size(); p.Do(n); if (p.mode == p.MODE_READ) { clear(); - for (size_t i = 0; i < n; ++i) + for (int i = 0; i < n; ++i) { int subIntrNum; p.Do(subIntrNum); diff --git a/Core/HLE/sceKernelThread.cpp b/Core/HLE/sceKernelThread.cpp index 9cfecf7874..7732c558ce 100644 --- a/Core/HLE/sceKernelThread.cpp +++ b/Core/HLE/sceKernelThread.cpp @@ -222,12 +222,12 @@ public: void DoState(PointerWrap &p) { - size_t n = (int) calls_.size(); + int n = (int) calls_.size(); p.Do(n); if (p.mode == p.MODE_READ) { clear(); - for (size_t i = 0; i < n; ++i) { + for (int i = 0; i < n; ++i) { int k; p.Do(k); MipsCall *call = new MipsCall(); diff --git a/Core/SaveState.cpp b/Core/SaveState.cpp index 69ba1a517c..35f91ce900 100644 --- a/Core/SaveState.cpp +++ b/Core/SaveState.cpp @@ -21,10 +21,12 @@ #include "SaveState.h" #include "Core.h" #include "CoreTiming.h" +#include "HLE/HLE.h" #include "HLE/sceKernel.h" #include "HW/MemoryStick.h" #include "MemMap.h" #include "MIPS/MIPS.h" +#include "System.h" namespace SaveState { @@ -72,8 +74,9 @@ namespace SaveState Memory::DoState(p); MemoryStick_DoState(p); currentMIPS->DoState(p); + pspFileSystem.DoState(p); + HLEDoState(p); __KernelDoState(p); - // TODO: filesystem, HLE? } void Enqueue(SaveState::Operation op) From 1768365c13df95b56b8c39add91b4afed13ba74a Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Thu, 27 Dec 2012 22:16:23 -0800 Subject: [PATCH 18/29] Fix a memory leak in the ISO filesystem. --- Core/FileSystems/ISOFileSystem.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Core/FileSystems/ISOFileSystem.cpp b/Core/FileSystems/ISOFileSystem.cpp index 712a10e953..b054b6bf72 100644 --- a/Core/FileSystems/ISOFileSystem.cpp +++ b/Core/FileSystems/ISOFileSystem.cpp @@ -143,6 +143,11 @@ ISOFileSystem::ISOFileSystem(IHandleAllocator *_hAlloc, BlockDevice *_blockDevic } treeroot = new TreeEntry; + treeroot->isDirectory = true; + treeroot->startingPosition = 0; + treeroot->size = 0; + treeroot->isBlockSectorMode = false; + treeroot->flags = 0; treeroot->parent = NULL; u32 rootSector = desc.root.firstDataSectorLE; @@ -154,6 +159,7 @@ ISOFileSystem::ISOFileSystem(IHandleAllocator *_hAlloc, BlockDevice *_blockDevic ISOFileSystem::~ISOFileSystem() { delete blockDevice; + delete treeroot; } void ISOFileSystem::ReadDirectory(u32 startsector, u32 dirsize, TreeEntry *root) From cd1d4367bfa3c1bfbb12b32a36e8e7521908fc77 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Thu, 27 Dec 2012 23:00:04 -0800 Subject: [PATCH 19/29] Save state of a bunch of small modules. --- Core/HLE/sceCtrl.cpp | 24 +++++++++++++++++++++++ Core/HLE/sceCtrl.h | 3 +++ Core/HLE/sceFont.cpp | 35 ++++++++++++++++++++++------------ Core/HLE/sceFont.h | 5 +++++ Core/HLE/sceImpose.cpp | 8 ++++++++ Core/HLE/sceImpose.h | 3 +++ Core/HLE/sceKernel.cpp | 13 ++++++++++++- Core/HLE/scePower.cpp | 6 ++++++ Core/HLE/scePower.h | 3 +++ Core/HLE/sceSsl.cpp | 8 ++++++++ Core/HLE/sceSsl.h | 5 ++++- Core/HLE/sceUmd.cpp | 23 ++++++++++++++++------ Core/HLE/sceUmd.h | 1 + Core/HLE/sceUsb.cpp | 6 ++++++ Core/HLE/sceUsb.h | 1 + Core/Util/PPGeDraw.cpp | 43 ++++++++++++++++++++++++++++++++---------- Core/Util/PPGeDraw.h | 4 ++++ 17 files changed, 161 insertions(+), 30 deletions(-) diff --git a/Core/HLE/sceCtrl.cpp b/Core/HLE/sceCtrl.cpp index 5874ae2865..fbaac32477 100644 --- a/Core/HLE/sceCtrl.cpp +++ b/Core/HLE/sceCtrl.cpp @@ -284,6 +284,30 @@ void __CtrlInit() memcpy(&ctrlBufs[i], &ctrlCurrent, sizeof(_ctrl_data)); } +void __CtrlDoState(PointerWrap &p) +{ + p.Do(analogEnabled); + p.Do(ctrlLatchBufs); + p.Do(ctrlOldButtons); + + p.DoVoid(ctrlBufs, sizeof(ctrlBufs)); + p.Do(ctrlCurrent); + p.Do(ctrlBuf); + p.Do(ctrlBufRead); + p.Do(latch); + + p.Do(ctrlIdleReset); + p.Do(ctrlIdleBack); + + p.Do(ctrlCycle); + + p.Do(waitingThreads); + + p.Do(ctrlTimer); + CoreTiming::RestoreRegisterEvent(ctrlTimer, "CtrlSampleTimer", __CtrlTimerUpdate); + p.DoMarker("sceCtrl"); +} + void __CtrlShutdown() { waitingThreads.clear(); diff --git a/Core/HLE/sceCtrl.h b/Core/HLE/sceCtrl.h index 62dff53bcc..5f9b4e3e05 100644 --- a/Core/HLE/sceCtrl.h +++ b/Core/HLE/sceCtrl.h @@ -17,6 +17,8 @@ #pragma once +#include "../../Common/ChunkFile.h" + void Register_sceCtrl(); #define CTRL_SQUARE 0x8000 @@ -33,6 +35,7 @@ void Register_sceCtrl(); #define CTRL_RTRIGGER 0x0200 void __CtrlInit(); +void __CtrlDoState(PointerWrap &p); void __CtrlShutdown(); void __CtrlButtonDown(u32 buttonBit); diff --git a/Core/HLE/sceFont.cpp b/Core/HLE/sceFont.cpp index 294b092a2d..8c026e1913 100644 --- a/Core/HLE/sceFont.cpp +++ b/Core/HLE/sceFont.cpp @@ -12,19 +12,19 @@ typedef u32 FontLibraryHandle; typedef u32 FontHandle; typedef struct { - u32* userDataAddr; - u32 numFonts; - u32* cacheDataAddr; + u32 userDataAddr; + u32 numFonts; + u32 cacheDataAddr; // Driver callbacks. - void *(*allocFuncAddr)(void *, u32); - void (*freeFuncAddr )(void *, void *); - u32* openFuncAddr; - u32* closeFuncAddr; - u32* readFuncAddr; - u32* seekFuncAddr; - u32* errorFuncAddr; - u32* ioFinishFuncAddr; + u32 allocFuncAddr; + u32 freeFuncAddr; + u32 openFuncAddr; + u32 closeFuncAddr; + u32 readFuncAddr; + u32 seekFuncAddr; + u32 errorFuncAddr; + u32 ioFinishFuncAddr; } FontNewLibParams; typedef enum { @@ -138,11 +138,22 @@ typedef struct { u16 bufHeight; u16 bytesPerLine; u16 pad; - void *buffer; + u32 bufferPtr; } GlyphImage; FontNewLibParams fontLib; +void __FontInit() +{ + memset(&fontLib, 0, sizeof(fontLib)); +} + +void __FontDoState(PointerWrap &p) +{ + p.Do(fontLib); + p.DoMarker("sceFont"); +} + u32 sceFontNewLib(u32 FontNewLibParamsPtr, u32 errorCodePtr) { ERROR_LOG(HLE, "sceFontNewLib %x, %x", FontNewLibParamsPtr, errorCodePtr); diff --git a/Core/HLE/sceFont.h b/Core/HLE/sceFont.h index d5ff49a150..9ca1bcd6d6 100644 --- a/Core/HLE/sceFont.h +++ b/Core/HLE/sceFont.h @@ -1,3 +1,8 @@ #pragma once +#include "../../Common/ChunkFile.h" + void Register_sceFont(); + +void __FontInit(); +void __FontDoState(PointerWrap &p); diff --git a/Core/HLE/sceImpose.cpp b/Core/HLE/sceImpose.cpp index 8e098f3d70..2f201c0bcf 100644 --- a/Core/HLE/sceImpose.cpp +++ b/Core/HLE/sceImpose.cpp @@ -44,6 +44,14 @@ void __ImposeInit() umdPopup = 0; } +void __ImposeDoState(PointerWrap &p) +{ + p.Do(language); + p.Do(buttonValue); + p.Do(umdPopup); + p.DoMarker("sceImpose"); +} + u32 sceImposeGetBatteryIconStatus(u32 chargingPtr, u32 iconStatusPtr) { DEBUG_LOG(HLE, "sceImposeGetBatteryIconStatus(%08x, %08x)", chargingPtr, iconStatusPtr); diff --git a/Core/HLE/sceImpose.h b/Core/HLE/sceImpose.h index 86eabedcec..f340cd5722 100644 --- a/Core/HLE/sceImpose.h +++ b/Core/HLE/sceImpose.h @@ -17,5 +17,8 @@ #pragma once +#include "../../Common/ChunkFile.h" + void Register_sceImpose(); void __ImposeInit(); +void __ImposeDoState(PointerWrap &p); diff --git a/Core/HLE/sceKernel.cpp b/Core/HLE/sceKernel.cpp index 3e18b4c6b8..ff3f9202f6 100644 --- a/Core/HLE/sceKernel.cpp +++ b/Core/HLE/sceKernel.cpp @@ -34,6 +34,7 @@ #include "sceAudio.h" #include "sceCtrl.h" #include "sceDisplay.h" +#include "sceFont.h" #include "sceGe.h" #include "sceIo.h" #include "sceKernel.h" @@ -98,6 +99,7 @@ void __KernelInit() __SslInit(); __ImposeInit(); __UsbInit(); + __FontInit(); // "Internal" PSP libraries __PPGeInit(); @@ -152,8 +154,17 @@ void __KernelDoState(PointerWrap &p) __KernelModuleDoState(p); __KernelMutexDoState(p); __KernelSemaDoState(p); + // TODO: non-kernel modules - // TODO: PPGe + __CtrlDoState(p); + __FontDoState(p); + __ImposeDoState(p); + __PowerDoState(p); + __SslDoState(p); + __UmdDoState(p); + __UsbDoState(p); + + __PPGeDoState(p); __InterruptsDoStateLate(p); __KernelThreadingDoStateLate(p); diff --git a/Core/HLE/scePower.cpp b/Core/HLE/scePower.cpp index 68fd2215d7..f486c064f9 100644 --- a/Core/HLE/scePower.cpp +++ b/Core/HLE/scePower.cpp @@ -33,6 +33,12 @@ void __PowerInit() { volatileMemLocked = false; } +void __PowerDoState(PointerWrap &p) { + p.DoArray(powerCbSlots, ARRAY_SIZE(powerCbSlots)); + p.Do(volatileMemLocked); + p.DoMarker("scePower"); +} + int scePowerGetBatteryLifePercent() { DEBUG_LOG(HLE, "100=scePowerGetBatteryLifePercent"); return 100; diff --git a/Core/HLE/scePower.h b/Core/HLE/scePower.h index ac99c6a769..49a1b8b444 100644 --- a/Core/HLE/scePower.h +++ b/Core/HLE/scePower.h @@ -17,7 +17,10 @@ #pragma once +#include "../../Common/ChunkFile.h" + void __PowerInit(); +void __PowerDoState(PointerWrap &p); void Register_scePower(); void Register_sceSuspendForUser(); diff --git a/Core/HLE/sceSsl.cpp b/Core/HLE/sceSsl.cpp index 0a762af122..b588135b88 100644 --- a/Core/HLE/sceSsl.cpp +++ b/Core/HLE/sceSsl.cpp @@ -35,6 +35,14 @@ void __SslInit() currentMemSize = 0; } +void __SslDoState(PointerWrap &p) +{ + p.Do(isSslInit); + p.Do(maxMemSize); + p.Do(currentMemSize); + p.DoMarker("sceSsl"); +} + int sceSslInit(int heapSize) { DEBUG_LOG(HLE, "sceSslInit %d", heapSize); diff --git a/Core/HLE/sceSsl.h b/Core/HLE/sceSsl.h index c8e46f976b..6a1239f892 100644 --- a/Core/HLE/sceSsl.h +++ b/Core/HLE/sceSsl.h @@ -17,6 +17,9 @@ #pragma once +#include "../../Common/ChunkFile.h" + void Register_sceSsl(); -void __SslInit(); \ No newline at end of file +void __SslInit(); +void __SslDoState(PointerWrap &p); diff --git a/Core/HLE/sceUmd.cpp b/Core/HLE/sceUmd.cpp index 3e358d36a3..4d3b425b51 100644 --- a/Core/HLE/sceUmd.cpp +++ b/Core/HLE/sceUmd.cpp @@ -31,11 +31,11 @@ const int PSP_ERROR_UMD_INVALID_PARAM = 0x80010016; #define UMD_READABLE 0x20 -u8 umdActivated = 1; -u32 umdStatus = 0; -u32 umdErrorStat = 0; -static int driveCBId= -1; -int umdStatTimer = 0; +static u8 umdActivated = 1; +static u32 umdStatus = 0; +static u32 umdErrorStat = 0; +static int driveCBId = -1; +static int umdStatTimer = 0; #define PSP_UMD_TYPE_GAME 0x10 @@ -51,13 +51,24 @@ void __UmdStatTimeout(u64 userdata, int cyclesLate); void __UmdInit() { - umdStatTimer = CoreTiming::RegisterEvent("UmdTimeout", &__UmdStatTimeout); + umdStatTimer = CoreTiming::RegisterEvent("UmdTimeout", __UmdStatTimeout); umdActivated = 1; umdStatus = 0; umdErrorStat = 0; driveCBId = -1; } +void __UmdDoState(PointerWrap &p) +{ + p.Do(umdActivated); + p.Do(umdStatus); + p.Do(umdErrorStat); + p.Do(driveCBId); + p.Do(umdStatTimer); + CoreTiming::RestoreRegisterEvent(umdStatTimer, "UmdTimeout", __UmdStatTimeout); + p.DoMarker("sceUmd"); +} + u8 __KernelUmdGetState() { u8 state = UMD_PRESENT; diff --git a/Core/HLE/sceUmd.h b/Core/HLE/sceUmd.h index ceaa832a42..b0026e6eb0 100644 --- a/Core/HLE/sceUmd.h +++ b/Core/HLE/sceUmd.h @@ -27,5 +27,6 @@ enum pspUmdState { }; void __UmdInit(); +void __UmdDoState(PointerWrap &p); void Register_sceUmdUser(); diff --git a/Core/HLE/sceUsb.cpp b/Core/HLE/sceUsb.cpp index 1d1ebc2189..a76751cf2e 100644 --- a/Core/HLE/sceUsb.cpp +++ b/Core/HLE/sceUsb.cpp @@ -27,6 +27,12 @@ void __UsbInit() usbActivated = false; } +void __UsbDoState(PointerWrap &p) +{ + p.Do(usbActivated); + p.DoMarker("sceUsb"); +} + u32 sceUsbActivate() { ERROR_LOG(HLE, "UNIMPL sceUsbActivate"); usbActivated = true; diff --git a/Core/HLE/sceUsb.h b/Core/HLE/sceUsb.h index d521a0a9da..d1b280be76 100644 --- a/Core/HLE/sceUsb.h +++ b/Core/HLE/sceUsb.h @@ -20,3 +20,4 @@ void Register_sceUsb(); void __UsbInit(); +void __UsbDoState(PointerWrap &p); diff --git a/Core/Util/PPGeDraw.cpp b/Core/Util/PPGeDraw.cpp index f7655f0cbc..bd8032dd0b 100644 --- a/Core/Util/PPGeDraw.cpp +++ b/Core/Util/PPGeDraw.cpp @@ -39,21 +39,21 @@ struct PPGeVertex { s16 x, y; u16 z; }; -u32 savedContextPtr; -u32 savedContextSize = 512 * 4; +static u32 savedContextPtr; +static u32 savedContextSize = 512 * 4; // Display list writer -u32 dlPtr; -u32 dlWritePtr; -u32 dlSize = 0x10000; // should be enough for a frame of gui... +static u32 dlPtr; +static u32 dlWritePtr; +static u32 dlSize = 0x10000; // should be enough for a frame of gui... -u32 dataPtr; -u32 dataWritePtr; -u32 dataSize = 0x10000; // should be enough for a frame of gui... +static u32 dataPtr; +static u32 dataWritePtr; +static u32 dataSize = 0x10000; // should be enough for a frame of gui... // Vertex collector -u32 vertexStart; -u32 vertexCount; +static u32 vertexStart; +static u32 vertexCount; //only 0xFFFFFF of data is used static void WriteCmd(u8 cmd, u32 data) { @@ -141,6 +141,29 @@ void __PPGeInit() dlPtr, dataPtr, atlasPtr, atlasSize, savedContextPtr); } +void __PPGeDoState(PointerWrap &p) +{ + p.Do(atlasPtr); + p.Do(atlasWidth); + p.Do(atlasHeight); + + p.Do(savedContextPtr); + p.Do(savedContextSize); + + p.Do(dlPtr); + p.Do(dlWritePtr); + p.Do(dlSize); + + p.Do(dataPtr); + p.Do(dataWritePtr); + p.Do(dataSize); + + p.Do(vertexStart); + p.Do(vertexCount); + + p.DoMarker("PPGeDraw"); +} + void __PPGeShutdown() { if (atlasPtr) diff --git a/Core/Util/PPGeDraw.h b/Core/Util/PPGeDraw.h index e77a53cd89..48f23bca4b 100644 --- a/Core/Util/PPGeDraw.h +++ b/Core/Util/PPGeDraw.h @@ -18,6 +18,7 @@ #pragma once #include "../../Globals.h" +#include "../../Common/ChunkFile.h" #include "ppge_atlas.h" ///////////////////////////////////////////////////////////////////////////////////////////// @@ -29,6 +30,9 @@ // space for the display list. The PSP must be inited. void __PPGeInit(); +// Saves to and restores from savestates (kernel RAM pointers, etc.) +void __PPGeDoState(PointerWrap &p); + // Just frees up the allocated kernel memory. void __PPGeShutdown(); From 042e515037de4ce9e6620c88c2ef7e75b6ac5903 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Thu, 27 Dec 2012 23:08:38 -0800 Subject: [PATCH 20/29] Warniof the sceIo defAction is used when stating. This is broken anyway so skipping for now. --- Core/HLE/sceIo.cpp | 8 ++++++++ Core/HLE/sceIo.h | 1 + Core/HLE/sceKernel.cpp | 1 + 3 files changed, 10 insertions(+) diff --git a/Core/HLE/sceIo.cpp b/Core/HLE/sceIo.cpp index 70af694f7b..afe2c8615c 100644 --- a/Core/HLE/sceIo.cpp +++ b/Core/HLE/sceIo.cpp @@ -204,6 +204,14 @@ void __IoInit() { pspFileSystem.Mount("flash1:", flash); } +void __IoDoState(PointerWrap &p) { + // TODO: defAction is hard to save, and not the right way anyway. + // Should probbly be an enum and on the FileNode anyway. + if (defAction != NULL) { + WARN_LOG(HLE, "FIXME: Savestate failure: deferred IO not saved yet."); + } +} + void __IoShutdown() { defAction = 0; defParam = 0; diff --git a/Core/HLE/sceIo.h b/Core/HLE/sceIo.h index 8015bd93d9..0f87cde613 100644 --- a/Core/HLE/sceIo.h +++ b/Core/HLE/sceIo.h @@ -22,6 +22,7 @@ #include "sceKernel.h" void __IoInit(); +void __IoDoState(PointerWrap &p); void __IoShutdown(); KernelObject *__KernelFileNodeObject(); KernelObject *__KernelDirListingObject(); diff --git a/Core/HLE/sceKernel.cpp b/Core/HLE/sceKernel.cpp index ff3f9202f6..00904fd152 100644 --- a/Core/HLE/sceKernel.cpp +++ b/Core/HLE/sceKernel.cpp @@ -163,6 +163,7 @@ void __KernelDoState(PointerWrap &p) __SslDoState(p); __UmdDoState(p); __UsbDoState(p); + __IoDoState(p); __PPGeDoState(p); From 19aaca2705e62f3bb1dd554f62925d281637929f Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Fri, 28 Dec 2012 00:05:54 -0800 Subject: [PATCH 21/29] Start save stating audio, plus minor fixes. --- Common/FixedSizeQueue.h | 21 ++++++-- Core/CoreTiming.cpp | 2 + Core/HLE/__sceAudio.cpp | 27 ++++++++++ Core/HLE/__sceAudio.h | 1 + Core/HLE/sceAudio.h | 46 ++++++++++------ Core/HLE/sceCtrl.cpp | 2 + Core/HLE/sceKernel.cpp | 2 + Core/HLE/sceKernelMsgPipe.cpp | 5 +- Core/HLE/sceSas.cpp | 7 +++ Core/HLE/sceSas.h | 1 + Core/HW/SasAudio.cpp | 98 +++++++++++++++++++++++++++++++++-- Core/HW/SasAudio.h | 11 +++- 12 files changed, 196 insertions(+), 27 deletions(-) diff --git a/Common/FixedSizeQueue.h b/Common/FixedSizeQueue.h index 55bf3015ae..b7c9b4d458 100644 --- a/Common/FixedSizeQueue.h +++ b/Common/FixedSizeQueue.h @@ -95,9 +95,24 @@ public: return N - count_; } - bool empty() { - return count_; - } + bool empty() { + return count_ == 0; + } + + void DoState(PointerWrap &p) { + int size = N; + p.Do(size); + if (size != N) + { + ERROR_LOG(HLE, "Savestate failure: Incompatible queue size."); + return; + } + p.DoArray(storage_, N); + p.Do(head_); + p.Do(tail_); + p.Do(count_); + p.DoMarker("FixedSizeQueue"); + } private: T *storage_; diff --git a/Core/CoreTiming.cpp b/Core/CoreTiming.cpp index 504d28fb5b..01f6627a3b 100644 --- a/Core/CoreTiming.cpp +++ b/Core/CoreTiming.cpp @@ -550,6 +550,8 @@ void Event_DoState(PointerWrap &p, BaseEvent *ev) void DoState(PointerWrap &p) { + std::lock_guard lk(externalEventSection); + int n = (int) event_types.size(); p.Do(n); // These (should) be filled in later by the modules. diff --git a/Core/HLE/__sceAudio.cpp b/Core/HLE/__sceAudio.cpp index 7676ac0ea6..48261e457b 100644 --- a/Core/HLE/__sceAudio.cpp +++ b/Core/HLE/__sceAudio.cpp @@ -73,6 +73,33 @@ void __AudioInit() chans[i].clear(); } +void __AudioDoState(PointerWrap &p) +{ + section.lock(); + + p.Do(eventAudioUpdate); + CoreTiming::RestoreRegisterEvent(eventAudioUpdate, "AudioUpdate", &hleAudioUpdate); + p.Do(eventHostAudioUpdate); + CoreTiming::RestoreRegisterEvent(eventHostAudioUpdate, "AudioUpdateHost", &hleAudioUpdate); + + p.Do(mixFrequency); + outAudioQueue.DoState(p); + + int chanCount = ARRAY_SIZE(chans); + p.Do(chanCount); + if (chanCount != ARRAY_SIZE(chans)) + { + ERROR_LOG(HLE, "Savestate failure: different number of audio channels."); + section.unlock(); + return; + } + for (int i = 0; i < chanCount; ++i) + chans[i].DoState(p); + + section.unlock(); + p.DoMarker("sceAudio"); +} + void __AudioShutdown() { for (int i = 0; i < 8; i++) diff --git a/Core/HLE/__sceAudio.h b/Core/HLE/__sceAudio.h index 196c16a7b8..21a83ef953 100644 --- a/Core/HLE/__sceAudio.h +++ b/Core/HLE/__sceAudio.h @@ -22,6 +22,7 @@ // Easy interface for sceAudio to write to, to keep the complexity in check. void __AudioInit(); +void __AudioDoState(PointerWrap &p); void __AudioUpdate(); void __AudioShutdown(); void __AudioSetOutputFrequency(int freq); diff --git a/Core/HLE/sceAudio.h b/Core/HLE/sceAudio.h index ba37523c36..013b818bde 100644 --- a/Core/HLE/sceAudio.h +++ b/Core/HLE/sceAudio.h @@ -40,41 +40,53 @@ enum PspAudioFrequencies { PSP_AUDIO_FREQ_44K = 44100, PSP_AUDIO_FREQ_48K = 48 struct AudioChannel { - AudioChannel() { + AudioChannel() { clear(); } - // PSP side + // PSP side - bool reserved; + bool reserved; - // last sample address - u32 sampleAddress; - u32 sampleCount; // Number of samples written in each OutputBlocking + // last sample address + u32 sampleAddress; + u32 sampleCount; // Number of samples written in each OutputBlocking - int leftVolume; - int rightVolume; + int leftVolume; + int rightVolume; - int format; + int format; SceUID waitingThread; - // PC side - should probably split out + // PC side - should probably split out - // We copy samples as they are written into this simple ring buffer. - // Might try something more efficient later. - FixedSizeQueue sampleQueue; + // We copy samples as they are written into this simple ring buffer. + // Might try something more efficient later. + FixedSizeQueue sampleQueue; - void clear() { - reserved = false; + void DoState(PointerWrap &p) { + p.Do(reserved); + p.Do(sampleAddress); + p.Do(sampleCount); + p.Do(leftVolume); + p.Do(rightVolume); + p.Do(format); + p.Do(waitingThread); + sampleQueue.DoState(p); + p.DoMarker("AudioChannel"); + } + + void clear() { + reserved = false; waitingThread = 0; leftVolume = 0; rightVolume = 0; format = 0; sampleAddress = 0; sampleCount = 0; - sampleQueue.clear(); - } + sampleQueue.clear(); + } }; extern AudioChannel chans[8]; diff --git a/Core/HLE/sceCtrl.cpp b/Core/HLE/sceCtrl.cpp index fbaac32477..4fbc8bb455 100644 --- a/Core/HLE/sceCtrl.cpp +++ b/Core/HLE/sceCtrl.cpp @@ -286,6 +286,8 @@ void __CtrlInit() void __CtrlDoState(PointerWrap &p) { + std::lock_guard guard(ctrlMutex); + p.Do(analogEnabled); p.Do(ctrlLatchBufs); p.Do(ctrlOldButtons); diff --git a/Core/HLE/sceKernel.cpp b/Core/HLE/sceKernel.cpp index 00904fd152..0c450708cb 100644 --- a/Core/HLE/sceKernel.cpp +++ b/Core/HLE/sceKernel.cpp @@ -156,10 +156,12 @@ void __KernelDoState(PointerWrap &p) __KernelSemaDoState(p); // TODO: non-kernel modules + __AudioDoState(p); __CtrlDoState(p); __FontDoState(p); __ImposeDoState(p); __PowerDoState(p); + __SasDoState(p); __SslDoState(p); __UmdDoState(p); __UsbDoState(p); diff --git a/Core/HLE/sceKernelMsgPipe.cpp b/Core/HLE/sceKernelMsgPipe.cpp index 8d60cccf48..80c99cd623 100644 --- a/Core/HLE/sceKernelMsgPipe.cpp +++ b/Core/HLE/sceKernelMsgPipe.cpp @@ -150,7 +150,10 @@ struct MsgPipe : public KernelObject p.Do(nmp); p.Do(sendWaitingThreads); p.Do(receiveWaitingThreads); - p.DoArray(buffer, nmp.bufSize); + bool hasBuffer = buffer != NULL; + p.Do(hasBuffer); + if (hasBuffer) + p.DoArray(buffer, nmp.bufSize); p.DoMarker("MsgPipe"); } diff --git a/Core/HLE/sceSas.cpp b/Core/HLE/sceSas.cpp index 7693592688..45693a80e5 100644 --- a/Core/HLE/sceSas.cpp +++ b/Core/HLE/sceSas.cpp @@ -50,6 +50,13 @@ void __SasInit() { sas = new SasInstance(); } +void __SasDoState(PointerWrap &p) { + if (sas != NULL) { + sas->DoState(p); + } + p.DoMarker("sceSas"); +} + void __SasShutdown() { delete sas; sas = 0; diff --git a/Core/HLE/sceSas.h b/Core/HLE/sceSas.h index 58efddd75b..bf798dee45 100644 --- a/Core/HLE/sceSas.h +++ b/Core/HLE/sceSas.h @@ -18,6 +18,7 @@ #pragma once void __SasInit(); +void __SasDoState(PointerWrap &p); void __SasShutdown(); void Register_sceSasCore(); diff --git a/Core/HW/SasAudio.cpp b/Core/HW/SasAudio.cpp index ed17365368..1da73af6be 100644 --- a/Core/HW/SasAudio.cpp +++ b/Core/HW/SasAudio.cpp @@ -27,14 +27,14 @@ static const double f[5][2] = { 98.0 / 64.0, -55.0 / 64.0 }, { 122.0 / 64.0, -60.0 / 64.0 } }; -void VagDecoder::Start(u8 *data, int vagSize, bool loopEnabled) { +void VagDecoder::Start(u32 dataPtr, int vagSize, bool loopEnabled) { loopEnabled_ = loopEnabled; loopAtNextBlock_ = false; loopStartBlock_ = 0; numBlocks_ = vagSize / 16; end_ = false; - data_ = data; - read_ = data; + data_ = Memory::GetPointer(dataPtr); + read_ = Memory::GetPointer(dataPtr); curSample = 28; curBlock_ = -1; s_1 = 0.0; // per block? @@ -99,6 +99,28 @@ void VagDecoder::GetSamples(s16 *outSamples, int numSamples) { } } +void VagDecoder::DoState(PointerWrap &p) { + p.DoArray(samples, ARRAY_SIZE(samples)); + p.Do(curSample); + p.Do(dataPtr_); + int diff = read_ - data_; + p.Do(diff); + if (p.mode == p.MODE_READ) { + data_ = Memory::GetPointer(dataPtr_); + read_ = data_ + diff; + } + p.Do(curBlock_); + p.Do(loopStartBlock_); + p.Do(numBlocks_); + + p.Do(s_1); + p.Do(s_2); + p.Do(loopEnabled_); + p.Do(loopAtNextBlock_); + p.Do(end_); + p.DoMarker("VagDecoder"); +} + // http://code.google.com/p/jpcsp/source/browse/trunk/src/jpcsp/HLE/modules150/sceSasCore.java int simpleRate(int n) { @@ -190,6 +212,7 @@ SasInstance::~SasInstance() { void SasInstance::SetGrainSize(int newGrainSize) { grainSize = newGrainSize; + // If you change the sizes here, don't forget DoState(). if (mixBuffer) delete [] mixBuffer; if (sendBuffer) @@ -303,6 +326,40 @@ void SasInstance::Mix(u32 outAddr) { } } +void SasInstance::DoState(PointerWrap &p) { + p.Do(grainSize); + if (p.mode == p.MODE_READ) { + SetGrainSize(grainSize); + } + + p.Do(maxVoices); + p.Do(sampleRate); + p.Do(outputMode); + + if (mixBuffer != NULL) { + p.DoArray(mixBuffer, grainSize * 2); + } + if (sendBuffer != NULL) { + p.DoArray(sendBuffer, grainSize * 2); + } + if (resampleBuffer != NULL) { + p.DoArray(resampleBuffer, grainSize * 4 + 2); + } + + int n = PSP_SAS_VOICES_MAX; + p.Do(n); + if (n != PSP_SAS_VOICES_MAX) + { + ERROR_LOG(HLE, "Savestate failure: wrong number of SAS voices"); + return; + } + for (int i = 0; i < n; ++i) + voices[i].DoState(p); + p.Do(waveformEffect); + + p.DoMarker("SasInstance"); +} + void SasVoice::Reset() { resampleHist[0] = 0; resampleHist[1] = 0; @@ -313,7 +370,7 @@ void SasVoice::KeyOn() { switch (type) { case VOICETYPE_VAG: if (Memory::IsValidAddress(vagAddr)) { - vag.Start(Memory::GetPointer(vagAddr), vagSize, loop); + vag.Start(vagAddr, vagSize, loop); } else { ERROR_LOG(SAS, "Invalid VAG address %08x", vagAddr); return; @@ -336,11 +393,42 @@ void SasVoice::ChangedParams(bool changedVag) { if (!playing && on) { playing = true; if (changedVag) - vag.Start(Memory::GetPointer(vagAddr), vagSize, loop); + vag.Start(vagAddr, vagSize, loop); } // TODO: restart VAG somehow } +void SasVoice::DoState(PointerWrap &p) { + p.Do(playing); + p.Do(paused); + p.Do(on); + p.Do(type); + + p.Do(vagAddr); + p.Do(vagSize); + p.Do(pcmAddr); + p.Do(pcmSize); + p.Do(sampleRate); + + p.Do(sampleFrac); + p.Do(pitch); + p.Do(loop); + + p.Do(noiseFreq); + + p.Do(volumeLeft); + p.Do(volumeRight); + p.Do(volumeLeftSend); + p.Do(volumeRightSend); + p.DoArray(resampleHist, ARRAY_SIZE(resampleHist)); + + p.Do(envelope); + + vag.DoState(p); + + p.DoMarker("SasVoice"); +} + // This is horribly stolen from JPCSP. // Need to find a real solution. static const short expCurve[] = { diff --git a/Core/HW/SasAudio.h b/Core/HW/SasAudio.h index b32ba7d347..71103c6386 100644 --- a/Core/HW/SasAudio.h +++ b/Core/HW/SasAudio.h @@ -23,6 +23,7 @@ #pragma once #include "../Globals.h" +#include "../../Common/ChunkFile.h" enum { PSP_SAS_VOICES_MAX = 32, @@ -77,7 +78,7 @@ enum VoiceType { class VagDecoder { public: VagDecoder() : data_(0), read_(0) {} - void Start(u8 *data, int vagSize, bool loopEnabled); + void Start(u32 dataPtr, int vagSize, bool loopEnabled); void GetSamples(s16 *outSamples, int numSamples); @@ -88,10 +89,14 @@ public: return *read_++; } + void DoState(PointerWrap &p); + private: double samples[28]; int curSample; + // Original pointer, for save states. + u32 dataPtr_; u8 *data_; u8 *read_; int curBlock_; @@ -180,6 +185,8 @@ struct SasVoice void KeyOff(); void ChangedParams(bool changedVag); + void DoState(PointerWrap &p); + bool playing; bool paused; // a voice can be playing AND paused. In that case, it won't play. bool on; // key-on, key-off. @@ -228,6 +235,8 @@ public: void Mix(u32 outAddr); + void DoState(PointerWrap &p); + SasVoice voices[PSP_SAS_VOICES_MAX]; WaveformEffect waveformEffect; From 7a2adfd8a578266971edc8316461e1b7cf389be8 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Fri, 28 Dec 2012 02:09:44 -0800 Subject: [PATCH 22/29] Don't store pointers in VagDecoder directly. I'm assuming it's fine to not fix read_ when end_ happens. Shouldn't be any performance penality, really. --- Core/HW/SasAudio.cpp | 76 +++++++++----------------------------------- Core/HW/SasAudio.h | 16 ++-------- 2 files changed, 18 insertions(+), 74 deletions(-) diff --git a/Core/HW/SasAudio.cpp b/Core/HW/SasAudio.cpp index 1da73af6be..3977537af5 100644 --- a/Core/HW/SasAudio.cpp +++ b/Core/HW/SasAudio.cpp @@ -27,25 +27,25 @@ static const double f[5][2] = { 98.0 / 64.0, -55.0 / 64.0 }, { 122.0 / 64.0, -60.0 / 64.0 } }; -void VagDecoder::Start(u32 dataPtr, int vagSize, bool loopEnabled) { +void VagDecoder::Start(u32 data, int vagSize, bool loopEnabled) { loopEnabled_ = loopEnabled; loopAtNextBlock_ = false; loopStartBlock_ = 0; numBlocks_ = vagSize / 16; end_ = false; - data_ = Memory::GetPointer(dataPtr); - read_ = Memory::GetPointer(dataPtr); + data_ = data; + read_ = data; curSample = 28; curBlock_ = -1; s_1 = 0.0; // per block? s_2 = 0.0; } -void VagDecoder::DecodeBlock() { - int predict_nr = GetByte(); +void VagDecoder::DecodeBlock(u8 *&readp) { + int predict_nr = *readp++; int shift_factor = predict_nr & 0xf; predict_nr >>= 4; - int flags = GetByte(); + int flags = *readp++; if (flags == 7) { end_ = true; return; @@ -57,7 +57,7 @@ void VagDecoder::DecodeBlock() { loopAtNextBlock_ = true; } for (int i = 0; i < 28; i += 2) { - int d = GetByte(); + int d = *readp++; int s = (short)((d & 0xf) << 12); samples[i] = (double)(s >> shift_factor); s = (short)((d & 0xf0) << 8); @@ -80,15 +80,19 @@ void VagDecoder::GetSamples(s16 *outSamples, int numSamples) { memset(outSamples, 0, numSamples * sizeof(s16)); return; } + u8 *readp = Memory::GetPointer(read_); + u8 *origp = readp; for (int i = 0; i < numSamples; i++) { if (curSample == 28) { if (loopAtNextBlock_) { read_ = data_ + 16 * loopStartBlock_; + readp = Memory::GetPointer(read_); + origp = readp; curBlock_ = loopStartBlock_; s_1 = 0.0; s_2 = 0.0; } - DecodeBlock(); + DecodeBlock(readp); if (end_) { // Clear the rest of the buffer and return. memset(&outSamples[i], 0, (numSamples - i) * sizeof(s16)); @@ -97,28 +101,10 @@ void VagDecoder::GetSamples(s16 *outSamples, int numSamples) { } outSamples[i] = end_ ? 0 : samples[curSample++]; } -} -void VagDecoder::DoState(PointerWrap &p) { - p.DoArray(samples, ARRAY_SIZE(samples)); - p.Do(curSample); - p.Do(dataPtr_); - int diff = read_ - data_; - p.Do(diff); - if (p.mode == p.MODE_READ) { - data_ = Memory::GetPointer(dataPtr_); - read_ = data_ + diff; + if (readp > origp) { + read_ += readp - origp; } - p.Do(curBlock_); - p.Do(loopStartBlock_); - p.Do(numBlocks_); - - p.Do(s_1); - p.Do(s_2); - p.Do(loopEnabled_); - p.Do(loopAtNextBlock_); - p.Do(end_); - p.DoMarker("VagDecoder"); } // http://code.google.com/p/jpcsp/source/browse/trunk/src/jpcsp/HLE/modules150/sceSasCore.java @@ -353,8 +339,7 @@ void SasInstance::DoState(PointerWrap &p) { ERROR_LOG(HLE, "Savestate failure: wrong number of SAS voices"); return; } - for (int i = 0; i < n; ++i) - voices[i].DoState(p); + p.DoArray(voices, ARRAY_SIZE(voices)); p.Do(waveformEffect); p.DoMarker("SasInstance"); @@ -398,37 +383,6 @@ void SasVoice::ChangedParams(bool changedVag) { // TODO: restart VAG somehow } -void SasVoice::DoState(PointerWrap &p) { - p.Do(playing); - p.Do(paused); - p.Do(on); - p.Do(type); - - p.Do(vagAddr); - p.Do(vagSize); - p.Do(pcmAddr); - p.Do(pcmSize); - p.Do(sampleRate); - - p.Do(sampleFrac); - p.Do(pitch); - p.Do(loop); - - p.Do(noiseFreq); - - p.Do(volumeLeft); - p.Do(volumeRight); - p.Do(volumeLeftSend); - p.Do(volumeRightSend); - p.DoArray(resampleHist, ARRAY_SIZE(resampleHist)); - - p.Do(envelope); - - vag.DoState(p); - - p.DoMarker("SasVoice"); -} - // This is horribly stolen from JPCSP. // Need to find a real solution. static const short expCurve[] = { diff --git a/Core/HW/SasAudio.h b/Core/HW/SasAudio.h index 71103c6386..c2da15a969 100644 --- a/Core/HW/SasAudio.h +++ b/Core/HW/SasAudio.h @@ -82,23 +82,15 @@ public: void GetSamples(s16 *outSamples, int numSamples); - void DecodeBlock(); + void DecodeBlock(u8 *&readp); bool End() const { return end_; } - u8 GetByte() { - return *read_++; - } - - void DoState(PointerWrap &p); - private: double samples[28]; int curSample; - // Original pointer, for save states. - u32 dataPtr_; - u8 *data_; - u8 *read_; + u32 data_; + u32 read_; int curBlock_; int loopStartBlock_; int numBlocks_; @@ -185,8 +177,6 @@ struct SasVoice void KeyOff(); void ChangedParams(bool changedVag); - void DoState(PointerWrap &p); - bool playing; bool paused; // a voice can be playing AND paused. In that case, it won't play. bool on; // key-on, key-off. From 5999fac10dc983128b81c03f6fe63e359fcf6f71 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Fri, 28 Dec 2012 02:22:39 -0800 Subject: [PATCH 23/29] Start saving the state of the GPU. Not 100% sure this is all that's needed, but let's try it. --- Common/ChunkFile.h | 9 ++++++++- Core/HLE/sceDisplay.cpp | 39 ++++++++++++++++++++++++++++++--------- Core/HLE/sceDisplay.h | 2 ++ Core/HLE/sceGe.cpp | 11 +++++++++++ Core/HLE/sceGe.h | 1 + Core/HLE/sceKernel.cpp | 2 ++ 6 files changed, 54 insertions(+), 10 deletions(-) diff --git a/Common/ChunkFile.h b/Common/ChunkFile.h index f6e3f0a0ce..1671cecc8a 100644 --- a/Common/ChunkFile.h +++ b/Common/ChunkFile.h @@ -154,10 +154,17 @@ public: // Store vectors. template void Do(std::vector &x) + { + T dv; + Do(x, dv); + } + + template + void Do(std::vector &x, T &default_val) { u32 vec_size = (u32)x.size(); Do(vec_size); - x.resize(vec_size); + x.resize(vec_size, default_val); if (vec_size > 0) DoArray(&x[0], vec_size); } diff --git a/Core/HLE/sceDisplay.cpp b/Core/HLE/sceDisplay.cpp index ac780633a2..2eaa41f069 100644 --- a/Core/HLE/sceDisplay.cpp +++ b/Core/HLE/sceDisplay.cpp @@ -52,6 +52,13 @@ struct FrameBufferState { int pspFramebufLinesize; }; +struct WaitVBlankInfo +{ + WaitVBlankInfo(u32 tid) : threadID(tid), vcountUnblock(0) {} + u32 threadID; + int vcountUnblock; // what was this for again? +}; + // STATE BEGIN static FrameBufferState framebuf; static FrameBufferState latchedFramebuf; @@ -67,8 +74,11 @@ static int isVblank; static bool hasSetMode; double lastFrameTime; +std::vector vblankWaitingThreads; + // STATE END +// Called when vblank happens (like an internal interrupt.) Not part of state, should be static. std::vector vblankListeners; // The vblank period is 731.5 us (0.7315 ms) @@ -80,15 +90,6 @@ enum { PSP_DISPLAY_SETBUF_NEXTFRAME = 1 }; -struct WaitVBlankInfo -{ - WaitVBlankInfo(u32 tid) : threadID(tid), vcountUnblock(0) {} - u32 threadID; - int vcountUnblock; // what was this for again? -}; - -std::vector vblankWaitingThreads; - void hleEnterVblank(u64 userdata, int cyclesLate); void hleLeaveVblank(u64 userdata, int cyclesLate); @@ -114,6 +115,26 @@ void __DisplayInit() { InitGfxState(); } +void __DisplayDoState(PointerWrap &p) { + p.Do(framebuf); + p.Do(latchedFramebuf); + p.Do(framebufIsLatched); + p.Do(hCount); + p.Do(hCountTotal); + p.Do(vCount); + p.Do(isVblank); + p.Do(hasSetMode); + p.Do(lastFrameTime); + p.Do(vblankWaitingThreads, WaitVBlankInfo(0)); + + p.Do(enterVblankEvent); + CoreTiming::RestoreRegisterEvent(enterVblankEvent, "EnterVBlank", &hleEnterVblank); + p.Do(leaveVblankEvent); + CoreTiming::RestoreRegisterEvent(leaveVblankEvent, "LeaveVBlank", &hleLeaveVblank); + + p.DoMarker("sceDisplay"); +} + void __DisplayShutdown() { vblankListeners.clear(); vblankWaitingThreads.clear(); diff --git a/Core/HLE/sceDisplay.h b/Core/HLE/sceDisplay.h index c7b1afc8ff..c75faf93f7 100644 --- a/Core/HLE/sceDisplay.h +++ b/Core/HLE/sceDisplay.h @@ -18,6 +18,7 @@ #pragma once void __DisplayInit(); +void __DisplayDoState(PointerWrap &p); void __DisplayShutdown(); void Register_sceDisplay(); @@ -26,4 +27,5 @@ void Register_sceDisplay(); bool __DisplayFrameDone(); typedef void (*VblankCallback)(); +// Listen for vblank events. Only register during init. void __DisplayListenVblank(VblankCallback callback); diff --git a/Core/HLE/sceGe.cpp b/Core/HLE/sceGe.cpp index 8cbff40b80..023ac3aaa0 100644 --- a/Core/HLE/sceGe.cpp +++ b/Core/HLE/sceGe.cpp @@ -33,6 +33,17 @@ void __GeInit() state = 0; } +void __GeDoState(PointerWrap &p) +{ + p.Do(state); + p.Do(gstate); + p.Do(gstate_c); + + ReapplyGfxState(); + gpu->InvalidateCache(0, -1); + p.DoMarker("sceGe"); +} + void __GeShutdown() { diff --git a/Core/HLE/sceGe.h b/Core/HLE/sceGe.h index 7b92c863b8..d6a19a0767 100644 --- a/Core/HLE/sceGe.h +++ b/Core/HLE/sceGe.h @@ -37,6 +37,7 @@ typedef struct PspGeCallbackData void Register_sceGe_user(); void __GeInit(); +void __GeDoState(PointerWrap &p); void __GeShutdown(); diff --git a/Core/HLE/sceKernel.cpp b/Core/HLE/sceKernel.cpp index 0c450708cb..b9edf154cc 100644 --- a/Core/HLE/sceKernel.cpp +++ b/Core/HLE/sceKernel.cpp @@ -158,7 +158,9 @@ void __KernelDoState(PointerWrap &p) // TODO: non-kernel modules __AudioDoState(p); __CtrlDoState(p); + __DisplayDoState(p); __FontDoState(p); + __GeDoState(p); __ImposeDoState(p); __PowerDoState(p); __SasDoState(p); From e665618891a1212847d06cddaf906818e2d32d9a Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Fri, 28 Dec 2012 03:54:16 -0800 Subject: [PATCH 24/29] Fix kernel object loading (ouch) from save states. Also a fix to SAS voices not saving right. --- Core/HLE/sceKernel.cpp | 1 + Core/HW/SasAudio.cpp | 28 +++++++++++++++++++++------- Core/HW/SasAudio.h | 1 + 3 files changed, 23 insertions(+), 7 deletions(-) diff --git a/Core/HLE/sceKernel.cpp b/Core/HLE/sceKernel.cpp index b9edf154cc..64909528d0 100644 --- a/Core/HLE/sceKernel.cpp +++ b/Core/HLE/sceKernel.cpp @@ -363,6 +363,7 @@ void KernelObjectPool::DoState(PointerWrap &p) { p.Do(type); pool[i] = CreateByIDType(type); + pool[i]->uid = i + handleOffset; // Already logged an error. if (pool[i] == NULL) diff --git a/Core/HW/SasAudio.cpp b/Core/HW/SasAudio.cpp index 3977537af5..6eb53d3f0d 100644 --- a/Core/HW/SasAudio.cpp +++ b/Core/HW/SasAudio.cpp @@ -190,9 +190,19 @@ SasInstance::SasInstance() } SasInstance::~SasInstance() { - delete [] mixBuffer; - delete [] sendBuffer; - delete [] resampleBuffer; + ClearGrainSize(); +} + +void SasInstance::ClearGrainSize() { + if (mixBuffer) + delete [] mixBuffer; + if (sendBuffer) + delete [] sendBuffer; + if (resampleBuffer) + delete [] resampleBuffer; + mixBuffer = NULL; + sendBuffer = NULL; + resampleBuffer = NULL; } void SasInstance::SetGrainSize(int newGrainSize) { @@ -315,20 +325,24 @@ void SasInstance::Mix(u32 outAddr) { void SasInstance::DoState(PointerWrap &p) { p.Do(grainSize); if (p.mode == p.MODE_READ) { - SetGrainSize(grainSize); + if (grainSize > 0) { + SetGrainSize(grainSize); + } else { + ClearGrainSize(); + } } p.Do(maxVoices); p.Do(sampleRate); p.Do(outputMode); - if (mixBuffer != NULL) { + if (mixBuffer != NULL && grainSize > 0) { p.DoArray(mixBuffer, grainSize * 2); } - if (sendBuffer != NULL) { + if (sendBuffer != NULL && grainSize > 0) { p.DoArray(sendBuffer, grainSize * 2); } - if (resampleBuffer != NULL) { + if (resampleBuffer != NULL && grainSize > 0) { p.DoArray(resampleBuffer, grainSize * 4 + 2); } diff --git a/Core/HW/SasAudio.h b/Core/HW/SasAudio.h index c2da15a969..1c204782fa 100644 --- a/Core/HW/SasAudio.h +++ b/Core/HW/SasAudio.h @@ -212,6 +212,7 @@ public: SasInstance(); ~SasInstance(); + void ClearGrainSize(); void SetGrainSize(int newGrainSize); int GetGrainSize() const { return grainSize; } From 644e6b615cc1dcbc79c08ab84aae55b0cfbcca4a Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Fri, 28 Dec 2012 12:38:00 -0800 Subject: [PATCH 25/29] Fix memory leak in msgpipe when loading state. --- Core/HLE/sceKernelMsgPipe.cpp | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/Core/HLE/sceKernelMsgPipe.cpp b/Core/HLE/sceKernelMsgPipe.cpp index 80c99cd623..6e727c7da0 100644 --- a/Core/HLE/sceKernelMsgPipe.cpp +++ b/Core/HLE/sceKernelMsgPipe.cpp @@ -56,6 +56,13 @@ struct MsgPipe : public KernelObject static u32 GetMissingErrorCode() { return SCE_KERNEL_ERROR_UNKNOWN_MPPID; } int GetIDType() const { return SCE_KERNEL_TMID_Mpipe; } + MsgPipe() : buffer(NULL) {} + ~MsgPipe() + { + if (buffer != NULL) + delete [] buffer; + } + void AddWaitingThread(std::vector &list, SceUID id, u32 addr, u32 size, int waitMode, u32 transferredBytesAddr, bool usePrio) { MsgPipeWaitingThread thread = { id, addr, size, size, waitMode, transferredBytesAddr }; @@ -211,10 +218,6 @@ void sceKernelDeleteMsgPipe() RETURN(error); return; } - if (m->buffer != 0) - { - delete [] m->buffer; - } for (u32 i = 0; i < m->sendWaitingThreads.size(); i++) { __KernelResumeThreadFromWait(m->sendWaitingThreads[i].id); From bcecd881b189a86ad8886eeaa4259aac29d4e501 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Fri, 28 Dec 2012 13:01:46 -0800 Subject: [PATCH 26/29] Savestate cleanup + be more careful with vectors. For some reason I debugged it going into std::string so I just made them all more explicit which fixed everything. --- Core/HLE/HLE.cpp | 2 +- Core/HLE/sceCtrl.cpp | 3 ++- Core/HLE/sceKernelEventFlag.cpp | 2 +- Core/HLE/sceKernelMbx.cpp | 2 +- Core/HLE/sceKernelModule.cpp | 1 + Core/HLE/sceKernelMsgPipe.cpp | 8 ++++++-- Core/HLE/sceKernelMutex.cpp | 6 ++++-- Core/HLE/sceKernelSemaphore.cpp | 3 ++- Core/HLE/sceKernelThread.cpp | 4 ++-- Core/HW/SasAudio.cpp | 1 + Core/Util/BlockAllocator.cpp | 3 +-- 11 files changed, 22 insertions(+), 13 deletions(-) diff --git a/Core/HLE/HLE.cpp b/Core/HLE/HLE.cpp index 7d5c426c49..ef81fa2a23 100644 --- a/Core/HLE/HLE.cpp +++ b/Core/HLE/HLE.cpp @@ -60,7 +60,7 @@ void HLEInit() void HLEDoState(PointerWrap &p) { - p.Do(unresolvedSyscalls); + p.Do(unresolvedSyscalls, Syscall()); p.DoMarker("HLE"); } diff --git a/Core/HLE/sceCtrl.cpp b/Core/HLE/sceCtrl.cpp index 4fbc8bb455..234bb3dc5f 100644 --- a/Core/HLE/sceCtrl.cpp +++ b/Core/HLE/sceCtrl.cpp @@ -303,7 +303,8 @@ void __CtrlDoState(PointerWrap &p) p.Do(ctrlCycle); - p.Do(waitingThreads); + SceUID dv = 0; + p.Do(waitingThreads, dv); p.Do(ctrlTimer); CoreTiming::RestoreRegisterEvent(ctrlTimer, "CtrlSampleTimer", __CtrlTimerUpdate); diff --git a/Core/HLE/sceKernelEventFlag.cpp b/Core/HLE/sceKernelEventFlag.cpp index 80471c4c4d..d57d63c9bd 100644 --- a/Core/HLE/sceKernelEventFlag.cpp +++ b/Core/HLE/sceKernelEventFlag.cpp @@ -66,7 +66,7 @@ public: virtual void DoState(PointerWrap &p) { p.Do(nef); - p.Do(waitingThreads); + p.Do(waitingThreads, EventFlagTh()); p.DoMarker("EventFlag"); } diff --git a/Core/HLE/sceKernelMbx.cpp b/Core/HLE/sceKernelMbx.cpp index 34aea59532..205a97460d 100644 --- a/Core/HLE/sceKernelMbx.cpp +++ b/Core/HLE/sceKernelMbx.cpp @@ -156,7 +156,7 @@ struct Mbx : public KernelObject virtual void DoState(PointerWrap &p) { p.Do(nmb); - p.Do(waitingThreads); + p.Do(waitingThreads, MbxWaitingThread()); p.DoMarker("Mbx"); } diff --git a/Core/HLE/sceKernelModule.cpp b/Core/HLE/sceKernelModule.cpp index 701b51297c..8f35526859 100644 --- a/Core/HLE/sceKernelModule.cpp +++ b/Core/HLE/sceKernelModule.cpp @@ -145,6 +145,7 @@ public: virtual void DoState(PointerWrap &p) { p.Do(moduleID_); p.Do(retValAddr); + p.DoMarker("AfterModuleEntryCall"); } static Action *Create() { return new AfterModuleEntryCall; diff --git a/Core/HLE/sceKernelMsgPipe.cpp b/Core/HLE/sceKernelMsgPipe.cpp index 6e727c7da0..92ef03c74a 100644 --- a/Core/HLE/sceKernelMsgPipe.cpp +++ b/Core/HLE/sceKernelMsgPipe.cpp @@ -155,12 +155,16 @@ struct MsgPipe : public KernelObject virtual void DoState(PointerWrap &p) { p.Do(nmp); - p.Do(sendWaitingThreads); - p.Do(receiveWaitingThreads); + p.Do(sendWaitingThreads, MsgPipeWaitingThread()); + p.Do(receiveWaitingThreads, MsgPipeWaitingThread()); bool hasBuffer = buffer != NULL; p.Do(hasBuffer); if (hasBuffer) + { + if (buffer == NULL) + buffer = new u8[nmp.bufSize]; p.DoArray(buffer, nmp.bufSize); + } p.DoMarker("MsgPipe"); } diff --git a/Core/HLE/sceKernelMutex.cpp b/Core/HLE/sceKernelMutex.cpp index a6243fff08..a591e4ce6d 100644 --- a/Core/HLE/sceKernelMutex.cpp +++ b/Core/HLE/sceKernelMutex.cpp @@ -66,7 +66,8 @@ struct Mutex : public KernelObject virtual void DoState(PointerWrap &p) { p.Do(nm); - p.Do(waitingThreads); + SceUID dv = 0; + p.Do(waitingThreads, dv); p.DoMarker("Mutex"); } @@ -115,7 +116,8 @@ struct LwMutex : public KernelObject virtual void DoState(PointerWrap &p) { p.Do(nm); - p.Do(waitingThreads); + SceUID dv = 0; + p.Do(waitingThreads, dv); p.DoMarker("LwMutex"); } diff --git a/Core/HLE/sceKernelSemaphore.cpp b/Core/HLE/sceKernelSemaphore.cpp index 6e213ff31d..f9e5cd4e0b 100644 --- a/Core/HLE/sceKernelSemaphore.cpp +++ b/Core/HLE/sceKernelSemaphore.cpp @@ -60,7 +60,8 @@ struct Semaphore : public KernelObject virtual void DoState(PointerWrap &p) { p.Do(ns); - p.Do(waitingThreads); + SceUID dv = 0; + p.Do(waitingThreads, dv); p.DoMarker("Semaphore"); } diff --git a/Core/HLE/sceKernelThread.cpp b/Core/HLE/sceKernelThread.cpp index 7732c558ce..e791219d2b 100644 --- a/Core/HLE/sceKernelThread.cpp +++ b/Core/HLE/sceKernelThread.cpp @@ -431,7 +431,6 @@ public: for (size_t i = 0; i < THREAD_CALLBACK_NUM_TYPES; ++i) { - std::set::iterator it, end; p.Do(registeredCallbacks[i]); p.Do(readyCallbacks[i]); } @@ -615,7 +614,8 @@ void __KernelThreadingDoState(PointerWrap &p) p.Do(intReturnHackAddr); p.Do(currentThread); - p.Do(threadqueue); + SceUID dv = 0; + p.Do(threadqueue, dv); p.DoArray(threadIdleID, ARRAY_SIZE(threadIdleID)); p.Do(dispatchEnabled); p.Do(curModule); diff --git a/Core/HW/SasAudio.cpp b/Core/HW/SasAudio.cpp index 6eb53d3f0d..3845922fbe 100644 --- a/Core/HW/SasAudio.cpp +++ b/Core/HW/SasAudio.cpp @@ -336,6 +336,7 @@ void SasInstance::DoState(PointerWrap &p) { p.Do(sampleRate); p.Do(outputMode); + // SetGrainSize() / ClearGrainSize() should've made our buffers match. if (mixBuffer != NULL && grainSize > 0) { p.DoArray(mixBuffer, grainSize * 2); } diff --git a/Core/Util/BlockAllocator.cpp b/Core/Util/BlockAllocator.cpp index 66cc8484e7..d778012ab9 100644 --- a/Core/Util/BlockAllocator.cpp +++ b/Core/Util/BlockAllocator.cpp @@ -300,8 +300,7 @@ u32 BlockAllocator::GetTotalFreeBytes() void BlockAllocator::DoState(PointerWrap &p) { - Block default_value(0, 0, false); - p.Do(blocks, default_value); + p.Do(blocks, Block(0, 0, false)); p.Do(rangeStart_); p.Do(rangeSize_); p.Do(grain_); From fd2f609367c44e4fab47cf8bfba0b1621f6442d8 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Fri, 28 Dec 2012 13:36:37 -0800 Subject: [PATCH 27/29] Save the savedata and other dialog state. Although, hopefully it wouldn't be running anyway. --- Core/Dialog/PSPDialog.cpp | 8 ++++++++ Core/Dialog/PSPDialog.h | 2 ++ Core/Dialog/PSPMsgDialog.cpp | 12 ++++++++++++ Core/Dialog/PSPMsgDialog.h | 3 ++- Core/Dialog/PSPOskDialog.cpp | 13 +++++++++++++ Core/Dialog/PSPOskDialog.h | 1 + Core/Dialog/PSPSaveDialog.cpp | 16 ++++++++++++++++ Core/Dialog/PSPSaveDialog.h | 3 ++- Core/Dialog/SavedataParam.cpp | 23 +++++++++++++++++------ Core/Dialog/SavedataParam.h | 4 +++- Core/HLE/sceKernel.cpp | 4 ++-- Core/HLE/sceUtility.cpp | 9 +++++++++ Core/HLE/sceUtility.h | 1 + 13 files changed, 88 insertions(+), 11 deletions(-) diff --git a/Core/Dialog/PSPDialog.cpp b/Core/Dialog/PSPDialog.cpp index daf9c967ce..9750fb917d 100644 --- a/Core/Dialog/PSPDialog.cpp +++ b/Core/Dialog/PSPDialog.cpp @@ -64,6 +64,14 @@ int PSPDialog::Update() return 0; } +void PSPDialog::DoState(PointerWrap &p) +{ + p.Do(status); + p.Do(lastButtons); + p.Do(buttons); + p.DoMarker("PSPDialog"); +} + bool PSPDialog::IsButtonPressed(int checkButton) { return (!(lastButtons & checkButton)) && (buttons & checkButton); diff --git a/Core/Dialog/PSPDialog.h b/Core/Dialog/PSPDialog.h index c9c06120c8..f4884cda13 100644 --- a/Core/Dialog/PSPDialog.h +++ b/Core/Dialog/PSPDialog.h @@ -19,6 +19,7 @@ #include "../Config.h" +#include "../../Common/ChunkFile.h" #define SCE_UTILITY_DIALOG_RESULT_SUCCESS 0 #define SCE_UTILITY_DIALOG_RESULT_CANCEL 1 @@ -47,6 +48,7 @@ public: virtual int Update(); virtual int Shutdown(); + virtual void DoState(PointerWrap &p); enum DialogStatus { diff --git a/Core/Dialog/PSPMsgDialog.cpp b/Core/Dialog/PSPMsgDialog.cpp index 5d0fa4a06b..a5ef5ceb6e 100644 --- a/Core/Dialog/PSPMsgDialog.cpp +++ b/Core/Dialog/PSPMsgDialog.cpp @@ -206,3 +206,15 @@ int PSPMsgDialog::Shutdown() return PSPDialog::Shutdown(); } +void PSPMsgDialog::DoState(PointerWrap &p) +{ + p.Do(display); + p.Do(messageDialog); + p.Do(messageDialogAddr); + p.Do(yesnoChoice); + p.Do(okButtonImg); + p.Do(cancelButtonImg); + p.Do(okButtonFlag); + p.Do(cancelButtonFlag); + p.DoMarker("PSPMsgDialog"); +} diff --git a/Core/Dialog/PSPMsgDialog.h b/Core/Dialog/PSPMsgDialog.h index 80b1f24e9f..779a77f4e6 100644 --- a/Core/Dialog/PSPMsgDialog.h +++ b/Core/Dialog/PSPMsgDialog.h @@ -43,7 +43,8 @@ public: virtual int Init(unsigned int paramAddr); virtual int Update(); - int Shutdown(); + virtual int Shutdown(); + virtual void DoState(PointerWrap &p); private : void DisplayBack(); diff --git a/Core/Dialog/PSPOskDialog.cpp b/Core/Dialog/PSPOskDialog.cpp index 791a6d565d..abe367b96e 100644 --- a/Core/Dialog/PSPOskDialog.cpp +++ b/Core/Dialog/PSPOskDialog.cpp @@ -233,3 +233,16 @@ int PSPOskDialog::Update() return 0; } + +void PSPOskDialog::DoState(PointerWrap &p) +{ + p.Do(oskParams); + p.Do(oskData); + p.Do(oskDesc); + p.Do(oskIntext); + p.Do(oskOuttext); + p.Do(oskParamsAddr); + p.Do(selectedChar); + p.Do(inputChars); + p.DoMarker("PSPOskDialog"); +} diff --git a/Core/Dialog/PSPOskDialog.h b/Core/Dialog/PSPOskDialog.h index 387abc32b9..1683edf040 100644 --- a/Core/Dialog/PSPOskDialog.h +++ b/Core/Dialog/PSPOskDialog.h @@ -146,6 +146,7 @@ public: virtual int Init(u32 oskPtr); virtual int Update(); + virtual void DoState(PointerWrap &p); private: void HackyGetStringWide(std::string& _string, const u32 em_address); void RenderKeyboard(); diff --git a/Core/Dialog/PSPSaveDialog.cpp b/Core/Dialog/PSPSaveDialog.cpp index 44d110f5ab..4c02582986 100644 --- a/Core/Dialog/PSPSaveDialog.cpp +++ b/Core/Dialog/PSPSaveDialog.cpp @@ -706,3 +706,19 @@ int PSPSaveDialog::Shutdown() return 0; } +void PSPSaveDialog::DoState(PointerWrap &p) +{ + p.Do(display); + param.DoState(p); + p.Do(request); + // Just reset it. + param.SetPspParam(&request); + p.Do(requestAddr); + p.Do(currentSelectedSave); + p.Do(yesnoChoice); + p.Do(okButtonImg); + p.Do(cancelButtonImg); + p.Do(okButtonFlag); + p.Do(cancelButtonFlag); + p.DoMarker("PSPSaveDialog"); +} diff --git a/Core/Dialog/PSPSaveDialog.h b/Core/Dialog/PSPSaveDialog.h index c8149b7702..1e9eaea054 100644 --- a/Core/Dialog/PSPSaveDialog.h +++ b/Core/Dialog/PSPSaveDialog.h @@ -66,7 +66,8 @@ public: virtual int Init(int paramAddr); virtual int Update(); - int Shutdown(); + virtual int Shutdown(); + virtual void DoState(PointerWrap &p); private : diff --git a/Core/Dialog/SavedataParam.cpp b/Core/Dialog/SavedataParam.cpp index 6fd27dd0e9..4abafe0c73 100644 --- a/Core/Dialog/SavedataParam.cpp +++ b/Core/Dialog/SavedataParam.cpp @@ -80,9 +80,9 @@ namespace SavedataParam::SavedataParam() : pspParam(0) , selectedSave(0) - , saveNameListData(0) , saveDataList(0) , saveNameListDataCount(0) + , saveDataListCount(0) { } @@ -431,23 +431,24 @@ int SavedataParam::SetPspParam(SceUtilitySavedataParam *param) listEmptyFile = false; } + char (*saveNameListData)[20]; if (param->saveNameList != 0) { saveNameListData = (char(*)[20])Memory::GetPointer(param->saveNameList); // Get number of fileName in array - int count = 0; + saveDataListCount = 0; do { - count++; - } while(saveNameListData[count][0] != 0); + saveDataListCount++; + } while(saveNameListData[saveDataListCount][0] != 0); Clear(); - saveDataList = new SaveFileInfo[count]; + saveDataList = new SaveFileInfo[saveDataListCount]; // get and stock file info for each file int realCount = 0; - for (int i = 0; i < count; i++) + for (int i = 0; i < saveDataListCount; i++) { DEBUG_LOG(HLE,"Name : %s",saveNameListData[i]); @@ -600,3 +601,13 @@ void SavedataParam::SetSelectedSave(int idx) { selectedSave = idx; } + +void SavedataParam::DoState(PointerWrap &p) +{ + // pspParam is handled in PSPSaveDialog. + p.Do(selectedSave); + p.Do(saveDataListCount); + p.Do(saveNameListDataCount); + p.DoArray(saveDataList, saveDataListCount); + p.DoMarker("SavedataParam"); +} diff --git a/Core/Dialog/SavedataParam.h b/Core/Dialog/SavedataParam.h index 78b6d8fec0..4a1384a8ac 100644 --- a/Core/Dialog/SavedataParam.h +++ b/Core/Dialog/SavedataParam.h @@ -166,14 +166,16 @@ public: int GetSelectedSave(); void SetSelectedSave(int idx); + void DoState(PointerWrap &p); + private: void Clear(); void SetFileInfo(int idx, PSPFileInfo &info, std::string saveName); SceUtilitySavedataParam* pspParam; int selectedSave; - char (*saveNameListData)[20]; SaveFileInfo* saveDataList; + int saveDataListCount; int saveNameListDataCount; }; diff --git a/Core/HLE/sceKernel.cpp b/Core/HLE/sceKernel.cpp index 64909528d0..b590393c49 100644 --- a/Core/HLE/sceKernel.cpp +++ b/Core/HLE/sceKernel.cpp @@ -155,19 +155,19 @@ void __KernelDoState(PointerWrap &p) __KernelMutexDoState(p); __KernelSemaDoState(p); - // TODO: non-kernel modules __AudioDoState(p); __CtrlDoState(p); __DisplayDoState(p); __FontDoState(p); __GeDoState(p); __ImposeDoState(p); + __IoDoState(p); __PowerDoState(p); __SasDoState(p); __SslDoState(p); __UmdDoState(p); + __UtilityDoState(p); __UsbDoState(p); - __IoDoState(p); __PPGeDoState(p); diff --git a/Core/HLE/sceUtility.cpp b/Core/HLE/sceUtility.cpp index bebd56436d..c5dbc84934 100644 --- a/Core/HLE/sceUtility.cpp +++ b/Core/HLE/sceUtility.cpp @@ -39,6 +39,15 @@ void __UtilityInit() SavedataParam::Init(); } +void __UtilityDoState(PointerWrap &p) +{ + saveDialog.DoState(p); + msgDialog.DoState(p); + oskDialog.DoState(p); + netDialog.DoState(p); + p.DoMarker("sceUtility"); +} + void __UtilityShutdown() { saveDialog.Shutdown(); diff --git a/Core/HLE/sceUtility.h b/Core/HLE/sceUtility.h index ba85cd06c9..1518332972 100644 --- a/Core/HLE/sceUtility.h +++ b/Core/HLE/sceUtility.h @@ -18,6 +18,7 @@ #pragma once void __UtilityInit(); +void __UtilityDoState(PointerWrap &p); void __UtilityShutdown(); void Register_sceUtility(); From 94969c4eadb0aaf0794115be2f71c7e7ddff1f35 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Fri, 28 Dec 2012 13:50:59 -0800 Subject: [PATCH 28/29] Add some basic Windows UI for save states. --- Windows/WndMainWindow.cpp | 19 ++++++++++++++----- Windows/WndMainWindow.h | 1 + Windows/ppsspp.rc | Bin 28864 -> 29384 bytes 3 files changed, 15 insertions(+), 5 deletions(-) diff --git a/Windows/WndMainWindow.cpp b/Windows/WndMainWindow.cpp index debfc928bd..1e8a469a6d 100644 --- a/Windows/WndMainWindow.cpp +++ b/Windows/WndMainWindow.cpp @@ -18,8 +18,9 @@ #include "main.h" #include "../Core/Core.h" -#include "../Core/System.h" #include "../Core/MemMap.h" +#include "../Core/SaveState.h" +#include "../Core/System.h" #include "EmuThread.h" #include "resource.h" @@ -312,18 +313,18 @@ namespace MainWindow break; case ID_FILE_LOADSTATE: - if (W32Util::BrowseForFileName(true, hWnd, "Load state",0,"Save States (*.gcs)\0*.gcs\0All files\0*.*\0\0","gcs",fn)) + if (W32Util::BrowseForFileName(true, hWnd, "Load state",0,"Save States (*.ppssppst)\0*.ppssppst\0All files\0*.*\0\0","ppssppst",fn)) { SetCursor(LoadCursor(0,IDC_WAIT)); - SetCursor(LoadCursor(0,IDC_ARROW)); + SaveState::Load(fn, SaveStateActionFinished); } break; case ID_FILE_SAVESTATE: - if (W32Util::BrowseForFileName(false, hWnd, "Save state",0,"Save States (*.gcs)\0*.gcs\0All files\0*.*\0\0","gcs",fn)) + if (W32Util::BrowseForFileName(false, hWnd, "Save state",0,"Save States (*.ppssppst)\0*.ppssppst\0All files\0*.*\0\0","ppssppst",fn)) { SetCursor(LoadCursor(0,IDC_WAIT)); - SetCursor(LoadCursor(0,IDC_ARROW)); + SaveState::Save(fn, SaveStateActionFinished); } break; @@ -766,6 +767,14 @@ namespace MainWindow } } + void SaveStateActionFinished(bool result) + { + // TODO: Improve messaging? + if (!result) + MessageBox(0, "Savestate failure. Please try again later.", "Sorry", MB_OK); + SetCursor(LoadCursor(0, IDC_ARROW)); + } + void SetNextState(CoreState state) { nextState = state; diff --git a/Windows/WndMainWindow.h b/Windows/WndMainWindow.h index 7aaaaab423..b58823ca25 100644 --- a/Windows/WndMainWindow.h +++ b/Windows/WndMainWindow.h @@ -17,6 +17,7 @@ namespace MainWindow void SetPlaying(const char*text); void BrowseAndBoot(); void SetNextState(CoreState state); + void SaveStateActionFinished(bool result); void _ViewFullScreen(HWND hWnd); void _ViewNormal(HWND hWnd); } diff --git a/Windows/ppsspp.rc b/Windows/ppsspp.rc index 3c691428661e75dc9a4105a434f708ed81e8a7dd..e9561bdac4468508cfa78c949648e089abb2f193 100644 GIT binary patch delta 327 zcmX@`knzM*#tqkunK>CaCttJ_m-S)DXGmm7VNhTQW+(x&N*GcZVt}L@g9(Gul@>KO{;` zR&e5BHDrij(3$)&%6sy!I4P*8z+|g;{sUS`tKEgA2>#oFtfjv(5XGxC8)-Vk$)d From 269a776363fef304c398e62e9561a0e5614ee870 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Fri, 28 Dec 2012 14:13:34 -0800 Subject: [PATCH 29/29] Add a simple devctl to verify the state. Could do more, but this should be useful. --- Core/HLE/sceIo.cpp | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/Core/HLE/sceIo.cpp b/Core/HLE/sceIo.cpp index afe2c8615c..a7f8e00564 100644 --- a/Core/HLE/sceIo.cpp +++ b/Core/HLE/sceIo.cpp @@ -22,6 +22,7 @@ #include "../System.h" #include "../Config.h" +#include "../SaveState.h" #include "HLE.h" #include "../MIPS/MIPS.h" #include "../HW/MemoryStick.h" @@ -658,7 +659,12 @@ u32 sceIoDevctl(const char *name, int cmd, u32 argAddr, int argLen, u32 outPtr, } case 3: // EMULATOR_DEVCTL__IS_EMULATOR if (Memory::IsValidAddress(outPtr)) - Memory::Write_U32(1, outPtr); // TODO: Make a headless mode for running tests! + Memory::Write_U32(1, outPtr); + return 0; + case 4: // EMULATOR_DEVCTL__VERIFY_STATE + // Note that this is async, and makes sure the save state matches up. + SaveState::Verify(); + // TODO: Maybe save/load to a file just to be sure? return 0; }