Atmosphere/stratosphere/dmnt/source/dmnt_service_target_io.cpp

260 lines
8.9 KiB
C++
Raw Normal View History

/*
* Copyright (c) 2018-2020 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 "dmnt_service.hpp"
2019-10-18 06:18:27 +02:00
namespace std {
template<>
struct hash<ams::dmnt::TargetIOFileHandle> {
u64 operator()(ams::dmnt::TargetIOFileHandle const &handle) const noexcept {
2019-10-18 06:18:27 +02:00
return handle.GetValue();
}
};
}
namespace ams::dmnt {
2019-06-20 07:19:53 +02:00
2019-09-16 10:22:08 +02:00
namespace {
2019-09-16 10:22:08 +02:00
enum TIOCreateOption : u32 {
TIOCreateOption_CreateNew = 1,
TIOCreateOption_CreateAlways = 2,
TIOCreateOption_OpenExisting = 3,
TIOCreateOption_OpenAlways = 4,
TIOCreateOption_ResetSize = 5,
};
2019-06-20 07:19:53 +02:00
2019-09-16 10:22:08 +02:00
/* Nintendo uses actual pointers as file handles. We'll add a layer of indirection... */
bool g_sd_initialized = false;
2020-04-08 11:21:35 +02:00
os::Mutex g_sd_lock(false);
2019-09-16 10:22:08 +02:00
FsFileSystem g_sd_fs;
2020-04-08 11:21:35 +02:00
os::Mutex g_file_handle_lock(false);
2019-09-16 10:22:08 +02:00
u64 g_cur_fd;
2019-10-18 06:18:27 +02:00
std::unordered_map<TargetIOFileHandle, FsFile> g_file_handles;
2019-06-20 07:19:53 +02:00
2019-09-16 10:22:08 +02:00
Result EnsureSdInitialized() {
2019-09-24 12:15:36 +02:00
std::scoped_lock lk(g_sd_lock);
Implement the NCM sysmodule (closes #91) * Implement NCM * Modernize ncm_main * Remove unnecessary smExit * Give access to svcCallSecureMonitor * Stack size bump * Fix incorrect setup for NandUser's content storage entry * Fix a potential data abort when flushing the placeholder accessor cache * Fix HasFile and HasDirectory * Use r+b, not w+b * Misc fixes * errno begone * Fixed more stdio error handling * More main fixes * Various command improvements * Make dispatch tables great again * Fix logic inversion * Fixed content path generation * Bump heap size, fix CleanupAllPlaceHolder * Various fixes. Note: This contains debug stuff which will be removed later. I was getting tired of having to cherrypick tiny changes * Fixed placeholder/content deletion * Fixed incorrect content manager destruction * Prevent automatic placeholder creation on open * Fixed List implementation. Also lots of debug logging. * Removed debug code * Added a scope guard for WritePlaceHolder * Manually prevent placeholder/content appending * Revert "Removed debug code" This reverts commit d6ff261fcc8c1f26968e894b02c17a01a12ec98b. * Always cache placeholder file. Switch to ftell for preventing appending * Universally use EnsureEnabled * Abstract away file writing logic * Misc cleanup * Refactor placeholder cacheing * Remove debug code (again) * Revert "Remove debug code (again)" This reverts commit 168447d80e9640768fb1b43f04a385507c1bb5ab. * Misc changes * Fixed file modes * Fixed ContentId/PlaceHolderId alignment * Improved type safety * Fixed reinitialization * Fixed doubleup on path creation * Remove debug code * Fixed 1.0.0 booting * Correct amount of add on content * Correct main thread stack size * lr: Introducing registered data * Reorder stratosphere Makefile * Move results to libstrat * lr: Cleanup lr_redirection * lr: lr_manager tweaks * lr: Imrpoved path handling and adjust ResolveAddOnContentPath order * lr: Organise types * Add eof newlines * lr: Eliminate unnecessary vars * lr: Unnecessary vars 2 electric boogaloo * lr: Various helpers * lr: RegisteredLocationResolver helpers * ncm: Move ncm_types to libstrat * ncm: Misc cleanup * Implement NCM * Modernize ncm_main * Remove unnecessary smExit * Give access to svcCallSecureMonitor * Stack size bump * Fix incorrect setup for NandUser's content storage entry * Fix a potential data abort when flushing the placeholder accessor cache * Fix HasFile and HasDirectory * Use r+b, not w+b * Misc fixes * errno begone * Fixed more stdio error handling * More main fixes * Various command improvements * Make dispatch tables great again * Fix logic inversion * Fixed content path generation * Bump heap size, fix CleanupAllPlaceHolder * Various fixes. Note: This contains debug stuff which will be removed later. I was getting tired of having to cherrypick tiny changes * Fixed placeholder/content deletion * Fixed incorrect content manager destruction * Prevent automatic placeholder creation on open * Fixed List implementation. Also lots of debug logging. * Removed debug code * Added a scope guard for WritePlaceHolder * Manually prevent placeholder/content appending * Revert "Removed debug code" This reverts commit d6ff261fcc8c1f26968e894b02c17a01a12ec98b. * Always cache placeholder file. Switch to ftell for preventing appending * Universally use EnsureEnabled * Abstract away file writing logic * Misc cleanup * Refactor placeholder cacheing * Remove debug code (again) * Revert "Remove debug code (again)" This reverts commit 168447d80e9640768fb1b43f04a385507c1bb5ab. * Misc changes * Fixed file modes * Fixed ContentId/PlaceHolderId alignment * Improved type safety * Fixed reinitialization * Fixed doubleup on path creation * Remove debug code * Fixed 1.0.0 booting * Correct amount of add on content * Correct main thread stack size * lr: Introducing registered data * Reorder stratosphere Makefile * Move results to libstrat * lr: Cleanup lr_redirection * lr: lr_manager tweaks * lr: Imrpoved path handling and adjust ResolveAddOnContentPath order * lr: Organise types * Add eof newlines * lr: Eliminate unnecessary vars * lr: Unnecessary vars 2 electric boogaloo * lr: Various helpers * lr: RegisteredLocationResolver helpers * ncm: Move ncm_types to libstrat * ncm: Misc cleanup * Updated AddOnContentLocationResolver and RegisteredLocationResolver to 9.0.0 * Finished updating lr to 9.0.0 * Updated NCM to 9.0.0 * Fix libstrat includes * Fixed application launching * title_id_2 -> owner_tid * Updated to new-ipc * Change to using pure virtuals * Title Id -> Program Id * Fixed compilation against master * std::scoped_lock<> -> std::scoped_lock * Adopted R_UNLESS and R_CONVERT * Prefix namespace to Results * Adopt std::numeric_limits * Fixed incorrect error handling in ReadFile * Adopted AMS_ABORT_UNLESS * Adopt util::GenerateUuid() * Syntax improvements * ncm_types: Address review * Address more review comments * Updated copyrights * Address more feedback * More feedback addressed * More changes * Move dispatch tables out of interface files * Addressed remaining comments * lr: move into libstratosphere * ncm: Fix logic inversion * lr: Add comments * lr: Remove whitespace * ncm: Start addressing feedback * ncm: Cleanup InitializeContentManager * lr: support client-side usage * lr_service -> lr_api * ncm: Begin refactoring content manager * ncm: More content manager improvements * ncm: Content manager mount improvements * ldr: use lr bindings * lr bindings usage: minor fixes * ncm/lr: Pointer placement * ncm: placeholder accessor cleanup * ncm: minor fixes * ncm: refactor rights cache * ncm: content meta database cleanup * ncm: move content meta database impl out of interface file * ncm: Use const ContentMetaKey & * ncm: fix other non-const ContentMetaKey references * ncm: content meta database cleanup * ncm: content storage fixes for 2.0.0 * ncm: add missing end of file newlines * ncm: implement ContentMetaReader * ncm: client-side api * ncm: trim trailing spaces * ncm: FS_MAX_PATH-1 -> fs::EntryNameLengthMax * ncm: Use PathString and Path * fs: implement accessor wrappers for ncm * fs: implement user fs wrappers * fs: add MountSdCard * ncm: move to content manager impl * ncm: fix up main * kvdb: use fs:: * fs: Add wrappers needed for ncm * ncm: use fs bindings, other refactoring * ncm: minor fixes * fsa: fix ReadFile without size output * fs: add substorage, rom path tool * ncm: fix dangling fsdev usage * fs: fix bug in Commit * fs: fixed incorrect mode check * fs: implement Mount(System)Data * ncm: don't delete hos * results: add R_SUCCEED_IF * ams-except-ncm: use R_SUCCEED_IF * ncm: added comments * ncm: fix api definitions * ncm: use R_SUCCEED_IF * pm: think of the savings * ncm: employ kernel strats * ncm: Nintendo has 5 MiB of heap. Give ourselves 4 to be safe, pending analysis * ncm: refactor IDs, split types header into many headers * ams.mitm: use fs bindings instead of stdio * fs: SystemData uses SystemDataId * ncm: improve meta-db accuracy * ncm: inline getlatestkey * fs: improve UnsupportedOperation results * fs: modernize mount utils * ams: misc fixes for merge-errors * fs: improve unsupportedoperation results * git subrepo pull emummc subrepo: subdir: "emummc" merged: "d12dd546" upstream: origin: "https://github.com/m4xw/emuMMC" branch: "develop" commit: "d12dd546" git-subrepo: version: "0.4.1" origin: "???" commit: "???" * util: add boundedmap * ncm: minor style fixes * ncm: don't unmount if mounting fails * lr: bug fixes * ncm: implement ncm.for-initialize + ncm.for-safemode * lr: ncm::ProgramId::Invalid -> ncm::InvalidProgramId * ncm: fix open directory mode on 1.0.0 * ncm: fix fs use, implement more of < 4.0.0 for-initialize/safemode * ncm: implement packagedcontent -> content for building metadb * ncm: fix save data flag management * ncm: address some review suggestions (thanks @leoetlino!) * updater: use fs bindings * fs: implement MountCode * fs: prefer make_unique to operator new * ncm: implement remaining ContentMetaDatabaseBuilder functionality Co-authored-by: Michael Scire <SciresM@gmail.com>
2020-03-08 09:06:23 +01:00
R_SUCCEED_IF(g_sd_initialized);
R_TRY(fsOpenSdCardFileSystem(&g_sd_fs));
2019-09-16 10:22:08 +02:00
g_sd_initialized = true;
return ResultSuccess();
2019-09-16 10:22:08 +02:00
}
2019-06-20 07:19:53 +02:00
2019-10-18 06:18:27 +02:00
TargetIOFileHandle GetNewFileHandle(FsFile f) {
2019-09-24 12:15:36 +02:00
std::scoped_lock lk(g_file_handle_lock);
2019-06-20 07:19:53 +02:00
2019-10-18 06:18:27 +02:00
TargetIOFileHandle fd = { .value = g_cur_fd++ };
2019-09-16 10:22:08 +02:00
g_file_handles[fd] = f;
return fd;
}
2019-10-18 06:18:27 +02:00
Result GetFileByHandle(FsFile *out, TargetIOFileHandle handle) {
2019-09-24 12:15:36 +02:00
std::scoped_lock lk(g_file_handle_lock);
2019-06-20 07:19:53 +02:00
2019-09-16 10:22:08 +02:00
if (g_file_handles.find(handle) != g_file_handles.end()) {
*out = g_file_handles[handle];
return ResultSuccess();
2019-09-16 10:22:08 +02:00
}
2019-06-20 07:19:53 +02:00
return fs::ResultInvalidArgument();
}
2019-06-20 07:19:53 +02:00
2019-10-18 06:18:27 +02:00
Result CloseFileByHandle(TargetIOFileHandle handle) {
2019-09-24 12:15:36 +02:00
std::scoped_lock lk(g_file_handle_lock);
2019-06-20 07:19:53 +02:00
2019-09-16 10:22:08 +02:00
if (g_file_handles.find(handle) != g_file_handles.end()) {
fsFileClose(&g_file_handles[handle]);
g_file_handles.erase(handle);
return ResultSuccess();
2019-09-16 10:22:08 +02:00
}
return fs::ResultInvalidArgument();
2019-09-16 10:22:08 +02:00
}
2019-06-20 07:19:53 +02:00
2019-10-18 06:18:27 +02:00
void FixPath(char *dst, size_t dst_size, const sf::InBuffer &path) {
2019-09-16 10:22:08 +02:00
dst[dst_size - 1] = 0;
strncpy(dst, "/", dst_size - 1);
2019-10-18 06:18:27 +02:00
const char *src = reinterpret_cast<const char *>(path.GetPointer());
2019-09-16 10:22:08 +02:00
size_t src_idx = 0;
size_t dst_idx = 1;
2019-10-18 06:18:27 +02:00
while (src_idx < path.GetSize() && (src[src_idx] == '/' || src[src_idx] == '\\')) {
2019-09-16 10:22:08 +02:00
src_idx++;
}
2019-10-18 06:18:27 +02:00
while (src_idx < path.GetSize() && dst_idx < dst_size - 1 && src[src_idx] != 0) {
2019-09-16 10:22:08 +02:00
if (src[src_idx] == '\\') {
dst[dst_idx] = '/';
} else {
dst[dst_idx] = src[src_idx];
}
src_idx++;
dst_idx++;
}
if (dst_idx < dst_size) {
dst[dst_idx] = 0;
}
}
2019-06-20 07:19:53 +02:00
}
2019-06-20 07:19:53 +02:00
2019-10-18 06:18:27 +02:00
Result DebugMonitorService::TargetIO_FileOpen(sf::Out<TargetIOFileHandle> out_hnd, const sf::InBuffer &path, int open_mode, u32 create_mode) {
2019-09-16 10:22:08 +02:00
R_TRY(EnsureSdInitialized());
2019-06-20 07:19:53 +02:00
2019-09-16 10:22:08 +02:00
char fs_path[FS_MAX_PATH];
FixPath(fs_path, sizeof(fs_path), path);
2019-06-20 07:19:53 +02:00
2019-09-16 10:22:08 +02:00
/* Create file as required by mode. */
if (create_mode == TIOCreateOption_CreateAlways) {
fsFsDeleteFile(&g_sd_fs, fs_path);
R_TRY(fsFsCreateFile(&g_sd_fs, fs_path, 0, 0));
} else if (create_mode == TIOCreateOption_CreateNew) {
R_TRY(fsFsCreateFile(&g_sd_fs, fs_path, 0, 0));
} else if (create_mode == TIOCreateOption_OpenAlways) {
fsFsCreateFile(&g_sd_fs, fs_path, 0, 0);
}
2019-09-16 10:22:08 +02:00
/* Open the file, guard to prevent failure to close. */
FsFile f;
R_TRY(fsFsOpenFile(&g_sd_fs, fs_path, open_mode, &f));
auto file_guard = SCOPE_GUARD { fsFileClose(&f); };
2019-09-16 10:22:08 +02:00
/* Set size if needed. */
if (create_mode == TIOCreateOption_ResetSize) {
R_TRY(fsFileSetSize(&f, 0));
}
/* Cancel guard, output file handle. */
file_guard.Cancel();
2019-10-18 06:18:27 +02:00
out_hnd.SetValue(GetNewFileHandle(f));
2019-09-16 10:22:08 +02:00
return ResultSuccess();
}
2019-06-20 07:19:53 +02:00
2019-10-18 06:18:27 +02:00
Result DebugMonitorService::TargetIO_FileClose(TargetIOFileHandle hnd) {
return CloseFileByHandle(hnd);
}
2019-06-20 07:19:53 +02:00
2019-11-29 07:19:39 +01:00
Result DebugMonitorService::TargetIO_FileRead(TargetIOFileHandle hnd, const sf::OutNonSecureBuffer &out_data, sf::Out<u32> out_read, s64 offset) {
2019-09-16 10:22:08 +02:00
FsFile f;
size_t read = 0;
2019-06-20 07:19:53 +02:00
2019-10-18 06:18:27 +02:00
R_TRY(GetFileByHandle(&f, hnd));
R_TRY(fsFileRead(&f, offset, out_data.GetPointer(), out_data.GetSize(), FsReadOption_None, &read));
2019-09-16 10:22:08 +02:00
out_read.SetValue(static_cast<u32>(read));
return ResultSuccess();
}
2019-06-20 07:19:53 +02:00
2019-11-29 07:19:39 +01:00
Result DebugMonitorService::TargetIO_FileWrite(TargetIOFileHandle hnd, const sf::InNonSecureBuffer &data, sf::Out<u32> out_written, s64 offset) {
2019-09-16 10:22:08 +02:00
FsFile f;
2019-06-20 07:19:53 +02:00
2019-10-18 06:18:27 +02:00
R_TRY(GetFileByHandle(&f, hnd));
R_TRY(fsFileWrite(&f, offset, data.GetPointer(), data.GetSize(), FsWriteOption_None));
2019-10-18 06:18:27 +02:00
out_written.SetValue(data.GetSize());
return ResultSuccess();
2019-09-16 10:22:08 +02:00
}
2019-10-18 06:18:27 +02:00
Result DebugMonitorService::TargetIO_FileSetAttributes(const sf::InBuffer &path, const sf::InBuffer &attributes) {
2019-09-16 10:22:08 +02:00
/* I don't really know why this command exists, Horizon doesn't allow you to set any attributes. */
/* N just returns ResultSuccess unconditionally here. */
return ResultSuccess();
}
2019-06-20 07:19:53 +02:00
2019-10-18 06:18:27 +02:00
Result DebugMonitorService::TargetIO_FileGetInformation(const sf::InBuffer &path, const sf::OutArray<u64> &out_info, sf::Out<int> is_directory) {
2019-09-16 10:22:08 +02:00
R_TRY(EnsureSdInitialized());
2019-06-20 07:19:53 +02:00
2019-09-16 10:22:08 +02:00
char fs_path[FS_MAX_PATH];
FixPath(fs_path, sizeof(fs_path), path);
2019-06-20 07:19:53 +02:00
2019-10-18 06:18:27 +02:00
for (size_t i = 0; i < out_info.GetSize(); i++) {
2019-09-16 10:22:08 +02:00
out_info[i] = 0;
}
is_directory.SetValue(0);
2019-06-20 07:19:53 +02:00
2019-09-16 10:22:08 +02:00
FsFile f;
2019-10-18 06:18:27 +02:00
if (R_SUCCEEDED(fsFsOpenFile(&g_sd_fs, fs_path, FsOpenMode_Read, &f))) {
2019-09-16 10:22:08 +02:00
ON_SCOPE_EXIT { fsFileClose(&f); };
2019-06-20 07:19:53 +02:00
2019-09-16 10:22:08 +02:00
/* N doesn't check this return code. */
2019-10-18 06:18:27 +02:00
if (out_info.GetSize() > 0) {
2019-11-29 07:19:39 +01:00
fsFileGetSize(&f, reinterpret_cast<s64 *>(&out_info[0]));
2019-10-18 06:18:27 +02:00
}
2019-06-20 07:19:53 +02:00
2019-09-16 10:22:08 +02:00
/* TODO: N does not call fsFsGetFileTimestampRaw here, but we possibly could. */
} else {
FsDir dir;
2019-10-18 06:18:27 +02:00
R_TRY(fsFsOpenDirectory(&g_sd_fs, fs_path, FsDirOpenMode_ReadFiles | FsDirOpenMode_ReadDirs, &dir));
2019-09-16 10:22:08 +02:00
fsDirClose(&dir);
is_directory.SetValue(1);
}
return ResultSuccess();
2019-09-16 10:22:08 +02:00
}
2019-10-18 06:18:27 +02:00
Result DebugMonitorService::TargetIO_FileSetTime(const sf::InBuffer &path, u64 create, u64 access, u64 modify) {
2019-09-16 10:22:08 +02:00
/* This is another function that doesn't really need to exist, because Horizon doesn't let you set anything. */
return ResultSuccess();
2019-09-16 10:22:08 +02:00
}
2019-06-20 07:19:53 +02:00
2019-11-29 07:19:39 +01:00
Result DebugMonitorService::TargetIO_FileSetSize(const sf::InBuffer &input, s64 size) {
2019-09-16 10:22:08 +02:00
/* Why does this function take in a path and not a file handle? */
2019-10-18 06:18:27 +02:00
R_TRY(EnsureSdInitialized());
2019-09-16 10:22:08 +02:00
/* We will try to be better than N, here. N only treats input as a path. */
2019-10-18 06:18:27 +02:00
FsFile f;
if (input.GetSize() == sizeof(TargetIOFileHandle)) {
R_UNLESS(R_FAILED(GetFileByHandle(&f, *reinterpret_cast<const TargetIOFileHandle *>(input.GetPointer()))), fsFileSetSize(&f, size));
}
2019-06-20 07:19:53 +02:00
2019-09-16 10:22:08 +02:00
char fs_path[FS_MAX_PATH];
FixPath(fs_path, sizeof(fs_path), input);
2019-06-20 07:19:53 +02:00
2019-10-18 06:18:27 +02:00
R_TRY(fsFsOpenFile(&g_sd_fs, fs_path, FsOpenMode_Write, &f));
2019-09-16 10:22:08 +02:00
ON_SCOPE_EXIT { fsFileClose(&f); };
2019-06-20 07:19:53 +02:00
2019-09-16 10:22:08 +02:00
return fsFileSetSize(&f, size);
}
2019-10-18 06:18:27 +02:00
Result DebugMonitorService::TargetIO_FileDelete(const sf::InBuffer &path) {
2019-09-16 10:22:08 +02:00
R_TRY(EnsureSdInitialized());
2019-06-20 07:19:53 +02:00
2019-09-16 10:22:08 +02:00
char fs_path[FS_MAX_PATH];
FixPath(fs_path, sizeof(fs_path), path);
2019-06-20 07:19:53 +02:00
2019-09-16 10:22:08 +02:00
return fsFsDeleteFile(&g_sd_fs, fs_path);
}
2019-10-18 06:18:27 +02:00
Result DebugMonitorService::TargetIO_FileMove(const sf::InBuffer &src_path, const sf::InBuffer &dst_path) {
2019-09-16 10:22:08 +02:00
R_TRY(EnsureSdInitialized());
2019-06-20 07:19:53 +02:00
2019-10-18 06:18:27 +02:00
char fs_src_path[FS_MAX_PATH];
char fs_dst_path[FS_MAX_PATH];
FixPath(fs_src_path, sizeof(fs_src_path), src_path);
FixPath(fs_dst_path, sizeof(fs_dst_path), dst_path);
2019-09-16 10:22:08 +02:00
2019-10-18 06:18:27 +02:00
return fsFsRenameFile(&g_sd_fs, fs_src_path, fs_dst_path);
2019-09-16 10:22:08 +02:00
}
2019-06-20 07:19:53 +02:00
}