ams_mitm: Implement emummc Nintendo folder redirection

This commit is contained in:
Michael Scire
2019-12-05 23:41:33 -08:00
committed by SciresM
parent 733f2b3cdd
commit 746dbfe018
78 changed files with 2190 additions and 187 deletions

View File

@@ -74,7 +74,7 @@ namespace ams::emummc {
/* Retrieve and cache values. */
{
typename std::aligned_storage<2 * (MaxDirLen + 1), 0x1000>::type path_storage;
typename std::aligned_storage<2 * (MaxDirLen + 1), os::MemoryPageSize>::type path_storage;
struct {
char file_path[MaxDirLen + 1];

View File

@@ -19,7 +19,7 @@ namespace ams::dd {
uintptr_t QueryIoMapping(uintptr_t phys_addr, size_t size) {
u64 virtual_addr;
const u64 aligned_addr = util::AlignDown(phys_addr, 0x1000);
const u64 aligned_addr = util::AlignDown(phys_addr, os::MemoryPageSize);
const size_t offset = phys_addr - aligned_addr;
const u64 aligned_size = size + offset;
R_TRY_CATCH(svcQueryIoMapping(&virtual_addr, aligned_addr, aligned_size)) {

View File

@@ -0,0 +1,248 @@
/*
* Copyright (c) 2018-2019 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams::fs {
Result PathTool::Normalize(char *out, size_t *out_len, const char *src, size_t max_out_size, bool unc_preserved) {
/* Paths must start with / */
R_UNLESS(IsSeparator(src[0]), fs::ResultInvalidPathFormat());
bool skip_next_sep = false;
size_t i = 0;
size_t len = 0;
while (!IsNullTerminator(src[i])) {
if (IsSeparator(src[i])) {
/* Swallow separators. */
while (IsSeparator(src[++i])) { }
if (IsNullTerminator(src[i])) {
break;
}
/* Handle skip if needed */
if (!skip_next_sep) {
if (len + 1 == max_out_size) {
out[len] = StringTraits::NullTerminator;
if (out_len != nullptr) {
*out_len = len;
}
return fs::ResultTooLongPath();
}
out[len++] = StringTraits::DirectorySeparator;
if (unc_preserved && len == 1) {
while (len < i) {
if (len + 1 == max_out_size) {
out[len] = StringTraits::NullTerminator;
if (out_len != nullptr) {
*out_len = len;
}
return fs::ResultTooLongPath();
}
out[len++] = StringTraits::DirectorySeparator;
}
}
}
skip_next_sep = false;
}
/* See length of current dir. */
size_t dir_len = 0;
while (!IsSeparator(src[i+dir_len]) && !IsNullTerminator(src[i+dir_len])) {
dir_len++;
}
if (IsCurrentDirectory(&src[i])) {
skip_next_sep = true;
} else if (IsParentDirectory(&src[i])) {
AMS_ASSERT(IsSeparator(out[0]));
AMS_ASSERT(IsSeparator(out[len - 1]));
R_UNLESS(len != 1, fs::ResultDirectoryUnobtainable());
/* Walk up a directory. */
len -= 2;
while (!IsSeparator(out[len])) {
len--;
}
} else {
/* Copy, possibly truncating. */
if (len + dir_len + 1 <= max_out_size) {
for (size_t j = 0; j < dir_len; j++) {
out[len++] = src[i+j];
}
} else {
const size_t copy_len = max_out_size - 1 - len;
for (size_t j = 0; j < copy_len; j++) {
out[len++] = src[i+j];
}
out[len] = StringTraits::NullTerminator;
if (out_len != nullptr) {
*out_len = len;
}
return fs::ResultTooLongPath();
}
}
i += dir_len;
}
if (skip_next_sep) {
len--;
}
if (len == 0 && max_out_size) {
out[len++] = StringTraits::DirectorySeparator;
}
R_UNLESS(max_out_size >= len - 1, fs::ResultTooLongPath());
/* Null terminate. */
out[len] = StringTraits::NullTerminator;
if (out_len != nullptr) {
*out_len = len;
}
/* Assert normalized. */
bool normalized = false;
AMS_ASSERT(unc_preserved || (R_SUCCEEDED(IsNormalized(&normalized, out)) && normalized));
return ResultSuccess();
}
Result PathTool::IsNormalized(bool *out, const char *path) {
/* Nintendo uses a state machine here. */
enum class PathState {
Start,
Normal,
FirstSeparator,
Separator,
CurrentDir,
ParentDir,
WindowsDriveLetter,
};
PathState state = PathState::Start;
for (const char *cur = path; *cur != StringTraits::NullTerminator; cur++) {
const char c = *cur;
switch (state) {
case PathState::Start:
if (IsWindowsDriveCharacter(c)) {
state = PathState::WindowsDriveLetter;
} else if (IsSeparator(c)) {
state = PathState::FirstSeparator;
} else {
return fs::ResultInvalidPathFormat();
}
break;
case PathState::Normal:
if (IsSeparator(c)) {
state = PathState::Separator;
}
break;
case PathState::FirstSeparator:
case PathState::Separator:
if (IsSeparator(c)) {
*out = false;
return ResultSuccess();
} else if (IsDot(c)) {
state = PathState::CurrentDir;
} else {
state = PathState::Normal;
}
break;
case PathState::CurrentDir:
if (IsSeparator(c)) {
*out = false;
return ResultSuccess();
} else if (IsDot(c)) {
state = PathState::ParentDir;
} else {
state = PathState::Normal;
}
break;
case PathState::ParentDir:
if (IsSeparator(c)) {
*out = false;
return ResultSuccess();
} else {
state = PathState::Normal;
}
break;
case PathState::WindowsDriveLetter:
if (IsDriveSeparator(c)) {
*out = true;
return ResultSuccess();
} else {
return fs::ResultInvalidPathFormat();
}
break;
}
}
switch (state) {
case PathState::Start:
case PathState::WindowsDriveLetter:
return fs::ResultInvalidPathFormat();
case PathState::FirstSeparator:
case PathState::Normal:
*out = true;
break;
case PathState::CurrentDir:
case PathState::ParentDir:
case PathState::Separator:
*out = false;
break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
return ResultSuccess();
}
bool PathTool::IsSubPath(const char *lhs, const char *rhs) {
AMS_ASSERT(lhs != nullptr);
AMS_ASSERT(rhs != nullptr);
/* Special case certain paths. */
if (IsSeparator(lhs[0]) && !IsSeparator(lhs[1]) && IsSeparator(rhs[0]) && IsSeparator(rhs[1])) {
return false;
}
if (IsSeparator(rhs[0]) && !IsSeparator(rhs[1]) && IsSeparator(lhs[0]) && IsSeparator(lhs[1])) {
return false;
}
if (IsSeparator(lhs[0]) && IsNullTerminator(lhs[1]) && IsSeparator(rhs[0]) && !IsNullTerminator(rhs[1])) {
return true;
}
if (IsSeparator(rhs[0]) && IsNullTerminator(rhs[1]) && IsSeparator(lhs[0]) && !IsNullTerminator(lhs[1])) {
return true;
}
/* Check subpath. */
for (size_t i = 0; /* No terminating condition */; i++) {
if (IsNullTerminator(lhs[i])) {
return IsSeparator(rhs[i]);
} else if (IsNullTerminator(rhs[i])) {
return IsSeparator(lhs[i]);
} else if (lhs[i] != rhs[i]) {
return false;
}
}
}
}

View File

@@ -0,0 +1,47 @@
/*
* Copyright (c) 2018-2019 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams::fs {
Result VerifyPath(const char *path, size_t max_path_len, size_t max_name_len) {
const char *cur = path;
size_t name_len = 0;
for (size_t path_len = 0; path_len <= max_path_len && name_len <= max_name_len; path_len++) {
const char c = *(cur++);
/* If terminated, we're done. */
R_UNLESS(c != StringTraits::NullTerminator, ResultSuccess());
/* TODO: Nintendo converts the path from utf-8 to utf-32, one character at a time. */
/* We should do this. */
/* Banned characters: :*?<>| */
R_UNLESS((c != ':' && c != '*' && c != '?' && c != '<' && c != '>' && c != '|'), fs::ResultInvalidCharacter());
name_len++;
/* Check for separator. */
if (c == '\\' || c == '/') {
name_len = 0;
}
}
return fs::ResultTooLongPath();
}
}

View File

@@ -0,0 +1,343 @@
/*
* Copyright (c) 2018-2019 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include <stratosphere/fssrv/fssrv_interface_adapters.hpp>
namespace ams::fssrv::impl {
FileInterfaceAdapter::FileInterfaceAdapter(std::unique_ptr<fs::fsa::IFile> &&file, std::shared_ptr<FileSystemInterfaceAdapter> &&parent, std::unique_lock<fssystem::SemaphoreAdapter> &&sema)
: parent_filesystem(std::move(parent)), base_file(std::move(file)), open_count_semaphore(std::move(sema))
{
/* ... */
}
FileInterfaceAdapter::~FileInterfaceAdapter() {
/* ... */
}
void FileInterfaceAdapter::InvalidateCache() {
AMS_ASSERT(this->parent_filesystem->IsDeepRetryEnabled());
std::scoped_lock<os::ReadWriteLock> scoped_write_lock(this->parent_filesystem->GetReadWriteLockForCacheInvalidation());
this->base_file->OperateRange(nullptr, 0, fs::OperationId::InvalidateCache, 0, std::numeric_limits<s64>::max(), nullptr, 0);
}
Result FileInterfaceAdapter::Read(ams::sf::Out<s64> out, s64 offset, const ams::sf::OutNonSecureBuffer &buffer, s64 size, fs::ReadOption option) {
/* TODO: N retries on ResultDataCorrupted, we may want to eventually. */
/* TODO: Deep retry */
R_UNLESS(offset >= 0, fs::ResultInvalidOffset());
R_UNLESS(size >= 0, fs::ResultInvalidSize());
size_t read_size = 0;
R_TRY(this->base_file->Read(&read_size, offset, buffer.GetPointer(), static_cast<size_t>(size), option));
out.SetValue(read_size);
return ResultSuccess();
}
Result FileInterfaceAdapter::Write(s64 offset, const ams::sf::InNonSecureBuffer &buffer, s64 size, fs::WriteOption option) {
/* TODO: N increases thread priority temporarily when writing. We may want to eventually. */
R_UNLESS(offset >= 0, fs::ResultInvalidOffset());
R_UNLESS(size >= 0, fs::ResultInvalidSize());
auto read_lock = this->parent_filesystem->AcquireCacheInvalidationReadLock();
return this->base_file->Write(offset, buffer.GetPointer(), size, option);
}
Result FileInterfaceAdapter::Flush() {
auto read_lock = this->parent_filesystem->AcquireCacheInvalidationReadLock();
return this->base_file->Flush();
}
Result FileInterfaceAdapter::SetSize(s64 size) {
R_UNLESS(size >= 0, fs::ResultInvalidSize());
auto read_lock = this->parent_filesystem->AcquireCacheInvalidationReadLock();
return this->base_file->SetSize(size);
}
Result FileInterfaceAdapter::GetSize(ams::sf::Out<s64> out) {
auto read_lock = this->parent_filesystem->AcquireCacheInvalidationReadLock();
return this->base_file->GetSize(out.GetPointer());
}
Result FileInterfaceAdapter::OperateRange(ams::sf::Out<fs::FileQueryRangeInfo> out, s32 op_id, s64 offset, s64 size) {
/* N includes this redundant check, so we will too. */
R_UNLESS(out.GetPointer() != nullptr, fs::ResultNullptrArgument());
out->Clear();
if (op_id == static_cast<s32>(fs::OperationId::QueryRange)) {
auto read_lock = this->parent_filesystem->AcquireCacheInvalidationReadLock();
fs::FileQueryRangeInfo info;
R_TRY(this->base_file->OperateRange(&info, sizeof(info), fs::OperationId::QueryRange, offset, size, nullptr, 0));
out->Merge(info);
}
return ResultSuccess();
}
DirectoryInterfaceAdapter::DirectoryInterfaceAdapter(std::unique_ptr<fs::fsa::IDirectory> &&dir, std::shared_ptr<FileSystemInterfaceAdapter> &&parent, std::unique_lock<fssystem::SemaphoreAdapter> &&sema)
: parent_filesystem(std::move(parent)), base_dir(std::move(dir)), open_count_semaphore(std::move(sema))
{
/* ... */
}
DirectoryInterfaceAdapter::~DirectoryInterfaceAdapter() {
/* ... */
}
Result DirectoryInterfaceAdapter::Read(ams::sf::Out<s64> out, const ams::sf::OutBuffer &out_entries) {
auto read_lock = this->parent_filesystem->AcquireCacheInvalidationReadLock();
const size_t max_num_entries = out_entries.GetSize() / sizeof(fs::DirectoryEntry);
R_UNLESS(max_num_entries >= 0, fs::ResultInvalidSize());
/* TODO: N retries on ResultDataCorrupted, we may want to eventually. */
return this->base_dir->Read(out.GetPointer(), reinterpret_cast<fs::DirectoryEntry *>(out_entries.GetPointer()), max_num_entries);
}
Result DirectoryInterfaceAdapter::GetEntryCount(ams::sf::Out<s64> out) {
auto read_lock = this->parent_filesystem->AcquireCacheInvalidationReadLock();
return this->base_dir->GetEntryCount(out.GetPointer());
}
FileSystemInterfaceAdapter::FileSystemInterfaceAdapter(std::shared_ptr<fs::fsa::IFileSystem> &&fs, bool open_limited)
: base_fs(std::move(fs)), open_count_limited(open_limited), deep_retry_enabled(false)
{
/* ... */
}
FileSystemInterfaceAdapter::~FileSystemInterfaceAdapter() {
/* ... */
}
bool FileSystemInterfaceAdapter::IsDeepRetryEnabled() const {
return this->deep_retry_enabled;
}
bool FileSystemInterfaceAdapter::IsAccessFailureDetectionObserved() const {
/* TODO: This calls into fssrv::FileSystemProxyImpl, which we don't have yet. */
AMS_ASSERT(false);
}
std::optional<std::shared_lock<os::ReadWriteLock>> FileSystemInterfaceAdapter::AcquireCacheInvalidationReadLock() {
std::optional<std::shared_lock<os::ReadWriteLock>> lock;
if (this->deep_retry_enabled) {
lock.emplace(this->invalidation_lock);
}
return lock;
}
os::ReadWriteLock &FileSystemInterfaceAdapter::GetReadWriteLockForCacheInvalidation() {
return this->invalidation_lock;
}
Result FileSystemInterfaceAdapter::CreateFile(const fssrv::sf::Path &path, s64 size, s32 option) {
auto read_lock = this->AcquireCacheInvalidationReadLock();
R_UNLESS(size >= 0, fs::ResultInvalidSize());
PathNormalizer normalizer(path.str);
R_UNLESS(normalizer.GetPath() != nullptr, normalizer.GetResult());
return this->base_fs->CreateFile(normalizer.GetPath(), size, option);
}
Result FileSystemInterfaceAdapter::DeleteFile(const fssrv::sf::Path &path) {
auto read_lock = this->AcquireCacheInvalidationReadLock();
PathNormalizer normalizer(path.str);
R_UNLESS(normalizer.GetPath() != nullptr, normalizer.GetResult());
return this->base_fs->DeleteFile(normalizer.GetPath());
}
Result FileSystemInterfaceAdapter::CreateDirectory(const fssrv::sf::Path &path) {
auto read_lock = this->AcquireCacheInvalidationReadLock();
PathNormalizer normalizer(path.str);
R_UNLESS(normalizer.GetPath() != nullptr, normalizer.GetResult());
R_UNLESS(strncmp(normalizer.GetPath(), "/", 2) != 0, fs::ResultPathAlreadyExists());
return this->base_fs->CreateDirectory(normalizer.GetPath());
}
Result FileSystemInterfaceAdapter::DeleteDirectory(const fssrv::sf::Path &path) {
auto read_lock = this->AcquireCacheInvalidationReadLock();
PathNormalizer normalizer(path.str);
R_UNLESS(normalizer.GetPath() != nullptr, normalizer.GetResult());
R_UNLESS(strncmp(normalizer.GetPath(), "/", 2) != 0, fs::ResultDirectoryNotDeletable());
return this->base_fs->DeleteDirectory(normalizer.GetPath());
}
Result FileSystemInterfaceAdapter::DeleteDirectoryRecursively(const fssrv::sf::Path &path) {
auto read_lock = this->AcquireCacheInvalidationReadLock();
PathNormalizer normalizer(path.str);
R_UNLESS(normalizer.GetPath() != nullptr, normalizer.GetResult());
R_UNLESS(strncmp(normalizer.GetPath(), "/", 2) != 0, fs::ResultDirectoryNotDeletable());
return this->base_fs->DeleteDirectoryRecursively(normalizer.GetPath());
}
Result FileSystemInterfaceAdapter::RenameFile(const fssrv::sf::Path &old_path, const fssrv::sf::Path &new_path) {
auto read_lock = this->AcquireCacheInvalidationReadLock();
PathNormalizer old_normalizer(old_path.str);
PathNormalizer new_normalizer(new_path.str);
R_UNLESS(old_normalizer.GetPath() != nullptr, old_normalizer.GetResult());
R_UNLESS(new_normalizer.GetPath() != nullptr, new_normalizer.GetResult());
return this->base_fs->RenameFile(old_normalizer.GetPath(), new_normalizer.GetPath());
}
Result FileSystemInterfaceAdapter::RenameDirectory(const fssrv::sf::Path &old_path, const fssrv::sf::Path &new_path) {
auto read_lock = this->AcquireCacheInvalidationReadLock();
PathNormalizer old_normalizer(old_path.str);
PathNormalizer new_normalizer(new_path.str);
R_UNLESS(old_normalizer.GetPath() != nullptr, old_normalizer.GetResult());
R_UNLESS(new_normalizer.GetPath() != nullptr, new_normalizer.GetResult());
const bool is_subpath = fssystem::PathTool::IsSubPath(old_normalizer.GetPath(), new_normalizer.GetPath());
R_UNLESS(!is_subpath, fs::ResultDirectoryNotRenamable());
return this->base_fs->RenameFile(old_normalizer.GetPath(), new_normalizer.GetPath());
}
Result FileSystemInterfaceAdapter::GetEntryType(ams::sf::Out<u32> out, const fssrv::sf::Path &path) {
auto read_lock = this->AcquireCacheInvalidationReadLock();
PathNormalizer normalizer(path.str);
R_UNLESS(normalizer.GetPath() != nullptr, normalizer.GetResult());
static_assert(sizeof(*out.GetPointer()) == sizeof(fs::DirectoryEntryType));
return this->base_fs->GetEntryType(reinterpret_cast<fs::DirectoryEntryType *>(out.GetPointer()), normalizer.GetPath());
}
Result FileSystemInterfaceAdapter::OpenFile(ams::sf::Out<std::shared_ptr<FileInterfaceAdapter>> out, const fssrv::sf::Path &path, u32 mode) {
auto read_lock = this->AcquireCacheInvalidationReadLock();
std::unique_lock<fssystem::SemaphoreAdapter> open_count_semaphore;
if (this->open_count_limited) {
/* TODO: This calls into fssrv::FileSystemProxyImpl, which we don't have yet. */
AMS_ASSERT(false);
}
PathNormalizer normalizer(path.str);
R_UNLESS(normalizer.GetPath() != nullptr, normalizer.GetResult());
/* TODO: N retries on ResultDataCorrupted, we may want to eventually. */
std::unique_ptr<fs::fsa::IFile> file;
R_TRY(this->base_fs->OpenFile(&file, normalizer.GetPath(), static_cast<fs::OpenMode>(mode)));
/* TODO: This is a hack to get the mitm API to work. Better solution? */
const auto target_object_id = file->GetDomainObjectId();
/* TODO: N creates an nn::fssystem::AsynchronousAccessFile here. */
std::shared_ptr<FileSystemInterfaceAdapter> shared_this = this->shared_from_this();
std::shared_ptr<FileInterfaceAdapter> file_intf = std::make_shared<FileInterfaceAdapter>(std::move(file), std::move(shared_this), std::move(open_count_semaphore));
R_UNLESS(file_intf != nullptr, fs::ResultAllocationFailureInFileSystemInterfaceAdapter());
out.SetValue(std::move(file_intf), target_object_id);
return ResultSuccess();
}
Result FileSystemInterfaceAdapter::OpenDirectory(ams::sf::Out<std::shared_ptr<DirectoryInterfaceAdapter>> out, const fssrv::sf::Path &path, u32 mode) {
auto read_lock = this->AcquireCacheInvalidationReadLock();
std::unique_lock<fssystem::SemaphoreAdapter> open_count_semaphore;
if (this->open_count_limited) {
/* TODO: This calls into fssrv::FileSystemProxyImpl, which we don't have yet. */
AMS_ASSERT(false);
}
PathNormalizer normalizer(path.str);
R_UNLESS(normalizer.GetPath() != nullptr, normalizer.GetResult());
/* TODO: N retries on ResultDataCorrupted, we may want to eventually. */
std::unique_ptr<fs::fsa::IDirectory> dir;
R_TRY(this->base_fs->OpenDirectory(&dir, normalizer.GetPath(), static_cast<fs::OpenDirectoryMode>(mode)));
/* TODO: This is a hack to get the mitm API to work. Better solution? */
const auto target_object_id = dir->GetDomainObjectId();
std::shared_ptr<FileSystemInterfaceAdapter> shared_this = this->shared_from_this();
std::shared_ptr<DirectoryInterfaceAdapter> dir_intf = std::make_shared<DirectoryInterfaceAdapter>(std::move(dir), std::move(shared_this), std::move(open_count_semaphore));
R_UNLESS(dir_intf != nullptr, fs::ResultAllocationFailureInFileSystemInterfaceAdapter());
out.SetValue(std::move(dir_intf), target_object_id);
return ResultSuccess();
}
Result FileSystemInterfaceAdapter::Commit() {
auto read_lock = this->AcquireCacheInvalidationReadLock();
return this->base_fs->Commit();
}
Result FileSystemInterfaceAdapter::GetFreeSpaceSize(ams::sf::Out<s64> out, const fssrv::sf::Path &path) {
auto read_lock = this->AcquireCacheInvalidationReadLock();
PathNormalizer normalizer(path.str);
R_UNLESS(normalizer.GetPath() != nullptr, normalizer.GetResult());
return this->base_fs->GetFreeSpaceSize(out.GetPointer(), normalizer.GetPath());
}
Result FileSystemInterfaceAdapter::GetTotalSpaceSize(ams::sf::Out<s64> out, const fssrv::sf::Path &path) {
auto read_lock = this->AcquireCacheInvalidationReadLock();
PathNormalizer normalizer(path.str);
R_UNLESS(normalizer.GetPath() != nullptr, normalizer.GetResult());
return this->base_fs->GetTotalSpaceSize(out.GetPointer(), normalizer.GetPath());
}
Result FileSystemInterfaceAdapter::CleanDirectoryRecursively(const fssrv::sf::Path &path) {
auto read_lock = this->AcquireCacheInvalidationReadLock();
PathNormalizer normalizer(path.str);
R_UNLESS(normalizer.GetPath() != nullptr, normalizer.GetResult());
return this->base_fs->CleanDirectoryRecursively(normalizer.GetPath());
}
Result FileSystemInterfaceAdapter::GetFileTimeStampRaw(ams::sf::Out<fs::FileTimeStampRaw> out, const fssrv::sf::Path &path) {
auto read_lock = this->AcquireCacheInvalidationReadLock();
PathNormalizer normalizer(path.str);
R_UNLESS(normalizer.GetPath() != nullptr, normalizer.GetResult());
return this->base_fs->GetFileTimeStampRaw(out.GetPointer(), normalizer.GetPath());
}
Result FileSystemInterfaceAdapter::QueryEntry(const ams::sf::OutBuffer &out_buf, const ams::sf::InBuffer &in_buf, s32 query_id, const fssrv::sf::Path &path) {
auto read_lock = this->AcquireCacheInvalidationReadLock();
/* TODO: Nintendo does not normalize the path. Should we? */
char *dst = reinterpret_cast< char *>(out_buf.GetPointer());
const char *src = reinterpret_cast<const char *>(in_buf.GetPointer());
return this->base_fs->QueryEntry(dst, out_buf.GetSize(), src, in_buf.GetSize(), static_cast<fs::fsa::QueryId>(query_id), path.str);
}
}

