Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hrydgard
GitHub Repository: hrydgard/ppsspp
Path: blob/master/Core/Dialog/SavedataParam.cpp
5659 views
1
// Copyright (c) 2012- PPSSPP Project.
2
3
// This program is free software: you can redistribute it and/or modify
4
// it under the terms of the GNU General Public License as published by
5
// the Free Software Foundation, version 2.0 or later versions.
6
7
// This program is distributed in the hope that it will be useful,
8
// but WITHOUT ANY WARRANTY; without even the implied warranty of
9
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10
// GNU General Public License 2.0 for more details.
11
12
// A copy of the GPL 2.0 should have been included with the program.
13
// If not, see http://www.gnu.org/licenses/
14
15
// Official git repository and contact information can be found at
16
// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/.
17
18
#include <algorithm>
19
#include <memory>
20
#include "Common/Log.h"
21
#include "Common/Data/Text/I18n.h"
22
#include "Common/Serialize/Serializer.h"
23
#include "Common/Serialize/SerializeFuncs.h"
24
#include "Common/System/OSD.h"
25
#include "Common/StringUtils.h"
26
#include "Core/Config.h"
27
#include "Core/Reporting.h"
28
#include "Core/System.h"
29
#include "Core/Debugger/MemBlockInfo.h"
30
#include "Core/Dialog/SavedataParam.h"
31
#include "Core/Dialog/PSPSaveDialog.h"
32
#include "Core/FileSystems/MetaFileSystem.h"
33
#include "Core/HLE/sceIo.h"
34
#include "Core/HLE/sceKernelMemory.h"
35
#include "Core/HLE/sceChnnlsv.h"
36
#include "Core/ELF/ParamSFO.h"
37
#include "Core/HW/MemoryStick.h"
38
#include "Core/Util/PPGeDraw.h"
39
40
static const std::string ICON0_FILENAME = "ICON0.PNG";
41
static const std::string ICON1_FILENAME = "ICON1.PMF";
42
static const std::string PIC1_FILENAME = "PIC1.PNG";
43
static const std::string SND0_FILENAME = "SND0.AT3";
44
static const std::string SFO_FILENAME = "PARAM.SFO";
45
46
static const int FILE_LIST_COUNT_MAX = 99;
47
static const u32 FILE_LIST_TOTAL_SIZE = sizeof(SaveSFOFileListEntry) * FILE_LIST_COUNT_MAX;
48
49
static const std::string savePath = "ms0:/PSP/SAVEDATA/";
50
51
namespace
52
{
53
int getSizeNormalized(int size)
54
{
55
int sizeCluster = (int)MemoryStick_SectorSize();
56
return ((int)((size + sizeCluster - 1) / sizeCluster)) * sizeCluster;
57
}
58
59
void SetStringFromSFO(ParamSFOData &sfoFile, const char *name, char *str, int strLength)
60
{
61
truncate_cpy(str, strLength, sfoFile.GetValueString(name));
62
}
63
64
bool ReadPSPFile(const std::string &filename, u8 **data, s64 dataSize, s64 *readSize)
65
{
66
int handle = pspFileSystem.OpenFile(filename, FILEACCESS_READ);
67
if (handle < 0)
68
return false;
69
70
if (dataSize == -1) {
71
// Determine the size through seeking instead of querying.
72
pspFileSystem.SeekFile(handle, 0, FILEMOVE_END);
73
dataSize = pspFileSystem.GetSeekPos(handle);
74
pspFileSystem.SeekFile(handle, 0, FILEMOVE_BEGIN);
75
76
*data = new u8[(size_t)dataSize];
77
}
78
79
size_t result = pspFileSystem.ReadFile(handle, *data, dataSize);
80
pspFileSystem.CloseFile(handle);
81
if (readSize)
82
*readSize = result;
83
84
return result != 0;
85
}
86
87
bool WritePSPFile(const std::string &filename, const u8 *data, SceSize dataSize)
88
{
89
int handle = pspFileSystem.OpenFile(filename, (FileAccess)(FILEACCESS_WRITE | FILEACCESS_CREATE | FILEACCESS_TRUNCATE));
90
if (handle < 0)
91
return false;
92
93
size_t result = pspFileSystem.WriteFile(handle, data, dataSize);
94
pspFileSystem.CloseFile(handle);
95
96
return result == dataSize;
97
}
98
99
PSPFileInfo FileFromListing(const std::vector<PSPFileInfo> &listing, const std::string &filename) {
100
for (const PSPFileInfo &sub : listing) {
101
if (sub.name == filename)
102
return sub;
103
}
104
105
PSPFileInfo info;
106
info.name = filename;
107
info.exists = false;
108
return info;
109
}
110
111
bool PSPMatch(std::string_view text, std::string_view regexp) {
112
if (text.empty() && regexp.empty())
113
return true;
114
else if (regexp == "*")
115
return true;
116
else if (text.empty())
117
return false;
118
else if (regexp.empty())
119
return false;
120
else if (regexp == "?" && text.length() == 1)
121
return true;
122
else if (text == regexp)
123
return true;
124
else if (regexp.data()[0] == '*')
125
{
126
bool res = PSPMatch(text.substr(1),regexp.substr(1));
127
if(!res)
128
res = PSPMatch(text.substr(1),regexp);
129
return res;
130
}
131
else if (regexp.data()[0] == '?')
132
{
133
return PSPMatch(text.substr(1),regexp.substr(1));
134
}
135
else if (regexp.data()[0] == text.data()[0])
136
{
137
return PSPMatch(text.substr(1),regexp.substr(1));
138
}
139
140
return false;
141
}
142
143
int align16(int address)
144
{
145
return (address + 15) & ~15;
146
}
147
148
int GetSDKMainVersion(int sdkVersion)
149
{
150
if(sdkVersion > 0x0307FFFF)
151
return 6;
152
if(sdkVersion > 0x0300FFFF)
153
return 5;
154
if(sdkVersion > 0x0206FFFF)
155
return 4;
156
if(sdkVersion > 0x0205FFFF)
157
return 3;
158
if(sdkVersion >= 0x02000000)
159
return 2;
160
if(sdkVersion >= 0x01000000)
161
return 1;
162
return 0;
163
};
164
}
165
166
void SaveFileInfo::DoState(PointerWrap &p)
167
{
168
auto s = p.Section("SaveFileInfo", 1, 2);
169
if (!s)
170
return;
171
172
Do(p, size);
173
Do(p, saveName);
174
Do(p, idx);
175
176
DoArray(p, title, sizeof(title));
177
DoArray(p, saveTitle, sizeof(saveTitle));
178
DoArray(p, saveDetail, sizeof(saveDetail));
179
180
Do(p, modif_time);
181
182
if (s <= 1) {
183
u32 textureData;
184
int textureWidth;
185
int textureHeight;
186
Do(p, textureData);
187
Do(p, textureWidth);
188
Do(p, textureHeight);
189
190
if (textureData != 0) {
191
// Must be MODE_READ.
192
texture = new PPGeImage("");
193
texture->CompatLoad(textureData, textureWidth, textureHeight);
194
}
195
} else {
196
bool hasTexture = texture != NULL;
197
Do(p, hasTexture);
198
if (hasTexture) {
199
if (p.mode == p.MODE_READ) {
200
delete texture;
201
texture = new PPGeImage("");
202
}
203
if (texture) {
204
texture->DoState(p);
205
}
206
}
207
}
208
}
209
210
SavedataParam::SavedataParam() { }
211
212
void SavedataParam::Init() {
213
// If the folder already exists, this is a no-op.
214
pspFileSystem.MkDir(savePath);
215
// Create a nomedia file to hide save icons form Android image viewer
216
#if PPSSPP_PLATFORM(ANDROID)
217
int handle = pspFileSystem.OpenFile(savePath + ".nomedia", (FileAccess)(FILEACCESS_CREATE | FILEACCESS_WRITE), 0);
218
if (handle >= 0) {
219
pspFileSystem.CloseFile(handle);
220
} else {
221
INFO_LOG(Log::IO, "Failed to create .nomedia file (might be ok if it already exists)");
222
}
223
#endif
224
}
225
226
std::string SavedataParam::GetSaveDirName(const SceUtilitySavedataParam *param, int saveId) const
227
{
228
if (!param) {
229
return "";
230
}
231
232
if (saveId >= 0 && saveNameListDataCount > 0) // if user selection, use it
233
return GetFilename(saveId);
234
else
235
return GetSaveName(param);
236
}
237
238
std::string SavedataParam::GetSaveDir(const SceUtilitySavedataParam *param, const std::string &saveDirName) const
239
{
240
if (!param) {
241
return "";
242
}
243
244
return GetGameName(param) + saveDirName;
245
}
246
247
std::string SavedataParam::GetSaveDir(const SceUtilitySavedataParam *param, int saveId) const
248
{
249
return GetSaveDir(param, GetSaveDirName(param, saveId));
250
}
251
252
std::string SavedataParam::GetSaveFilePath(const SceUtilitySavedataParam *param, const std::string &saveDir) const
253
{
254
if (!param) {
255
return "";
256
}
257
258
if (!saveDir.size())
259
return "";
260
261
return savePath + saveDir;
262
}
263
264
std::string SavedataParam::GetSaveFilePath(const SceUtilitySavedataParam *param, int saveId) const
265
{
266
return GetSaveFilePath(param, GetSaveDir(param, saveId));
267
}
268
269
inline static std::string FixedToString(const char *str, size_t n)
270
{
271
if (!str) {
272
return std::string();
273
} else {
274
return std::string(str, strnlen(str, n));
275
}
276
}
277
278
std::string SavedataParam::GetGameName(const SceUtilitySavedataParam *param) const
279
{
280
return FixedToString(param->gameName, ARRAY_SIZE(param->gameName));
281
}
282
283
std::string SavedataParam::GetSaveName(const SceUtilitySavedataParam *param) const
284
{
285
const std::string saveName = FixedToString(param->saveName, ARRAY_SIZE(param->saveName));
286
if (saveName == "<>")
287
return "";
288
return saveName;
289
}
290
291
std::string SavedataParam::GetFileName(const SceUtilitySavedataParam *param) const
292
{
293
return FixedToString(param->fileName, ARRAY_SIZE(param->fileName));
294
}
295
296
std::string SavedataParam::GetKey(const SceUtilitySavedataParam *param) const
297
{
298
static const char* const lut = "0123456789ABCDEF";
299
300
std::string output;
301
if (HasKey(param))
302
{
303
output.reserve(2 * sizeof(param->key));
304
for (size_t i = 0; i < sizeof(param->key); ++i)
305
{
306
const unsigned char c = param->key[i];
307
output.push_back(lut[c >> 4]);
308
output.push_back(lut[c & 15]);
309
}
310
}
311
return output;
312
}
313
314
bool SavedataParam::HasKey(const SceUtilitySavedataParam *param) const
315
{
316
for (size_t i = 0; i < ARRAY_SIZE(param->key); ++i)
317
{
318
if (param->key[i] != 0)
319
return true;
320
}
321
return false;
322
}
323
324
bool SavedataParam::Delete(SceUtilitySavedataParam* param, int saveId) {
325
if (!param) {
326
return false;
327
}
328
329
// Sanity check, preventing full delete of savedata/ in MGS PW demo (!)
330
if (!strnlen(param->gameName, sizeof(param->gameName)) && param->mode != SCE_UTILITY_SAVEDATA_TYPE_LISTALLDELETE) {
331
ERROR_LOG(Log::sceUtility, "Bad param with gameName empty - cannot delete save directory");
332
return false;
333
}
334
335
std::string dirPath = GetSaveFilePath(param, GetSaveDir(saveId));
336
if (dirPath.size() == 0) {
337
ERROR_LOG(Log::sceUtility, "GetSaveFilePath (%.*s) returned empty - cannot delete save directory. Might already be deleted?", (int)sizeof(param->gameName), param->gameName);
338
return false;
339
}
340
341
if (!pspFileSystem.GetFileInfo(dirPath).exists) {
342
return false;
343
}
344
345
ClearSFOCache();
346
pspFileSystem.RmDir(dirPath);
347
return true;
348
}
349
350
int SavedataParam::DeleteData(SceUtilitySavedataParam* param) {
351
if (!param) {
352
return SCE_UTILITY_SAVEDATA_ERROR_RW_FILE_NOT_FOUND;
353
}
354
355
std::string subFolder = GetGameName(param) + GetSaveName(param);
356
std::string fileName = GetFileName(param);
357
std::string dirPath = savePath + subFolder;
358
std::string filePath = dirPath + "/" + fileName;
359
std::string sfoPath = dirPath + "/" + SFO_FILENAME;
360
361
if (!pspFileSystem.GetFileInfo(dirPath).exists) {
362
return SCE_UTILITY_SAVEDATA_ERROR_RW_NO_DATA;
363
}
364
365
if (!pspFileSystem.GetFileInfo(sfoPath).exists)
366
return SCE_UTILITY_SAVEDATA_ERROR_RW_DATA_BROKEN;
367
368
if (!fileName.empty() && !pspFileSystem.GetFileInfo(filePath).exists) {
369
return SCE_UTILITY_SAVEDATA_ERROR_RW_FILE_NOT_FOUND;
370
}
371
372
if (fileName.empty()) {
373
return 0;
374
}
375
376
if (!subFolder.size()) {
377
ERROR_LOG(Log::sceUtility, "Bad subfolder, ignoring delete of %s", filePath.c_str());
378
return 0;
379
}
380
381
ClearSFOCache();
382
pspFileSystem.RemoveFile(filePath);
383
384
// Update PARAM.SFO to remove the file, if it was in the list.
385
std::shared_ptr<ParamSFOData> sfoFile = LoadCachedSFO(sfoPath);
386
if (sfoFile) {
387
// Note: do not update values such as TITLE in this operation.
388
u32 fileListSize = 0;
389
SaveSFOFileListEntry *fileList = (SaveSFOFileListEntry *)sfoFile->GetValueData("SAVEDATA_FILE_LIST", &fileListSize);
390
size_t fileListCount = fileListSize / sizeof(SaveSFOFileListEntry);
391
bool changed = false;
392
for (size_t i = 0; i < fileListCount; ++i) {
393
if (strncmp(fileList[i].filename, fileName.c_str(), sizeof(fileList[i].filename)) != 0)
394
continue;
395
396
memset(fileList[i].filename, 0, sizeof(fileList[i].filename));
397
memset(fileList[i].hash, 0, sizeof(fileList[i].hash));
398
changed = true;
399
break;
400
}
401
402
if (changed) {
403
auto updatedList = std::make_unique<u8[]> (fileListSize);
404
memcpy(updatedList.get(), fileList, fileListSize);
405
sfoFile->SetValue("SAVEDATA_FILE_LIST", updatedList.get(), fileListSize, (int)FILE_LIST_TOTAL_SIZE);
406
407
u8 *sfoData;
408
size_t sfoSize;
409
sfoFile->WriteSFO(&sfoData, &sfoSize);
410
411
ClearSFOCache();
412
WritePSPFile(sfoPath, sfoData, (SceSize)sfoSize);
413
delete[] sfoData;
414
}
415
}
416
417
return 0;
418
}
419
420
int SavedataParam::Save(SceUtilitySavedataParam* param, const std::string &saveDirName, bool secureMode) {
421
if (!param) {
422
return SCE_UTILITY_SAVEDATA_ERROR_SAVE_MS_NOSPACE;
423
}
424
if (param->dataSize > param->dataBufSize) {
425
ERROR_LOG_REPORT(Log::sceUtility, "Savedata buffer overflow: %d / %d", param->dataSize, param->dataBufSize);
426
return SCE_UTILITY_SAVEDATA_ERROR_RW_BAD_PARAMS;
427
}
428
auto validateSize = [](const PspUtilitySavedataFileData &data) {
429
if (data.buf.IsValid() && data.bufSize < data.size) {
430
ERROR_LOG_REPORT(Log::sceUtility, "Savedata subdata buffer overflow: %d / %d", data.size, data.bufSize);
431
return false;
432
}
433
return true;
434
};
435
if (!validateSize(param->icon0FileData) || !validateSize(param->icon1FileData) || !validateSize(param->pic1FileData) || !validateSize(param->snd0FileData)) {
436
return SCE_UTILITY_SAVEDATA_ERROR_RW_BAD_PARAMS;
437
}
438
439
if (param->secureVersion > 3) {
440
ERROR_LOG_REPORT(Log::sceUtility, "Savedata version requested on save: %d", param->secureVersion);
441
return SCE_UTILITY_SAVEDATA_ERROR_SAVE_PARAM;
442
} else if (param->secureVersion != 0) {
443
if (param->secureVersion != 1 && !HasKey(param) && secureMode) {
444
ERROR_LOG_REPORT(Log::sceUtility, "Savedata version with missing key on save: %d", param->secureVersion);
445
return SCE_UTILITY_SAVEDATA_ERROR_SAVE_PARAM;
446
}
447
INFO_LOG(Log::sceUtility, "Savedata version requested on save: %d", param->secureVersion);
448
}
449
450
std::string dirPath = GetSaveFilePath(param, GetSaveDir(param, saveDirName));
451
452
if (!pspFileSystem.GetFileInfo(dirPath).exists) {
453
if (!pspFileSystem.MkDir(dirPath)) {
454
auto err = GetI18NCategory(I18NCat::ERRORS);
455
g_OSD.Show(OSDType::MESSAGE_ERROR, err->T("Unable to write savedata, disk may be full"));
456
}
457
}
458
459
u8* cryptedData = nullptr;
460
int cryptedSize = 0;
461
u8 cryptedHash[0x10]{};
462
// Encrypt save.
463
// TODO: Is this the correct difference between MAKEDATA and MAKEDATASECURE?
464
if (param->dataBuf.IsValid() && g_Config.bEncryptSave && secureMode)
465
{
466
cryptedSize = param->dataSize;
467
if (cryptedSize == 0 || (SceSize)cryptedSize > param->dataBufSize) {
468
ERROR_LOG(Log::sceUtility, "Bad cryptedSize %d", cryptedSize);
469
cryptedSize = param->dataBufSize; // fallback, should never use this
470
}
471
u8 *data_ = param->dataBuf;
472
473
int aligned_len = align16(cryptedSize);
474
if (aligned_len != cryptedSize) {
475
WARN_LOG(Log::sceUtility, "cryptedSize unaligned: %d (%d)", cryptedSize, cryptedSize & 15);
476
}
477
478
cryptedData = new u8[aligned_len + 0x10]();
479
memcpy(cryptedData, data_, cryptedSize);
480
// EncryptData will do a memmove to make room for the key in front.
481
// Technically we could just copy it into place here to avoid that.
482
483
int decryptMode = DetermineCryptMode(param);
484
bool hasKey = decryptMode > 1;
485
if (hasKey && !HasKey(param)) {
486
delete[] cryptedData;
487
return SCE_UTILITY_SAVEDATA_ERROR_SAVE_PARAM;
488
}
489
490
if (EncryptData(decryptMode, cryptedData, &cryptedSize, &aligned_len, cryptedHash, (hasKey ? param->key : 0)) != 0) {
491
auto err = GetI18NCategory(I18NCat::ERRORS);
492
g_OSD.Show(OSDType::MESSAGE_WARNING, err->T("Save encryption failed. This save won't work on real PSP"), 6.0f);
493
ERROR_LOG(Log::sceUtility,"Save encryption failed. This save won't work on real PSP");
494
delete[] cryptedData;
495
cryptedData = 0;
496
}
497
}
498
499
// SAVE PARAM.SFO
500
std::string sfopath = dirPath + "/" + SFO_FILENAME;
501
std::shared_ptr<ParamSFOData> sfoFile = LoadCachedSFO(sfopath, true);
502
503
// This was added in #18430, see below.
504
bool subWrite = param->mode == SCE_UTILITY_SAVEDATA_TYPE_WRITEDATASECURE || param->mode == SCE_UTILITY_SAVEDATA_TYPE_WRITEDATA;
505
bool wasCrypted = GetSaveCryptMode(param, saveDirName) != 0;
506
507
// Update values. NOTE! #18430 made this conditional on !subWrite, but this is not correct, as it causes #18687.
508
// So now we do a hacky trick and just check for a valid title before we proceed with updating the sfoFile.
509
if (strnlen(param->sfoParam.title, sizeof(param->sfoParam.title)) > 0) {
510
sfoFile->SetValue("TITLE", param->sfoParam.title, 128);
511
sfoFile->SetValue("SAVEDATA_TITLE", param->sfoParam.savedataTitle, 128);
512
sfoFile->SetValue("SAVEDATA_DETAIL", param->sfoParam.detail, 1024);
513
sfoFile->SetValue("PARENTAL_LEVEL", param->sfoParam.parentalLevel, 4);
514
sfoFile->SetValue("CATEGORY", "MS", 4);
515
sfoFile->SetValue("SAVEDATA_DIRECTORY", GetSaveDir(param, saveDirName), 64);
516
}
517
518
// Always write and update the file list.
519
// For each file, 13 bytes for filename, 16 bytes for file hash (0 in PPSSPP), 3 byte for padding
520
u32 tmpDataSize = 0;
521
SaveSFOFileListEntry *tmpDataOrig = (SaveSFOFileListEntry *)sfoFile->GetValueData("SAVEDATA_FILE_LIST", &tmpDataSize);
522
SaveSFOFileListEntry *updatedList = new SaveSFOFileListEntry[FILE_LIST_COUNT_MAX];
523
if (tmpDataSize != 0)
524
memcpy(updatedList, tmpDataOrig, std::min(tmpDataSize, FILE_LIST_TOTAL_SIZE));
525
if (tmpDataSize < FILE_LIST_TOTAL_SIZE)
526
memset(updatedList + tmpDataSize, 0, FILE_LIST_TOTAL_SIZE - tmpDataSize);
527
// Leave a hash there and unchanged if it was already there.
528
if (secureMode && param->dataBuf.IsValid()) {
529
const std::string saveFilename = GetFileName(param);
530
for (auto entry = updatedList; entry < updatedList + FILE_LIST_COUNT_MAX; ++entry) {
531
if (entry->filename[0] != '\0') {
532
if (strncmp(entry->filename, saveFilename.c_str(), sizeof(entry->filename)) != 0)
533
continue;
534
}
535
536
snprintf(entry->filename, sizeof(entry->filename), "%s", saveFilename.c_str());
537
memcpy(entry->hash, cryptedHash, 16);
538
break;
539
}
540
}
541
542
sfoFile->SetValue("SAVEDATA_FILE_LIST", (u8 *)updatedList, FILE_LIST_TOTAL_SIZE, (int)FILE_LIST_TOTAL_SIZE);
543
delete[] updatedList;
544
545
// Init param with 0. This will be used to detect crypted save or not on loading
546
u8 zeroes[128]{};
547
sfoFile->SetValue("SAVEDATA_PARAMS", zeroes, 128, 128);
548
549
u8 *sfoData;
550
size_t sfoSize;
551
sfoFile->WriteSFO(&sfoData, &sfoSize);
552
553
// Calc SFO hash for PSP.
554
if (cryptedData != 0 || (subWrite && wasCrypted)) {
555
int offset = sfoFile->GetDataOffset(sfoData, "SAVEDATA_PARAMS");
556
if (offset >= 0)
557
UpdateHash(sfoData, (int)sfoSize, offset, DetermineCryptMode(param));
558
}
559
560
ClearSFOCache();
561
WritePSPFile(sfopath, sfoData, (SceSize)sfoSize);
562
delete[] sfoData;
563
sfoData = nullptr;
564
565
if(param->dataBuf.IsValid()) // Can launch save without save data in mode 13
566
{
567
std::string fileName = GetFileName(param);
568
std::string filePath = dirPath + "/" + fileName;
569
u8 *data_ = 0;
570
SceSize saveSize = 0;
571
if(cryptedData == 0) // Save decrypted data
572
{
573
saveSize = param->dataSize;
574
if(saveSize == 0 || saveSize > param->dataBufSize)
575
saveSize = param->dataBufSize; // fallback, should never use this
576
577
data_ = param->dataBuf;
578
}
579
else
580
{
581
data_ = cryptedData;
582
saveSize = cryptedSize;
583
}
584
585
INFO_LOG(Log::sceUtility,"Saving file with size %u in %s",saveSize,filePath.c_str());
586
587
// copy back save name in request
588
strncpy(param->saveName, saveDirName.c_str(), 20);
589
590
if (!fileName.empty()) {
591
if (!WritePSPFile(filePath, data_, saveSize)) {
592
ERROR_LOG(Log::sceUtility, "Error writing file %s", filePath.c_str());
593
delete[] cryptedData;
594
return SCE_UTILITY_SAVEDATA_ERROR_SAVE_MS_NOSPACE;
595
}
596
}
597
delete[] cryptedData;
598
}
599
600
// SAVE ICON0
601
if (param->icon0FileData.buf.IsValid())
602
{
603
std::string icon0path = dirPath + "/" + ICON0_FILENAME;
604
WritePSPFile(icon0path, param->icon0FileData.buf, param->icon0FileData.size);
605
}
606
// SAVE ICON1
607
if (param->icon1FileData.buf.IsValid())
608
{
609
std::string icon1path = dirPath + "/" + ICON1_FILENAME;
610
WritePSPFile(icon1path, param->icon1FileData.buf, param->icon1FileData.size);
611
}
612
// SAVE PIC1
613
if (param->pic1FileData.buf.IsValid())
614
{
615
std::string pic1path = dirPath + "/" + PIC1_FILENAME;
616
WritePSPFile(pic1path, param->pic1FileData.buf, param->pic1FileData.size);
617
}
618
// Save SND
619
if (param->snd0FileData.buf.IsValid())
620
{
621
std::string snd0path = dirPath + "/" + SND0_FILENAME;
622
WritePSPFile(snd0path, param->snd0FileData.buf, param->snd0FileData.size);
623
}
624
return 0;
625
}
626
627
int SavedataParam::Load(SceUtilitySavedataParam *param, const std::string &saveDirName, int saveId, bool secureMode) {
628
if (!param) {
629
return SCE_UTILITY_SAVEDATA_ERROR_LOAD_NO_DATA;
630
}
631
632
bool isRWMode = param->mode == SCE_UTILITY_SAVEDATA_TYPE_READDATA || param->mode == SCE_UTILITY_SAVEDATA_TYPE_READDATASECURE;
633
634
std::string dirPath = GetSaveFilePath(param, GetSaveDir(param, saveDirName));
635
std::string fileName = GetFileName(param);
636
std::string filePath = dirPath + "/" + fileName;
637
638
if (!pspFileSystem.GetFileInfo(dirPath).exists) {
639
return isRWMode ? SCE_UTILITY_SAVEDATA_ERROR_RW_NO_DATA : SCE_UTILITY_SAVEDATA_ERROR_LOAD_NO_DATA;
640
}
641
642
if (!fileName.empty() && !pspFileSystem.GetFileInfo(filePath).exists) {
643
return isRWMode ? SCE_UTILITY_SAVEDATA_ERROR_RW_FILE_NOT_FOUND : SCE_UTILITY_SAVEDATA_ERROR_LOAD_FILE_NOT_FOUND;
644
}
645
646
// If it wasn't zero, force to zero before loading and especially in case of error.
647
// This isn't reset if the path doesn't even exist.
648
param->dataSize = 0;
649
int result = LoadSaveData(param, saveDirName, dirPath, secureMode);
650
if (result != 0)
651
return result;
652
653
// Load sfo
654
if (!LoadSFO(param, dirPath)) {
655
WARN_LOG(Log::sceUtility, "Load: Failed to load SFO from %s", dirPath.c_str());
656
return isRWMode ? SCE_UTILITY_SAVEDATA_ERROR_RW_DATA_BROKEN : SCE_UTILITY_SAVEDATA_ERROR_LOAD_DATA_BROKEN;
657
}
658
659
// Don't know what it is, but PSP always respond this and this unlock some game
660
param->bind = 1021;
661
662
// Load other files, seems these are required by some games, e.g. Fushigi no Dungeon Fuurai no Shiren 4 Plus.
663
664
// Load ICON0.PNG
665
LoadFile(dirPath, ICON0_FILENAME, &param->icon0FileData);
666
// Load ICON1.PNG
667
LoadFile(dirPath, ICON1_FILENAME, &param->icon1FileData);
668
// Load PIC1.PNG
669
LoadFile(dirPath, PIC1_FILENAME, &param->pic1FileData);
670
// Load SND0.AT3
671
LoadFile(dirPath, SND0_FILENAME, &param->snd0FileData);
672
673
return 0;
674
}
675
676
int SavedataParam::LoadSaveData(SceUtilitySavedataParam *param, const std::string &saveDirName, const std::string &dirPath, bool secureMode) {
677
if (param->secureVersion > 3) {
678
ERROR_LOG_REPORT(Log::sceUtility, "Savedata version requested: %d", param->secureVersion);
679
return SCE_UTILITY_SAVEDATA_ERROR_LOAD_PARAM;
680
} else if (param->secureVersion != 0) {
681
if (param->secureVersion != 1 && !HasKey(param) && secureMode) {
682
ERROR_LOG_REPORT(Log::sceUtility, "Savedata version with missing key: %d", param->secureVersion);
683
return SCE_UTILITY_SAVEDATA_ERROR_LOAD_PARAM;
684
}
685
WARN_LOG_REPORT(Log::sceUtility, "Savedata version requested: %d", param->secureVersion);
686
}
687
688
std::string filename = GetFileName(param);
689
std::string filePath = dirPath + "/" + filename;
690
// Blank filename always means success, if secureVersion was correct.
691
if (filename.empty())
692
return 0;
693
694
s64 readSize;
695
INFO_LOG(Log::sceUtility, "Loading file with size %u in %s", param->dataBufSize, filePath.c_str());
696
u8 *saveData = nullptr;
697
int saveSize = -1;
698
if (!ReadPSPFile(filePath, &saveData, saveSize, &readSize)) {
699
ERROR_LOG(Log::sceUtility,"Error reading file %s",filePath.c_str());
700
return SCE_UTILITY_SAVEDATA_ERROR_LOAD_NO_DATA;
701
}
702
saveSize = (int)readSize;
703
704
// copy back save name in request
705
strncpy(param->saveName, saveDirName.c_str(), 20);
706
707
int prevCryptMode = GetSaveCryptMode(param, saveDirName);
708
bool isCrypted = prevCryptMode != 0 && secureMode;
709
bool saveDone = false;
710
u32 loadedSize = 0;
711
if (isCrypted) {
712
if (DetermineCryptMode(param) > 1 && !HasKey(param)) {
713
return SCE_UTILITY_SAVEDATA_ERROR_LOAD_PARAM;
714
}
715
u8 hash[16];
716
bool hasExpectedHash = GetExpectedHash(dirPath, filename, hash);
717
loadedSize = LoadCryptedSave(param, param->dataBuf, saveData, saveSize, prevCryptMode, hasExpectedHash ? hash : nullptr, saveDone);
718
// TODO: Should return SCE_UTILITY_SAVEDATA_ERROR_LOAD_DATA_BROKEN here if !saveDone.
719
}
720
if (!saveDone) {
721
loadedSize = LoadNotCryptedSave(param, param->dataBuf, saveData, saveSize);
722
}
723
delete[] saveData;
724
725
// Ignore error codes.
726
if (loadedSize != 0 && (loadedSize & 0x80000000) == 0) {
727
std::string tag = "LoadSaveData/" + filePath;
728
NotifyMemInfo(MemBlockFlags::WRITE, param->dataBuf.ptr, loadedSize, tag.c_str(), tag.size());
729
}
730
731
if ((loadedSize & 0x80000000) != 0)
732
return loadedSize;
733
734
param->dataSize = (SceSize)saveSize;
735
return 0;
736
}
737
738
int SavedataParam::DetermineCryptMode(const SceUtilitySavedataParam *param) const {
739
int decryptMode = 1;
740
if (param->secureVersion == 1) {
741
decryptMode = 1;
742
} else if (param->secureVersion == 2) {
743
decryptMode = 3;
744
} else if (param->secureVersion == 3) {
745
decryptMode = GetSDKMainVersion(sceKernelGetCompiledSdkVersion()) >= 4 ? 5 : 1;
746
} else if (HasKey(param)) {
747
// TODO: This should ignore HasKey(), which would trigger errors. Not doing that yet to play it safe.
748
decryptMode = GetSDKMainVersion(sceKernelGetCompiledSdkVersion()) >= 4 ? 5 : 3;
749
}
750
return decryptMode;
751
}
752
753
u32 SavedataParam::LoadCryptedSave(SceUtilitySavedataParam *param, u8 *data, const u8 *saveData, int &saveSize, int prevCryptMode, const u8 *expectedHash, bool &saveDone) {
754
int orig_size = saveSize;
755
int align_len = align16(saveSize);
756
u8 *data_base = new u8[align_len];
757
u8 *cryptKey = new u8[0x10];
758
759
int decryptMode = DetermineCryptMode(param);
760
const int detectedMode = decryptMode;
761
bool hasKey;
762
763
auto resetData = [&](int mode) {
764
saveSize = orig_size;
765
align_len = align16(saveSize);
766
hasKey = mode > 1;
767
768
if (hasKey) {
769
memcpy(cryptKey, param->key, 0x10);
770
}
771
memcpy(data_base, saveData, saveSize);
772
memset(data_base + saveSize, 0, align_len - saveSize);
773
};
774
resetData(decryptMode);
775
776
if (decryptMode != prevCryptMode) {
777
if (prevCryptMode == 1 && param->key[0] == 0) {
778
// Backwards compat for a bug we used to have.
779
WARN_LOG(Log::sceUtility, "Savedata loading with hashmode %d instead of detected %d", prevCryptMode, decryptMode);
780
decryptMode = prevCryptMode;
781
782
// Don't notify the user if we're not going to upgrade the save.
783
if (!g_Config.bEncryptSave) {
784
auto di = GetI18NCategory(I18NCat::DIALOG);
785
g_OSD.Show(OSDType::MESSAGE_WARNING, di->T("When you save, it will load on a PSP, but not an older PPSSPP"), 6.0f);
786
g_OSD.Show(OSDType::MESSAGE_WARNING, di->T("Old savedata detected"), 6.0f);
787
}
788
} else {
789
if (decryptMode == 5 && prevCryptMode == 3) {
790
WARN_LOG(Log::sceUtility, "Savedata loading with detected hashmode %d instead of file's %d", decryptMode, prevCryptMode);
791
} else {
792
WARN_LOG_REPORT(Log::sceUtility, "Savedata loading with detected hashmode %d instead of file's %d", decryptMode, prevCryptMode);
793
}
794
795
decryptMode = prevCryptMode;
796
auto di = GetI18NCategory(I18NCat::DIALOG);
797
g_OSD.Show(OSDType::MESSAGE_WARNING, di->T("When you save, it will not work on outdated PSP Firmware anymore"), 6.0f);
798
g_OSD.Show(OSDType::MESSAGE_WARNING, di->T("Old savedata detected"), 6.0f);
799
}
800
hasKey = decryptMode > 1;
801
}
802
803
int err = DecryptData(decryptMode, data_base, &saveSize, &align_len, hasKey ? cryptKey : nullptr, expectedHash);
804
// Perhaps the file had the wrong mode....
805
if (err != 0 && detectedMode != decryptMode) {
806
resetData(detectedMode);
807
err = DecryptData(detectedMode, data_base, &saveSize, &align_len, hasKey ? cryptKey : nullptr, expectedHash);
808
}
809
// TODO: Should return an error, but let's just try with a bad hash.
810
if (err != 0 && expectedHash != nullptr) {
811
WARN_LOG(Log::sceUtility, "Incorrect hash on save data, likely corrupt");
812
resetData(decryptMode);
813
err = DecryptData(decryptMode, data_base, &saveSize, &align_len, hasKey ? cryptKey : nullptr, nullptr);
814
}
815
816
u32 sz = 0;
817
if (err == 0) {
818
if (param->dataBuf.IsValid()) {
819
if ((u32)saveSize > param->dataBufSize || !Memory::IsValidRange(param->dataBuf.ptr, saveSize)) {
820
sz = SCE_UTILITY_SAVEDATA_ERROR_LOAD_DATA_BROKEN;
821
} else {
822
sz = (u32)saveSize;
823
memcpy(data, data_base, sz);
824
}
825
}
826
saveDone = true;
827
}
828
delete[] data_base;
829
delete[] cryptKey;
830
831
return sz;
832
}
833
834
u32 SavedataParam::LoadNotCryptedSave(SceUtilitySavedataParam *param, u8 *data, u8 *saveData, int &saveSize) {
835
if (param->dataBuf.IsValid()) {
836
if ((u32)saveSize > param->dataBufSize || !Memory::IsValidRange(param->dataBuf.ptr, saveSize)) {
837
return SCE_UTILITY_SAVEDATA_ERROR_LOAD_DATA_BROKEN;
838
}
839
memcpy(data, saveData, saveSize);
840
return saveSize;
841
}
842
return 0;
843
}
844
845
bool SavedataParam::LoadSFO(SceUtilitySavedataParam *param, const std::string& dirPath) {
846
std::string sfopath = dirPath + "/" + SFO_FILENAME;
847
std::shared_ptr<ParamSFOData> sfoFile = LoadCachedSFO(sfopath);
848
if (sfoFile) {
849
// copy back info in request
850
strncpy(param->sfoParam.title, sfoFile->GetValueString("TITLE").c_str(), 128);
851
strncpy(param->sfoParam.savedataTitle, sfoFile->GetValueString("SAVEDATA_TITLE").c_str(), 128);
852
strncpy(param->sfoParam.detail, sfoFile->GetValueString("SAVEDATA_DETAIL").c_str(), 1024);
853
param->sfoParam.parentalLevel = sfoFile->GetValueInt("PARENTAL_LEVEL");
854
return true;
855
}
856
return false;
857
}
858
859
std::vector<SaveSFOFileListEntry> SavedataParam::GetSFOEntries(const std::string &dirPath) {
860
std::vector<SaveSFOFileListEntry> result;
861
const std::string sfoPath = dirPath + "/" + SFO_FILENAME;
862
863
std::shared_ptr<ParamSFOData> sfoFile = LoadCachedSFO(sfoPath);
864
if (!sfoFile) {
865
return result;
866
}
867
868
u32 sfoFileListSize = 0;
869
SaveSFOFileListEntry *sfoFileList = (SaveSFOFileListEntry *)sfoFile->GetValueData("SAVEDATA_FILE_LIST", &sfoFileListSize);
870
const u32 count = std::min((u32)FILE_LIST_COUNT_MAX, sfoFileListSize / (u32)sizeof(SaveSFOFileListEntry));
871
872
for (u32 i = 0; i < count; ++i) {
873
if (sfoFileList[i].filename[0] != '\0')
874
result.push_back(sfoFileList[i]);
875
}
876
877
return result;
878
}
879
880
std::set<std::string> SavedataParam::GetSecureFileNames(const std::string &dirPath) {
881
auto entries = GetSFOEntries(dirPath);
882
883
std::set<std::string> secureFileNames;
884
for (const auto &entry : entries) {
885
char temp[14]{};
886
truncate_cpy(temp, entry.filename);
887
secureFileNames.insert(temp);
888
}
889
return secureFileNames;
890
}
891
892
bool SavedataParam::GetExpectedHash(const std::string &dirPath, const std::string &filename, u8 hash[16]) {
893
auto entries = GetSFOEntries(dirPath);
894
895
for (const auto &entry : entries) {
896
if (strncmp(entry.filename, filename.c_str(), sizeof(entry.filename)) == 0) {
897
memcpy(hash, entry.hash, sizeof(entry.hash));
898
return true;
899
}
900
}
901
return false;
902
}
903
904
void SavedataParam::LoadFile(const std::string& dirPath, const std::string& filename, PspUtilitySavedataFileData *fileData) {
905
std::string filePath = dirPath + "/" + filename;
906
if (!fileData->buf.IsValid())
907
return;
908
909
u8 *buf = fileData->buf;
910
u32 size = Memory::ClampValidSizeAt(fileData->buf.ptr, fileData->bufSize);
911
s64 readSize = -1;
912
if (ReadPSPFile(filePath, &buf, size, &readSize)) {
913
fileData->size = readSize;
914
const std::string tag = "SavedataLoad/" + filePath;
915
NotifyMemInfo(MemBlockFlags::WRITE, fileData->buf.ptr, fileData->size, tag.c_str(), tag.size());
916
INFO_LOG(Log::sceUtility, "Loaded subfile %s (size: %d bytes) into %08x", filePath.c_str(), fileData->size, fileData->buf.ptr);
917
} else {
918
WARN_LOG(Log::sceUtility, "Failed to load subfile %s into %08x", filePath.c_str(), fileData->buf.ptr);
919
}
920
}
921
922
// Note: The work is done in-place, hence the memmove etc.
923
int SavedataParam::EncryptData(unsigned int mode, unsigned char *data, int *dataLen, int *alignedLen, unsigned char *hash, const u8 *cryptkey) {
924
pspChnnlsvContext1 ctx1{};
925
pspChnnlsvContext2 ctx2{};
926
927
INFO_LOG(Log::sceUtility, "EncryptData(mode=%d, *dataLen=%d, *alignedLen=%d)", mode, *dataLen, *alignedLen);
928
929
/* Make room for the IV in front of the data. */
930
memmove(data + 0x10, data, *alignedLen);
931
932
/* Set up buffers */
933
memset(hash, 0, 0x10);
934
935
// Zero out the IV before we begin.
936
memset(data, 0, 0x10);
937
938
/* Build the 0x10-byte IV and setup encryption */
939
if (sceSdCipherInit(ctx2, mode, 1, data, cryptkey) < 0)
940
return -1;
941
if (sceSdMacInit(ctx1, mode) < 0)
942
return -2;
943
if (sceSdMacUpdate(ctx1, data, 0x10) < 0)
944
return -3;
945
if (sceSdCipherUpdate(ctx2, data + 0x10, *alignedLen) < 0)
946
return -4;
947
948
/* Clear any extra bytes left from the previous steps */
949
memset(data + 0x10 + *dataLen, 0, *alignedLen - *dataLen);
950
951
/* Encrypt the data */
952
if (sceSdMacUpdate(ctx1, data + 0x10, *alignedLen) < 0)
953
return -5;
954
955
/* Verify encryption */
956
if (sceSdCipherFinal(ctx2) < 0)
957
return -6;
958
959
/* Build the file hash from this PSP */
960
if (sceSdMacFinal(ctx1, hash, cryptkey) < 0)
961
return -7;
962
963
/* Adjust sizes to account for IV */
964
*alignedLen += 0x10;
965
*dataLen += 0x10;
966
967
/* All done */
968
return 0;
969
}
970
971
// Note: The work is done in-place, hence the memmove etc.
972
int SavedataParam::DecryptData(unsigned int mode, unsigned char *data, int *dataLen, int *alignedLen, const u8 *cryptkey, const u8 *expectedHash) {
973
pspChnnlsvContext1 ctx1{};
974
pspChnnlsvContext2 ctx2{};
975
976
/* Need a 16-byte IV plus some data */
977
if (*alignedLen <= 0x10)
978
return -1;
979
*dataLen -= 0x10;
980
*alignedLen -= 0x10;
981
982
/* Perform the magic */
983
if (sceSdMacInit(ctx1, mode) < 0)
984
return -2;
985
if (sceSdCipherInit(ctx2, mode, 2, data, cryptkey) < 0)
986
return -3;
987
if (sceSdMacUpdate(ctx1, data, 0x10) < 0)
988
return -4;
989
if (sceSdMacUpdate(ctx1, data + 0x10, *alignedLen) < 0)
990
return -5;
991
if (sceSdCipherUpdate(ctx2, data + 0x10, *alignedLen) < 0)
992
return -6;
993
994
/* Verify that it decrypted correctly */
995
if (sceSdCipherFinal(ctx2) < 0)
996
return -7;
997
998
if (expectedHash) {
999
u8 hash[16];
1000
if (sceSdMacFinal(ctx1, hash, cryptkey) < 0)
1001
return -7;
1002
if (memcmp(hash, expectedHash, sizeof(hash)) != 0)
1003
return -8;
1004
}
1005
1006
/* The decrypted data starts at data + 0x10, so shift it back. */
1007
memmove(data, data + 0x10, *dataLen);
1008
return 0;
1009
}
1010
1011
// Requires sfoData to be padded with zeroes to the next 16-byte boundary (due to BuildHash)
1012
int SavedataParam::UpdateHash(u8 *sfoData, int sfoSize, int sfoDataParamsOffset, int encryptmode) {
1013
int alignedLen = align16(sfoSize);
1014
memset(sfoData + sfoDataParamsOffset, 0, 128);
1015
u8 filehash[16];
1016
int ret = 0;
1017
1018
int firstHashMode = encryptmode & 2 ? 4 : 2;
1019
int secondHashMode = encryptmode & 2 ? 3 : 0;
1020
if (encryptmode & 4) {
1021
firstHashMode = 6;
1022
secondHashMode = 5;
1023
}
1024
1025
// Compute 11D0 hash over entire file
1026
if ((ret = BuildHash(filehash, sfoData, sfoSize, alignedLen, firstHashMode, 0)) < 0)
1027
{
1028
// Not sure about "2"
1029
return ret - 400;
1030
}
1031
1032
// Copy 11D0 hash to param.sfo and set flag indicating it's there
1033
memcpy(sfoData + sfoDataParamsOffset + 0x20, filehash, 0x10);
1034
*(sfoData + sfoDataParamsOffset) |= 0x01;
1035
1036
// If new encryption mode, compute and insert the 1220 hash.
1037
if (encryptmode & 6)
1038
{
1039
/* Enable the hash bit first */
1040
*(sfoData+sfoDataParamsOffset) |= (encryptmode & 6) << 4;
1041
1042
if ((ret = BuildHash(filehash, sfoData, sfoSize, alignedLen, secondHashMode, 0)) < 0)
1043
{
1044
return ret - 500;
1045
}
1046
memcpy(sfoData+sfoDataParamsOffset + 0x70, filehash, 0x10);
1047
}
1048
1049
/* Compute and insert the 11C0 hash. */
1050
if ((ret = BuildHash(filehash, sfoData, sfoSize, alignedLen, 1, 0)) < 0)
1051
{
1052
return ret - 600;
1053
}
1054
memcpy(sfoData+sfoDataParamsOffset + 0x10, filehash, 0x10);
1055
1056
/* All done. */
1057
return 0;
1058
}
1059
1060
// Requires sfoData to be padded with zeroes to the next 16-byte boundary.
1061
int SavedataParam::BuildHash(uint8_t *output,
1062
const uint8_t *data,
1063
unsigned int len,
1064
unsigned int alignedLen,
1065
int mode,
1066
const uint8_t *cryptkey) {
1067
pspChnnlsvContext1 ctx1;
1068
1069
/* Set up buffers */
1070
memset(&ctx1, 0, sizeof(pspChnnlsvContext1));
1071
memset(output, 0, 0x10);
1072
1073
/* Perform the magic */
1074
if (sceSdMacInit(ctx1, mode & 0xFF) < 0)
1075
return -1;
1076
if (sceSdMacUpdate(ctx1, data, alignedLen) < 0)
1077
return -2;
1078
if (sceSdMacFinal(ctx1, output, cryptkey) < 0)
1079
{
1080
// Got here since Kirk CMD5 missing, return random value;
1081
memset(output,0x1,0x10);
1082
return 0;
1083
}
1084
/* All done. */
1085
return 0;
1086
}
1087
1088
// TODO: Merge with NiceSizeFormat? That one has a decimal though.
1089
std::string SavedataParam::GetSpaceText(u64 size, bool roundUp)
1090
{
1091
char text[50];
1092
static const char * const suffixes[] = {"B", "KB", "MB", "GB"};
1093
for (size_t i = 0; i < ARRAY_SIZE(suffixes); ++i)
1094
{
1095
if (size < 1024)
1096
{
1097
snprintf(text, sizeof(text), "%lld %s", size, suffixes[i]);
1098
return std::string(text);
1099
}
1100
if (roundUp) {
1101
size = (size + 1023) / 1024;
1102
} else {
1103
size /= 1024;
1104
}
1105
}
1106
snprintf(text, sizeof(text), "%llu TB", size);
1107
return std::string(text);
1108
}
1109
1110
inline std::string FmtPspTime(const ScePspDateTime &dt) {
1111
return StringFromFormat("%04d-%02d-%02d %02d:%02d:%02d.%06d", dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond);
1112
}
1113
1114
int SavedataParam::GetSizes(SceUtilitySavedataParam *param) {
1115
if (!param) {
1116
return SCE_UTILITY_SAVEDATA_ERROR_SIZES_NO_DATA;
1117
}
1118
1119
int ret = 0;
1120
if (param->msFree.IsValid())
1121
{
1122
const u64 freeBytes = MemoryStick_FreeSpace(GetGameName(param));
1123
param->msFree->clusterSize = (u32)MemoryStick_SectorSize();
1124
param->msFree->freeClusters = (u32)(freeBytes / MemoryStick_SectorSize());
1125
param->msFree->freeSpaceKB = (u32)(freeBytes / 0x400);
1126
const std::string spaceTxt = SavedataParam::GetSpaceText(freeBytes, false);
1127
memset(param->msFree->freeSpaceStr, 0, sizeof(param->msFree->freeSpaceStr));
1128
strncpy(param->msFree->freeSpaceStr, spaceTxt.c_str(), sizeof(param->msFree->freeSpaceStr));
1129
NotifyMemInfo(MemBlockFlags::WRITE, param->msFree.ptr, sizeof(SceUtilitySavedataMsFreeInfo), "SavedataGetSizes");
1130
}
1131
if (param->msData.IsValid())
1132
{
1133
const SceUtilitySavedataMsDataInfo *msData = param->msData;
1134
const std::string gameName(msData->gameName, strnlen(msData->gameName, sizeof(msData->gameName)));
1135
const std::string saveName(msData->saveName, strnlen(msData->saveName, sizeof(msData->saveName)));
1136
// TODO: How should <> be handled?
1137
std::string path = GetSaveFilePath(param, gameName + (saveName == "<>" ? "" : saveName));
1138
bool listingExists = false;
1139
auto listing = pspFileSystem.GetDirListing(path, &listingExists);
1140
if (listingExists) {
1141
param->msData->info.usedClusters = 0;
1142
for (auto &item : listing) {
1143
param->msData->info.usedClusters += (item.size + (u32)MemoryStick_SectorSize() - 1) / (u32)MemoryStick_SectorSize();
1144
}
1145
1146
// The usedSpaceKB value is definitely based on clusters, not bytes or even KB.
1147
// Fieldrunners expects 736 KB, even though the files add up to ~600 KB.
1148
int total_size = param->msData->info.usedClusters * (u32)MemoryStick_SectorSize();
1149
param->msData->info.usedSpaceKB = total_size / 0x400;
1150
std::string spaceTxt = SavedataParam::GetSpaceText(total_size, true);
1151
strncpy(param->msData->info.usedSpaceStr, spaceTxt.c_str(), sizeof(param->msData->info.usedSpaceStr));
1152
1153
// TODO: What does this mean, then? Seems to be the same.
1154
param->msData->info.usedSpace32KB = param->msData->info.usedSpaceKB;
1155
strncpy(param->msData->info.usedSpace32Str, spaceTxt.c_str(), sizeof(param->msData->info.usedSpace32Str));
1156
}
1157
else
1158
{
1159
param->msData->info.usedClusters = 0;
1160
param->msData->info.usedSpaceKB = 0;
1161
strncpy(param->msData->info.usedSpaceStr, "", sizeof(param->msData->info.usedSpaceStr));
1162
param->msData->info.usedSpace32KB = 0;
1163
strncpy(param->msData->info.usedSpace32Str, "", sizeof(param->msData->info.usedSpace32Str));
1164
ret = SCE_UTILITY_SAVEDATA_ERROR_SIZES_NO_DATA;
1165
}
1166
NotifyMemInfo(MemBlockFlags::WRITE, param->msData.ptr, sizeof(SceUtilitySavedataMsDataInfo), "SavedataGetSizes");
1167
}
1168
if (param->utilityData.IsValid())
1169
{
1170
int total_size = 0;
1171
1172
// The directory record itself.
1173
// TODO: Account for number of files / actual record size?
1174
total_size += getSizeNormalized(1);
1175
// Account for the SFO (is this always 1 sector?)
1176
total_size += getSizeNormalized(1);
1177
// Add the size of the data itself (don't forget encryption overhead.)
1178
// This is only added if a filename is specified.
1179
if (param->fileName[0] != 0) {
1180
if (g_Config.bEncryptSave) {
1181
total_size += getSizeNormalized((u32)param->dataSize + 16);
1182
} else {
1183
total_size += getSizeNormalized((u32)param->dataSize);
1184
}
1185
}
1186
total_size += getSizeNormalized(param->icon0FileData.size);
1187
total_size += getSizeNormalized(param->icon1FileData.size);
1188
total_size += getSizeNormalized(param->pic1FileData.size);
1189
total_size += getSizeNormalized(param->snd0FileData.size);
1190
1191
param->utilityData->usedClusters = total_size / (u32)MemoryStick_SectorSize();
1192
param->utilityData->usedSpaceKB = total_size / 0x400;
1193
std::string spaceTxt = SavedataParam::GetSpaceText(total_size, true);
1194
memset(param->utilityData->usedSpaceStr, 0, sizeof(param->utilityData->usedSpaceStr));
1195
strncpy(param->utilityData->usedSpaceStr, spaceTxt.c_str(), sizeof(param->utilityData->usedSpaceStr));
1196
1197
// TODO: Maybe these are rounded to the nearest 32KB? Or something?
1198
param->utilityData->usedSpace32KB = total_size / 0x400;
1199
std::string spaceTxt32 = SavedataParam::GetSpaceText(total_size, true);
1200
memset(param->utilityData->usedSpace32Str, 0, sizeof(param->utilityData->usedSpace32Str));
1201
strncpy(param->utilityData->usedSpace32Str, spaceTxt32.c_str(), sizeof(param->utilityData->usedSpace32Str));
1202
1203
INFO_LOG(Log::sceUtility, "GetSize: usedSpaceKB: %d (str: %s) (clusters: %d)", param->utilityData->usedSpaceKB, spaceTxt.c_str(), param->utilityData->usedClusters);
1204
INFO_LOG(Log::sceUtility, "GetSize: usedSpace32KB: %d (str32: %s)", param->utilityData->usedSpace32KB, spaceTxt32.c_str());
1205
1206
NotifyMemInfo(MemBlockFlags::WRITE, param->utilityData.ptr, sizeof(SceUtilitySavedataUsedDataInfo), "SavedataGetSizes");
1207
}
1208
return ret;
1209
}
1210
1211
bool SavedataParam::GetList(SceUtilitySavedataParam *param)
1212
{
1213
if (!param) {
1214
return false;
1215
}
1216
1217
if (param->idList.IsValid())
1218
{
1219
u32 maxFileCount = param->idList->maxCount;
1220
1221
std::vector<PSPFileInfo> validDir;
1222
std::vector<PSPFileInfo> sfoFiles;
1223
1224
// TODO: Here we can filter by prefix - only the savename in param is likely to be a regex.
1225
std::vector<PSPFileInfo> allDir = pspFileSystem.GetDirListing(savePath);
1226
1227
std::string searchString = GetGameName(param) + GetSaveName(param);
1228
for (size_t i = 0; i < allDir.size() && validDir.size() < maxFileCount; i++) {
1229
std::string dirName = allDir[i].name;
1230
if (PSPMatch(dirName, searchString)) {
1231
validDir.push_back(allDir[i]);
1232
}
1233
}
1234
1235
PSPFileInfo sfoFile;
1236
for (size_t i = 0; i < validDir.size(); ++i) {
1237
// GetFileName(param) == null here
1238
// so use sfo files to set the date.
1239
sfoFile = pspFileSystem.GetFileInfo(savePath + validDir[i].name + "/" + SFO_FILENAME);
1240
sfoFiles.push_back(sfoFile);
1241
}
1242
1243
SceUtilitySavedataIdListEntry *entries = param->idList->entries;
1244
for (u32 i = 0; i < (u32)validDir.size(); i++)
1245
{
1246
entries[i].st_mode = 0x11FF;
1247
if (sfoFiles[i].exists) {
1248
__IoCopyDate(entries[i].st_ctime, sfoFiles[i].ctime);
1249
__IoCopyDate(entries[i].st_atime, sfoFiles[i].atime);
1250
__IoCopyDate(entries[i].st_mtime, sfoFiles[i].mtime);
1251
} else {
1252
__IoCopyDate(entries[i].st_ctime, validDir[i].ctime);
1253
__IoCopyDate(entries[i].st_atime, validDir[i].atime);
1254
__IoCopyDate(entries[i].st_mtime, validDir[i].mtime);
1255
}
1256
// folder name without gamename (max 20 u8)
1257
std::string outName = validDir[i].name.substr(GetGameName(param).size());
1258
memset(entries[i].name, 0, sizeof(entries[i].name));
1259
strncpy(entries[i].name, outName.c_str(), sizeof(entries[i].name));
1260
}
1261
// Save num of folder found
1262
param->idList->resultCount = (u32)validDir.size();
1263
// Log out the listing.
1264
if (GenericLogEnabled(Log::sceUtility, LogLevel::LINFO)) {
1265
INFO_LOG(Log::sceUtility, "LIST (searchstring=%s): %d files (max: %d)", searchString.c_str(), param->idList->resultCount, maxFileCount);
1266
for (int i = 0; i < validDir.size(); i++) {
1267
INFO_LOG(Log::sceUtility, "%s: mode %08x, ctime: %s, atime: %s, mtime: %s",
1268
entries[i].name, entries[i].st_mode, FmtPspTime(entries[i].st_ctime).c_str(), FmtPspTime(entries[i].st_atime).c_str(), FmtPspTime(entries[i].st_mtime).c_str());
1269
}
1270
}
1271
NotifyMemInfo(MemBlockFlags::WRITE, param->idList.ptr, sizeof(SceUtilitySavedataIdListInfo), "SavedataGetList");
1272
NotifyMemInfo(MemBlockFlags::WRITE, param->idList->entries.ptr, (uint32_t)validDir.size() * sizeof(SceUtilitySavedataIdListEntry), "SavedataGetList");
1273
}
1274
return true;
1275
}
1276
1277
int SavedataParam::GetFilesList(SceUtilitySavedataParam *param, u32 requestAddr) {
1278
if (!param) {
1279
return SCE_UTILITY_SAVEDATA_ERROR_RW_BAD_STATUS;
1280
}
1281
1282
if (!param->fileList.IsValid()) {
1283
ERROR_LOG_REPORT(Log::sceUtility, "SavedataParam::GetFilesList(): bad fileList address %08x", param->fileList.ptr);
1284
// Should crash.
1285
return -1;
1286
}
1287
1288
PSPPointer<SceUtilitySavedataFileListInfo> fileList = param->fileList;
1289
if (fileList->secureEntries.IsValid() && fileList->maxSecureEntries > 99) {
1290
ERROR_LOG_REPORT(Log::sceUtility, "SavedataParam::GetFilesList(): too many secure entries, %d", fileList->maxSecureEntries);
1291
return SCE_UTILITY_SAVEDATA_ERROR_RW_BAD_PARAMS;
1292
}
1293
if (fileList->normalEntries.IsValid() && fileList->maxNormalEntries > 8192) {
1294
ERROR_LOG_REPORT(Log::sceUtility, "SavedataParam::GetFilesList(): too many normal entries, %d", fileList->maxNormalEntries);
1295
return SCE_UTILITY_SAVEDATA_ERROR_RW_BAD_PARAMS;
1296
}
1297
if (sceKernelGetCompiledSdkVersion() >= 0x02060000) {
1298
if (fileList->systemEntries.IsValid() && fileList->maxSystemEntries > 5) {
1299
ERROR_LOG_REPORT(Log::sceUtility, "SavedataParam::GetFilesList(): too many system entries, %d", fileList->maxSystemEntries);
1300
return SCE_UTILITY_SAVEDATA_ERROR_RW_BAD_PARAMS;
1301
}
1302
}
1303
1304
std::string dirPath = savePath + GetGameName(param) + GetSaveName(param);
1305
bool dirPathExists = false;
1306
auto files = pspFileSystem.GetDirListing(dirPath, &dirPathExists);
1307
if (!dirPathExists) {
1308
DEBUG_LOG(Log::sceUtility, "SavedataParam::GetFilesList(): directory %s does not exist", dirPath.c_str());
1309
return SCE_UTILITY_SAVEDATA_ERROR_RW_NO_DATA;
1310
}
1311
1312
// Even if there are no files, initialize to 0.
1313
fileList->resultNumSecureEntries = 0;
1314
fileList->resultNumNormalEntries = 0;
1315
fileList->resultNumSystemEntries = 0;
1316
1317
// We need PARAM.SFO's SAVEDATA_FILE_LIST to determine which entries are secure.
1318
PSPFileInfo sfoFileInfo = FileFromListing(files, SFO_FILENAME);
1319
std::set<std::string> secureFilenames;
1320
1321
if (sfoFileInfo.exists) {
1322
secureFilenames = GetSecureFileNames(dirPath);
1323
} else {
1324
return SCE_UTILITY_SAVEDATA_ERROR_RW_DATA_BROKEN;
1325
}
1326
1327
// TODO: Does this always happen?
1328
// Don't know what it is, but PSP always respond this.
1329
param->bind = 1021;
1330
// This should be set around the same time as the file data. This runs on a thread, so set immediately.
1331
auto requestPtr = PSPPointer<SceUtilitySavedataParam>::Create(requestAddr);
1332
requestPtr->bind = 1021;
1333
1334
// Does not list directories, nor recurse into them, and ignores files not ALL UPPERCASE.
1335
bool isCrypted = GetSaveCryptMode(param, GetSaveDirName(param, 0)) != 0;
1336
for (auto file = files.begin(), end = files.end(); file != end; ++file) {
1337
if (file->type == FILETYPE_DIRECTORY) {
1338
continue;
1339
}
1340
// TODO: What are the exact rules? It definitely skips lowercase, and allows FILE or FILE.EXT.
1341
if (file->name.find_first_of("abcdefghijklmnopqrstuvwxyz") != file->name.npos) {
1342
DEBUG_LOG(Log::sceUtility, "SavedataParam::GetFilesList(): skipping file %s with lowercase", file->name.c_str());
1343
continue;
1344
}
1345
1346
bool isSystemFile = file->name == ICON0_FILENAME || file->name == ICON1_FILENAME || file->name == PIC1_FILENAME;
1347
isSystemFile = isSystemFile || file->name == SND0_FILENAME || file->name == SFO_FILENAME;
1348
1349
SceUtilitySavedataFileListEntry *entry = NULL;
1350
int sizeOffset = 0;
1351
if (isSystemFile) {
1352
if (fileList->systemEntries.IsValid() && fileList->resultNumSystemEntries < fileList->maxSystemEntries) {
1353
entry = &fileList->systemEntries[fileList->resultNumSystemEntries++];
1354
}
1355
} else if (secureFilenames.find(file->name) != secureFilenames.end()) {
1356
if (fileList->secureEntries.IsValid() && fileList->resultNumSecureEntries < fileList->maxSecureEntries) {
1357
entry = &fileList->secureEntries[fileList->resultNumSecureEntries++];
1358
}
1359
// Secure files are slightly bigger.
1360
if (isCrypted) {
1361
sizeOffset = -0x10;
1362
}
1363
} else {
1364
if (fileList->normalEntries.IsValid() && fileList->resultNumNormalEntries < fileList->maxNormalEntries) {
1365
entry = &fileList->normalEntries[fileList->resultNumNormalEntries++];
1366
}
1367
}
1368
1369
// Out of space for this file in the list.
1370
if (entry == NULL) {
1371
continue;
1372
}
1373
1374
entry->st_mode = 0x21FF;
1375
entry->st_size = file->size + sizeOffset;
1376
__IoCopyDate(entry->st_ctime, file->ctime);
1377
__IoCopyDate(entry->st_atime, file->atime);
1378
__IoCopyDate(entry->st_mtime, file->mtime);
1379
// TODO: Probably actually 13 + 3 pad...
1380
strncpy(entry->name, file->name.c_str(), 16);
1381
entry->name[15] = '\0';
1382
}
1383
1384
if (GenericLogEnabled(Log::sceUtility, LogLevel::LINFO)) {
1385
INFO_LOG(Log::sceUtility, "FILES: %d files listed (+ %d system, %d secure)", fileList->resultNumNormalEntries, fileList->resultNumSystemEntries, fileList->resultNumSecureEntries);
1386
if (fileList->normalEntries.IsValid()) {
1387
for (int i = 0; i < (int)fileList->resultNumNormalEntries; i++) {
1388
const SceUtilitySavedataFileListEntry &info = fileList->normalEntries[i];
1389
INFO_LOG(Log::sceUtility, "%s: mode %08x, ctime: %s, atime: %s, mtime: %s",
1390
info.name, info.st_mode, FmtPspTime(info.st_ctime).c_str(), FmtPspTime(info.st_atime).c_str(), FmtPspTime(info.st_mtime).c_str());
1391
}
1392
} else if (fileList->resultNumNormalEntries > 0) {
1393
WARN_LOG(Log::sceUtility, "Invalid normalEntries pointer (%d entries)", fileList->resultNumNormalEntries);
1394
}
1395
// TODO: Log system and secure entries?
1396
}
1397
1398
NotifyMemInfo(MemBlockFlags::WRITE, fileList.ptr, sizeof(SceUtilitySavedataFileListInfo), "SavedataGetFilesList");
1399
if (fileList->resultNumSystemEntries != 0)
1400
NotifyMemInfo(MemBlockFlags::WRITE, fileList->systemEntries.ptr, fileList->resultNumSystemEntries * sizeof(SceUtilitySavedataFileListEntry), "SavedataGetFilesList");
1401
if (fileList->resultNumSecureEntries != 0)
1402
NotifyMemInfo(MemBlockFlags::WRITE, fileList->secureEntries.ptr, fileList->resultNumSecureEntries * sizeof(SceUtilitySavedataFileListEntry), "SavedataGetFilesList");
1403
if (fileList->resultNumNormalEntries != 0)
1404
NotifyMemInfo(MemBlockFlags::WRITE, fileList->normalEntries.ptr, fileList->resultNumNormalEntries * sizeof(SceUtilitySavedataFileListEntry), "SavedataGetFilesList");
1405
1406
return 0;
1407
}
1408
1409
bool SavedataParam::GetSize(SceUtilitySavedataParam *param) {
1410
if (!param) {
1411
return false;
1412
}
1413
1414
const std::string saveDir = savePath + GetGameName(param) + GetSaveName(param);
1415
bool exists = false;
1416
1417
if (param->sizeInfo.IsValid()) {
1418
auto listing = pspFileSystem.GetDirListing(saveDir, &exists);
1419
const u64 freeBytes = MemoryStick_FreeSpace(GetGameName(param));
1420
1421
s64 overwriteBytes = 0;
1422
s64 writeBytes = 0;
1423
for (int i = 0; i < param->sizeInfo->numNormalEntries; ++i) {
1424
const auto &entry = param->sizeInfo->normalEntries[i];
1425
overwriteBytes += FileFromListing(listing, entry.name).size;
1426
writeBytes += entry.size;
1427
}
1428
for (int i = 0; i < param->sizeInfo->numSecureEntries; ++i) {
1429
const auto &entry = param->sizeInfo->secureEntries[i];
1430
overwriteBytes += FileFromListing(listing, entry.name).size;
1431
writeBytes += entry.size + 0x10;
1432
}
1433
1434
param->sizeInfo->sectorSize = (int)MemoryStick_SectorSize();
1435
param->sizeInfo->freeSectors = (int)(freeBytes / MemoryStick_SectorSize());
1436
1437
// TODO: Is this after the specified files? Probably before?
1438
param->sizeInfo->freeKB = (int)(freeBytes / 1024);
1439
std::string spaceTxt = SavedataParam::GetSpaceText(freeBytes, false);
1440
truncate_cpy(param->sizeInfo->freeString, spaceTxt);
1441
1442
if (writeBytes - overwriteBytes < (s64)freeBytes) {
1443
param->sizeInfo->neededKB = 0;
1444
1445
// Note: this is "needed to overwrite".
1446
param->sizeInfo->overwriteKB = 0;
1447
1448
spaceTxt = GetSpaceText(0, true);
1449
truncate_cpy(param->sizeInfo->neededString, spaceTxt);
1450
truncate_cpy(param->sizeInfo->overwriteString, spaceTxt);
1451
} else {
1452
// Bytes needed to save additional data.
1453
s64 neededBytes = writeBytes - freeBytes;
1454
param->sizeInfo->neededKB = (neededBytes + 1023) / 1024;
1455
spaceTxt = GetSpaceText(neededBytes, true);
1456
truncate_cpy(param->sizeInfo->neededString, spaceTxt);
1457
1458
if (writeBytes - overwriteBytes < (s64)freeBytes) {
1459
param->sizeInfo->overwriteKB = 0;
1460
spaceTxt = GetSpaceText(0, true);
1461
truncate_cpy(param->sizeInfo->overwriteString, spaceTxt);
1462
} else {
1463
s64 neededOverwriteBytes = writeBytes - freeBytes - overwriteBytes;
1464
param->sizeInfo->overwriteKB = (neededOverwriteBytes + 1023) / 1024;
1465
spaceTxt = GetSpaceText(neededOverwriteBytes, true);
1466
truncate_cpy(param->sizeInfo->overwriteString, spaceTxt);
1467
}
1468
}
1469
1470
INFO_LOG(Log::sceUtility, "SectorSize: %d FreeSectors: %d FreeKB: %d neededKb: %d overwriteKb: %d",
1471
param->sizeInfo->sectorSize, param->sizeInfo->freeSectors, param->sizeInfo->freeKB, param->sizeInfo->neededKB, param->sizeInfo->overwriteKB);
1472
1473
NotifyMemInfo(MemBlockFlags::WRITE, param->sizeInfo.ptr, sizeof(PspUtilitySavedataSizeInfo), "SavedataGetSize");
1474
}
1475
1476
return exists;
1477
}
1478
1479
void SavedataParam::Clear()
1480
{
1481
if (saveDataList)
1482
{
1483
for (int i = 0; i < saveNameListDataCount; i++)
1484
{
1485
if (saveDataList[i].texture != NULL && (!noSaveIcon || saveDataList[i].texture != noSaveIcon->texture))
1486
delete saveDataList[i].texture;
1487
saveDataList[i].texture = NULL;
1488
}
1489
1490
delete [] saveDataList;
1491
saveDataList = NULL;
1492
saveDataListCount = 0;
1493
}
1494
if (noSaveIcon)
1495
{
1496
delete noSaveIcon->texture;
1497
noSaveIcon->texture = NULL;
1498
delete noSaveIcon;
1499
noSaveIcon = NULL;
1500
}
1501
}
1502
1503
int SavedataParam::SetPspParam(SceUtilitySavedataParam *param)
1504
{
1505
pspParam = param;
1506
if (!pspParam) {
1507
Clear();
1508
return 0;
1509
}
1510
1511
std::string gameName = GetGameName(param);
1512
if (!gameName.empty()) {
1513
MemoryStick_NotifyGameName(gameName);
1514
}
1515
1516
if (param->mode == SCE_UTILITY_SAVEDATA_TYPE_LISTALLDELETE) {
1517
Clear();
1518
int realCount = 0;
1519
auto allSaves = pspFileSystem.GetDirListing(savePath);
1520
saveDataListCount = (int)allSaves.size();
1521
saveDataList = new SaveFileInfo[saveDataListCount];
1522
for (auto save : allSaves) {
1523
if (save.type != FILETYPE_DIRECTORY || save.name == "." || save.name == "..")
1524
continue;
1525
std::string fileDataDir = savePath + save.name;
1526
PSPFileInfo info = GetSaveInfo(fileDataDir);
1527
SetFileInfo(realCount, info, "", save.name);
1528
realCount++;
1529
}
1530
saveNameListDataCount = realCount;
1531
return 0;
1532
}
1533
1534
bool listEmptyFile = true;
1535
if (param->mode == SCE_UTILITY_SAVEDATA_TYPE_LISTLOAD || param->mode == SCE_UTILITY_SAVEDATA_TYPE_LISTDELETE) {
1536
listEmptyFile = false;
1537
}
1538
1539
SceUtilitySavedataSaveName *saveNameListData;
1540
bool hasMultipleFileName = false;
1541
if (param->saveNameList.IsValid()) {
1542
Clear();
1543
1544
saveNameListData = param->saveNameList;
1545
1546
// Get number of fileName in array
1547
saveDataListCount = 0;
1548
while (saveNameListData[saveDataListCount][0] != 0) {
1549
saveDataListCount++;
1550
}
1551
1552
if (saveDataListCount > 0 && WouldHaveMultiSaveName(param)) {
1553
hasMultipleFileName = true;
1554
saveDataList = new SaveFileInfo[saveDataListCount];
1555
1556
// get and stock file info for each file
1557
int realCount = 0;
1558
1559
// TODO: Filter away non-directories directly?
1560
std::vector<PSPFileInfo> allSaves = pspFileSystem.GetDirListing(savePath);
1561
1562
std::string gameName = GetGameName(param);
1563
1564
for (int i = 0; i < saveDataListCount; i++) {
1565
// "<>" means saveName can be anything...
1566
if (strncmp(saveNameListData[i], "<>", ARRAY_SIZE(saveNameListData[i])) == 0) {
1567
// TODO: Maybe we need a way to reorder the files?
1568
for (auto it = allSaves.begin(); it != allSaves.end(); ++it) {
1569
if (it->name.compare(0, gameName.length(), gameName) == 0) {
1570
std::string saveName = it->name.substr(gameName.length());
1571
1572
if (IsInSaveDataList(saveName, realCount)) // Already in SaveDataList, skip...
1573
continue;
1574
1575
std::string fileDataPath = savePath + it->name;
1576
if (it->exists) {
1577
SetFileInfo(realCount, *it, saveName);
1578
++realCount;
1579
} else {
1580
if (listEmptyFile) {
1581
// If file doesn't exist,we only skip...
1582
continue;
1583
}
1584
}
1585
break;
1586
}
1587
}
1588
continue;
1589
}
1590
1591
const std::string thisSaveName = FixedToString(saveNameListData[i], ARRAY_SIZE(saveNameListData[i]));
1592
1593
const std::string folderName = gameName + thisSaveName;
1594
1595
// Check if thisSaveName is in the list before processing.
1596
// This is hopefully faster than doing file I/O.
1597
bool found = false;
1598
for (int i = 0; i < allSaves.size(); i++) {
1599
if (allSaves[i].name == folderName) {
1600
found = true;
1601
}
1602
}
1603
1604
const std::string fileDataDir = savePath + gameName + thisSaveName;
1605
if (found) {
1606
PSPFileInfo info = GetSaveInfo(fileDataDir);
1607
if (info.exists) {
1608
SetFileInfo(realCount, info, thisSaveName);
1609
INFO_LOG(Log::sceUtility, "Save data exists: %s = %s", thisSaveName.c_str(), fileDataDir.c_str());
1610
realCount++;
1611
} else {
1612
found = false;
1613
}
1614
}
1615
1616
if (!found) { // NOTE: May be changed above, can't merge with the expression
1617
if (listEmptyFile) {
1618
ClearFileInfo(saveDataList[realCount], thisSaveName);
1619
DEBUG_LOG(Log::sceUtility, "Listing missing save data: %s = %s", thisSaveName.c_str(), fileDataDir.c_str());
1620
realCount++;
1621
} else {
1622
INFO_LOG(Log::sceUtility, "Save data not found: %s = %s", thisSaveName.c_str(), fileDataDir.c_str());
1623
}
1624
}
1625
}
1626
saveNameListDataCount = realCount;
1627
}
1628
}
1629
// Load info on only save
1630
if (!hasMultipleFileName) {
1631
saveNameListData = 0;
1632
1633
Clear();
1634
saveDataList = new SaveFileInfo[1];
1635
saveDataListCount = 1;
1636
1637
// get and stock file info for each file
1638
std::string fileDataDir = savePath + GetGameName(param) + GetSaveName(param);
1639
PSPFileInfo info = GetSaveInfo(fileDataDir);
1640
if (info.exists) {
1641
SetFileInfo(0, info, GetSaveName(param));
1642
INFO_LOG(Log::sceUtility, "Save data exists: %s = %s", GetSaveName(param).c_str(), fileDataDir.c_str());
1643
saveNameListDataCount = 1;
1644
} else {
1645
if (listEmptyFile) {
1646
ClearFileInfo(saveDataList[0], GetSaveName(param));
1647
DEBUG_LOG(Log::sceUtility, "Listing missing save data: %s = %s", GetSaveName(param).c_str(), fileDataDir.c_str());
1648
} else {
1649
INFO_LOG(Log::sceUtility, "Save data not found: %s = %s", GetSaveName(param).c_str(), fileDataDir.c_str());
1650
}
1651
saveNameListDataCount = 0;
1652
return 0;
1653
}
1654
}
1655
return 0;
1656
}
1657
1658
void SavedataParam::SetFileInfo(SaveFileInfo &saveInfo, PSPFileInfo &info, const std::string &saveName, const std::string &savrDir)
1659
{
1660
saveInfo.size = info.size;
1661
saveInfo.saveName = saveName;
1662
saveInfo.idx = 0;
1663
saveInfo.modif_time = info.mtime;
1664
1665
std::string saveDir = savrDir.empty() ? GetGameName(pspParam) + saveName : savrDir;
1666
saveInfo.saveDir = saveDir;
1667
1668
// Start with a blank slate.
1669
if (saveInfo.texture != NULL) {
1670
if (!noSaveIcon || saveInfo.texture != noSaveIcon->texture) {
1671
delete saveInfo.texture;
1672
}
1673
saveInfo.texture = NULL;
1674
}
1675
saveInfo.title[0] = 0;
1676
saveInfo.saveTitle[0] = 0;
1677
saveInfo.saveDetail[0] = 0;
1678
1679
// Search save image icon0
1680
// TODO : If icon0 don't exist, need to use icon1 which is a moving icon. Also play sound
1681
if (!ignoreTextures_) {
1682
saveInfo.texture = new PPGeImage(savePath + saveDir + "/" + ICON0_FILENAME);
1683
}
1684
1685
// Load info in PARAM.SFO
1686
std::string sfoFilename = savePath + saveDir + "/" + SFO_FILENAME;
1687
std::shared_ptr<ParamSFOData> sfoFile = LoadCachedSFO(sfoFilename);
1688
if (sfoFile) {
1689
SetStringFromSFO(*sfoFile, "TITLE", saveInfo.title, sizeof(saveInfo.title));
1690
SetStringFromSFO(*sfoFile, "SAVEDATA_TITLE", saveInfo.saveTitle, sizeof(saveInfo.saveTitle));
1691
SetStringFromSFO(*sfoFile, "SAVEDATA_DETAIL", saveInfo.saveDetail, sizeof(saveInfo.saveDetail));
1692
} else {
1693
saveInfo.broken = true;
1694
truncate_cpy(saveInfo.title, saveDir);
1695
}
1696
}
1697
1698
void SavedataParam::SetFileInfo(int idx, PSPFileInfo &info, const std::string &saveName, const std::string &saveDir)
1699
{
1700
SetFileInfo(saveDataList[idx], info, saveName, saveDir);
1701
saveDataList[idx].idx = idx;
1702
}
1703
1704
void SavedataParam::ClearFileInfo(SaveFileInfo &saveInfo, const std::string &saveName) {
1705
saveInfo.size = 0;
1706
saveInfo.saveName = saveName;
1707
saveInfo.idx = 0;
1708
saveInfo.broken = false;
1709
if (saveInfo.texture != NULL) {
1710
if (!noSaveIcon || saveInfo.texture != noSaveIcon->texture) {
1711
delete saveInfo.texture;
1712
}
1713
saveInfo.texture = NULL;
1714
}
1715
1716
if (GetPspParam()->newData.IsValid() && GetPspParam()->newData->buf.IsValid()) {
1717
// We may have a png to show
1718
if (!noSaveIcon) {
1719
noSaveIcon = new SaveFileInfo();
1720
PspUtilitySavedataFileData *newData = GetPspParam()->newData;
1721
if (Memory::IsValidRange(newData->buf.ptr, newData->size)) {
1722
noSaveIcon->texture = new PPGeImage(newData->buf.ptr, (SceSize)newData->size);
1723
}
1724
}
1725
saveInfo.texture = noSaveIcon->texture;
1726
} else if ((u32)GetPspParam()->mode == SCE_UTILITY_SAVEDATA_TYPE_SAVE && GetPspParam()->icon0FileData.buf.IsValid()) {
1727
const PspUtilitySavedataFileData &icon0FileData = GetPspParam()->icon0FileData;
1728
saveInfo.texture = new PPGeImage(icon0FileData.buf.ptr, (SceSize)icon0FileData.size);
1729
}
1730
}
1731
1732
PSPFileInfo SavedataParam::GetSaveInfo(const std::string &saveDir) {
1733
PSPFileInfo info = pspFileSystem.GetFileInfo(saveDir);
1734
if (info.exists) {
1735
info.access = 0777;
1736
auto allFiles = pspFileSystem.GetDirListing(saveDir);
1737
bool firstFile = true;
1738
for (auto file : allFiles) {
1739
if (file.type == FILETYPE_DIRECTORY || file.name == "." || file.name == "..")
1740
continue;
1741
// Use a file to determine save date.
1742
if (firstFile) {
1743
info.ctime = file.ctime;
1744
info.mtime = file.mtime;
1745
info.atime = file.atime;
1746
info.size += file.size;
1747
firstFile = false;
1748
} else {
1749
info.size += file.size;
1750
}
1751
}
1752
}
1753
return info;
1754
}
1755
1756
SceUtilitySavedataParam *SavedataParam::GetPspParam()
1757
{
1758
return pspParam;
1759
}
1760
1761
const SceUtilitySavedataParam *SavedataParam::GetPspParam() const
1762
{
1763
return pspParam;
1764
}
1765
1766
int SavedataParam::GetFilenameCount()
1767
{
1768
return saveNameListDataCount;
1769
}
1770
1771
const SaveFileInfo& SavedataParam::GetFileInfo(int idx)
1772
{
1773
return saveDataList[idx];
1774
}
1775
1776
std::string SavedataParam::GetFilename(int idx) const
1777
{
1778
return saveDataList[idx].saveName;
1779
}
1780
1781
std::string SavedataParam::GetSaveDir(int idx) const {
1782
return saveDataList[idx].saveDir;
1783
}
1784
1785
int SavedataParam::GetSelectedSave()
1786
{
1787
// The slot # of the same save on LOAD/SAVE lists can dismatch so this isn't right anyhow
1788
return selectedSave < saveNameListDataCount ? selectedSave : 0;
1789
}
1790
1791
void SavedataParam::SetSelectedSave(int idx)
1792
{
1793
selectedSave = idx;
1794
}
1795
1796
int SavedataParam::GetFirstListSave()
1797
{
1798
return 0;
1799
}
1800
1801
int SavedataParam::GetLastListSave()
1802
{
1803
return saveNameListDataCount - 1;
1804
}
1805
1806
int SavedataParam::GetLatestSave()
1807
{
1808
int idx = 0;
1809
time_t idxTime = 0;
1810
for (int i = 0; i < saveNameListDataCount; ++i)
1811
{
1812
if (saveDataList[i].size == 0)
1813
continue;
1814
time_t thisTime = mktime(&saveDataList[i].modif_time);
1815
if ((s64)idxTime < (s64)thisTime)
1816
{
1817
idx = i;
1818
idxTime = thisTime;
1819
}
1820
}
1821
return idx;
1822
}
1823
1824
int SavedataParam::GetOldestSave()
1825
{
1826
int idx = 0;
1827
time_t idxTime = 0;
1828
for (int i = 0; i < saveNameListDataCount; ++i)
1829
{
1830
if (saveDataList[i].size == 0)
1831
continue;
1832
time_t thisTime = mktime(&saveDataList[i].modif_time);
1833
if ((s64)idxTime > (s64)thisTime)
1834
{
1835
idx = i;
1836
idxTime = thisTime;
1837
}
1838
}
1839
return idx;
1840
}
1841
1842
int SavedataParam::GetFirstDataSave()
1843
{
1844
int idx = 0;
1845
for (int i = 0; i < saveNameListDataCount; ++i)
1846
{
1847
if (saveDataList[i].size != 0)
1848
{
1849
idx = i;
1850
break;
1851
}
1852
}
1853
return idx;
1854
}
1855
1856
int SavedataParam::GetLastDataSave()
1857
{
1858
int idx = 0;
1859
for (int i = saveNameListDataCount; i > 0; )
1860
{
1861
--i;
1862
if (saveDataList[i].size != 0)
1863
{
1864
idx = i;
1865
break;
1866
}
1867
}
1868
return idx;
1869
}
1870
1871
int SavedataParam::GetFirstEmptySave()
1872
{
1873
int idx = 0;
1874
for (int i = 0; i < saveNameListDataCount; ++i)
1875
{
1876
if (saveDataList[i].size == 0)
1877
{
1878
idx = i;
1879
break;
1880
}
1881
}
1882
return idx;
1883
}
1884
1885
int SavedataParam::GetLastEmptySave()
1886
{
1887
int idx = 0;
1888
for (int i = saveNameListDataCount; i > 0; )
1889
{
1890
--i;
1891
if (saveDataList[i].size == 0)
1892
{
1893
idx = i;
1894
break;
1895
}
1896
}
1897
return idx;
1898
}
1899
1900
int SavedataParam::GetSaveNameIndex(const SceUtilitySavedataParam *param) {
1901
std::string saveName = GetSaveName(param);
1902
for (int i = 0; i < saveNameListDataCount; i++)
1903
{
1904
// TODO: saveName may contain wildcards
1905
if (saveDataList[i].saveName == saveName)
1906
{
1907
return i;
1908
}
1909
}
1910
1911
return 0;
1912
}
1913
1914
bool SavedataParam::WouldHaveMultiSaveName(const SceUtilitySavedataParam *param) {
1915
switch ((SceUtilitySavedataType)(u32)param->mode) {
1916
case SCE_UTILITY_SAVEDATA_TYPE_LOAD:
1917
case SCE_UTILITY_SAVEDATA_TYPE_AUTOLOAD:
1918
case SCE_UTILITY_SAVEDATA_TYPE_SAVE:
1919
case SCE_UTILITY_SAVEDATA_TYPE_AUTOSAVE:
1920
case SCE_UTILITY_SAVEDATA_TYPE_MAKEDATASECURE:
1921
case SCE_UTILITY_SAVEDATA_TYPE_MAKEDATA:
1922
case SCE_UTILITY_SAVEDATA_TYPE_READDATASECURE:
1923
case SCE_UTILITY_SAVEDATA_TYPE_READDATA:
1924
case SCE_UTILITY_SAVEDATA_TYPE_WRITEDATASECURE:
1925
case SCE_UTILITY_SAVEDATA_TYPE_WRITEDATA:
1926
case SCE_UTILITY_SAVEDATA_TYPE_AUTODELETE:
1927
case SCE_UTILITY_SAVEDATA_TYPE_DELETE:
1928
case SCE_UTILITY_SAVEDATA_TYPE_ERASESECURE:
1929
case SCE_UTILITY_SAVEDATA_TYPE_ERASE:
1930
case SCE_UTILITY_SAVEDATA_TYPE_DELETEDATA:
1931
return false;
1932
default:
1933
return true;
1934
}
1935
}
1936
1937
void SavedataParam::DoState(PointerWrap &p) {
1938
auto s = p.Section("SavedataParam", 1, 2);
1939
if (!s)
1940
return;
1941
1942
// pspParam is handled in PSPSaveDialog.
1943
Do(p, selectedSave);
1944
Do(p, saveDataListCount);
1945
Do(p, saveNameListDataCount);
1946
if (p.mode == p.MODE_READ) {
1947
delete [] saveDataList;
1948
if (saveDataListCount != 0) {
1949
saveDataList = new SaveFileInfo[saveDataListCount];
1950
DoArray(p, saveDataList, saveDataListCount);
1951
} else {
1952
saveDataList = nullptr;
1953
}
1954
}
1955
else
1956
DoArray(p, saveDataList, saveDataListCount);
1957
1958
if (s >= 2) {
1959
Do(p, ignoreTextures_);
1960
} else {
1961
ignoreTextures_ = false;
1962
}
1963
}
1964
1965
void SavedataParam::ClearSFOCache() {
1966
std::lock_guard<std::mutex> guard(cacheLock_);
1967
sfoCache_.clear();
1968
}
1969
1970
std::shared_ptr<ParamSFOData> SavedataParam::LoadCachedSFO(const std::string &path, bool orCreate) {
1971
std::lock_guard<std::mutex> guard(cacheLock_);
1972
if (sfoCache_.find(path) == sfoCache_.end()) {
1973
std::vector<u8> data;
1974
if (pspFileSystem.ReadEntireFile(path, data, true) < 0) {
1975
// Mark as not existing for later.
1976
sfoCache_[path].reset();
1977
} else {
1978
sfoCache_.emplace(path, new ParamSFOData());
1979
// If it fails to load, also keep it to indicate failed.
1980
if (!sfoCache_.at(path)->ReadSFO(data))
1981
sfoCache_.at(path).reset();
1982
}
1983
}
1984
1985
if (!sfoCache_.at(path)) {
1986
if (!orCreate)
1987
return nullptr;
1988
sfoCache_.at(path).reset(new ParamSFOData());
1989
}
1990
return sfoCache_.at(path);
1991
}
1992
1993
int SavedataParam::GetSaveCryptMode(const SceUtilitySavedataParam *param, const std::string &saveDirName) {
1994
std::string dirPath = GetSaveFilePath(param, GetSaveDir(param, saveDirName));
1995
std::string sfopath = dirPath + "/" + SFO_FILENAME;
1996
std::shared_ptr<ParamSFOData> sfoFile = LoadCachedSFO(sfopath);
1997
if (sfoFile) {
1998
// save created in PPSSPP and not encrypted has '0' in SAVEDATA_PARAMS
1999
u32 tmpDataSize = 0;
2000
const u8 *tmpDataOrig = sfoFile->GetValueData("SAVEDATA_PARAMS", &tmpDataSize);
2001
if (tmpDataSize == 0 || !tmpDataOrig) {
2002
return 0;
2003
}
2004
switch (tmpDataOrig[0]) {
2005
case 0:
2006
return 0;
2007
case 0x01:
2008
return 1;
2009
case 0x21:
2010
return 3;
2011
case 0x41:
2012
return 5;
2013
default:
2014
// Well, it's not zero, so yes.
2015
ERROR_LOG_REPORT(Log::sceUtility, "Unexpected SAVEDATA_PARAMS hash flag: %02x", tmpDataOrig[0]);
2016
return 1;
2017
}
2018
}
2019
return 0;
2020
}
2021
2022
bool SavedataParam::IsInSaveDataList(const std::string &saveName, int count) {
2023
for(int i = 0; i < count; ++i) {
2024
if (saveDataList[i].saveName == saveName)
2025
return true;
2026
}
2027
return false;
2028
}
2029
2030