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
ApplyPathStringToComponentsVector(std::vector<std::string> & vector,const std::string & pathString)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(FILESYS, "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 */
RealPath(const std::string & currentDirectory,const std::string & inPath,std::string & outPath)77 static bool RealPath(const std::string ¤tDirectory, const std::string &inPath, std::string &outPath)
78 {
79 size_t inLen = inPath.length();
80 if (inLen == 0)
81 {
82 WARN_LOG(FILESYS, "RealPath: inPath is empty");
83 outPath = currentDirectory;
84 return true;
85 }
86
87 size_t inColon = inPath.find(':');
88 if (inColon + 1 == inLen)
89 {
90 // There's nothing after the colon, e.g. umd0: - this is perfectly valid.
91 outPath = inPath;
92 return true;
93 }
94
95 bool relative = (inColon == std::string::npos);
96
97 std::string prefix, inAfterColon;
98 std::vector<std::string> cmpnts; // path components
99 size_t outPathCapacityGuess = inPath.length();
100
101 if (relative)
102 {
103 size_t curDirLen = currentDirectory.length();
104 if (curDirLen == 0)
105 {
106 ERROR_LOG(FILESYS, "RealPath: inPath \"%s\" is relative, but current directory is empty", inPath.c_str());
107 return false;
108 }
109
110 size_t curDirColon = currentDirectory.find(':');
111 if (curDirColon == std::string::npos)
112 {
113 ERROR_LOG(FILESYS, "RealPath: inPath \"%s\" is relative, but current directory \"%s\" has no prefix", inPath.c_str(), currentDirectory.c_str());
114 return false;
115 }
116 if (curDirColon + 1 == curDirLen)
117 {
118 WARN_LOG(FILESYS, "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());
119 }
120 else
121 {
122 const std::string curDirAfter = currentDirectory.substr(curDirColon + 1);
123 if (! ApplyPathStringToComponentsVector(cmpnts, curDirAfter) )
124 {
125 ERROR_LOG(FILESYS,"RealPath: currentDirectory is not a valid path: \"%s\"", currentDirectory.c_str());
126 return false;
127 }
128
129 outPathCapacityGuess += curDirLen;
130 }
131
132 prefix = currentDirectory.substr(0, curDirColon + 1);
133 inAfterColon = inPath;
134 }
135 else
136 {
137 prefix = inPath.substr(0, inColon + 1);
138 inAfterColon = inPath.substr(inColon + 1);
139
140 // Special case: "disc0:" is different from "disc0:/", so keep track of the single slash.
141 if (inAfterColon == "/")
142 {
143 outPath = prefix + inAfterColon;
144 return true;
145 }
146 }
147
148 if (! ApplyPathStringToComponentsVector(cmpnts, inAfterColon) )
149 {
150 WARN_LOG(FILESYS, "RealPath: inPath is not a valid path: \"%s\"", inPath.c_str());
151 return false;
152 }
153
154 outPath.clear();
155 outPath.reserve(outPathCapacityGuess);
156
157 outPath.append(prefix);
158
159 size_t numCmpnts = cmpnts.size();
160 for (size_t i = 0; i < numCmpnts; i++)
161 {
162 outPath.append(1, '/');
163 outPath.append(cmpnts[i]);
164 }
165
166 return true;
167 }
168
GetHandleOwner(u32 handle)169 IFileSystem *MetaFileSystem::GetHandleOwner(u32 handle)
170 {
171 std::lock_guard<std::recursive_mutex> guard(lock);
172 for (size_t i = 0; i < fileSystems.size(); i++)
173 {
174 if (fileSystems[i].system->OwnsHandle(handle))
175 return fileSystems[i].system.get();
176 }
177
178 // Not found
179 return nullptr;
180 }
181
MapFilePath(const std::string & _inpath,std::string & outpath,MountPoint ** system)182 int MetaFileSystem::MapFilePath(const std::string &_inpath, std::string &outpath, MountPoint **system)
183 {
184 int error = SCE_KERNEL_ERROR_ERRNO_FILE_NOT_FOUND;
185 std::lock_guard<std::recursive_mutex> guard(lock);
186 std::string realpath;
187
188 std::string inpath = _inpath;
189
190 // "ms0:/file.txt" is equivalent to " ms0:/file.txt". Yes, really.
191 if (inpath.find(':') != inpath.npos) {
192 size_t offset = 0;
193 while (inpath[offset] == ' ') {
194 offset++;
195 }
196 if (offset > 0) {
197 inpath = inpath.substr(offset);
198 }
199 }
200
201 // Special handling: host0:command.txt (as seen in Super Monkey Ball Adventures, for example)
202 // appears to mean the current directory on the UMD. Let's just assume the current directory.
203 if (strncasecmp(inpath.c_str(), "host0:", strlen("host0:")) == 0) {
204 INFO_LOG(FILESYS, "Host0 path detected, stripping: %s", inpath.c_str());
205 // However, this causes trouble when running tests, since our test framework uses host0:.
206 // Maybe it's really just supposed to map to umd0 or something?
207 if (PSP_CoreParameter().headLess) {
208 inpath = "umd0:" + inpath.substr(strlen("host0:"));
209 } else {
210 inpath = inpath.substr(strlen("host0:"));
211 }
212 }
213
214 const std::string *currentDirectory = &startingDirectory;
215
216 int currentThread = __KernelGetCurThread();
217 currentDir_t::iterator it = currentDir.find(currentThread);
218 if (it == currentDir.end())
219 {
220 //Attempt to emulate SCE_KERNEL_ERROR_NOCWD / 8002032C: may break things requiring fixes elsewhere
221 if (inpath.find(':') == std::string::npos /* means path is relative */)
222 {
223 error = SCE_KERNEL_ERROR_NOCWD;
224 WARN_LOG(FILESYS, "Path is relative, but current directory not set for thread %i. returning 8002032C(SCE_KERNEL_ERROR_NOCWD) instead.", currentThread);
225 }
226 }
227 else
228 {
229 currentDirectory = &(it->second);
230 }
231
232 if (RealPath(*currentDirectory, inpath, realpath))
233 {
234 std::string prefix = realpath;
235 size_t prefixPos = realpath.find(':');
236 if (prefixPos != realpath.npos)
237 prefix = NormalizePrefix(realpath.substr(0, prefixPos + 1));
238
239 for (size_t i = 0; i < fileSystems.size(); i++)
240 {
241 size_t prefLen = fileSystems[i].prefix.size();
242 if (strncasecmp(fileSystems[i].prefix.c_str(), prefix.c_str(), prefLen) == 0)
243 {
244 outpath = realpath.substr(prefixPos + 1);
245 *system = &(fileSystems[i]);
246
247 VERBOSE_LOG(FILESYS, "MapFilePath: mapped \"%s\" to prefix: \"%s\", path: \"%s\"", inpath.c_str(), fileSystems[i].prefix.c_str(), outpath.c_str());
248
249 return error == SCE_KERNEL_ERROR_NOCWD ? error : 0;
250 }
251 }
252
253 error = SCE_KERNEL_ERROR_NODEV;
254 }
255
256 DEBUG_LOG(FILESYS, "MapFilePath: failed mapping \"%s\", returning false", inpath.c_str());
257 return error;
258 }
259
NormalizePrefix(std::string prefix) const260 std::string MetaFileSystem::NormalizePrefix(std::string prefix) const {
261 // Let's apply some mapping here since it won't break savestates.
262 if (prefix == "memstick:")
263 prefix = "ms0:";
264 // Seems like umd00: etc. work just fine... avoid umd1/umd for tests.
265 if (startsWith(prefix, "umd") && prefix != "umd1:" && prefix != "umd:")
266 prefix = "umd0:";
267 // Seems like umd00: etc. work just fine...
268 if (startsWith(prefix, "host"))
269 prefix = "host0:";
270
271 // Should we simply make this case insensitive?
272 if (prefix == "DISC0:")
273 prefix = "disc0:";
274
275 return prefix;
276 }
277
Mount(std::string prefix,std::shared_ptr<IFileSystem> system)278 void MetaFileSystem::Mount(std::string prefix, std::shared_ptr<IFileSystem> system) {
279 std::lock_guard<std::recursive_mutex> guard(lock);
280
281 MountPoint x;
282 x.prefix = prefix;
283 x.system = system;
284 for (auto &it : fileSystems) {
285 if (it.prefix == prefix) {
286 // Overwrite the old mount. Don't create a new one.
287 it = x;
288 return;
289 }
290 }
291
292 // Prefix not yet mounted, do so.
293 fileSystems.push_back(x);
294 }
295
UnmountAll()296 void MetaFileSystem::UnmountAll() {
297 fileSystems.clear();
298 currentDir.clear();
299 }
300
Unmount(std::string prefix)301 void MetaFileSystem::Unmount(std::string prefix) {
302 for (auto iter = fileSystems.begin(); iter != fileSystems.end(); iter++) {
303 if (iter->prefix == prefix) {
304 fileSystems.erase(iter);
305 return;
306 }
307 }
308 }
309
Remount(std::string prefix,std::shared_ptr<IFileSystem> system)310 bool MetaFileSystem::Remount(std::string prefix, std::shared_ptr<IFileSystem> system) {
311 std::lock_guard<std::recursive_mutex> guard(lock);
312 for (auto &it : fileSystems) {
313 if (it.prefix == prefix) {
314 it.system = system;
315 return true;
316 }
317 }
318 return false;
319 }
320
GetSystemFromFilename(const std::string & filename)321 IFileSystem *MetaFileSystem::GetSystemFromFilename(const std::string &filename) {
322 size_t prefixPos = filename.find(':');
323 if (prefixPos == filename.npos)
324 return 0;
325 return GetSystem(filename.substr(0, prefixPos + 1));
326 }
327
GetSystem(const std::string & prefix)328 IFileSystem *MetaFileSystem::GetSystem(const std::string &prefix) {
329 for (auto it = fileSystems.begin(); it != fileSystems.end(); ++it) {
330 if (it->prefix == NormalizePrefix(prefix))
331 return it->system.get();
332 }
333 return NULL;
334 }
335
Shutdown()336 void MetaFileSystem::Shutdown() {
337 std::lock_guard<std::recursive_mutex> guard(lock);
338
339 UnmountAll();
340 Reset();
341 }
342
OpenFile(std::string filename,FileAccess access,const char * devicename)343 int MetaFileSystem::OpenFile(std::string filename, FileAccess access, const char *devicename)
344 {
345 std::lock_guard<std::recursive_mutex> guard(lock);
346 std::string of;
347 MountPoint *mount;
348 int error = MapFilePath(filename, of, &mount);
349 if (error == 0)
350 return mount->system->OpenFile(of, access, mount->prefix.c_str());
351 else
352 return error;
353 }
354
GetFileInfo(std::string filename)355 PSPFileInfo MetaFileSystem::GetFileInfo(std::string filename)
356 {
357 std::lock_guard<std::recursive_mutex> guard(lock);
358 std::string of;
359 IFileSystem *system;
360 int error = MapFilePath(filename, of, &system);
361 if (error == 0)
362 {
363 return system->GetFileInfo(of);
364 }
365 else
366 {
367 PSPFileInfo bogus;
368 return bogus;
369 }
370 }
371
GetDirListing(std::string path)372 std::vector<PSPFileInfo> MetaFileSystem::GetDirListing(std::string path)
373 {
374 std::lock_guard<std::recursive_mutex> guard(lock);
375 std::string of;
376 IFileSystem *system;
377 int error = MapFilePath(path, of, &system);
378 if (error == 0)
379 {
380 return system->GetDirListing(of);
381 }
382 else
383 {
384 std::vector<PSPFileInfo> empty;
385 return empty;
386 }
387 }
388
ThreadEnded(int threadID)389 void MetaFileSystem::ThreadEnded(int threadID)
390 {
391 std::lock_guard<std::recursive_mutex> guard(lock);
392 currentDir.erase(threadID);
393 }
394
ChDir(const std::string & dir)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(FILESYS, "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(FILESYS, "ChDir failed to map device for \"%s\", failing", dir.c_str());
427 return SCE_KERNEL_ERROR_NODEV;
428 }
429 }
430
MkDir(const std::string & dirname)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
RmDir(const std::string & dirname)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
RenameFile(const std::string & from,const std::string & to)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
RemoveFile(const std::string & filename)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
Ioctl(u32 handle,u32 cmd,u32 indataPtr,u32 inlen,u32 outdataPtr,u32 outlen,int & usec)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
DevType(u32 handle)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
CloseFile(u32 handle)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
ReadFile(u32 handle,u8 * pointer,s64 size)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
WriteFile(u32 handle,const u8 * pointer,s64 size)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
ReadFile(u32 handle,u8 * pointer,s64 size,int & usec)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
WriteFile(u32 handle,const u8 * pointer,s64 size,int & usec)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
SeekFile(u32 handle,s32 position,FileMove type)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
ReadEntireFile(const std::string & filename,std::vector<u8> & data)586 int MetaFileSystem::ReadEntireFile(const std::string &filename, std::vector<u8> &data) {
587 int handle = OpenFile(filename, FILEACCESS_READ);
588 if (handle < 0)
589 return handle;
590
591 SeekFile(handle, 0, FILEMOVE_END);
592 size_t dataSize = GetSeekPos(handle);
593 SeekFile(handle, 0, FILEMOVE_BEGIN);
594 data.resize(dataSize);
595
596 size_t result = ReadFile(handle, (u8 *)&data[0], dataSize);
597 CloseFile(handle);
598
599 if (result != dataSize)
600 return SCE_KERNEL_ERROR_ERROR;
601
602 return 0;
603 }
604
FreeSpace(const std::string & path)605 u64 MetaFileSystem::FreeSpace(const std::string &path)
606 {
607 std::lock_guard<std::recursive_mutex> guard(lock);
608 std::string of;
609 IFileSystem *system;
610 int error = MapFilePath(path, of, &system);
611 if (error == 0)
612 return system->FreeSpace(of);
613 else
614 return 0;
615 }
616
DoState(PointerWrap & p)617 void MetaFileSystem::DoState(PointerWrap &p)
618 {
619 std::lock_guard<std::recursive_mutex> guard(lock);
620
621 auto s = p.Section("MetaFileSystem", 1);
622 if (!s)
623 return;
624
625 Do(p, current);
626
627 // Save/load per-thread current directory map
628 Do(p, currentDir);
629
630 u32 n = (u32) fileSystems.size();
631 Do(p, n);
632 bool skipPfat0 = false;
633 if (n != (u32) fileSystems.size())
634 {
635 if (n == (u32) fileSystems.size() - 1) {
636 skipPfat0 = true;
637 } else {
638 p.SetError(p.ERROR_FAILURE);
639 ERROR_LOG(FILESYS, "Savestate failure: number of filesystems doesn't match.");
640 return;
641 }
642 }
643
644 for (u32 i = 0; i < n; ++i) {
645 if (!skipPfat0 || fileSystems[i].prefix != "pfat0:") {
646 fileSystems[i].system->DoState(p);
647 }
648 }
649 }
650
RecursiveSize(const std::string & dirPath)651 int64_t MetaFileSystem::RecursiveSize(const std::string &dirPath) {
652 u64 result = 0;
653 auto allFiles = GetDirListing(dirPath);
654 for (auto file : allFiles) {
655 if (file.name == "." || file.name == "..")
656 continue;
657 if (file.type == FILETYPE_DIRECTORY) {
658 result += RecursiveSize(dirPath + file.name);
659 } else {
660 result += file.size;
661 }
662 }
663 return result;
664 }
665
ComputeRecursiveDirectorySize(const std::string & filename)666 int64_t MetaFileSystem::ComputeRecursiveDirectorySize(const std::string &filename) {
667 std::lock_guard<std::recursive_mutex> guard(lock);
668 std::string of;
669 IFileSystem *system;
670 int error = MapFilePath(filename, of, &system);
671 if (error == 0) {
672 int64_t size;
673 if (system->ComputeRecursiveDirSizeIfFast(of, &size)) {
674 // Some file systems can optimize this.
675 return size;
676 } else {
677 // Those that can't, we just run a generic implementation.
678 return RecursiveSize(filename);
679 }
680 } else {
681 return false;
682 }
683 }
684