View File

@@ -0,0 +1,77 @@
/*
* Copyright (c) 2018-2019 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams::fssrv {
Result PathNormalizer::Normalize(const char **out_path, Buffer *out_buf, const char *path, bool preserve_unc, bool preserve_tail_sep, bool has_mount_name) {
/* Clear output. */
*out_path = nullptr;
*out_buf = Buffer();
/* Find start of path. */
const char *path_start = path;
if (has_mount_name) {
while (path_start < path + fs::MountNameLengthMax + 1) {
if (fssystem::PathTool::IsNullTerminator(*path_start)) {
break;
} else if (fssystem::PathTool::IsDriveSeparator(*(path_start++))) {
break;
}
}
R_UNLESS(path < path_start - 1, fs::ResultInvalidPath());
R_UNLESS(fssystem::PathTool::IsDriveSeparator(*(path_start - 1)), fs::ResultInvalidPath());
}
/* Check if we're normalized. */
bool normalized = false;
R_TRY(fssystem::PathTool::IsNormalized(&normalized, path_start));
if (normalized) {
/* If we're already normalized, no allocation is needed. */
*out_path = path;
} else {
/* Allocate a new buffer. */
auto buffer = std::make_unique<char[]>(fs::EntryNameLengthMax + 1);
R_UNLESS(buffer != nullptr, fs::ResultAllocationFailureInPathNormalizer());
/* Copy in mount name. */
const size_t mount_name_len = path_start - path;
std::memcpy(buffer.get(), path, mount_name_len);
/* Generate normalized path. */
size_t normalized_len = 0;
R_TRY(fssystem::PathTool::Normalize(buffer.get() + mount_name_len, &normalized_len, path_start, fs::EntryNameLengthMax + 1 - mount_name_len, preserve_unc));
/* Preserve the tail separator, if we should. */
if (preserve_tail_sep) {
if (fssystem::PathTool::IsSeparator(path[strnlen(path, fs::EntryNameLengthMax) - 1])) {
/* Nintendo doesn't actually validate this. */
R_UNLESS(mount_name_len + normalized_len < fs::EntryNameLengthMax, fs::ResultTooLongPath());
buffer[mount_name_len + normalized_len] = fssystem::StringTraits::DirectorySeparator;
buffer[mount_name_len + normalized_len + 1] = fssystem::StringTraits::NullTerminator;
}
}
/* Save output. */
*out_path = buffer.get();
*out_buf = std::move(buffer);
}
return ResultSuccess();
}
}

