Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hrydgard
GitHub Repository: hrydgard/ppsspp
Path: blob/master/Core/FileSystems/MetaFileSystem.cpp
5654 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 "Common/Serialize/Serializer.h"
19
#include "Common/Serialize/SerializeFuncs.h"
20
#include "Common/Serialize/SerializeMap.h"
21
#include "Common/StringUtils.h"
22
#include "Core/FileSystems/MetaFileSystem.h"
23
#include "Core/HLE/sceKernelThread.h"
24
#include "Core/Reporting.h"
25
#include "Core/System.h"
26
27
static bool ApplyPathStringToComponentsVector(std::vector<std::string> &vector, const std::string &pathString)
28
{
29
size_t len = pathString.length();
30
size_t start = 0;
31
32
while (start < len)
33
{
34
// TODO: This should only be done for ms0:/ etc.
35
size_t i = pathString.find_first_of("/\\", start);
36
if (i == std::string::npos)
37
i = len;
38
39
if (i > start)
40
{
41
std::string component = pathString.substr(start, i - start);
42
if (component != ".")
43
{
44
if (component == "..")
45
{
46
if (vector.size() != 0)
47
{
48
vector.pop_back();
49
}
50
else
51
{
52
// The PSP silently ignores attempts to .. to parent of root directory
53
WARN_LOG(Log::FileSystem, "RealPath: ignoring .. beyond root - root directory is its own parent: \"%s\"", pathString.c_str());
54
}
55
}
56
else
57
{
58
vector.push_back(component);
59
}
60
}
61
}
62
63
start = i + 1;
64
}
65
66
return true;
67
}
68
69
/*
70
* Changes relative paths to absolute, removes ".", "..", and trailing "/"
71
* "drive:./blah" is absolute (ignore the dot) and "/blah" is relative (because it's missing "drive:")
72
* babel (and possibly other games) use "/directoryThatDoesNotExist/../directoryThatExists/filename"
73
*/
74
static bool RealPath(const std::string &currentDirectory, const std::string &inPath, std::string &outPath)
75
{
76
size_t inLen = inPath.length();
77
if (inLen == 0)
78
{
79
outPath = currentDirectory;
80
return true;
81
}
82
83
size_t inColon = inPath.find(':');
84
if (inColon + 1 == inLen)
85
{
86
// There's nothing after the colon, e.g. umd0: - this is perfectly valid.
87
outPath = inPath;
88
return true;
89
}
90
91
bool relative = (inColon == std::string::npos);
92
93
std::string prefix, inAfterColon;
94
std::vector<std::string> cmpnts; // path components
95
size_t outPathCapacityGuess = inPath.length();
96
97
if (relative)
98
{
99
size_t curDirLen = currentDirectory.length();
100
if (curDirLen == 0)
101
{
102
ERROR_LOG(Log::FileSystem, "RealPath: inPath \"%s\" is relative, but current directory is empty", inPath.c_str());
103
return false;
104
}
105
106
size_t curDirColon = currentDirectory.find(':');
107
if (curDirColon == std::string::npos)
108
{
109
ERROR_LOG(Log::FileSystem, "RealPath: inPath \"%s\" is relative, but current directory \"%s\" has no prefix", inPath.c_str(), currentDirectory.c_str());
110
return false;
111
}
112
if (curDirColon + 1 == curDirLen)
113
{
114
WARN_LOG(Log::FileSystem, "RealPath: inPath \"%s\" is relative, but current directory \"%s\" is all prefix and no path. Using \"/\" as path for current directory.", inPath.c_str(), currentDirectory.c_str());
115
}
116
else
117
{
118
const std::string curDirAfter = currentDirectory.substr(curDirColon + 1);
119
if (! ApplyPathStringToComponentsVector(cmpnts, curDirAfter) )
120
{
121
ERROR_LOG(Log::FileSystem,"RealPath: currentDirectory is not a valid path: \"%s\"", currentDirectory.c_str());
122
return false;
123
}
124
125
outPathCapacityGuess += curDirLen;
126
}
127
128
prefix = currentDirectory.substr(0, curDirColon + 1);
129
inAfterColon = inPath;
130
}
131
else
132
{
133
prefix = inPath.substr(0, inColon + 1);
134
inAfterColon = inPath.substr(inColon + 1);
135
136
// Special case: "disc0:" is different from "disc0:/", so keep track of the single slash.
137
if (inAfterColon == "/")
138
{
139
outPath = prefix + inAfterColon;
140
return true;
141
}
142
}
143
144
if (! ApplyPathStringToComponentsVector(cmpnts, inAfterColon) )
145
{
146
WARN_LOG(Log::FileSystem, "RealPath: inPath is not a valid path: \"%s\"", inPath.c_str());
147
return false;
148
}
149
150
outPath.clear();
151
outPath.reserve(outPathCapacityGuess);
152
153
outPath.append(prefix);
154
155
size_t numCmpnts = cmpnts.size();
156
for (size_t i = 0; i < numCmpnts; i++)
157
{
158
outPath.append(1, '/');
159
outPath.append(cmpnts[i]);
160
}
161
162
return true;
163
}
164
165
IFileSystem *MetaFileSystem::GetHandleOwner(u32 handle) const
166
{
167
std::lock_guard<std::recursive_mutex> guard(lock);
168
for (size_t i = 0; i < fileSystems.size(); i++)
169
{
170
if (fileSystems[i].system->OwnsHandle(handle))
171
return fileSystems[i].system.get();
172
}
173
174
// Not found
175
return nullptr;
176
}
177
178
int MetaFileSystem::MapFilePath(std::string_view _inpath, std::string *outpath, MountPoint **system) {
179
int error = SCE_KERNEL_ERROR_ERRNO_FILE_NOT_FOUND;
180
std::lock_guard<std::recursive_mutex> guard(lock);
181
std::string realpath;
182
183
std::string inpath(_inpath);
184
185
// "ms0:/file.txt" is equivalent to " ms0:/file.txt". Yes, really.
186
if (inpath.find(':') != inpath.npos) {
187
size_t offset = 0;
188
while (inpath[offset] == ' ') {
189
offset++;
190
}
191
if (offset > 0) {
192
inpath = inpath.substr(offset);
193
}
194
}
195
196
// Special handling: host0:command.txt (as seen in Super Monkey Ball Adventures, for example)
197
// appears to mean the current directory on the UMD. Let's just assume the current directory.
198
if (strncasecmp(inpath.c_str(), "host0:", strlen("host0:")) == 0) {
199
INFO_LOG(Log::FileSystem, "Host0 path detected, stripping: %s", inpath.c_str());
200
// However, this causes trouble when running tests, since our test framework uses host0:.
201
// Maybe it's really just supposed to map to umd0 or something?
202
if (PSP_CoreParameter().headLess) {
203
inpath = "umd0:" + inpath.substr(strlen("host0:"));
204
} else {
205
inpath = inpath.substr(strlen("host0:"));
206
}
207
}
208
209
const std::string *currentDirectory = &startingDirectory;
210
211
int currentThread = __KernelGetCurThread();
212
currentDir_t::iterator it = currentDir.find(currentThread);
213
if (it == currentDir.end())
214
{
215
//Attempt to emulate SCE_KERNEL_ERROR_NOCWD / 8002032C: may break things requiring fixes elsewhere
216
if (inpath.find(':') == std::string::npos /* means path is relative */)
217
{
218
error = SCE_KERNEL_ERROR_NOCWD;
219
WARN_LOG(Log::FileSystem, "Path is relative, but current directory not set for thread %i. returning 8002032C(SCE_KERNEL_ERROR_NOCWD) instead.", currentThread);
220
}
221
}
222
else
223
{
224
currentDirectory = &(it->second);
225
}
226
227
if (RealPath(*currentDirectory, inpath, realpath))
228
{
229
std::string prefix = realpath;
230
size_t prefixPos = realpath.find(':');
231
if (prefixPos != realpath.npos)
232
prefix = NormalizePrefix(realpath.substr(0, prefixPos + 1));
233
234
for (size_t i = 0; i < fileSystems.size(); i++)
235
{
236
size_t prefLen = fileSystems[i].prefix.size();
237
if (strncasecmp(fileSystems[i].prefix.c_str(), prefix.c_str(), prefLen) == 0)
238
{
239
*outpath = realpath.substr(prefixPos + 1);
240
*system = &(fileSystems[i]);
241
242
VERBOSE_LOG(Log::FileSystem, "MapFilePath: mapped \"%s\" to prefix: \"%s\", path: \"%s\"", inpath.c_str(), fileSystems[i].prefix.c_str(), outpath->c_str());
243
244
return error == SCE_KERNEL_ERROR_NOCWD ? error : 0;
245
}
246
}
247
248
error = SCE_KERNEL_ERROR_NODEV;
249
}
250
251
DEBUG_LOG(Log::FileSystem, "MapFilePath: failed mapping \"%s\", returning false", inpath.c_str());
252
return error;
253
}
254
255
std::string MetaFileSystem::NormalizePrefix(std::string_view prefix) const {
256
// Let's apply some mapping here since it won't break savestates.
257
if (prefix == "memstick:")
258
prefix = "ms0:";
259
// Seems like umd00: etc. work just fine... avoid umd1/umd for tests.
260
if (startsWith(prefix, "umd") && prefix != "umd1:" && prefix != "umd:")
261
prefix = "umd0:";
262
// Seems like umd00: etc. work just fine...
263
if (startsWith(prefix, "host"))
264
prefix = "host0:";
265
266
// Should we simply make this case insensitive?
267
if (prefix == "DISC0:")
268
prefix = "disc0:";
269
270
return std::string(prefix);
271
}
272
273
void MetaFileSystem::Mount(std::string_view prefix, std::shared_ptr<IFileSystem> system) {
274
std::lock_guard<std::recursive_mutex> guard(lock);
275
for (auto &it : fileSystems) {
276
if (it.prefix == prefix) {
277
// Overwrite the old mount.
278
// shared_ptr makes sure there's no leak.
279
it.system = system;
280
return;
281
}
282
}
283
284
// Prefix not yet mounted, do so.
285
MountPoint x;
286
x.prefix = prefix;
287
x.system = system;
288
fileSystems.push_back(x);
289
}
290
291
// Assumes the lock is held
292
void MetaFileSystem::UnmountAll() {
293
fileSystems.clear();
294
currentDir.clear();
295
}
296
297
void MetaFileSystem::Unmount(std::string_view prefix) {
298
std::lock_guard<std::recursive_mutex> guard(lock);
299
for (auto iter = fileSystems.begin(); iter != fileSystems.end(); iter++) {
300
if (iter->prefix == prefix) {
301
fileSystems.erase(iter);
302
return;
303
}
304
}
305
}
306
307
IFileSystem *MetaFileSystem::GetSystemFromFilename(std::string_view filename) {
308
size_t prefixPos = filename.find(':');
309
if (prefixPos == filename.npos)
310
return 0;
311
return GetSystem(filename.substr(0, prefixPos + 1));
312
}
313
314
IFileSystem *MetaFileSystem::GetSystem(std::string_view prefix) {
315
std::lock_guard<std::recursive_mutex> guard(lock);
316
for (auto it = fileSystems.begin(); it != fileSystems.end(); ++it) {
317
if (it->prefix == NormalizePrefix(prefix))
318
return it->system.get();
319
}
320
return NULL;
321
}
322
323
void MetaFileSystem::Shutdown() {
324
std::lock_guard<std::recursive_mutex> guard(lock);
325
326
UnmountAll();
327
Reset();
328
}
329
330
int MetaFileSystem::OpenFile(std::string filename, FileAccess access, const char *devicename)
331
{
332
std::lock_guard<std::recursive_mutex> guard(lock);
333
std::string of;
334
MountPoint *mount;
335
int error = MapFilePath(filename, &of, &mount);
336
if (error == 0)
337
return mount->system->OpenFile(of, access, mount->prefix.c_str());
338
else
339
return error;
340
}
341
342
PSPFileInfo MetaFileSystem::GetFileInfo(std::string filename)
343
{
344
std::lock_guard<std::recursive_mutex> guard(lock);
345
std::string of;
346
IFileSystem *system;
347
int error = MapFilePath(filename, &of, &system);
348
if (error == 0)
349
{
350
return system->GetFileInfo(of);
351
}
352
else
353
{
354
PSPFileInfo bogus;
355
return bogus;
356
}
357
}
358
359
PSPFileInfo MetaFileSystem::GetFileInfoByHandle(u32 handle) {
360
std::lock_guard<std::recursive_mutex> guard(lock);
361
IFileSystem *sys = GetHandleOwner(handle);
362
if (sys)
363
return sys->GetFileInfoByHandle(handle);
364
return PSPFileInfo();
365
}
366
367
std::vector<PSPFileInfo> MetaFileSystem::GetDirListing(const std::string &path, bool *exists) {
368
std::lock_guard<std::recursive_mutex> guard(lock);
369
std::string of;
370
IFileSystem *system;
371
int error = MapFilePath(path, &of, &system);
372
if (error == 0) {
373
return system->GetDirListing(of, exists);
374
} else {
375
std::vector<PSPFileInfo> empty;
376
if (exists)
377
*exists = false;
378
return empty;
379
}
380
}
381
382
void MetaFileSystem::ThreadEnded(int threadID)
383
{
384
std::lock_guard<std::recursive_mutex> guard(lock);
385
currentDir.erase(threadID);
386
}
387
388
int MetaFileSystem::ChDir(const std::string &dir)
389
{
390
std::lock_guard<std::recursive_mutex> guard(lock);
391
// Retain the old path and fail if the arg is 1023 bytes or longer.
392
if (dir.size() >= 1023)
393
return SCE_KERNEL_ERROR_NAMETOOLONG;
394
395
int curThread = __KernelGetCurThread();
396
397
std::string of;
398
MountPoint *mountPoint;
399
int error = MapFilePath(dir, &of, &mountPoint);
400
if (error == 0)
401
{
402
currentDir[curThread] = mountPoint->prefix + of;
403
return 0;
404
}
405
else
406
{
407
for (size_t i = 0; i < fileSystems.size(); i++)
408
{
409
const std::string &prefix = fileSystems[i].prefix;
410
if (strncasecmp(prefix.c_str(), dir.c_str(), prefix.size()) == 0)
411
{
412
// The PSP is completely happy with invalid current dirs as long as they have a valid device.
413
WARN_LOG(Log::FileSystem, "ChDir failed to map path \"%s\", saving as current directory anyway", dir.c_str());
414
currentDir[curThread] = dir;
415
return 0;
416
}
417
}
418
419
WARN_LOG_REPORT(Log::FileSystem, "ChDir failed to map device for \"%s\", failing", dir.c_str());
420
return SCE_KERNEL_ERROR_NODEV;
421
}
422
}
423
424
bool MetaFileSystem::MkDir(const std::string &dirname)
425
{
426
std::lock_guard<std::recursive_mutex> guard(lock);
427
std::string of;
428
IFileSystem *system;
429
int error = MapFilePath(dirname, &of, &system);
430
if (error == 0)
431
{
432
return system->MkDir(of);
433
}
434
else
435
{
436
return false;
437
}
438
}
439
440
bool MetaFileSystem::RmDir(const std::string &dirname)
441
{
442
std::lock_guard<std::recursive_mutex> guard(lock);
443
std::string of;
444
IFileSystem *system;
445
int error = MapFilePath(dirname, &of, &system);
446
if (error == 0)
447
{
448
return system->RmDir(of);
449
}
450
else
451
{
452
return false;
453
}
454
}
455
456
int MetaFileSystem::RenameFile(const std::string &from, const std::string &to)
457
{
458
std::lock_guard<std::recursive_mutex> guard(lock);
459
std::string of;
460
std::string rf;
461
IFileSystem *osystem;
462
IFileSystem *rsystem = NULL;
463
int error = MapFilePath(from, &of, &osystem);
464
if (error == 0)
465
{
466
// If it's a relative path, it seems to always use from's filesystem.
467
if (to.find(":/") != to.npos)
468
{
469
error = MapFilePath(to, &rf, &rsystem);
470
if (error < 0)
471
return -1;
472
}
473
else
474
{
475
rf = to;
476
rsystem = osystem;
477
}
478
479
if (osystem != rsystem)
480
return SCE_KERNEL_ERROR_XDEV;
481
482
return osystem->RenameFile(of, rf);
483
}
484
else
485
{
486
return -1;
487
}
488
}
489
490
bool MetaFileSystem::RemoveFile(const std::string &filename)
491
{
492
std::lock_guard<std::recursive_mutex> guard(lock);
493
std::string of;
494
IFileSystem *system;
495
int error = MapFilePath(filename, &of, &system);
496
if (error == 0) {
497
return system->RemoveFile(of);
498
} else {
499
return false;
500
}
501
}
502
503
int MetaFileSystem::Ioctl(u32 handle, u32 cmd, u32 indataPtr, u32 inlen, u32 outdataPtr, u32 outlen, int &usec)
504
{
505
std::lock_guard<std::recursive_mutex> guard(lock);
506
IFileSystem *sys = GetHandleOwner(handle);
507
if (sys)
508
return sys->Ioctl(handle, cmd, indataPtr, inlen, outdataPtr, outlen, usec);
509
return SCE_KERNEL_ERROR_ERROR;
510
}
511
512
PSPDevType MetaFileSystem::DevType(u32 handle)
513
{
514
std::lock_guard<std::recursive_mutex> guard(lock);
515
IFileSystem *sys = GetHandleOwner(handle);
516
if (sys)
517
return sys->DevType(handle);
518
return PSPDevType::INVALID;
519
}
520
521
void MetaFileSystem::CloseFile(u32 handle)
522
{
523
std::lock_guard<std::recursive_mutex> guard(lock);
524
IFileSystem *sys = GetHandleOwner(handle);
525
if (sys)
526
sys->CloseFile(handle);
527
}
528
529
size_t MetaFileSystem::ReadFile(u32 handle, u8 *pointer, s64 size)
530
{
531
std::lock_guard<std::recursive_mutex> guard(lock);
532
IFileSystem *sys = GetHandleOwner(handle);
533
if (sys)
534
return sys->ReadFile(handle, pointer, size);
535
else
536
return 0;
537
}
538
539
size_t MetaFileSystem::WriteFile(u32 handle, const u8 *pointer, s64 size)
540
{
541
std::lock_guard<std::recursive_mutex> guard(lock);
542
IFileSystem *sys = GetHandleOwner(handle);
543
if (sys)
544
return sys->WriteFile(handle, pointer, size);
545
else
546
return 0;
547
}
548
549
size_t MetaFileSystem::ReadFile(u32 handle, u8 *pointer, s64 size, int &usec)
550
{
551
std::lock_guard<std::recursive_mutex> guard(lock);
552
IFileSystem *sys = GetHandleOwner(handle);
553
if (sys)
554
return sys->ReadFile(handle, pointer, size, usec);
555
else
556
return 0;
557
}
558
559
size_t MetaFileSystem::WriteFile(u32 handle, const u8 *pointer, s64 size, int &usec)
560
{
561
std::lock_guard<std::recursive_mutex> guard(lock);
562
IFileSystem *sys = GetHandleOwner(handle);
563
if (sys)
564
return sys->WriteFile(handle, pointer, size, usec);
565
else
566
return 0;
567
}
568
569
size_t MetaFileSystem::SeekFile(u32 handle, s32 position, FileMove type)
570
{
571
std::lock_guard<std::recursive_mutex> guard(lock);
572
IFileSystem *sys = GetHandleOwner(handle);
573
if (sys)
574
return sys->SeekFile(handle, position, type);
575
else
576
return 0;
577
}
578
579
int MetaFileSystem::ReadEntireFile(const std::string &filename, std::vector<u8> &data, bool quiet) {
580
FileAccess access = FILEACCESS_READ;
581
if (quiet) {
582
access = (FileAccess)(access | FILEACCESS_PPSSPP_QUIET);
583
}
584
int handle = OpenFile(filename, access);
585
if (handle < 0)
586
return handle;
587
588
SeekFile(handle, 0, FILEMOVE_END);
589
size_t dataSize = GetSeekPos(handle);
590
SeekFile(handle, 0, FILEMOVE_BEGIN);
591
data.resize(dataSize);
592
593
size_t result = ReadFile(handle, data.data(), dataSize);
594
CloseFile(handle);
595
596
if (result != dataSize)
597
return SCE_KERNEL_ERROR_ERROR;
598
599
return 0;
600
}
601
602
u64 MetaFileSystem::FreeDiskSpace(const std::string &path) {
603
std::lock_guard<std::recursive_mutex> guard(lock);
604
std::string of;
605
IFileSystem *system;
606
int error = MapFilePath(path, &of, &system);
607
if (error == 0)
608
return system->FreeDiskSpace(of);
609
else
610
return 0;
611
}
612
613
void MetaFileSystem::DoState(PointerWrap &p) {
614
std::lock_guard<std::recursive_mutex> guard(lock);
615
616
auto s = p.Section("MetaFileSystem", 1);
617
if (!s)
618
return;
619
620
Do(p, current);
621
622
// Save/load per-thread current directory map
623
Do(p, currentDir);
624
625
u32 n = (u32) fileSystems.size();
626
Do(p, n);
627
bool skipPfat0 = false;
628
if (n != (u32) fileSystems.size()) {
629
if (n == (u32) fileSystems.size() - 1) {
630
skipPfat0 = true;
631
} else {
632
p.SetError(p.ERROR_FAILURE);
633
ERROR_LOG(Log::FileSystem, "Savestate failure: number of filesystems doesn't match.");
634
return;
635
}
636
}
637
638
for (u32 i = 0; i < n; ++i) {
639
if (!skipPfat0 || fileSystems[i].prefix != "pfat0:") {
640
fileSystems[i].system->DoState(p);
641
}
642
}
643
}
644
645
int64_t MetaFileSystem::RecursiveSize(std::string_view dirPath) {
646
u64 result = 0;
647
auto allFiles = GetDirListing(std::string(dirPath));
648
for (const auto &file : allFiles) {
649
if (file.name == "." || file.name == "..")
650
continue;
651
if (file.type == FILETYPE_DIRECTORY) {
652
result += RecursiveSize(join(dirPath, file.name));
653
} else {
654
result += file.size;
655
}
656
}
657
return result;
658
}
659
660
int64_t MetaFileSystem::ComputeRecursiveDirectorySize(std::string_view filename) {
661
std::lock_guard<std::recursive_mutex> guard(lock);
662
std::string of;
663
IFileSystem *system;
664
int error = MapFilePath(filename, &of, &system);
665
if (error == 0) {
666
int64_t size;
667
if (system->ComputeRecursiveDirSizeIfFast(of, &size)) {
668
// Some file systems can optimize this.
669
return size;
670
} else {
671
// Those that can't, we just run a generic implementation.
672
return RecursiveSize(filename);
673
}
674
} else {
675
return false;
676
}
677
}
678
679
bool MetaFileSystem::ComputeRecursiveDirSizeIfFast(const std::string &path, int64_t *size) {
680
// Shouldn't be called. Can't recurse MetaFileSystem.
681
_dbg_assert_(false);
682
return false;
683
}
684
685