CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
hrydgard

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

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