View File

@@ -0,0 +1,94 @@
/*
* Copyright (c) 2018-2019 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include <stratosphere/fssrv/fssrv_interface_adapters.hpp>
namespace ams::fssrv::impl {
StorageInterfaceAdapter::StorageInterfaceAdapter(fs::IStorage *storage) : base_storage(storage) {
/* ... */
}
StorageInterfaceAdapter::StorageInterfaceAdapter(std::unique_ptr<fs::IStorage> storage) : base_storage(storage.release()) {
/* ... */
}
StorageInterfaceAdapter::StorageInterfaceAdapter(std::shared_ptr<fs::IStorage> &&storage) : base_storage(std::move(storage)) {
/* ... */
}
StorageInterfaceAdapter::~StorageInterfaceAdapter() {
/* ... */
}
std::optional<std::shared_lock<os::ReadWriteLock>> StorageInterfaceAdapter::AcquireCacheInvalidationReadLock() {
std::optional<std::shared_lock<os::ReadWriteLock>> lock;
if (this->deep_retry_enabled) {
lock.emplace(this->invalidation_lock);
}
return lock;
}
Result StorageInterfaceAdapter::Read(s64 offset, const ams::sf::OutNonSecureBuffer &buffer, s64 size) {
/* TODO: N retries on ResultDataCorrupted, we may want to eventually. */
/* TODO: Deep retry */
R_UNLESS(offset >= 0, fs::ResultInvalidOffset());
R_UNLESS(size >= 0, fs::ResultInvalidSize());
return this->base_storage->Read(offset, buffer.GetPointer(), size);
}
Result StorageInterfaceAdapter::Write(s64 offset, const ams::sf::InNonSecureBuffer &buffer, s64 size) {
/* TODO: N increases thread priority temporarily when writing. We may want to eventually. */
R_UNLESS(offset >= 0, fs::ResultInvalidOffset());
R_UNLESS(size >= 0, fs::ResultInvalidSize());
auto read_lock = this->AcquireCacheInvalidationReadLock();
return this->base_storage->Write(offset, buffer.GetPointer(), size);
}
Result StorageInterfaceAdapter::Flush() {
auto read_lock = this->AcquireCacheInvalidationReadLock();
return this->base_storage->Flush();
}
Result StorageInterfaceAdapter::SetSize(s64 size) {
R_UNLESS(size >= 0, fs::ResultInvalidSize());
auto read_lock = this->AcquireCacheInvalidationReadLock();
return this->base_storage->SetSize(size);
}
Result StorageInterfaceAdapter::GetSize(ams::sf::Out<s64> out) {
auto read_lock = this->AcquireCacheInvalidationReadLock();
return this->base_storage->GetSize(out.GetPointer());
}
Result StorageInterfaceAdapter::OperateRange(ams::sf::Out<fs::StorageQueryRangeInfo> out, s32 op_id, s64 offset, s64 size) {
/* N includes this redundant check, so we will too. */
R_UNLESS(out.GetPointer() != nullptr, fs::ResultNullptrArgument());
out->Clear();
if (op_id == static_cast<s32>(fs::OperationId::QueryRange)) {
auto read_lock = this->AcquireCacheInvalidationReadLock();
fs::StorageQueryRangeInfo info;
R_TRY(this->base_storage->OperateRange(&info, sizeof(info), fs::OperationId::QueryRange, offset, size, nullptr, 0));
out->Merge(info);
}
return ResultSuccess();
}
}

