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/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/Common/ChunkFile.h b/Common/ChunkFile.h index 7228365ccd..1671cecc8a 100644 --- a/Common/ChunkFile.h +++ b/Common/ChunkFile.h @@ -31,6 +31,8 @@ #include #include #include +#include +#include #include "Common.h" #include "FileUtil.h" @@ -112,14 +114,59 @@ 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) + { + 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); - DoArray(&x[0], vec_size); + x.resize(vec_size, default_val); + if (vec_size > 0) + DoArray(&x[0], vec_size); } // Store deques. @@ -133,7 +180,62 @@ 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(); + Do(list_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 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) { @@ -371,6 +473,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/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/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/CoreTiming.cpp b/Core/CoreTiming.cpp index b5d40610dd..01f6627a3b 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; @@ -36,6 +37,11 @@ namespace CoreTiming struct EventType { + EventType() {} + + EventType(TimedCallback cb, const char *n) + : callback(cb), name(n) {} + TimedCallback callback; const char *name; }; @@ -50,12 +56,6 @@ struct BaseEvent // Event *next; }; -template -struct LinkedListItem : public T -{ - LinkedListItem *next; -}; - typedef LinkedListItem Event; Event *first; @@ -74,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) @@ -125,13 +126,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 RestoreRegisterEvent(int event_type, const char *name, TimedCallback callback) +{ + if (event_type >= (int) event_types.size()) + event_types.resize(event_type + 1, EventType(AntiCrashCallback, "INVALID EVENT")); + + event_types[event_type] = EventType(callback, name); +} + void UnregisterAllEvents() { if (first) @@ -295,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; @@ -530,4 +543,29 @@ std::string GetScheduledEventsSummary() return text; } +void Event_DoState(PointerWrap &p, BaseEvent *ev) +{ + p.Do(*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. + 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 f8883d9b35..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 @@ -78,6 +79,8 @@ namespace CoreTiming // Returns the event_type identifier. int RegisterEvent(const char *name, TimedCallback callback); + // For save states. + 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, @@ -103,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/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/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 ab1c1e48d2..4d8670effd 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 @@ -75,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; @@ -93,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..b054b6bf72 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,12 @@ 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; u32 rootSize = desc.root.dataLengthLE; @@ -152,6 +159,7 @@ ISOFileSystem::ISOFileSystem(IHandleAllocator *_hAlloc, BlockDevice *_blockDevic ISOFileSystem::~ISOFileSystem() { delete blockDevice; + delete treeroot; } void ISOFileSystem::ReadDirectory(u32 startsector, u32 dirsize, TreeEntry *root) @@ -211,6 +219,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 +549,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..ef81fa2a23 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, Syscall()); + p.DoMarker("HLE"); +} + void HLEShutdown() { hleAfterSyscall = HLE_AFTER_NOTHING; diff --git a/Core/HLE/HLE.h b/Core/HLE/HLE.h index fb0eefa1be..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); @@ -94,7 +95,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/__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 5874ae2865..234bb3dc5f 100644 --- a/Core/HLE/sceCtrl.cpp +++ b/Core/HLE/sceCtrl.cpp @@ -284,6 +284,33 @@ void __CtrlInit() memcpy(&ctrlBufs[i], &ctrlCurrent, sizeof(_ctrl_data)); } +void __CtrlDoState(PointerWrap &p) +{ + std::lock_guard guard(ctrlMutex); + + 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); + + SceUID dv = 0; + p.Do(waitingThreads, dv); + + 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/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/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/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/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/sceIo.cpp b/Core/HLE/sceIo.cpp index 2523539a0a..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" @@ -137,7 +138,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; @@ -193,6 +205,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; @@ -639,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; } @@ -836,7 +861,20 @@ 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? + int count = listing.size(); + p.Do(count); + listing.resize(count); + for (int i = 0; i < count; ++i) { + listing[i].DoState(p); + } + p.DoMarker("DirListing"); + } std::string name; std::vector listing; @@ -920,6 +958,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..0f87cde613 100644 --- a/Core/HLE/sceIo.h +++ b/Core/HLE/sceIo.h @@ -19,9 +19,13 @@ #include #include "HLE.h" +#include "sceKernel.h" void __IoInit(); +void __IoDoState(PointerWrap &p); 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 27d8464fb4..b590393c49 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" @@ -33,6 +34,7 @@ #include "sceAudio.h" #include "sceCtrl.h" #include "sceDisplay.h" +#include "sceFont.h" #include "sceGe.h" #include "sceIo.h" #include "sceKernel.h" @@ -58,8 +60,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 @@ -68,6 +68,7 @@ extern MetaFileSystem pspFileSystem; */ static bool kernelRunning = false; +KernelObjectPool kernelObjects; void __KernelInit() { @@ -77,18 +78,19 @@ void __KernelInit() return; } + SaveState::Init(); + __InterruptsInit(); __KernelMemoryInit(); __KernelThreadingInit(); - __KernelMutexInit(); - __KernelSemaInit(); __KernelAlarmInit(); __KernelEventFlagInit(); __KernelMbxInit(); + __KernelMutexInit(); + __KernelSemaInit(); __IoInit(); __AudioInit(); __SasInit(); __DisplayInit(); - __InterruptsInit(); __GeInit(); __PowerInit(); __UtilityInit(); @@ -97,6 +99,7 @@ void __KernelInit() __SslInit(); __ImposeInit(); __UsbInit(); + __FontInit(); // "Internal" PSP libraries __PPGeInit(); @@ -125,10 +128,10 @@ void __KernelShutdown() __DisplayShutdown(); __AudioShutdown(); __IoShutdown(); - __InterruptsShutdown(); __KernelMutexShutdown(); __KernelThreadingShutdown(); __KernelMemoryShutdown(); + __InterruptsShutdown(); CoreTiming::ClearPendingEvents(); CoreTiming::UnregisterAllEvents(); @@ -136,6 +139,42 @@ void __KernelShutdown() kernelRunning = false; } +void __KernelDoState(PointerWrap &p) +{ + p.Do(kernelRunning); + kernelObjects.DoState(p); + p.DoMarker("KernelObjects"); + + __InterruptsDoState(p); + __KernelMemoryDoState(p); + __KernelThreadingDoState(p); + __KernelAlarmDoState(p); + __KernelEventFlagDoState(p); + __KernelMbxDoState(p); + __KernelModuleDoState(p); + __KernelMutexDoState(p); + __KernelSemaDoState(p); + + __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); + + __PPGeDoState(p); + + __InterruptsDoStateLate(p); + __KernelThreadingDoStateLate(p); +} + bool __KernelIsRunning() { return kernelRunning; } @@ -219,8 +258,6 @@ void sceKernelDcacheWritebackInvalidateAll() gpu->InvalidateCache(0, -1); } -KernelObjectPool kernelObjects; - KernelObjectPool::KernelObjectPool() { memset(occupied, 0, sizeof(bool)*maxCount); @@ -304,6 +341,88 @@ int KernelObjectPool::GetCount() return count; } +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."); + + if (p.mode == p.MODE_READ) + kernelObjects.Clear(); + + p.DoArray(occupied, maxCount); + for (int i = 0; i < maxCount; ++i) + { + if (!occupied[i]) + continue; + + int type; + if (p.mode == p.MODE_READ) + { + p.Do(type); + pool[i] = CreateByIDType(type); + pool[i]->uid = i + handleOffset; + + // Already logged an error. + if (pool[i] == NULL) + return; + } + 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); + return NULL; + } +} + 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..90835442d1 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 @@ -223,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, @@ -242,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; @@ -263,6 +271,7 @@ struct SceKernelLoadExecParam void __KernelInit(); void __KernelShutdown(); +void __KernelDoState(PointerWrap &p); bool __KernelIsRunning(); bool __KernelLoadExec(const char *filename, SceKernelLoadExecParam *param); @@ -311,9 +320,10 @@ public: // Implement this in all subclasses: // static u32 GetMissingErrorCode() - // Future - // void Serialize(ChunkFile) - // void DeSerialize(ChunkFile) + virtual void DoState(PointerWrap &p) + { + _dbg_assert_msg_(HLE, false, "Unable to save state: bad kernel object."); + } }; @@ -325,7 +335,8 @@ 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); + static KernelObject *CreateByIDType(int type); template u32 Destroy(SceUID handle) diff --git a/Core/HLE/sceKernelAlarm.cpp b/Core/HLE/sceKernelAlarm.cpp index 4e378b2a49..bb29e077e6 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; }; @@ -45,9 +52,14 @@ void __KernelScheduleAlarm(Alarm *alarm, u64 ticks); class AlarmIntrHandler : public SubIntrHandler { public: - AlarmIntrHandler(Alarm *alarm) + static SubIntrHandler *Create() { - this->alarm = alarm; + return new AlarmIntrHandler(); + } + + void setAlarm(Alarm *alarm) + { + alarmID = alarm->GetUID(); handlerAddress = alarm->alm.handlerPtr; enabled = true; } @@ -56,26 +68,42 @@ 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); + __ReleaseSubIntrHandler(PSP_SYSTIMER0_INTR, alarmID); } } - Alarm *alarm; + virtual void DoState(PointerWrap &p) + { + SubIntrHandler::DoState(p); + p.Do(alarmID); + p.DoMarker("AlarmIntrHandler"); + } + + SceUID alarmID; }; static int alarmTimer = 0; @@ -93,6 +121,20 @@ void __KernelTriggerAlarm(u64 userdata, int cyclesLate) void __KernelAlarmInit() { alarmTimer = CoreTiming::RegisterEvent("Alarm", __KernelTriggerAlarm); + __RegisterSubIntrCreator(PSP_SYSTIMER0_INTR, AlarmIntrHandler::Create); +} + +void __KernelAlarmDoState(PointerWrap &p) +{ + p.Do(alarmTimer); + CoreTiming::RestoreRegisterEvent(alarmTimer, "Alarm", __KernelTriggerAlarm); + p.DoMarker("sceKernelAlarm"); +} + +KernelObject *__KernelAlarmObject() +{ + // Default object to load from state. + return new Alarm; } void __KernelScheduleAlarm(Alarm *alarm, u64 ticks) @@ -113,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; } @@ -145,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/sceKernelAlarm.h b/Core/HLE/sceKernelAlarm.h index 09dd2e2f82..4b286eb87a 100644 --- a/Core/HLE/sceKernelAlarm.h +++ b/Core/HLE/sceKernelAlarm.h @@ -23,3 +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 a28c06c0d6..d57d63c9bd 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, EventFlagTh()); + p.DoMarker("EventFlag"); + } + NativeEventFlag nef; std::vector waitingThreads; }; @@ -94,7 +101,20 @@ 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() +{ + // Default object to load from state. + return new EventFlag; } bool __KernelEventFlagMatches(u32 *pattern, u32 bits, u8 wait, u32 outAddr) diff --git a/Core/HLE/sceKernelEventFlag.h b/Core/HLE/sceKernelEventFlag.h index 4243b8d897..151efa25f7 100644 --- a/Core/HLE/sceKernelEventFlag.h +++ b/Core/HLE/sceKernelEventFlag.h @@ -28,3 +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/sceKernelInterrupt.cpp b/Core/HLE/sceKernelInterrupt.cpp index bc00c82254..7c8c9d2544 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; + } + + int n = (int) subIntrHandlers.size(); + p.Do(n); + + if (p.mode == p.MODE_READ) + { + clear(); + for (int 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,31 @@ 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); + 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) @@ -238,25 +318,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 +349,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 +357,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 +420,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 +436,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 +474,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 +492,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..6b60a7870f 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,21 @@ public: u32 handlerArg; }; +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" 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); diff --git a/Core/HLE/sceKernelMbx.cpp b/Core/HLE/sceKernelMbx.cpp index c8c758a215..205a97460d 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, MbxWaitingThread()); + p.DoMarker("Mbx"); + } + NativeMbx nmb; std::vector waitingThreads; @@ -160,7 +167,19 @@ 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() +{ + return new Mbx; } bool __KernelUnlockMbxForThread(Mbx *m, MbxWaitingThread &th, u32 &error, int result, bool &wokeThreads) diff --git a/Core/HLE/sceKernelMbx.h b/Core/HLE/sceKernelMbx.h index 7edf6309e9..c171461a8f 100644 --- a/Core/HLE/sceKernelMbx.h +++ b/Core/HLE/sceKernelMbx.h @@ -34,3 +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 0b5a3c49b7..97ce91136b 100644 --- a/Core/HLE/sceKernelMemory.cpp +++ b/Core/HLE/sceKernelMemory.cpp @@ -53,15 +53,12 @@ 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";} 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 @@ -97,15 +106,24 @@ struct SceKernelVplInfo int numWaitThreads; }; -struct VPL : KernelObject +struct VPL : public KernelObject { const char *GetName() {return nv.name;} 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; }; @@ -117,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: "); @@ -350,13 +375,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() { @@ -364,6 +394,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]; }; @@ -594,6 +632,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..0b6602d756 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, @@ -29,7 +30,11 @@ extern BlockAllocator userMemory; extern BlockAllocator kernelMemory; void __KernelMemoryInit(); +void __KernelMemoryDoState(PointerWrap &p); 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..8f35526859 100644 --- a/Core/HLE/sceKernelModule.cpp +++ b/Core/HLE/sceKernelModule.cpp @@ -117,13 +117,45 @@ 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; +} + +class AfterModuleEntryCall : public Action { +public: + AfterModuleEntryCall() {} + SceUID moduleID_; + u32 retValAddr; + virtual void run(); + virtual void DoState(PointerWrap &p) { + p.Do(moduleID_); + p.Do(retValAddr); + p.DoMarker("AfterModuleEntryCall"); + } + static Action *Create() { + return new AfterModuleEntryCall; + } +}; + +void AfterModuleEntryCall::run() { + Memory::Write_U32(retValAddr, currentMIPS->r[2]); +} + ////////////////////////////////////////////////////////////////////////// // MODULES ////////////////////////////////////////////////////////////////////////// @@ -156,10 +188,24 @@ 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"); +} + Module *__KernelLoadELFFromPtr(const u8 *ptr, u32 loadAddress, std::string *error_string) { Module *module = new Module; @@ -515,6 +561,7 @@ bool __KernelLoadExec(const char *filename, SceKernelLoadExecParam *param, std:: if (__KernelIsRunning()) __KernelShutdown(); + __KernelModuleInit(); __KernelInit(); PSPFileInfo info = pspFileSystem.GetFileInfo(filename); @@ -639,18 +686,6 @@ u32 sceKernelLoadModule(const char *name, u32 flags) return module->GetUID(); } -class AfterModuleEntryCall : public Action { -public: - AfterModuleEntryCall() {} - Module *module_; - 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/sceKernelModule.h b/Core/HLE/sceKernelModule.h index 2652e1e55f..732bd43173 100644 --- a/Core/HLE/sceKernelModule.h +++ b/Core/HLE/sceKernelModule.h @@ -20,6 +20,9 @@ #include "sceKernel.h" #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/sceKernelMsgPipe.cpp b/Core/HLE/sceKernelMsgPipe.cpp index 1521d5f188..92ef03c74a 100644 --- a/Core/HLE/sceKernelMsgPipe.cpp +++ b/Core/HLE/sceKernelMsgPipe.cpp @@ -56,10 +56,12 @@ 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; + 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) { @@ -150,9 +152,35 @@ struct MsgPipe : public KernelObject } } + virtual void DoState(PointerWrap &p) + { + p.Do(nmp); + 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"); + } + + NativeMsgPipe nmp; + + std::vector sendWaitingThreads; + std::vector receiveWaitingThreads; + u8 *buffer; }; +KernelObject *__KernelMsgPipeObject() +{ + return new MsgPipe; +} + void sceKernelCreateMsgPipe() { const char *name = Memory::GetCharPointer(PARAM(0)); @@ -194,10 +222,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); 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 e3d048e545..a591e4ce6d 100644 --- a/Core/HLE/sceKernelMutex.cpp +++ b/Core/HLE/sceKernelMutex.cpp @@ -62,6 +62,15 @@ 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); + SceUID dv = 0; + p.Do(waitingThreads, dv); + p.DoMarker("Mutex"); + } + NativeMutex nm; std::vector waitingThreads; }; @@ -103,6 +112,15 @@ 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); + SceUID dv = 0; + p.Do(waitingThreads, dv); + p.DoMarker("LwMutex"); + } + NativeLwMutex nm; std::vector waitingThreads; }; @@ -115,12 +133,32 @@ 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; +} + +KernelObject *__KernelLwMutexObject() +{ + return new LwMutex; +} + void __KernelMutexShutdown() { mutexHeldLocks.clear(); diff --git a/Core/HLE/sceKernelMutex.h b/Core/HLE/sceKernelMutex.h index de54371948..18eeb4fafb 100644 --- a/Core/HLE/sceKernelMutex.h +++ b/Core/HLE/sceKernelMutex.h @@ -37,4 +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 2fd575d0d4..f9e5cd4e0b 100644 --- a/Core/HLE/sceKernelSemaphore.cpp +++ b/Core/HLE/sceKernelSemaphore.cpp @@ -57,6 +57,14 @@ 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); + SceUID dv = 0; + p.Do(waitingThreads, dv); + p.DoMarker("Semaphore"); + } + NativeSemaphore ns; std::vector waitingThreads; }; @@ -65,7 +73,19 @@ 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() +{ + return new Semaphore; } // Returns whether the thread should be removed. diff --git a/Core/HLE/sceKernelSemaphore.h b/Core/HLE/sceKernelSemaphore.h index 9a8b9f2640..14df34cbed 100644 --- a/Core/HLE/sceKernelSemaphore.h +++ b/Core/HLE/sceKernelSemaphore.h @@ -29,3 +29,5 @@ int sceKernelWaitSemaCB(SceUID semaid, int signal, u32 timeoutPtr); void __KernelSemaTimeout(u64 userdata, int cycleslate); void __KernelSemaInit(); +void __KernelSemaDoState(PointerWrap &p); +KernelObject *__KernelSemaphoreObject(); diff --git a/Core/HLE/sceKernelThread.cpp b/Core/HLE/sceKernelThread.cpp index 8d03a17f8a..e791219d2b 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; @@ -163,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) {} @@ -181,13 +192,64 @@ public: return temp; } void clear() { + std::map::iterator it, end; + for (it = calls_.begin(), end = calls_.end(); it != end; ++it) { + delete it->second; + } calls_.clear(); idGen_ = 0; } + int registerActionType(ActionCreator creator) { + types_.push_back(creator); + return types_.size() - 1; + } + + void restoreActionType(int actionType, ActionCreator creator) { + if (actionType >= (int) types_.size()) + types_.resize(actionType + 1, NULL); + types_[actionType] = creator; + } + + Action *createActionByType(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) { + + int n = (int) calls_.size(); + p.Do(n); + + if (p.mode == p.MODE_READ) { + clear(); + for (int i = 0; i < n; ++i) { + int k; + p.Do(k); + 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.Do(idGen_); + p.DoMarker("MipsCallManager"); + } + private: int genId() { return ++idGen_; } std::map calls_; + std::vector types_; int idGen_; }; @@ -195,7 +257,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; @@ -207,6 +299,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: @@ -297,6 +414,33 @@ 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) + { + p.Do(registeredCallbacks[i]); + p.Do(readyCallbacks[i]); + } + + p.Do(pendingMipsCalls); + p.Do(stackBlock); + + p.DoMarker("Thread"); + } + NativeThread nt; ThreadWaitInfo waitInfo; @@ -328,12 +472,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]; @@ -343,6 +487,8 @@ int eventScheduledWakeup; bool dispatchEnabled = true; MipsCallManager mipsCalls; +int actionAfterCallback; +int actionAfterMipsCall; // This seems nasty SceUID curModule; @@ -351,11 +497,59 @@ SceUID curModule; //STATE END ////////////////////////////////////////////////////////////////////////// +int __KernelRegisterActionType(ActionCreator creator) +{ + return mipsCalls.registerActionType(creator); +} + +void __KernelRestoreActionType(int actionType, ActionCreator creator) +{ + mipsCalls.restoreActionType(actionType, creator); +} + +Action *__KernelCreateAction(int actionType) +{ + return mipsCalls.createActionByType(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. Thread *__GetCurrentThread() { - return currentThread; + u32 error; + if (currentThread != 0) + return kernelObjects.Get(currentThread, error); + else + return NULL; } u32 __KernelMipsCallReturnAddress() @@ -399,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... @@ -409,6 +605,48 @@ 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); + SceUID dv = 0; + p.Do(threadqueue, dv); + 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; +} + +KernelObject *__KernelCallbackObject() +{ + return new Callback; +} + void __KernelListenThreadEnd(ThreadCallback callback) { threadEndListeners.push_back(callback); @@ -442,7 +680,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]) { @@ -616,7 +854,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; @@ -712,10 +950,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(); @@ -755,12 +994,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 @@ -793,7 +1033,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); @@ -819,12 +1059,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) { @@ -835,7 +1076,7 @@ Thread *__KernelNextThread() { } if (bestthread != -1) - return threadqueue[bestthread]; + return kernelObjects.Get(threadqueue[bestthread], error); else return 0; } @@ -883,14 +1124,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; } @@ -970,7 +1211,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)); @@ -1002,13 +1243,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]; @@ -1032,7 +1275,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); @@ -1094,7 +1337,7 @@ void sceKernelGetThreadStackFreeSize() INFO_LOG(HLE,"sceKernelGetThreadStackFreeSize(%i)", threadID); if (threadID == 0) - thread = currentThread; + thread = __GetCurrentThread(); else { u32 error; @@ -1122,15 +1365,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. @@ -1144,10 +1390,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 @@ -1159,15 +1408,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. } @@ -1180,11 +1432,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; @@ -1224,7 +1476,7 @@ void sceKernelRotateThreadReadyQueue() int sceKernelDeleteThread(int threadHandle) { - if (threadHandle != currentThread->GetUID()) + if (threadHandle != currentThread) { //TODO: remove from threadqueue! DEBUG_LOG(HLE,"sceKernelDeleteThread(%i)",threadHandle); @@ -1249,14 +1501,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); @@ -1265,18 +1517,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); @@ -1293,25 +1546,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); } @@ -1328,14 +1584,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); @@ -1426,9 +1686,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); @@ -1615,11 +1882,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(); @@ -1629,7 +1900,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; @@ -1650,7 +1921,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); @@ -1740,23 +2011,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); } @@ -1765,7 +2038,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; } @@ -1792,9 +2065,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; @@ -1821,9 +2094,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; @@ -1842,8 +2115,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); @@ -1854,7 +2134,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; @@ -1864,7 +2144,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]; } @@ -1874,7 +2154,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); @@ -1886,26 +2173,31 @@ void __KernelReturnFromMipsCall() // Should also save/restore wait state here. if (call->doAfter) + { call->doAfter->run(); + delete call->doAfter; + } currentMIPS->pc = call->savedPc; currentMIPS->r[MIPS_REG_RA] = call->savedRa; 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"); } + + delete call; } bool __KernelExecutePendingMipsCalls(bool reschedAfter) @@ -1928,15 +2220,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) { @@ -1961,7 +2244,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); } @@ -2012,13 +2300,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; } } @@ -2103,8 +2392,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); diff --git a/Core/HLE/sceKernelThread.h b/Core/HLE/sceKernelThread.h index 913511fe65..b63fe58312 100644 --- a/Core/HLE/sceKernelThread.h +++ b/Core/HLE/sceKernelThread.h @@ -97,7 +97,11 @@ 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(); void __KernelScheduleWakeup(int usFromNow, int threadnumber); SceUID __KernelGetCurThread(); @@ -182,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; @@ -194,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 { diff --git a/Core/HLE/sceKernelVTimer.cpp b/Core/HLE/sceKernelVTimer.cpp index 299e47fd6b..35174f34f1 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; @@ -39,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(); 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/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/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/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(); 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/HW/SasAudio.cpp b/Core/HW/SasAudio.cpp index ed17365368..3845922fbe 100644 --- a/Core/HW/SasAudio.cpp +++ b/Core/HW/SasAudio.cpp @@ -27,7 +27,7 @@ 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 data, int vagSize, bool loopEnabled) { loopEnabled_ = loopEnabled; loopAtNextBlock_ = false; loopStartBlock_ = 0; @@ -41,11 +41,11 @@ void VagDecoder::Start(u8 *data, int vagSize, bool loopEnabled) { 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,6 +101,10 @@ void VagDecoder::GetSamples(s16 *outSamples, int numSamples) { } outSamples[i] = end_ ? 0 : samples[curSample++]; } + + if (readp > origp) { + read_ += readp - origp; + } } // http://code.google.com/p/jpcsp/source/browse/trunk/src/jpcsp/HLE/modules150/sceSasCore.java @@ -182,14 +190,25 @@ 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) { grainSize = newGrainSize; + // If you change the sizes here, don't forget DoState(). if (mixBuffer) delete [] mixBuffer; if (sendBuffer) @@ -303,6 +322,44 @@ void SasInstance::Mix(u32 outAddr) { } } +void SasInstance::DoState(PointerWrap &p) { + p.Do(grainSize); + if (p.mode == p.MODE_READ) { + if (grainSize > 0) { + SetGrainSize(grainSize); + } else { + ClearGrainSize(); + } + } + + p.Do(maxVoices); + p.Do(sampleRate); + p.Do(outputMode); + + // SetGrainSize() / ClearGrainSize() should've made our buffers match. + if (mixBuffer != NULL && grainSize > 0) { + p.DoArray(mixBuffer, grainSize * 2); + } + if (sendBuffer != NULL && grainSize > 0) { + p.DoArray(sendBuffer, grainSize * 2); + } + if (resampleBuffer != NULL && grainSize > 0) { + 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; + } + p.DoArray(voices, ARRAY_SIZE(voices)); + 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,7 +393,7 @@ 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 } diff --git a/Core/HW/SasAudio.h b/Core/HW/SasAudio.h index b32ba7d347..1c204782fa 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,23 +78,19 @@ 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); - void DecodeBlock(); + void DecodeBlock(u8 *&readp); bool End() const { return end_; } - u8 GetByte() { - return *read_++; - } - private: double samples[28]; int curSample; - u8 *data_; - u8 *read_; + u32 data_; + u32 read_; int curBlock_; int loopStartBlock_; int numBlocks_; @@ -215,6 +212,7 @@ public: SasInstance(); ~SasInstance(); + void ClearGrainSize(); void SetGrainSize(int newGrainSize); int GetGrainSize() const { return grainSize; } @@ -228,6 +226,8 @@ public: void Mix(u32 outAddr); + void DoState(PointerWrap &p); + SasVoice voices[PSP_SAS_VOICES_MAX]; WaveformEffect waveformEffect; 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 new file mode 100644 index 0000000000..35f91ce900 --- /dev/null +++ b/Core/SaveState.cpp @@ -0,0 +1,164 @@ +// 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/StdMutex.h" +#include + +#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 +{ + 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; + + 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. + CoreTiming::DoState(p); + + // This save state even saves its own state. + p.Do(timer); + CoreTiming::RestoreRegisterEvent(timer, "SaveState", Process); + p.DoMarker("SaveState"); + + Memory::DoState(p); + MemoryStick_DoState(p); + currentMIPS->DoState(p); + pspFileSystem.DoState(p); + HLEDoState(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. + 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) + { + 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); + } +} diff --git a/Core/SaveState.h b/Core/SaveState.h new file mode 100644 index 0000000000..411ad2f88c --- /dev/null +++ b/Core/SaveState.h @@ -0,0 +1,39 @@ +// 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" +#include + +namespace SaveState +{ + typedef void (*Callback)(bool status); + + // TODO: Better place for this? + const int REVISION = 1; + + void Init(); + + // 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 diff --git a/Core/Util/BlockAllocator.cpp b/Core/Util/BlockAllocator.cpp index 27183cbff8..d778012ab9 100644 --- a/Core/Util/BlockAllocator.cpp +++ b/Core/Util/BlockAllocator.cpp @@ -297,3 +297,12 @@ u32 BlockAllocator::GetTotalFreeBytes() } return sum; } + +void BlockAllocator::DoState(PointerWrap &p) +{ + p.Do(blocks, Block(0, 0, false)); + 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(); 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(); 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/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 3c69142866..e9561bdac4 100644 Binary files a/Windows/ppsspp.rc and b/Windows/ppsspp.rc differ 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 \