CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!
CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!
Path: blob/master/Core/FileSystems/MetaFileSystem.cpp
Views: 1401
// Copyright (c) 2012- PPSSPP Project.12// This program is free software: you can redistribute it and/or modify3// it under the terms of the GNU General Public License as published by4// the Free Software Foundation, version 2.0 or later versions.56// This program is distributed in the hope that it will be useful,7// but WITHOUT ANY WARRANTY; without even the implied warranty of8// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the9// GNU General Public License 2.0 for more details.1011// A copy of the GPL 2.0 should have been included with the program.12// If not, see http://www.gnu.org/licenses/1314// Official git repository and contact information can be found at15// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/.1617#include <algorithm>18#include <set>1920#include "Common/Serialize/Serializer.h"21#include "Common/Serialize/SerializeFuncs.h"22#include "Common/Serialize/SerializeMap.h"23#include "Common/StringUtils.h"24#include "Core/FileSystems/MetaFileSystem.h"25#include "Core/HLE/sceKernelThread.h"26#include "Core/Reporting.h"27#include "Core/System.h"2829static bool ApplyPathStringToComponentsVector(std::vector<std::string> &vector, const std::string &pathString)30{31size_t len = pathString.length();32size_t start = 0;3334while (start < len)35{36// TODO: This should only be done for ms0:/ etc.37size_t i = pathString.find_first_of("/\\", start);38if (i == std::string::npos)39i = len;4041if (i > start)42{43std::string component = pathString.substr(start, i - start);44if (component != ".")45{46if (component == "..")47{48if (vector.size() != 0)49{50vector.pop_back();51}52else53{54// The PSP silently ignores attempts to .. to parent of root directory55WARN_LOG(Log::FileSystem, "RealPath: ignoring .. beyond root - root directory is its own parent: \"%s\"", pathString.c_str());56}57}58else59{60vector.push_back(component);61}62}63}6465start = i + 1;66}6768return true;69}7071/*72* Changes relative paths to absolute, removes ".", "..", and trailing "/"73* "drive:./blah" is absolute (ignore the dot) and "/blah" is relative (because it's missing "drive:")74* babel (and possibly other games) use "/directoryThatDoesNotExist/../directoryThatExists/filename"75*/76static bool RealPath(const std::string ¤tDirectory, const std::string &inPath, std::string &outPath)77{78size_t inLen = inPath.length();79if (inLen == 0)80{81outPath = currentDirectory;82return true;83}8485size_t inColon = inPath.find(':');86if (inColon + 1 == inLen)87{88// There's nothing after the colon, e.g. umd0: - this is perfectly valid.89outPath = inPath;90return true;91}9293bool relative = (inColon == std::string::npos);9495std::string prefix, inAfterColon;96std::vector<std::string> cmpnts; // path components97size_t outPathCapacityGuess = inPath.length();9899if (relative)100{101size_t curDirLen = currentDirectory.length();102if (curDirLen == 0)103{104ERROR_LOG(Log::FileSystem, "RealPath: inPath \"%s\" is relative, but current directory is empty", inPath.c_str());105return false;106}107108size_t curDirColon = currentDirectory.find(':');109if (curDirColon == std::string::npos)110{111ERROR_LOG(Log::FileSystem, "RealPath: inPath \"%s\" is relative, but current directory \"%s\" has no prefix", inPath.c_str(), currentDirectory.c_str());112return false;113}114if (curDirColon + 1 == curDirLen)115{116WARN_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());117}118else119{120const std::string curDirAfter = currentDirectory.substr(curDirColon + 1);121if (! ApplyPathStringToComponentsVector(cmpnts, curDirAfter) )122{123ERROR_LOG(Log::FileSystem,"RealPath: currentDirectory is not a valid path: \"%s\"", currentDirectory.c_str());124return false;125}126127outPathCapacityGuess += curDirLen;128}129130prefix = currentDirectory.substr(0, curDirColon + 1);131inAfterColon = inPath;132}133else134{135prefix = inPath.substr(0, inColon + 1);136inAfterColon = inPath.substr(inColon + 1);137138// Special case: "disc0:" is different from "disc0:/", so keep track of the single slash.139if (inAfterColon == "/")140{141outPath = prefix + inAfterColon;142return true;143}144}145146if (! ApplyPathStringToComponentsVector(cmpnts, inAfterColon) )147{148WARN_LOG(Log::FileSystem, "RealPath: inPath is not a valid path: \"%s\"", inPath.c_str());149return false;150}151152outPath.clear();153outPath.reserve(outPathCapacityGuess);154155outPath.append(prefix);156157size_t numCmpnts = cmpnts.size();158for (size_t i = 0; i < numCmpnts; i++)159{160outPath.append(1, '/');161outPath.append(cmpnts[i]);162}163164return true;165}166167IFileSystem *MetaFileSystem::GetHandleOwner(u32 handle)168{169std::lock_guard<std::recursive_mutex> guard(lock);170for (size_t i = 0; i < fileSystems.size(); i++)171{172if (fileSystems[i].system->OwnsHandle(handle))173return fileSystems[i].system.get();174}175176// Not found177return nullptr;178}179180int MetaFileSystem::MapFilePath(const std::string &_inpath, std::string &outpath, MountPoint **system)181{182int error = SCE_KERNEL_ERROR_ERRNO_FILE_NOT_FOUND;183std::lock_guard<std::recursive_mutex> guard(lock);184std::string realpath;185186std::string inpath = _inpath;187188// "ms0:/file.txt" is equivalent to " ms0:/file.txt". Yes, really.189if (inpath.find(':') != inpath.npos) {190size_t offset = 0;191while (inpath[offset] == ' ') {192offset++;193}194if (offset > 0) {195inpath = inpath.substr(offset);196}197}198199// Special handling: host0:command.txt (as seen in Super Monkey Ball Adventures, for example)200// appears to mean the current directory on the UMD. Let's just assume the current directory.201if (strncasecmp(inpath.c_str(), "host0:", strlen("host0:")) == 0) {202INFO_LOG(Log::FileSystem, "Host0 path detected, stripping: %s", inpath.c_str());203// However, this causes trouble when running tests, since our test framework uses host0:.204// Maybe it's really just supposed to map to umd0 or something?205if (PSP_CoreParameter().headLess) {206inpath = "umd0:" + inpath.substr(strlen("host0:"));207} else {208inpath = inpath.substr(strlen("host0:"));209}210}211212const std::string *currentDirectory = &startingDirectory;213214int currentThread = __KernelGetCurThread();215currentDir_t::iterator it = currentDir.find(currentThread);216if (it == currentDir.end())217{218//Attempt to emulate SCE_KERNEL_ERROR_NOCWD / 8002032C: may break things requiring fixes elsewhere219if (inpath.find(':') == std::string::npos /* means path is relative */)220{221error = SCE_KERNEL_ERROR_NOCWD;222WARN_LOG(Log::FileSystem, "Path is relative, but current directory not set for thread %i. returning 8002032C(SCE_KERNEL_ERROR_NOCWD) instead.", currentThread);223}224}225else226{227currentDirectory = &(it->second);228}229230if (RealPath(*currentDirectory, inpath, realpath))231{232std::string prefix = realpath;233size_t prefixPos = realpath.find(':');234if (prefixPos != realpath.npos)235prefix = NormalizePrefix(realpath.substr(0, prefixPos + 1));236237for (size_t i = 0; i < fileSystems.size(); i++)238{239size_t prefLen = fileSystems[i].prefix.size();240if (strncasecmp(fileSystems[i].prefix.c_str(), prefix.c_str(), prefLen) == 0)241{242outpath = realpath.substr(prefixPos + 1);243*system = &(fileSystems[i]);244245VERBOSE_LOG(Log::FileSystem, "MapFilePath: mapped \"%s\" to prefix: \"%s\", path: \"%s\"", inpath.c_str(), fileSystems[i].prefix.c_str(), outpath.c_str());246247return error == SCE_KERNEL_ERROR_NOCWD ? error : 0;248}249}250251error = SCE_KERNEL_ERROR_NODEV;252}253254DEBUG_LOG(Log::FileSystem, "MapFilePath: failed mapping \"%s\", returning false", inpath.c_str());255return error;256}257258std::string MetaFileSystem::NormalizePrefix(std::string prefix) const {259// Let's apply some mapping here since it won't break savestates.260if (prefix == "memstick:")261prefix = "ms0:";262// Seems like umd00: etc. work just fine... avoid umd1/umd for tests.263if (startsWith(prefix, "umd") && prefix != "umd1:" && prefix != "umd:")264prefix = "umd0:";265// Seems like umd00: etc. work just fine...266if (startsWith(prefix, "host"))267prefix = "host0:";268269// Should we simply make this case insensitive?270if (prefix == "DISC0:")271prefix = "disc0:";272273return prefix;274}275276void MetaFileSystem::Mount(const std::string &prefix, std::shared_ptr<IFileSystem> system) {277std::lock_guard<std::recursive_mutex> guard(lock);278279MountPoint x;280x.prefix = prefix;281x.system = system;282for (auto &it : fileSystems) {283if (it.prefix == prefix) {284// Overwrite the old mount. Don't create a new one.285it = x;286return;287}288}289290// Prefix not yet mounted, do so.291fileSystems.push_back(x);292}293294// Assumes the lock is held295void MetaFileSystem::UnmountAll() {296fileSystems.clear();297currentDir.clear();298}299300void MetaFileSystem::Unmount(const std::string &prefix) {301std::lock_guard<std::recursive_mutex> guard(lock);302for (auto iter = fileSystems.begin(); iter != fileSystems.end(); iter++) {303if (iter->prefix == prefix) {304fileSystems.erase(iter);305return;306}307}308}309310bool MetaFileSystem::Remount(const std::string &prefix, std::shared_ptr<IFileSystem> system) {311std::lock_guard<std::recursive_mutex> guard(lock);312for (auto &it : fileSystems) {313if (it.prefix == prefix) {314it.system = system;315return true;316}317}318return false;319}320321IFileSystem *MetaFileSystem::GetSystemFromFilename(const std::string &filename) {322size_t prefixPos = filename.find(':');323if (prefixPos == filename.npos)324return 0;325return GetSystem(filename.substr(0, prefixPos + 1));326}327328IFileSystem *MetaFileSystem::GetSystem(const std::string &prefix) {329std::lock_guard<std::recursive_mutex> guard(lock);330for (auto it = fileSystems.begin(); it != fileSystems.end(); ++it) {331if (it->prefix == NormalizePrefix(prefix))332return it->system.get();333}334return NULL;335}336337void MetaFileSystem::Shutdown() {338std::lock_guard<std::recursive_mutex> guard(lock);339340UnmountAll();341Reset();342}343344int MetaFileSystem::OpenFile(std::string filename, FileAccess access, const char *devicename)345{346std::lock_guard<std::recursive_mutex> guard(lock);347std::string of;348MountPoint *mount;349int error = MapFilePath(filename, of, &mount);350if (error == 0)351return mount->system->OpenFile(of, access, mount->prefix.c_str());352else353return error;354}355356PSPFileInfo MetaFileSystem::GetFileInfo(std::string filename)357{358std::lock_guard<std::recursive_mutex> guard(lock);359std::string of;360IFileSystem *system;361int error = MapFilePath(filename, of, &system);362if (error == 0)363{364return system->GetFileInfo(of);365}366else367{368PSPFileInfo bogus;369return bogus;370}371}372373std::vector<PSPFileInfo> MetaFileSystem::GetDirListing(const std::string &path, bool *exists) {374std::lock_guard<std::recursive_mutex> guard(lock);375std::string of;376IFileSystem *system;377int error = MapFilePath(path, of, &system);378if (error == 0) {379return system->GetDirListing(of, exists);380} else {381std::vector<PSPFileInfo> empty;382if (exists)383*exists = false;384return empty;385}386}387388void MetaFileSystem::ThreadEnded(int threadID)389{390std::lock_guard<std::recursive_mutex> guard(lock);391currentDir.erase(threadID);392}393394int MetaFileSystem::ChDir(const std::string &dir)395{396std::lock_guard<std::recursive_mutex> guard(lock);397// Retain the old path and fail if the arg is 1023 bytes or longer.398if (dir.size() >= 1023)399return SCE_KERNEL_ERROR_NAMETOOLONG;400401int curThread = __KernelGetCurThread();402403std::string of;404MountPoint *mountPoint;405int error = MapFilePath(dir, of, &mountPoint);406if (error == 0)407{408currentDir[curThread] = mountPoint->prefix + of;409return 0;410}411else412{413for (size_t i = 0; i < fileSystems.size(); i++)414{415const std::string &prefix = fileSystems[i].prefix;416if (strncasecmp(prefix.c_str(), dir.c_str(), prefix.size()) == 0)417{418// The PSP is completely happy with invalid current dirs as long as they have a valid device.419WARN_LOG(Log::FileSystem, "ChDir failed to map path \"%s\", saving as current directory anyway", dir.c_str());420currentDir[curThread] = dir;421return 0;422}423}424425WARN_LOG_REPORT(Log::FileSystem, "ChDir failed to map device for \"%s\", failing", dir.c_str());426return SCE_KERNEL_ERROR_NODEV;427}428}429430bool MetaFileSystem::MkDir(const std::string &dirname)431{432std::lock_guard<std::recursive_mutex> guard(lock);433std::string of;434IFileSystem *system;435int error = MapFilePath(dirname, of, &system);436if (error == 0)437{438return system->MkDir(of);439}440else441{442return false;443}444}445446bool MetaFileSystem::RmDir(const std::string &dirname)447{448std::lock_guard<std::recursive_mutex> guard(lock);449std::string of;450IFileSystem *system;451int error = MapFilePath(dirname, of, &system);452if (error == 0)453{454return system->RmDir(of);455}456else457{458return false;459}460}461462int MetaFileSystem::RenameFile(const std::string &from, const std::string &to)463{464std::lock_guard<std::recursive_mutex> guard(lock);465std::string of;466std::string rf;467IFileSystem *osystem;468IFileSystem *rsystem = NULL;469int error = MapFilePath(from, of, &osystem);470if (error == 0)471{472// If it's a relative path, it seems to always use from's filesystem.473if (to.find(":/") != to.npos)474{475error = MapFilePath(to, rf, &rsystem);476if (error < 0)477return -1;478}479else480{481rf = to;482rsystem = osystem;483}484485if (osystem != rsystem)486return SCE_KERNEL_ERROR_XDEV;487488return osystem->RenameFile(of, rf);489}490else491{492return -1;493}494}495496bool MetaFileSystem::RemoveFile(const std::string &filename)497{498std::lock_guard<std::recursive_mutex> guard(lock);499std::string of;500IFileSystem *system;501int error = MapFilePath(filename, of, &system);502if (error == 0) {503return system->RemoveFile(of);504} else {505return false;506}507}508509int MetaFileSystem::Ioctl(u32 handle, u32 cmd, u32 indataPtr, u32 inlen, u32 outdataPtr, u32 outlen, int &usec)510{511std::lock_guard<std::recursive_mutex> guard(lock);512IFileSystem *sys = GetHandleOwner(handle);513if (sys)514return sys->Ioctl(handle, cmd, indataPtr, inlen, outdataPtr, outlen, usec);515return SCE_KERNEL_ERROR_ERROR;516}517518PSPDevType MetaFileSystem::DevType(u32 handle)519{520std::lock_guard<std::recursive_mutex> guard(lock);521IFileSystem *sys = GetHandleOwner(handle);522if (sys)523return sys->DevType(handle);524return PSPDevType::INVALID;525}526527void MetaFileSystem::CloseFile(u32 handle)528{529std::lock_guard<std::recursive_mutex> guard(lock);530IFileSystem *sys = GetHandleOwner(handle);531if (sys)532sys->CloseFile(handle);533}534535size_t MetaFileSystem::ReadFile(u32 handle, u8 *pointer, s64 size)536{537std::lock_guard<std::recursive_mutex> guard(lock);538IFileSystem *sys = GetHandleOwner(handle);539if (sys)540return sys->ReadFile(handle, pointer, size);541else542return 0;543}544545size_t MetaFileSystem::WriteFile(u32 handle, const u8 *pointer, s64 size)546{547std::lock_guard<std::recursive_mutex> guard(lock);548IFileSystem *sys = GetHandleOwner(handle);549if (sys)550return sys->WriteFile(handle, pointer, size);551else552return 0;553}554555size_t MetaFileSystem::ReadFile(u32 handle, u8 *pointer, s64 size, int &usec)556{557std::lock_guard<std::recursive_mutex> guard(lock);558IFileSystem *sys = GetHandleOwner(handle);559if (sys)560return sys->ReadFile(handle, pointer, size, usec);561else562return 0;563}564565size_t MetaFileSystem::WriteFile(u32 handle, const u8 *pointer, s64 size, int &usec)566{567std::lock_guard<std::recursive_mutex> guard(lock);568IFileSystem *sys = GetHandleOwner(handle);569if (sys)570return sys->WriteFile(handle, pointer, size, usec);571else572return 0;573}574575size_t MetaFileSystem::SeekFile(u32 handle, s32 position, FileMove type)576{577std::lock_guard<std::recursive_mutex> guard(lock);578IFileSystem *sys = GetHandleOwner(handle);579if (sys)580return sys->SeekFile(handle, position, type);581else582return 0;583}584585int MetaFileSystem::ReadEntireFile(const std::string &filename, std::vector<u8> &data, bool quiet) {586FileAccess access = FILEACCESS_READ;587if (quiet) {588access = (FileAccess)(access | FILEACCESS_PPSSPP_QUIET);589}590int handle = OpenFile(filename, access);591if (handle < 0)592return handle;593594SeekFile(handle, 0, FILEMOVE_END);595size_t dataSize = GetSeekPos(handle);596SeekFile(handle, 0, FILEMOVE_BEGIN);597data.resize(dataSize);598599size_t result = ReadFile(handle, data.data(), dataSize);600CloseFile(handle);601602if (result != dataSize)603return SCE_KERNEL_ERROR_ERROR;604605return 0;606}607608u64 MetaFileSystem::FreeSpace(const std::string &path)609{610std::lock_guard<std::recursive_mutex> guard(lock);611std::string of;612IFileSystem *system;613int error = MapFilePath(path, of, &system);614if (error == 0)615return system->FreeSpace(of);616else617return 0;618}619620void MetaFileSystem::DoState(PointerWrap &p)621{622std::lock_guard<std::recursive_mutex> guard(lock);623624auto s = p.Section("MetaFileSystem", 1);625if (!s)626return;627628Do(p, current);629630// Save/load per-thread current directory map631Do(p, currentDir);632633u32 n = (u32) fileSystems.size();634Do(p, n);635bool skipPfat0 = false;636if (n != (u32) fileSystems.size())637{638if (n == (u32) fileSystems.size() - 1) {639skipPfat0 = true;640} else {641p.SetError(p.ERROR_FAILURE);642ERROR_LOG(Log::FileSystem, "Savestate failure: number of filesystems doesn't match.");643return;644}645}646647for (u32 i = 0; i < n; ++i) {648if (!skipPfat0 || fileSystems[i].prefix != "pfat0:") {649fileSystems[i].system->DoState(p);650}651}652}653654int64_t MetaFileSystem::RecursiveSize(const std::string &dirPath) {655u64 result = 0;656auto allFiles = GetDirListing(dirPath);657for (auto file : allFiles) {658if (file.name == "." || file.name == "..")659continue;660if (file.type == FILETYPE_DIRECTORY) {661result += RecursiveSize(dirPath + file.name);662} else {663result += file.size;664}665}666return result;667}668669int64_t MetaFileSystem::ComputeRecursiveDirectorySize(const std::string &filename) {670std::lock_guard<std::recursive_mutex> guard(lock);671std::string of;672IFileSystem *system;673int error = MapFilePath(filename, of, &system);674if (error == 0) {675int64_t size;676if (system->ComputeRecursiveDirSizeIfFast(of, &size)) {677// Some file systems can optimize this.678return size;679} else {680// Those that can't, we just run a generic implementation.681return RecursiveSize(filename);682}683} else {684return false;685}686}687688689