View File

@@ -0,0 +1,115 @@
/*
* Copyright (c) 2018-2019 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams::fssystem {
DirectoryRedirectionFileSystem::DirectoryRedirectionFileSystem(std::shared_ptr<fs::fsa::IFileSystem> fs, const char *before, const char *after) : PathResolutionFileSystem(fs) {
this->before_dir = nullptr;
this->after_dir = nullptr;
R_ASSERT(this->Initialize(before, after));
}
DirectoryRedirectionFileSystem::DirectoryRedirectionFileSystem(std::shared_ptr<fs::fsa::IFileSystem> fs, const char *before, const char *after, bool unc) : PathResolutionFileSystem(fs, unc) {
this->before_dir = nullptr;
this->after_dir = nullptr;
R_ASSERT(this->Initialize(before, after));
}
DirectoryRedirectionFileSystem::~DirectoryRedirectionFileSystem() {
if (this->before_dir != nullptr) {
std::free(this->before_dir);
}
if (this->after_dir != nullptr) {
std::free(this->after_dir);
}
}
Result DirectoryRedirectionFileSystem::GetNormalizedDirectoryPath(char **out, size_t *out_size, const char *dir) {
/* Clear output. */
*out = nullptr;
*out_size = 0;
/* Make sure the path isn't too long. */
R_UNLESS(strnlen(dir, fs::EntryNameLengthMax + 1) <= fs::EntryNameLengthMax, fs::ResultTooLongPath());
/* Normalize the path. */
char normalized_path[fs::EntryNameLengthMax + 2];
size_t normalized_path_len;
R_TRY(PathTool::Normalize(normalized_path, &normalized_path_len, dir, sizeof(normalized_path), this->IsUncPreserved()));
/* Ensure terminating '/' */
if (!PathTool::IsSeparator(normalized_path[normalized_path_len - 1])) {
AMS_ASSERT(normalized_path_len + 2 <= sizeof(normalized_path));
normalized_path[normalized_path_len] = StringTraits::DirectorySeparator;
normalized_path[normalized_path_len + 1] = StringTraits::NullTerminator;
normalized_path_len++;
}
/* Allocate new path. */
const size_t size = normalized_path_len + 1;
char *new_dir = static_cast<char *>(std::malloc(size));
AMS_ASSERT(new_dir != nullptr);
/* TODO: custom ResultAllocationFailure? */
/* Copy path in. */
std::memcpy(new_dir, normalized_path, normalized_path_len);
new_dir[normalized_path_len] = StringTraits::NullTerminator;
/* Set output. */
*out = new_dir;
*out_size = size;
return ResultSuccess();
}
Result DirectoryRedirectionFileSystem::Initialize(const char *before, const char *after) {
/* Normalize both directories. */
this->GetNormalizedDirectoryPath(&this->before_dir, &this->before_dir_len, before);
this->GetNormalizedDirectoryPath(&this->after_dir, &this->after_dir_len, after);
return ResultSuccess();
}
Result DirectoryRedirectionFileSystem::ResolveFullPath(char *out, size_t out_size, const char *relative_path) {
/* Normalize the relative path. */
char normalized_rel_path[fs::EntryNameLengthMax + 1];
size_t normalized_rel_path_len;
R_TRY(PathTool::Normalize(normalized_rel_path, &normalized_rel_path_len, relative_path, sizeof(normalized_rel_path), this->IsUncPreserved()));
const bool is_prefixed = std::memcmp(normalized_rel_path, this->before_dir, this->before_dir_len - 2) == 0 &&
(PathTool::IsSeparator(normalized_rel_path[this->before_dir_len - 2]) || PathTool::IsNullTerminator(normalized_rel_path[this->before_dir_len - 2]));
if (is_prefixed) {
const size_t before_prefix_len = this->before_dir_len - 2;
const size_t after_prefix_len = this->after_dir_len - 2;
const size_t final_str_len = after_prefix_len + normalized_rel_path_len - before_prefix_len;
R_UNLESS(final_str_len < out_size, fs::ResultTooLongPath());
/* Copy normalized path. */
std::memcpy(out, this->after_dir, after_prefix_len);
std::memcpy(out + after_prefix_len, normalized_rel_path + before_prefix_len, normalized_rel_path_len - before_prefix_len);
out[final_str_len] = StringTraits::NullTerminator;
} else {
/* Path is not prefixed. */
R_UNLESS(normalized_rel_path_len + 1 <= out_size, fs::ResultTooLongPath());
std::memcpy(out, normalized_rel_path, normalized_rel_path_len);
out[normalized_rel_path_len] = StringTraits::NullTerminator;
}
return ResultSuccess();
}
}

