/
SaveState.cpp
1161 lines (964 loc) · 33.8 KB
/
SaveState.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* PCSX2 - PS2 Emulator for PCs
* Copyright (C) 2002-2010 PCSX2 Dev Team
*
* PCSX2 is free software: you can redistribute it and/or modify it under the terms
* of the GNU Lesser General Public License as published by the Free Software Found-
* ation, either version 3 of the License, or (at your option) any later version.
*
* PCSX2 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with PCSX2.
* If not, see <http://www.gnu.org/licenses/>.
*/
#include "PrecompiledHeader.h"
#include "SaveState.h"
#include "common/FileSystem.h"
#include "common/Path.h"
#include "common/SafeArray.inl"
#include "common/ScopedGuard.h"
#include "common/StringUtil.h"
#include "common/ZipHelpers.h"
#include "ps2/BiosTools.h"
#include "COP0.h"
#include "VUmicro.h"
#include "MTVU.h"
#include "Cache.h"
#include "Config.h"
#include "CDVD/CDVD.h"
#include "R3000A.h"
#include "Elfheader.h"
#include "Counters.h"
#include "Patch.h"
#include "DebugTools/Breakpoints.h"
#include "Host.h"
#include "GS.h"
#include "GS/GS.h"
#include "SPU2/spu2.h"
#include "USB/USB.h"
#include "PAD/Gamepad.h"
#ifndef PCSX2_CORE
#include "gui/App.h"
#include "gui/ConsoleLogger.h"
#include "gui/SysThreads.h"
#else
#include "VMManager.h"
#endif
#ifdef ENABLE_ACHIEVEMENTS
#include "Frontend/Achievements.h"
#endif
#include "fmt/core.h"
#include <csetjmp>
#include <png.h>
using namespace R5900;
static tlbs s_tlb_backup[std::size(tlb)];
static void PreLoadPrep()
{
// ensure everything is in sync before we start overwriting stuff.
if (THREAD_VU1)
vu1Thread.WaitVU();
GetMTGS().WaitGS(false);
// backup current TLBs, since we're going to overwrite them all
std::memcpy(s_tlb_backup, tlb, sizeof(s_tlb_backup));
// clear protected pages, since we don't want to fault loading EE memory
mmap_ResetBlockTracking();
SysClearExecutionCache();
#ifndef PCSX2_CORE
PatchesVerboseReset();
#endif
}
static void PostLoadPrep()
{
resetCache();
// WriteCP0Status(cpuRegs.CP0.n.Status.val);
for (int i = 0; i < 48; i++)
{
if (std::memcmp(&s_tlb_backup[i], &tlb[i], sizeof(tlbs)) != 0)
{
UnmapTLB(s_tlb_backup[i], i);
MapTLB(tlb[i], i);
}
}
if (EmuConfig.Gamefixes.GoemonTlbHack) GoemonPreloadTlb();
CBreakPoints::SetSkipFirst(BREAKPOINT_EE, 0);
CBreakPoints::SetSkipFirst(BREAKPOINT_IOP, 0);
UpdateVSyncRate();
}
// --------------------------------------------------------------------------------------
// SaveStateBase (implementations)
// --------------------------------------------------------------------------------------
#ifndef PCSX2_CORE
std::string SaveStateBase::GetSavestateFolder(int slot, bool isSavingOrLoading)
{
std::string CRCvalue(StringUtil::StdStringFromFormat("%08X", ElfCRC));
std::string serialName;
if (g_GameStarted || g_GameLoading)
{
if (DiscSerial.empty())
{
// Running homebrew/standalone ELF, return only the ELF name.
// can't use FileSystem here because it's DOS paths
const std::string::size_type pos = std::min(DiscSerial.rfind('/'), DiscSerial.rfind('\\'));
if (pos != std::string::npos)
serialName = DiscSerial.substr(pos + 1);
else
serialName = DiscSerial;
}
else
{
// Running a normal retail game
// Folder format is "SLXX-XXXX - (00000000)"
serialName = DiscSerial;
}
}
else
{
// Still inside the BIOS/not running a game (why would anyone want to do this?)
serialName = StringUtil::StdStringFromFormat("BIOS (%s v%u.%u)", BiosZone.c_str(), (BiosVersion >> 8), BiosVersion & 0xff);
CRCvalue = "None";
}
const std::string dir(StringUtil::StdStringFromFormat("%s" FS_OSPATH_SEPARATOR_STR "%s - (%s)",
g_Conf->Folders.Savestates.ToUTF8().data(), serialName.c_str(), CRCvalue.c_str()));
if (isSavingOrLoading)
{
if (!FileSystem::DirectoryExists(dir.c_str()))
{
// sstates should exist, no need to create it
FileSystem::CreateDirectoryPath(dir.c_str(), false);
}
}
return Path::Combine(dir, StringUtil::StdStringFromFormat("%s (%s).%02d.p2s",
serialName.c_str(), CRCvalue.c_str(), slot));
}
#endif
SaveStateBase::SaveStateBase( SafeArray<u8>& memblock )
{
Init( &memblock );
}
SaveStateBase::SaveStateBase( SafeArray<u8>* memblock )
{
Init( memblock );
}
void SaveStateBase::Init( SafeArray<u8>* memblock )
{
m_memory = memblock;
m_version = g_SaveVersion;
m_idx = 0;
}
void SaveStateBase::PrepBlock( int size )
{
pxAssertDev( m_memory, "Savestate memory/buffer pointer is null!" );
const int end = m_idx+size;
if( IsSaving() )
m_memory->MakeRoomFor( end );
else
{
if( m_memory->GetSizeInBytes() < end )
throw Exception::SaveStateLoadError();
}
}
void SaveStateBase::FreezeTag( const char* src )
{
const uint allowedlen = sizeof( m_tagspace )-1;
pxAssertDev(strlen(src) < allowedlen, "Tag name exceeds the allowed length");
memzero( m_tagspace );
strcpy( m_tagspace, src );
Freeze( m_tagspace );
if( strcmp( m_tagspace, src ) != 0 )
{
std::string msg(fmt::format("Savestate data corruption detected while reading tag: {}", src));
pxFail( msg.c_str() );
throw Exception::SaveStateLoadError().SetDiagMsg(std::move(msg));
}
}
SaveStateBase& SaveStateBase::FreezeBios()
{
FreezeTag( "BIOS" );
// Check the BIOS, and issue a warning if the bios for this state
// doesn't match the bios currently being used (chances are it'll still
// work fine, but some games are very picky).
u32 bioscheck = BiosChecksum;
char biosdesc[256];
memzero( biosdesc );
memcpy( biosdesc, BiosDescription.c_str(), std::min( sizeof(biosdesc), BiosDescription.length() ) );
Freeze( bioscheck );
Freeze( biosdesc );
if (bioscheck != BiosChecksum)
{
Console.Newline();
Console.Indent(1).Error( "Warning: BIOS Version Mismatch, savestate may be unstable!" );
Console.Indent(2).Error(
"Current BIOS: %s (crc=0x%08x)\n"
"Savestate BIOS: %s (crc=0x%08x)\n",
BiosDescription.c_str(), BiosChecksum,
biosdesc, bioscheck
);
}
return *this;
}
SaveStateBase& SaveStateBase::FreezeInternals()
{
#ifdef PCSX2_CORE
const u32 previousCRC = ElfCRC;
#endif
// Print this until the MTVU problem in gifPathFreeze is taken care of (rama)
if (THREAD_VU1) Console.Warning("MTVU speedhack is enabled, saved states may not be stable");
// Second Block - Various CPU Registers and States
// -----------------------------------------------
FreezeTag( "cpuRegs" );
Freeze(cpuRegs); // cpu regs + COP0
Freeze(psxRegs); // iop regs
Freeze(fpuRegs);
Freeze(tlb); // tlbs
Freeze(AllowParams1); //OSDConfig written (Fast Boot)
Freeze(AllowParams2);
Freeze(g_GameStarted);
Freeze(g_GameLoading);
Freeze(ElfCRC);
char localDiscSerial[256];
StringUtil::Strlcpy(localDiscSerial, DiscSerial.c_str(), sizeof(localDiscSerial));
Freeze(localDiscSerial);
if (IsLoading())
{
DiscSerial = localDiscSerial;
#ifdef PCSX2_CORE
if (ElfCRC != previousCRC)
{
// HACK: LastELF isn't in the save state... Load it before we go too far into restoring state.
// When we next bump save states, we should include it. We need this for achievements, because
// we want to load and activate achievements before restoring any of their tracked state.
if (const std::string& elf_override = VMManager::Internal::GetElfOverride(); !elf_override.empty())
cdvdReloadElfInfo(fmt::format("host:{}", elf_override));
else
cdvdReloadElfInfo();
}
#endif
}
// Third Block - Cycle Timers and Events
// -------------------------------------
FreezeTag( "Cycles" );
Freeze(EEsCycle);
Freeze(EEoCycle);
Freeze(nextCounter);
Freeze(nextsCounter);
Freeze(psxNextsCounter);
Freeze(psxNextCounter);
// Fourth Block - EE-related systems
// ---------------------------------
FreezeTag( "EE-Subsystems" );
rcntFreeze();
gsFreeze();
vuMicroFreeze();
vuJITFreeze();
vif0Freeze();
vif1Freeze();
sifFreeze();
ipuFreeze();
ipuDmaFreeze();
gifFreeze();
gifDmaFreeze();
sprFreeze();
mtvuFreeze();
// Fifth Block - iop-related systems
// ---------------------------------
FreezeTag( "IOP-Subsystems" );
FreezeMem(iopMem->Sif, sizeof(iopMem->Sif)); // iop's sif memory (not really needed, but oh well)
psxRcntFreeze();
sioFreeze();
sio2Freeze();
cdrFreeze();
cdvdFreeze();
// technically this is HLE BIOS territory, but we don't have enough such stuff
// to merit an HLE Bios sub-section... yet.
deci2Freeze();
InputRecordingFreeze();
return *this;
}
// --------------------------------------------------------------------------------------
// memSavingState (implementations)
// --------------------------------------------------------------------------------------
// uncompressed to/from memory state saves implementation
memSavingState::memSavingState( SafeArray<u8>& save_to )
: SaveStateBase( save_to )
{
}
memSavingState::memSavingState( SafeArray<u8>* save_to )
: SaveStateBase( save_to )
{
}
// Saving of state data
void memSavingState::FreezeMem( void* data, int size )
{
if (!size) return;
m_memory->MakeRoomFor( m_idx + size );
memcpy( m_memory->GetPtr(m_idx), data, size );
m_idx += size;
}
void memSavingState::MakeRoomForData()
{
pxAssertDev( m_memory, "Savestate memory/buffer pointer is null!" );
m_memory->ChunkSize = ReallocThreshold;
m_memory->MakeRoomFor( m_idx + MemoryBaseAllocSize );
}
// --------------------------------------------------------------------------------------
// memLoadingState (implementations)
// --------------------------------------------------------------------------------------
memLoadingState::memLoadingState( const SafeArray<u8>& load_from )
: SaveStateBase( const_cast<SafeArray<u8>&>(load_from) )
{
}
memLoadingState::memLoadingState( const SafeArray<u8>* load_from )
: SaveStateBase( const_cast<SafeArray<u8>*>(load_from) )
{
}
// Loading of state data from a memory buffer...
void memLoadingState::FreezeMem( void* data, int size )
{
const u8* const src = m_memory->GetPtr(m_idx);
m_idx += size;
memcpy( data, src, size );
}
std::string Exception::SaveStateLoadError::FormatDiagnosticMessage() const
{
std::string retval = "Savestate is corrupt or incomplete!\n";
Host::AddOSDMessage("Error: Savestate is corrupt or incomplete!", 15.0f);
_formatDiagMsg(retval);
return retval;
}
std::string Exception::SaveStateLoadError::FormatDisplayMessage() const
{
std::string retval = "The savestate cannot be loaded, as it appears to be corrupt or incomplete.\n";
Host::AddOSDMessage("Error: The savestate cannot be loaded, as it appears to be corrupt or incomplete.", 15.0f);
_formatUserMsg(retval);
return retval;
}
// Used to hold the current state backup (fullcopy of PS2 memory and subcomponents states).
//static VmStateBuffer state_buffer( L"Public Savestate Buffer" );
static const char* EntryFilename_StateVersion = "PCSX2 Savestate Version.id";
static const char* EntryFilename_Screenshot = "Screenshot.png";
static const char* EntryFilename_InternalStructures = "PCSX2 Internal Structures.dat";
struct SysState_Component
{
const char* name;
int (*freeze)(FreezeAction, freezeData*);
};
static int SysState_MTGSFreeze(FreezeAction mode, freezeData* fP)
{
#ifndef PCSX2_CORE
ScopedCoreThreadPause paused_core;
#endif
MTGS_FreezeData sstate = { fP, 0 };
GetMTGS().Freeze(mode, sstate);
#ifndef PCSX2_CORE
paused_core.AllowResume();
#endif
return sstate.retval;
}
static constexpr SysState_Component SPU2{ "SPU2", SPU2freeze };
static constexpr SysState_Component PAD_{ "PAD", PADfreeze };
static constexpr SysState_Component USB{ "USB", USBfreeze };
static constexpr SysState_Component GS{ "GS", SysState_MTGSFreeze };
static void SysState_ComponentFreezeOutRoot(void* dest, SysState_Component comp)
{
freezeData fP = { 0, (u8*)dest };
if (comp.freeze(FreezeAction::Size, &fP) != 0)
return;
if (!fP.size)
return;
Console.Indent().WriteLn("Saving %s", comp.name);
if (comp.freeze(FreezeAction::Save, &fP) != 0)
throw std::runtime_error(std::string(" * ") + comp.name + std::string(": Error saving state!\n"));
}
static void SysState_ComponentFreezeIn(zip_file_t* zf, SysState_Component comp)
{
if (!zf)
return;
freezeData fP = { 0, nullptr };
if (comp.freeze(FreezeAction::Size, &fP) != 0)
fP.size = 0;
Console.Indent().WriteLn("Loading %s", comp.name);
auto data = std::make_unique<u8[]>(fP.size);
fP.data = data.get();
if (zip_fread(zf, data.get(), fP.size) != static_cast<zip_int64_t>(fP.size) || comp.freeze(FreezeAction::Load, &fP) != 0)
throw std::runtime_error(std::string(" * ") + comp.name + std::string(": Error loading state!\n"));
}
static void SysState_ComponentFreezeOut(SaveStateBase& writer, SysState_Component comp)
{
freezeData fP = { 0, NULL };
if (comp.freeze(FreezeAction::Size, &fP) == 0)
{
const int size = fP.size;
writer.PrepBlock(size);
SysState_ComponentFreezeOutRoot(writer.GetBlockPtr(), comp);
writer.CommitBlock(size);
}
return;
}
// --------------------------------------------------------------------------------------
// BaseSavestateEntry
// --------------------------------------------------------------------------------------
class BaseSavestateEntry
{
protected:
BaseSavestateEntry() = default;
public:
virtual ~BaseSavestateEntry() = default;
virtual const char* GetFilename() const = 0;
virtual void FreezeIn(zip_file_t* zf) const = 0;
virtual void FreezeOut(SaveStateBase& writer) const = 0;
virtual bool IsRequired() const = 0;
};
class MemorySavestateEntry : public BaseSavestateEntry
{
protected:
MemorySavestateEntry() {}
virtual ~MemorySavestateEntry() = default;
public:
virtual void FreezeIn(zip_file_t* zf) const;
virtual void FreezeOut(SaveStateBase& writer) const;
virtual bool IsRequired() const { return true; }
protected:
virtual u8* GetDataPtr() const = 0;
virtual u32 GetDataSize() const = 0;
};
void MemorySavestateEntry::FreezeIn(zip_file_t* zf) const
{
const u32 expectedSize = GetDataSize();
const s64 bytesRead = zip_fread(zf, GetDataPtr(), expectedSize);
if (bytesRead != static_cast<s64>(expectedSize))
{
Console.WriteLn(Color_Yellow, " '%s' is incomplete (expected 0x%x bytes, loading only 0x%x bytes)",
GetFilename(), expectedSize, static_cast<u32>(bytesRead));
}
}
void MemorySavestateEntry::FreezeOut(SaveStateBase& writer) const
{
writer.FreezeMem(GetDataPtr(), GetDataSize());
}
// --------------------------------------------------------------------------------------
// SavestateEntry_* (EmotionMemory, IopMemory, etc)
// --------------------------------------------------------------------------------------
// Implementation Rationale:
// The address locations of PS2 virtual memory components is fully dynamic, so we need to
// resolve the pointers at the time they are requested (eeMem, iopMem, etc). Thusly, we
// cannot use static struct member initializers -- we need virtual functions that compute
// and resolve the addresses on-demand instead... --air
class SavestateEntry_EmotionMemory : public MemorySavestateEntry
{
public:
virtual ~SavestateEntry_EmotionMemory() = default;
const char* GetFilename() const { return "eeMemory.bin"; }
u8* GetDataPtr() const { return eeMem->Main; }
uint GetDataSize() const { return sizeof(eeMem->Main); }
virtual void FreezeIn(zip_file_t* zf) const
{
SysClearExecutionCache();
MemorySavestateEntry::FreezeIn(zf);
}
};
class SavestateEntry_IopMemory : public MemorySavestateEntry
{
public:
virtual ~SavestateEntry_IopMemory() = default;
const char* GetFilename() const { return "iopMemory.bin"; }
u8* GetDataPtr() const { return iopMem->Main; }
uint GetDataSize() const { return sizeof(iopMem->Main); }
};
class SavestateEntry_HwRegs : public MemorySavestateEntry
{
public:
virtual ~SavestateEntry_HwRegs() = default;
const char* GetFilename() const { return "eeHwRegs.bin"; }
u8* GetDataPtr() const { return eeHw; }
uint GetDataSize() const { return sizeof(eeHw); }
};
class SavestateEntry_IopHwRegs : public MemorySavestateEntry
{
public:
virtual ~SavestateEntry_IopHwRegs() = default;
const char* GetFilename() const { return "iopHwRegs.bin"; }
u8* GetDataPtr() const { return iopHw; }
uint GetDataSize() const { return sizeof(iopHw); }
};
class SavestateEntry_Scratchpad : public MemorySavestateEntry
{
public:
virtual ~SavestateEntry_Scratchpad() = default;
const char* GetFilename() const { return "Scratchpad.bin"; }
u8* GetDataPtr() const { return eeMem->Scratch; }
uint GetDataSize() const { return sizeof(eeMem->Scratch); }
};
class SavestateEntry_VU0mem : public MemorySavestateEntry
{
public:
virtual ~SavestateEntry_VU0mem() = default;
const char* GetFilename() const { return "vu0Memory.bin"; }
u8* GetDataPtr() const { return vuRegs[0].Mem; }
uint GetDataSize() const { return VU0_MEMSIZE; }
};
class SavestateEntry_VU1mem : public MemorySavestateEntry
{
public:
virtual ~SavestateEntry_VU1mem() = default;
const char* GetFilename() const { return "vu1Memory.bin"; }
u8* GetDataPtr() const { return vuRegs[1].Mem; }
uint GetDataSize() const { return VU1_MEMSIZE; }
};
class SavestateEntry_VU0prog : public MemorySavestateEntry
{
public:
virtual ~SavestateEntry_VU0prog() = default;
const char* GetFilename() const { return "vu0MicroMem.bin"; }
u8* GetDataPtr() const { return vuRegs[0].Micro; }
uint GetDataSize() const { return VU0_PROGSIZE; }
};
class SavestateEntry_VU1prog : public MemorySavestateEntry
{
public:
virtual ~SavestateEntry_VU1prog() = default;
const char* GetFilename() const { return "vu1MicroMem.bin"; }
u8* GetDataPtr() const { return vuRegs[1].Micro; }
uint GetDataSize() const { return VU1_PROGSIZE; }
};
class SavestateEntry_SPU2 : public BaseSavestateEntry
{
public:
virtual ~SavestateEntry_SPU2() = default;
const char* GetFilename() const { return "SPU2.bin"; }
void FreezeIn(zip_file_t* zf) const { return SysState_ComponentFreezeIn(zf, SPU2); }
void FreezeOut(SaveStateBase& writer) const { return SysState_ComponentFreezeOut(writer, SPU2); }
bool IsRequired() const { return true; }
};
class SavestateEntry_USB : public BaseSavestateEntry
{
public:
virtual ~SavestateEntry_USB() = default;
const char* GetFilename() const { return "USB.bin"; }
void FreezeIn(zip_file_t* zf) const { return SysState_ComponentFreezeIn(zf, USB); }
void FreezeOut(SaveStateBase& writer) const { return SysState_ComponentFreezeOut(writer, USB); }
bool IsRequired() const { return false; }
};
class SavestateEntry_PAD : public BaseSavestateEntry
{
public:
virtual ~SavestateEntry_PAD() = default;
const char* GetFilename() const { return "PAD.bin"; }
void FreezeIn(zip_file_t* zf) const { return SysState_ComponentFreezeIn(zf, PAD_); }
void FreezeOut(SaveStateBase& writer) const { return SysState_ComponentFreezeOut(writer, PAD_); }
bool IsRequired() const { return true; }
};
class SavestateEntry_GS : public BaseSavestateEntry
{
public:
virtual ~SavestateEntry_GS() = default;
const char* GetFilename() const { return "GS.bin"; }
void FreezeIn(zip_file_t* zf) const { return SysState_ComponentFreezeIn(zf, GS); }
void FreezeOut(SaveStateBase& writer) const { return SysState_ComponentFreezeOut(writer, GS); }
bool IsRequired() const { return true; }
};
#ifdef ENABLE_ACHIEVEMENTS
class SaveStateEntry_Achievements : public BaseSavestateEntry
{
virtual ~SaveStateEntry_Achievements() override = default;
const char* GetFilename() const override { return "Achievements.bin"; }
void FreezeIn(zip_file_t* zf) const override
{
if (!Achievements::IsActive())
return;
std::optional<std::vector<u8>> data;
if (zf)
data = ReadBinaryFileInZip(zf);
if (data.has_value() && !data->empty())
Achievements::LoadState(data->data(), data->size());
else
Achievements::LoadState(nullptr, 0);
}
void FreezeOut(SaveStateBase& writer) const override
{
if (!Achievements::IsActive())
return;
std::vector<u8> data(Achievements::SaveState());
if (!data.empty())
{
writer.PrepBlock(static_cast<int>(data.size()));
std::memcpy(writer.GetBlockPtr(), data.data(), data.size());
writer.CommitBlock(static_cast<int>(data.size()));
}
}
bool IsRequired() const override { return false; }
};
#endif
// (cpuRegs, iopRegs, VPU/GIF/DMAC structures should all remain as part of a larger unified
// block, since they're all PCSX2-dependent and having separate files in the archie for them
// would not be useful).
//
static const std::unique_ptr<BaseSavestateEntry> SavestateEntries[] = {
std::unique_ptr<BaseSavestateEntry>(new SavestateEntry_EmotionMemory),
std::unique_ptr<BaseSavestateEntry>(new SavestateEntry_IopMemory),
std::unique_ptr<BaseSavestateEntry>(new SavestateEntry_HwRegs),
std::unique_ptr<BaseSavestateEntry>(new SavestateEntry_IopHwRegs),
std::unique_ptr<BaseSavestateEntry>(new SavestateEntry_Scratchpad),
std::unique_ptr<BaseSavestateEntry>(new SavestateEntry_VU0mem),
std::unique_ptr<BaseSavestateEntry>(new SavestateEntry_VU1mem),
std::unique_ptr<BaseSavestateEntry>(new SavestateEntry_VU0prog),
std::unique_ptr<BaseSavestateEntry>(new SavestateEntry_VU1prog),
std::unique_ptr<BaseSavestateEntry>(new SavestateEntry_SPU2),
#ifndef PCSX2_CORE
std::unique_ptr<BaseSavestateEntry>(new SavestateEntry_USB),
#endif
std::unique_ptr<BaseSavestateEntry>(new SavestateEntry_PAD),
std::unique_ptr<BaseSavestateEntry>(new SavestateEntry_GS),
#ifdef ENABLE_ACHIEVEMENTS
std::unique_ptr<BaseSavestateEntry>(new SaveStateEntry_Achievements),
#endif
};
std::unique_ptr<ArchiveEntryList> SaveState_DownloadState()
{
#ifndef PCSX2_CORE
if (!GetCoreThread().HasActiveMachine())
throw Exception::RuntimeError()
.SetDiagMsg("SysExecEvent_DownloadState: Cannot freeze/download an invalid VM state!")
.SetUserMsg("There is no active virtual machine state to download or save.");
#endif
std::unique_ptr<ArchiveEntryList> destlist = std::make_unique<ArchiveEntryList>(new VmStateBuffer("Zippable Savestate"));
memSavingState saveme(destlist->GetBuffer());
ArchiveEntry internals(EntryFilename_InternalStructures);
internals.SetDataIndex(saveme.GetCurrentPos());
saveme.FreezeBios();
saveme.FreezeInternals();
internals.SetDataSize(saveme.GetCurrentPos() - internals.GetDataIndex());
destlist->Add(internals);
for (const std::unique_ptr<BaseSavestateEntry>& entry : SavestateEntries)
{
uint startpos = saveme.GetCurrentPos();
entry->FreezeOut(saveme);
destlist->Add(
ArchiveEntry(entry->GetFilename())
.SetDataIndex(startpos)
.SetDataSize(saveme.GetCurrentPos() - startpos));
}
return destlist;
}
std::unique_ptr<SaveStateScreenshotData> SaveState_SaveScreenshot()
{
static constexpr u32 SCREENSHOT_WIDTH = 640;
static constexpr u32 SCREENSHOT_HEIGHT = 480;
std::vector<u32> pixels(SCREENSHOT_WIDTH * SCREENSHOT_HEIGHT);
if (!GetMTGS().SaveMemorySnapshot(SCREENSHOT_WIDTH, SCREENSHOT_HEIGHT, &pixels))
{
// saving failed for some reason, device lost?
return nullptr;
}
std::unique_ptr<SaveStateScreenshotData> data = std::make_unique<SaveStateScreenshotData>();
data->width = SCREENSHOT_WIDTH;
data->height = SCREENSHOT_HEIGHT;
data->pixels = std::move(pixels);
return data;
}
static bool SaveState_CompressScreenshot(SaveStateScreenshotData* data, zip_t* zf)
{
zip_error_t ze = {};
zip_source_t* const zs = zip_source_buffer_create(nullptr, 0, 0, &ze);
if (!zs)
return false;
if (zip_source_begin_write(zs) != 0)
{
zip_source_free(zs);
return false;
}
ScopedGuard zs_free([zs]() { zip_source_free(zs); });
png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
png_infop info_ptr = nullptr;
if (!png_ptr)
return false;
ScopedGuard cleanup([&png_ptr, &info_ptr]() {
if (png_ptr)
png_destroy_write_struct(&png_ptr, info_ptr ? &info_ptr : nullptr);
});
info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr)
return false;
if (setjmp(png_jmpbuf(png_ptr)))
return false;
png_set_write_fn(png_ptr, zs, [](png_structp png_ptr, png_bytep data_ptr, png_size_t size) {
zip_source_write(static_cast<zip_source_t*>(png_get_io_ptr(png_ptr)), data_ptr, size);
}, [](png_structp png_ptr) {});
png_set_compression_level(png_ptr, 5);
png_set_IHDR(png_ptr, info_ptr, data->width, data->height, 8, PNG_COLOR_TYPE_RGBA,
PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
png_write_info(png_ptr, info_ptr);
for (u32 y = 0; y < data->height; ++y)
{
// ensure the alpha channel is set to opaque
u32* row = &data->pixels[y * data->width];
for (u32 x = 0; x < data->width; x++)
row[x] |= 0xFF000000u;
png_write_row(png_ptr, reinterpret_cast<png_bytep>(row));
}
png_write_end(png_ptr, nullptr);
if (zip_source_commit_write(zs) != 0)
return false;
const s64 file_index = zip_file_add(zf, EntryFilename_Screenshot, zs, 0);
if (file_index < 0)
return false;
// png is already compressed, no point doing it twice
zip_set_file_compression(zf, file_index, ZIP_CM_STORE, 0);
// source is now owned by the zip file for later compression
zs_free.Cancel();
return true;
}
static bool SaveState_ReadScreenshot(zip_t* zf, u32* out_width, u32* out_height, std::vector<u32>* out_pixels)
{
auto zff = zip_fopen_managed(zf, EntryFilename_Screenshot, 0);
if (!zff)
return false;
png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
if (!png_ptr)
return false;
png_infop info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr)
{
png_destroy_read_struct(&png_ptr, nullptr, nullptr);
return false;
}
ScopedGuard cleanup([&png_ptr, &info_ptr]() {
png_destroy_read_struct(&png_ptr, &info_ptr, nullptr);
});
if (setjmp(png_jmpbuf(png_ptr)))
return false;
png_set_read_fn(png_ptr, zff.get(), [](png_structp png_ptr, png_bytep data_ptr, png_size_t size) {
zip_fread(static_cast<zip_file_t*>(png_get_io_ptr(png_ptr)), data_ptr, size);
});
png_read_info(png_ptr, info_ptr);
png_uint_32 width = 0;
png_uint_32 height = 0;
int bitDepth = 0;
int colorType = -1;
if (png_get_IHDR(png_ptr, info_ptr, &width, &height, &bitDepth, &colorType, nullptr, nullptr, nullptr) != 1 ||
width == 0 || height == 0)
{
return false;
}
const png_uint_32 bytesPerRow = png_get_rowbytes(png_ptr, info_ptr);
std::vector<u8> rowData(bytesPerRow);
*out_width = width;
*out_height = height;
out_pixels->resize(width * height);
for (u32 y = 0; y < height; y++)
{
png_read_row(png_ptr, static_cast<png_bytep>(rowData.data()), nullptr);
const u8* row_ptr = rowData.data();
u32* out_ptr = &out_pixels->at(y * width);
if (colorType == PNG_COLOR_TYPE_RGB)
{
for (u32 x = 0; x < width; x++)
{
u32 pixel = static_cast<u32>(*(row_ptr)++);
pixel |= static_cast<u32>(*(row_ptr)++) << 8;
pixel |= static_cast<u32>(*(row_ptr)++) << 16;
pixel |= static_cast<u32>(*(row_ptr)++) << 24;
*(out_ptr++) = pixel | 0xFF000000u; // make opaque
}
}
else if (colorType == PNG_COLOR_TYPE_RGBA)
{
for (u32 x = 0; x < width; x++)
{
u32 pixel;
std::memcpy(&pixel, row_ptr, sizeof(u32));
row_ptr += sizeof(u32);
*(out_ptr++) = pixel | 0xFF000000u; // make opaque
}
}
}
return true;
}
// --------------------------------------------------------------------------------------
// CompressThread_VmState
// --------------------------------------------------------------------------------------
static bool SaveState_AddToZip(zip_t* zf, ArchiveEntryList* srclist, SaveStateScreenshotData* screenshot)
{
// use zstd compression, it can be 10x+ faster for saving.
const u32 compression = EmuConfig.SavestateZstdCompression ? ZIP_CM_ZSTD : ZIP_CM_DEFLATE;
const u32 compression_level = 0;
// version indicator
{
zip_source_t* const zs = zip_source_buffer(zf, &g_SaveVersion, sizeof(g_SaveVersion), 0);
if (!zs)
return false;
// NOTE: Source should not be freed if successful.
const s64 fi = zip_file_add(zf, EntryFilename_StateVersion, zs, ZIP_FL_ENC_UTF_8);
if (fi < 0)
{
zip_source_free(zs);
return false;
}
zip_set_file_compression(zf, fi, ZIP_CM_STORE, 0);
}
const uint listlen = srclist->GetLength();
for (uint i = 0; i < listlen; ++i)
{
const ArchiveEntry& entry = (*srclist)[i];
if (!entry.GetDataSize())
continue;
zip_source_t* const zs = zip_source_buffer(zf, srclist->GetPtr(entry.GetDataIndex()), entry.GetDataSize(), 0);
if (!zs)
return false;
const s64 fi = zip_file_add(zf, entry.GetFilename().c_str(), zs, ZIP_FL_ENC_UTF_8);
if (fi < 0)
{
zip_source_free(zs);
return false;
}
zip_set_file_compression(zf, fi, compression, compression_level);
}
if (screenshot)
{
if (!SaveState_CompressScreenshot(screenshot, zf))
return false;
}
return true;
}
bool SaveState_ZipToDisk(std::unique_ptr<ArchiveEntryList> srclist, std::unique_ptr<SaveStateScreenshotData> screenshot, const char* filename)
{
zip_error_t ze = {};
zip_source_t* zs = zip_source_file_create(filename, 0, 0, &ze);
zip_t* zf = nullptr;
if (zs && !(zf = zip_open_from_source(zs, ZIP_CREATE | ZIP_TRUNCATE, &ze)))
{