Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hrydgard
GitHub Repository: hrydgard/ppsspp
Path: blob/master/Core/FileSystems/MetaFileSystem.cpp
3186 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(const std::string &_inpath, std::string &outpath, MountPoint **system)
179
{
180
int error = SCE_KERNEL_ERROR_ERRNO_FILE_NOT_FOUND;
181
std::lock_guard<std::recursive_mutex> guard(lock);
182
std::string realpath;
183
184
std::string inpath = _inpath;
185
186
// "ms0:/file.txt" is equivalent to " ms0:/file.txt". Yes, really.
187
if (inpath.find(':') != inpath.npos) {
188
size_t offset = 0;
189
while (inpath[offset] == ' ') {
190
offset++;
191
}
192
if (offset > 0) {
193
inpath = inpath.substr(offset);
194
}
195
}
196
197
// Special handling: host0:command.txt (as seen in Super Monkey Ball Adventures, for example)
198
// appears to mean the current directory on the UMD. Let's just assume the current directory.
199
if (strncasecmp(inpath.c_str(), "host0:", strlen("host0:")) == 0) {
200
INFO_LOG(Log::FileSystem, "Host0 path detected, stripping: %s", inpath.c_str());
201
// However, this causes trouble when running tests, since our test framework uses host0:.
202
// Maybe it's really just supposed to map to umd0 or something?
203
if (PSP_CoreParameter().headLess) {
204
inpath = "umd0:" + inpath.substr(strlen("host0:"));
205
} else {
206
inpath = inpath.substr(strlen("host0:"));
207
}
208
}
209
210
const std::string *currentDirectory = &startingDirectory;
211
212
int currentThread = __KernelGetCurThread();
213
currentDir_t::iterator it = currentDir.find(currentThread);
214
if (it == currentDir.end())
215
{
216
//Attempt to emulate SCE_KERNEL_ERROR_NOCWD / 8002032C: may break things requiring fixes elsewhere
217
if (inpath.find(':') == std::string::npos /* means path is relative */)
218
{
219
error = SCE_KERNEL_ERROR_NOCWD;
220
WARN_LOG(Log::FileSystem, "Path is relative, but current directory not set for thread %i. returning 8002032C(SCE_KERNEL_ERROR_NOCWD) instead.", currentThread);
221
}
222
}
223
else
224
{
225
currentDirectory = &(it->second);
226
}
227
228
if (RealPath(*currentDirectory, inpath, realpath))
229
{
230
std::string prefix = realpath;
231
size_t prefixPos = realpath.find(':');
232
if (prefixPos != realpath.npos)
233
prefix = NormalizePrefix(realpath.substr(0, prefixPos + 1));
234
235
for (size_t i = 0; i < fileSystems.size(); i++)
236
{
237
size_t prefLen = fileSystems[i].prefix.size();
238
if (strncasecmp(fileSystems[i].prefix.c_str(), prefix.c_str(), prefLen) == 0)
239
{
240
outpath = realpath.substr(prefixPos + 1);
241
*system = &(fileSystems[i]);
242
243
VERBOSE_LOG(Log::FileSystem, "MapFilePath: mapped \"%s\" to prefix: \"%s\", path: \"%s\"", inpath.c_str(), fileSystems[i].prefix.c_str(), outpath.c_str());
244
245
return error == SCE_KERNEL_ERROR_NOCWD ? error : 0;
246
}
247
}
248
249
error = SCE_KERNEL_ERROR_NODEV;
250
}
251
252
DEBUG_LOG(Log::FileSystem, "MapFilePath: failed mapping \"%s\", returning false", inpath.c_str());
253
return error;
254
}
255
256
std::string MetaFileSystem::NormalizePrefix(std::string prefix) const {
257
// Let's apply some mapping here since it won't break savestates.
258
if (prefix == "memstick:")
259
prefix = "ms0:";
260
// Seems like umd00: etc. work just fine... avoid umd1/umd for tests.
261
if (startsWith(prefix, "umd") && prefix != "umd1:" && prefix != "umd:")
262
prefix = "umd0:";
263
// Seems like umd00: etc. work just fine...
264
if (startsWith(prefix, "host"))
265
prefix = "host0:";
266
267
// Should we simply make this case insensitive?
268
if (prefix == "DISC0:")
269
prefix = "disc0:";
270
271
return prefix;
272
}
273
274
void MetaFileSystem::Mount(const std::string &prefix, std::shared_ptr<IFileSystem> system) {
275
std::lock_guard<std::recursive_mutex> guard(lock);
276
for (auto &it : fileSystems) {
277
if (it.prefix == prefix) {
278
// Overwrite the old mount.
279
// shared_ptr makes sure there's no leak.
280
it.system = system;
281
return;
282
}
283
}
284
285
// Prefix not yet mounted, do so.
286
MountPoint x;
287
x.prefix = prefix;
288
x.system = system;
289
fileSystems.push_back(x);
290
}
291
292
// Assumes the lock is held
293
void MetaFileSystem::UnmountAll() {
294
fileSystems.clear();
295
currentDir.clear();
296
}
297
298
void MetaFileSystem::Unmount(const std::string &prefix) {
299
std::lock_guard<std::recursive_mutex> guard(lock);
300
for (auto iter = fileSystems.begin(); iter != fileSystems.end(); iter++) {
301
if (iter->prefix == prefix) {
302
fileSystems.erase(iter);
303
return;
304
}
305
}
306
}
307
308
IFileSystem *MetaFileSystem::GetSystemFromFilename(const std::string &filename) {
309
size_t prefixPos = filename.find(':');
310
if (prefixPos == filename.npos)
311
return 0;
312
return GetSystem(filename.substr(0, prefixPos + 1));
313
}
314
315
IFileSystem *MetaFileSystem::GetSystem(const std::string &prefix) {
316
std::lock_guard<std::recursive_mutex> guard(lock);
317
for (auto it = fileSystems.begin(); it != fileSystems.end(); ++it) {
318
if (it->prefix == NormalizePrefix(prefix))
319
return it->system.get();
320
}
321
return NULL;
322
}
323
324
void MetaFileSystem::Shutdown() {
325
std::lock_guard<std::recursive_mutex> guard(lock);
326
327
UnmountAll();
328
Reset();
329
}
330
331
int MetaFileSystem::OpenFile(std::string filename, FileAccess access, const char *devicename)
332
{
333
std::lock_guard<std::recursive_mutex> guard(lock);
334
std::string of;
335
MountPoint *mount;
336
int error = MapFilePath(filename, of, &mount);
337
if (error == 0)
338
return mount->system->OpenFile(of, access, mount->prefix.c_str());
339
else
340
return error;
341
}
342
343
PSPFileInfo MetaFileSystem::GetFileInfo(std::string filename)
344
{
345
std::lock_guard<std::recursive_mutex> guard(lock);
346
std::string of;
347
IFileSystem *system;
348
int error = MapFilePath(filename, of, &system);
349
if (error == 0)
350
{
351
return system->GetFileInfo(of);
352
}
353
else
354
{
355
PSPFileInfo bogus;
356
return bogus;
357
}
358
}
359
360
PSPFileInfo MetaFileSystem::GetFileInfoByHandle(u32 handle) {
361
std::lock_guard<std::recursive_mutex> guard(lock);
362
IFileSystem *sys = GetHandleOwner(handle);
363
if (sys)
364
return sys->GetFileInfoByHandle(handle);
365
return PSPFileInfo();
366
}
367
368
std::vector<PSPFileInfo> MetaFileSystem::GetDirListing(const std::string &path, bool *exists) {
369
std::lock_guard<std::recursive_mutex> guard(lock);
370
std::string of;
371
IFileSystem *system;
372
int error = MapFilePath(path, of, &system);
373
if (error == 0) {
374
return system->GetDirListing(of, exists);
375
} else {
376
std::vector<PSPFileInfo> empty;
377
if (exists)
378
*exists = false;
379
return empty;
380
}
381
}
382
383
void MetaFileSystem::ThreadEnded(int threadID)
384
{
385
std::lock_guard<std::recursive_mutex> guard(lock);
386
currentDir.erase(threadID);
387
}
388
389
int MetaFileSystem::ChDir(const std::string &dir)
390
{
391
std::lock_guard<std::recursive_mutex> guard(lock);
392
// Retain the old path and fail if the arg is 1023 bytes or longer.
393
if (dir.size() >= 1023)
394
return SCE_KERNEL_ERROR_NAMETOOLONG;
395
396
int curThread = __KernelGetCurThread();
397
398
std::string of;
399
MountPoint *mountPoint;
400
int error = MapFilePath(dir, of, &mountPoint);
401
if (error == 0)
402
{
403
currentDir[curThread] = mountPoint->prefix + of;
404
return 0;
405
}
406
else
407
{
408
for (size_t i = 0; i < fileSystems.size(); i++)
409
{
410
const std::string &prefix = fileSystems[i].prefix;
411
if (strncasecmp(prefix.c_str(), dir.c_str(), prefix.size()) == 0)
412
{
413
// The PSP is completely happy with invalid current dirs as long as they have a valid device.
414
WARN_LOG(Log::FileSystem, "ChDir failed to map path \"%s\", saving as current directory anyway", dir.c_str());
415
currentDir[curThread] = dir;
416
return 0;
417
}
418
}
419
420
WARN_LOG_REPORT(Log::FileSystem, "ChDir failed to map device for \"%s\", failing", dir.c_str());
421
return SCE_KERNEL_ERROR_NODEV;
422
}
423
}
424
425
bool MetaFileSystem::MkDir(const std::string &dirname)
426
{
427
std::lock_guard<std::recursive_mutex> guard(lock);
428
std::string of;
429
IFileSystem *system;
430
int error = MapFilePath(dirname, of, &system);
431
if (error == 0)
432
{
433
return system->MkDir(of);
434
}
435
else
436
{
437
return false;
438
}
439
}
440
441
bool MetaFileSystem::RmDir(const std::string &dirname)
442
{
443
std::lock_guard<std::recursive_mutex> guard(lock);
444
std::string of;
445
IFileSystem *system;
446
int error = MapFilePath(dirname, of, &system);
447
if (error == 0)
448
{
449
return system->RmDir(of);
450
}
451
else
452
{
453
return false;
454
}
455
}
456
457
int MetaFileSystem::RenameFile(const std::string &from, const std::string &to)
458
{
459
std::lock_guard<std::recursive_mutex> guard(lock);
460
std::string of;
461
std::string rf;
462
IFileSystem *osystem;
463
IFileSystem *rsystem = NULL;
464
int error = MapFilePath(from, of, &osystem);
465
if (error == 0)
466
{
467
// If it's a relative path, it seems to always use from's filesystem.
468
if (to.find(":/") != to.npos)
469
{
470
error = MapFilePath(to, rf, &rsystem);
471
if (error < 0)
472
return -1;
473
}
474
else
475
{
476
rf = to;
477
rsystem = osystem;
478
}
479
480
if (osystem != rsystem)
481
return SCE_KERNEL_ERROR_XDEV;
482
483
return osystem->RenameFile(of, rf);
484
}
485
else
486
{
487
return -1;
488
}
489
}
490
491
bool MetaFileSystem::RemoveFile(const std::string &filename)
492
{
493
std::lock_guard<std::recursive_mutex> guard(lock);
494
std::string of;
495
IFileSystem *system;
496
int error = MapFilePath(filename, of, &system);
497
if (error == 0) {
498
return system->RemoveFile(of);
499
} else {
500
return false;
501
}
502
}
503
504
int MetaFileSystem::Ioctl(u32 handle, u32 cmd, u32 indataPtr, u32 inlen, u32 outdataPtr, u32 outlen, int &usec)
505
{
506
std::lock_guard<std::recursive_mutex> guard(lock);
507
IFileSystem *sys = GetHandleOwner(handle);
508
if (sys)
509
return sys->Ioctl(handle, cmd, indataPtr, inlen, outdataPtr, outlen, usec);
510
return SCE_KERNEL_ERROR_ERROR;
511
}
512
513
PSPDevType MetaFileSystem::DevType(u32 handle)
514
{
515
std::lock_guard<std::recursive_mutex> guard(lock);
516
IFileSystem *sys = GetHandleOwner(handle);
517
if (sys)
518
return sys->DevType(handle);
519
return PSPDevType::INVALID;
520
}
521
522
void MetaFileSystem::CloseFile(u32 handle)
523
{
524
std::lock_guard<std::recursive_mutex> guard(lock);
525
IFileSystem *sys = GetHandleOwner(handle);
526
if (sys)
527
sys->CloseFile(handle);
528
}
529
530
size_t MetaFileSystem::ReadFile(u32 handle, u8 *pointer, s64 size)
531
{
532
std::lock_guard<std::recursive_mutex> guard(lock);
533
IFileSystem *sys = GetHandleOwner(handle);
534
if (sys)
535
return sys->ReadFile(handle, pointer, size);
536
else
537
return 0;
538
}
539
540
size_t MetaFileSystem::WriteFile(u32 handle, const u8 *pointer, s64 size)
541
{
542
std::lock_guard<std::recursive_mutex> guard(lock);
543
IFileSystem *sys = GetHandleOwner(handle);
544
if (sys)
545
return sys->WriteFile(handle, pointer, size);
546
else
547
return 0;
548
}
549
550
size_t MetaFileSystem::ReadFile(u32 handle, u8 *pointer, s64 size, int &usec)
551
{
552
std::lock_guard<std::recursive_mutex> guard(lock);
553
IFileSystem *sys = GetHandleOwner(handle);
554
if (sys)
555
return sys->ReadFile(handle, pointer, size, usec);
556
else
557
return 0;
558
}
559
560
size_t MetaFileSystem::WriteFile(u32 handle, const u8 *pointer, s64 size, int &usec)
561
{
562
std::lock_guard<std::recursive_mutex> guard(lock);
563
IFileSystem *sys = GetHandleOwner(handle);
564
if (sys)
565
return sys->WriteFile(handle, pointer, size, usec);
566
else
567
return 0;
568
}
569
570
size_t MetaFileSystem::SeekFile(u32 handle, s32 position, FileMove type)
571
{
572
std::lock_guard<std::recursive_mutex> guard(lock);
573
IFileSystem *sys = GetHandleOwner(handle);
574
if (sys)
575
return sys->SeekFile(handle, position, type);
576
else
577
return 0;
578
}
579
580
int MetaFileSystem::ReadEntireFile(const std::string &filename, std::vector<u8> &data, bool quiet) {
581
FileAccess access = FILEACCESS_READ;
582
if (quiet) {
583
access = (FileAccess)(access | FILEACCESS_PPSSPP_QUIET);
584
}
585
int handle = OpenFile(filename, access);
586
if (handle < 0)
587
return handle;
588
589
SeekFile(handle, 0, FILEMOVE_END);
590
size_t dataSize = GetSeekPos(handle);
591
SeekFile(handle, 0, FILEMOVE_BEGIN);
592
data.resize(dataSize);
593
594
size_t result = ReadFile(handle, data.data(), dataSize);
595
CloseFile(handle);
596
597
if (result != dataSize)
598
return SCE_KERNEL_ERROR_ERROR;
599
600
return 0;
601
}
602
603
u64 MetaFileSystem::FreeDiskSpace(const std::string &path) {
604
std::lock_guard<std::recursive_mutex> guard(lock);
605
std::string of;
606
IFileSystem *system;
607
int error = MapFilePath(path, of, &system);
608
if (error == 0)
609
return system->FreeDiskSpace(of);
610
else
611
return 0;
612
}
613
614
void MetaFileSystem::DoState(PointerWrap &p) {
615
std::lock_guard<std::recursive_mutex> guard(lock);
616
617
auto s = p.Section("MetaFileSystem", 1);
618
if (!s)
619
return;
620
621
Do(p, current);
622
623
// Save/load per-thread current directory map
624
Do(p, currentDir);
625
626
u32 n = (u32) fileSystems.size();
627
Do(p, n);
628
bool skipPfat0 = false;
629
if (n != (u32) fileSystems.size()) {
630
if (n == (u32) fileSystems.size() - 1) {
631
skipPfat0 = true;
632
} else {
633
p.SetError(p.ERROR_FAILURE);
634
ERROR_LOG(Log::FileSystem, "Savestate failure: number of filesystems doesn't match.");
635
return;
636
}
637
}
638
639
for (u32 i = 0; i < n; ++i) {
640
if (!skipPfat0 || fileSystems[i].prefix != "pfat0:") {
641
fileSystems[i].system->DoState(p);
642
}
643
}
644
}
645
646
int64_t MetaFileSystem::RecursiveSize(const std::string &dirPath) {
647
u64 result = 0;
648
auto allFiles = GetDirListing(dirPath);
649
for (const auto &file : allFiles) {
650
if (file.name == "." || file.name == "..")
651
continue;
652
if (file.type == FILETYPE_DIRECTORY) {
653
result += RecursiveSize(dirPath + file.name);
654
} else {
655
result += file.size;
656
}
657
}
658
return result;
659
}
660
661
int64_t MetaFileSystem::ComputeRecursiveDirectorySize(const std::string &filename) {
662
std::lock_guard<std::recursive_mutex> guard(lock);
663
std::string of;
664
IFileSystem *system;
665
int error = MapFilePath(filename, of, &system);
666
if (error == 0) {
667
int64_t size;
668
if (system->ComputeRecursiveDirSizeIfFast(of, &size)) {
669
// Some file systems can optimize this.
670
return size;
671
} else {
672
// Those that can't, we just run a generic implementation.
673
return RecursiveSize(filename);
674
}
675
} else {
676
return false;
677
}
678
}
679
680
bool MetaFileSystem::ComputeRecursiveDirSizeIfFast(const std::string &path, int64_t *size) {
681
// Shouldn't be called. Can't recurse MetaFileSystem.
682
_dbg_assert_(false);
683
return false;
684
}
685
686