View File

@@ -0,0 +1,78 @@
/*
* Copyright (c) 2018-2019 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams::fssystem {
SubDirectoryFileSystem::SubDirectoryFileSystem(std::shared_ptr<fs::fsa::IFileSystem> fs, const char *bp) : PathResolutionFileSystem(fs) {
this->base_path = nullptr;
R_ASSERT(this->Initialize(bp));
}
SubDirectoryFileSystem::SubDirectoryFileSystem(std::shared_ptr<fs::fsa::IFileSystem> fs, const char *bp, bool unc) : PathResolutionFileSystem(fs, unc) {
this->base_path = nullptr;
R_ASSERT(this->Initialize(bp));
}
SubDirectoryFileSystem::~SubDirectoryFileSystem() {
if (this->base_path != nullptr) {
std::free(this->base_path);
}
}
Result SubDirectoryFileSystem::Initialize(const char *bp) {
/* Make sure the path isn't too long. */
R_UNLESS(strnlen(bp, fs::EntryNameLengthMax + 1) <= fs::EntryNameLengthMax, fs::ResultTooLongPath());
/* Normalize the path. */
char normalized_path[fs::EntryNameLengthMax + 2];
size_t normalized_path_len;
R_TRY(PathTool::Normalize(normalized_path, &normalized_path_len, bp, sizeof(normalized_path), this->IsUncPreserved()));
/* Ensure terminating '/' */
if (!PathTool::IsSeparator(normalized_path[normalized_path_len - 1])) {
AMS_ASSERT(normalized_path_len + 2 <= sizeof(normalized_path));
normalized_path[normalized_path_len] = StringTraits::DirectorySeparator;
normalized_path[normalized_path_len + 1] = StringTraits::NullTerminator;
normalized_path_len++;
}
/* Allocate new path. */
this->base_path_len = normalized_path_len + 1;
this->base_path = static_cast<char *>(std::malloc(this->base_path_len));
R_UNLESS(this->base_path != nullptr, fs::ResultAllocationFailureInSubDirectoryFileSystem());
/* Copy path in. */
std::memcpy(this->base_path, normalized_path, normalized_path_len);
this->base_path[normalized_path_len] = StringTraits::NullTerminator;
return ResultSuccess();
}
Result SubDirectoryFileSystem::ResolveFullPath(char *out, size_t out_size, const char *relative_path) {
/* Ensure path will fit. */
R_UNLESS(this->base_path_len + strnlen(relative_path, fs::EntryNameLengthMax + 1) <= out_size, fs::ResultTooLongPath());
/* Copy base path. */
std::memcpy(out, this->base_path, this->base_path_len);
/* Normalize it. */
const size_t prefix_size = this->base_path_len - 2;
size_t normalized_len;
return PathTool::Normalize(out + prefix_size, &normalized_len, relative_path, out_size - prefix_size, this->IsUncPreserved());
}
}

View File

@@ -19,6 +19,7 @@
#include "os_waitable_holder_of_inter_process_event.hpp"
#include "os_waitable_holder_of_interrupt_event.hpp"
#include "os_waitable_holder_of_thread.hpp"
#include "os_waitable_holder_of_semaphore.hpp"
#include "os_waitable_holder_of_message_queue.hpp"
namespace ams::os::impl {
@@ -30,6 +31,7 @@ namespace ams::os::impl {
TYPED_STORAGE(WaitableHolderOfInterProcessEvent) holder_of_inter_process_event_storage;
TYPED_STORAGE(WaitableHolderOfInterruptEvent) holder_of_interrupt_event_storage;
TYPED_STORAGE(WaitableHolderOfThread) holder_of_thread_storage;
TYPED_STORAGE(WaitableHolderOfSemaphore) holder_of_semaphore_storage;
TYPED_STORAGE(WaitableHolderOfMessageQueueForNotFull) holder_of_mq_for_not_full_storage;
TYPED_STORAGE(WaitableHolderOfMessageQueueForNotEmpty) holder_of_mq_for_not_empty_storage;
};
@@ -43,6 +45,7 @@ namespace ams::os::impl {
CHECK_HOLDER(WaitableHolderOfInterProcessEvent);
CHECK_HOLDER(WaitableHolderOfInterruptEvent);
CHECK_HOLDER(WaitableHolderOfThread);
CHECK_HOLDER(WaitableHolderOfSemaphore);
CHECK_HOLDER(WaitableHolderOfMessageQueueForNotFull);
CHECK_HOLDER(WaitableHolderOfMessageQueueForNotEmpty);

View File

@@ -0,0 +1,52 @@
/*
* Copyright (c) 2018-2019 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "os_waitable_holder_base.hpp"
#include "os_waitable_object_list.hpp"
namespace ams::os::impl {
class WaitableHolderOfSemaphore : public WaitableHolderOfUserObject {
private:
Semaphore *semaphore;
private:
TriBool IsSignaledImpl() const {
return this->semaphore->count > 0 ? TriBool::True : TriBool::False;
}
public:
explicit WaitableHolderOfSemaphore(Semaphore *s) : semaphore(s) { /* ... */ }
/* IsSignaled, Link, Unlink implemented. */
virtual TriBool IsSignaled() const override {
std::scoped_lock lk(this->semaphore->mutex);
return this->IsSignaledImpl();
}
virtual TriBool LinkToObjectList() override {
std::scoped_lock lk(this->semaphore->mutex);
GetReference(this->semaphore->waitlist).LinkWaitableHolder(*this);
return this->IsSignaledImpl();
}
virtual void UnlinkFromObjectList() override {
std::scoped_lock lk(this->semaphore->mutex);
GetReference(this->semaphore->waitlist).UnlinkWaitableHolder(*this);
}
};
}

View File

@@ -0,0 +1,85 @@
/*
* Copyright (c) 2018-2019 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "impl/os_waitable_object_list.hpp"
namespace ams::os {
Semaphore::Semaphore(int c, int mc) : count(c), max_count(mc) {
new (GetPointer(this->waitlist)) impl::WaitableObjectList();
}
Semaphore::~Semaphore() {
GetReference(this->waitlist).~WaitableObjectList();
}
void Semaphore::Acquire() {
std::scoped_lock lk(this->mutex);
while (this->count == 0) {
this->condvar.Wait(&this->mutex);
}
this->count--;
}
bool Semaphore::TryAcquire() {
std::scoped_lock lk(this->mutex);
if (this->count == 0) {
return false;
}
this->count--;
return true;
}
bool Semaphore::TimedAcquire(u64 timeout) {
std::scoped_lock lk(this->mutex);
TimeoutHelper timeout_helper(timeout);
while (this->count == 0) {
if (timeout_helper.TimedOut()) {
return false;
}
this->condvar.TimedWait(&this->mutex, timeout_helper.NsUntilTimeout());
}
this->count--;
return true;
}
void Semaphore::Release() {
std::scoped_lock lk(this->mutex);
AMS_ASSERT(this->count + 1 <= this->max_count);
this->count++;
this->condvar.Signal();
GetReference(this->waitlist).SignalAllThreads();
}
void Semaphore::Release(int count) {
std::scoped_lock lk(this->mutex);
AMS_ASSERT(this->count + count <= this->max_count);
this->count += count;
this->condvar.Broadcast();
GetReference(this->waitlist).SignalAllThreads();
}
}

View File

@@ -70,6 +70,14 @@ namespace ams::os {
this->user_data = 0;
}
WaitableHolder::WaitableHolder(Semaphore *semaphore) {
/* Initialize appropriate holder. */
new (GetPointer(this->impl_storage)) impl::WaitableHolderOfSemaphore(semaphore);
/* Set user-data. */
this->user_data = 0;
}
WaitableHolder::WaitableHolder(MessageQueue *message_queue, MessageQueueWaitKind wait_kind) {
/* Initialize appropriate holder. */
switch (wait_kind) {

View File

@@ -363,7 +363,7 @@ namespace ams::spl::smc {
Result AtmosphereGetEmummcConfig(void *out_config, void *out_paths, u32 storage_id) {
const u64 paths = reinterpret_cast<u64>(out_paths);
AMS_ASSERT(util::IsAligned(paths, 0x1000));
AMS_ASSERT(util::IsAligned(paths, os::MemoryPageSize));
SecmonArgs args = {};
args.X[0] = static_cast<u64>(FunctionId::AtmosphereGetEmummcConfig);

View File

@@ -54,15 +54,9 @@ namespace ams::updater {
/* Implementations. */
Result ValidateWorkBuffer(const void *work_buffer, size_t work_buffer_size) {
if (work_buffer_size < BctSize + EksSize) {
return ResultTooSmallWorkBuffer();
}
if (!util::IsAligned(work_buffer, 0x1000)) {
return ResultNotAlignedWorkBuffer();
}
if (util::IsAligned(work_buffer_size, 0x200)) {
return ResultNotAlignedWorkBuffer();
}
R_UNLESS(work_buffer_size >= BctSize + EksSize, ResultTooSmallWorkBuffer());
R_UNLESS(util::IsAligned(work_buffer, os::MemoryPageSize), ResultNotAlignedWorkBuffer());
R_UNLESS(util::IsAligned(work_buffer_size, 0x200), ResultNotAlignedWorkBuffer());
return ResultSuccess();
}

View File

@@ -30,7 +30,7 @@ namespace ams::updater {
Result BisSave::Initialize(void *work_buffer, size_t work_buffer_size) {
AMS_ASSERT(work_buffer_size >= SaveSize);
AMS_ASSERT(util::IsAligned(reinterpret_cast<uintptr_t>(work_buffer), 0x1000));
AMS_ASSERT(util::IsAligned(reinterpret_cast<uintptr_t>(work_buffer), os::MemoryPageSize));
AMS_ASSERT(util::IsAligned(work_buffer_size, 0x200));
R_TRY(this->accessor.Initialize());