id
int64
0
755k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
6,323
htclow_mux_task_manager.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htclow/mux/htclow_mux_task_manager.cpp
/* * Copyright (c) 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 "htclow_mux_task_manager.hpp" namespace ams::htclow::mux { os::EventType *TaskManager::GetTaskEvent(u32 task_id) { /* Check pre-conditions. */ AMS_ASSERT(task_id < MaxTaskCount); AMS_ASSERT(m_valid[task_id]); return std::addressof(m_tasks[task_id].event); } EventTrigger TaskManager::GetTrigger(u32 task_id) { /* Check pre-conditions. */ AMS_ASSERT(task_id < MaxTaskCount); AMS_ASSERT(m_valid[task_id]); return m_tasks[task_id].event_trigger; } Result TaskManager::AllocateTask(u32 *out_task_id, impl::ChannelInternalType channel) { /* Find a free task. */ u32 task_id = 0; for (task_id = 0; task_id < util::size(m_tasks); ++task_id) { if (!m_valid[task_id]) { break; } } /* Verify the task is free. */ R_UNLESS(task_id < util::size(m_tasks), htclow::ResultOutOfTask()); /* Mark the task as allocated. */ m_valid[task_id] = true; /* Setup the task. */ m_tasks[task_id].channel = channel; m_tasks[task_id].has_event_trigger = false; os::InitializeEvent(std::addressof(m_tasks[task_id].event), false, os::EventClearMode_ManualClear); /* Return the task id. */ *out_task_id = task_id; R_SUCCEED(); } void TaskManager::FreeTask(u32 task_id) { /* Check pre-conditions. */ AMS_ASSERT(task_id < MaxTaskCount); /* Invalidate the task. */ if (m_valid[task_id]) { os::FinalizeEvent(std::addressof(m_tasks[task_id].event)); m_valid[task_id] = false; } } void TaskManager::ConfigureConnectTask(u32 task_id) { /* Check pre-conditions. */ AMS_ASSERT(task_id < MaxTaskCount); AMS_ASSERT(m_valid[task_id]); /* Set the task type. */ m_tasks[task_id].type = TaskType_Connect; } void TaskManager::ConfigureFlushTask(u32 task_id) { /* Check pre-conditions. */ AMS_ASSERT(task_id < MaxTaskCount); AMS_ASSERT(m_valid[task_id]); /* Set the task type. */ m_tasks[task_id].type = TaskType_Flush; } void TaskManager::ConfigureReceiveTask(u32 task_id, size_t size) { /* Check pre-conditions. */ AMS_ASSERT(task_id < MaxTaskCount); AMS_ASSERT(m_valid[task_id]); /* Set the task type. */ m_tasks[task_id].type = TaskType_Receive; /* Set the task size. */ m_tasks[task_id].size = size; } void TaskManager::ConfigureSendTask(u32 task_id) { /* Check pre-conditions. */ AMS_ASSERT(task_id < MaxTaskCount); AMS_ASSERT(m_valid[task_id]); /* Set the task type. */ m_tasks[task_id].type = TaskType_Send; } void TaskManager::NotifyDisconnect(impl::ChannelInternalType channel) { for (auto i = 0; i < MaxTaskCount; ++i) { if (m_valid[i] && m_tasks[i].channel == channel) { this->CompleteTask(i, EventTrigger_Disconnect); } } } void TaskManager::NotifyReceiveData(impl::ChannelInternalType channel, size_t size) { for (auto i = 0; i < MaxTaskCount; ++i) { if (m_valid[i] && m_tasks[i].channel == channel && m_tasks[i].type == TaskType_Receive && m_tasks[i].size <= size) { this->CompleteTask(i, EventTrigger_ReceiveData); } } } void TaskManager::NotifySendReady() { for (auto i = 0; i < MaxTaskCount; ++i) { if (m_valid[i] && m_tasks[i].type == TaskType_Send) { this->CompleteTask(i, EventTrigger_SendReady); } } } void TaskManager::NotifySendBufferEmpty(impl::ChannelInternalType channel) { for (auto i = 0; i < MaxTaskCount; ++i) { if (m_valid[i] && m_tasks[i].channel == channel && m_tasks[i].type == TaskType_Flush) { this->CompleteTask(i, EventTrigger_SendBufferEmpty); } } } void TaskManager::NotifyConnectReady() { for (auto i = 0; i < MaxTaskCount; ++i) { if (m_valid[i] && m_tasks[i].type == TaskType_Connect) { this->CompleteTask(i, EventTrigger_ConnectReady); } } } void TaskManager::CompleteTask(int index, EventTrigger trigger) { /* Check pre-conditions. */ AMS_ASSERT(0 <= index && index < MaxTaskCount); AMS_ASSERT(m_valid[index]); /* Complete the task. */ if (!m_tasks[index].has_event_trigger) { m_tasks[index].has_event_trigger = true; m_tasks[index].event_trigger = trigger; os::SignalEvent(std::addressof(m_tasks[index].event)); } } }
5,470
C++
.cpp
136
31.992647
128
0.594533
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,324
htclow_mux_global_send_buffer.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htclow/mux/htclow_mux_global_send_buffer.cpp
/* * Copyright (c) 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 "htclow_mux_global_send_buffer.hpp" #include "../htclow_packet_factory.hpp" namespace ams::htclow::mux { Packet *GlobalSendBuffer::GetNextPacket() { if (!m_packet_list.empty()) { return std::addressof(m_packet_list.front()); } else { return nullptr; } } Result GlobalSendBuffer::AddPacket(std::unique_ptr<Packet, PacketDeleter> ptr) { /* Global send buffer only supports adding error packets. */ R_UNLESS(ptr->GetHeader()->packet_type == PacketType_Error, htclow::ResultInvalidArgument()); /* Check if we already have an error packet for the channel. */ for (const auto &packet : m_packet_list) { R_SUCCEED_IF(packet.GetHeader()->channel == ptr->GetHeader()->channel); } /* We don't, so push back a new one. */ m_packet_list.push_back(*(ptr.release())); R_SUCCEED(); } void GlobalSendBuffer::RemovePacket() { auto *packet = std::addressof(m_packet_list.front()); m_packet_list.pop_front(); m_packet_factory->Delete(packet); } }
1,781
C++
.cpp
43
35.883721
101
0.672643
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,325
util_ini.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/util/util_ini.cpp
/* * Copyright (c) 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 "ini.h" namespace ams::util::ini { /* Ensure that types are the same for Handler vs ini_handler. */ static_assert(std::is_same<Handler, ::ini_handler>::value, "Bad ini::Handler definition!"); namespace { struct FileContext { fs::FileHandle file; s64 offset; s64 num_left; explicit FileContext(fs::FileHandle f) : file(f), offset(0) { R_ABORT_UNLESS(fs::GetFileSize(std::addressof(this->num_left), this->file)); } }; struct IFileContext { fs::fsa::IFile *file; s64 offset; s64 num_left; explicit IFileContext(fs::fsa::IFile *f) : file(f), offset(0) { R_ABORT_UNLESS(file->GetSize(std::addressof(this->num_left))); } }; char *ini_reader_file_handle(char *str, int num, void *stream) { FileContext *ctx = static_cast<FileContext *>(stream); if (ctx->num_left == 0 || num < 2) { return nullptr; } /* Read as many bytes as we can. */ s64 cur_read = std::min<s64>(num - 1, ctx->num_left); R_ABORT_UNLESS(fs::ReadFile(ctx->file, ctx->offset, str, cur_read, fs::ReadOption())); /* Only "read" up to the first \n. */ size_t offset = cur_read; for (auto i = 0; i < cur_read; i++) { if (str[i] == '\n') { offset = i + 1; break; } } /* Ensure null termination. */ str[offset] = '\0'; /* Update context. */ ctx->offset += offset; ctx->num_left -= offset; return str; } char *ini_reader_ifile(char *str, int num, void *stream) { IFileContext *ctx = static_cast<IFileContext *>(stream); if (ctx->num_left == 0 || num < 2) { return nullptr; } /* Read as many bytes as we can. */ s64 cur_read = std::min<s64>(num - 1, ctx->num_left); size_t read; R_ABORT_UNLESS(ctx->file->Read(std::addressof(read), ctx->offset, str, cur_read, fs::ReadOption())); AMS_ABORT_UNLESS(static_cast<s64>(read) == cur_read); /* Only "read" up to the first \n. */ size_t offset = cur_read; for (auto i = 0; i < cur_read; i++) { if (str[i] == '\n') { offset = i + 1; break; } } /* Ensure null termination. */ str[offset] = '\0'; /* Update context. */ ctx->offset += offset; ctx->num_left -= offset; return str; } } /* Utilities for dealing with INI file configuration. */ int ParseString(const char *ini_str, void *user_ctx, Handler h) { return ini_parse_string(ini_str, h, user_ctx); } int ParseFile(fs::FileHandle file, void *user_ctx, Handler h) { FileContext ctx(file); return ini_parse_stream(ini_reader_file_handle, std::addressof(ctx), h, user_ctx); } int ParseFile(fs::fsa::IFile *file, void *user_ctx, Handler h) { IFileContext ctx(file); return ini_parse_stream(ini_reader_ifile, std::addressof(ctx), h, user_ctx); } }
4,073
C++
.cpp
99
30.808081
112
0.544073
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,326
util_uuid_api.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/util/util_uuid_api.cpp
/* * Copyright (c) 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::util { namespace { struct UuidImpl { util::BitPack32 data[4]; using TimeLow = util::BitPack32::Field<0, BITSIZEOF(u32), u32>; using TimeMid = util::BitPack32::Field<0, BITSIZEOF(u16), u16>; using TimeHighAndVersion = util::BitPack32::Field<TimeMid::Next, BITSIZEOF(u16), u16>; using Version = util::BitPack32::Field<TimeMid::Next + 12, 4, u16>; static_assert(TimeHighAndVersion::Next == Version::Next); using ClockSeqHiAndReserved = util::BitPack32::Field<0, BITSIZEOF(u8), u8>; using Reserved = util::BitPack32::Field<6, 2, u8>; using ClockSeqLow = util::BitPack32::Field<ClockSeqHiAndReserved::Next, BITSIZEOF(u8), u8>; using NodeLow = util::BitPack32::Field<ClockSeqLow::Next, BITSIZEOF(u16), u16>; static_assert(ClockSeqHiAndReserved::Next == Reserved::Next); using NodeHigh = util::BitPack32::Field<0, BITSIZEOF(u32), u32>; inline Uuid Convert() const { /* Convert the fields from native endian to big endian. */ util::BitPack32 converted[4] = {util::BitPack32{0}, util::BitPack32{0}, util::BitPack32{0}, util::BitPack32{0}}; converted[0].Set<TimeLow>(util::ConvertToBigEndian(this->data[0].Get<TimeLow>())); converted[1].Set<TimeMid>(util::ConvertToBigEndian(this->data[1].Get<TimeMid>())); converted[1].Set<TimeHighAndVersion>(util::ConvertToBigEndian(this->data[1].Get<TimeHighAndVersion>())); converted[2].Set<ClockSeqHiAndReserved>(util::ConvertToBigEndian(this->data[2].Get<ClockSeqHiAndReserved>())); converted[2].Set<ClockSeqLow>(util::ConvertToBigEndian(this->data[2].Get<ClockSeqLow>())); u64 node_lo = static_cast<u64>(this->data[2].Get<NodeLow>()); u64 node_hi = static_cast<u64>(this->data[3].Get<NodeHigh>()); u64 node = util::ConvertToBigEndian48(static_cast<u64>((node_hi << BITSIZEOF(u16)) | (node_lo))); constexpr u64 NodeLoMask = (UINT64_C(1) << BITSIZEOF(u16)) - 1u; constexpr u64 NodeHiMask = (UINT64_C(1) << BITSIZEOF(u32)) - 1u; converted[2].Set<NodeLow>(static_cast<u16>(node & NodeLoMask)); converted[3].Set<NodeHigh>(static_cast<u32>((node >> BITSIZEOF(u16)) & NodeHiMask)); Uuid uuid; std::memcpy(uuid.data, converted, sizeof(uuid.data)); return uuid; } }; static_assert(sizeof(UuidImpl) == sizeof(Uuid)); ALWAYS_INLINE Uuid GenerateUuidVersion4() { constexpr u16 Version = 0x4; constexpr u8 Reserved = 0x1; /* Generate a random uuid. */ UuidImpl uuid = {util::BitPack32{0}, util::BitPack32{0}, util::BitPack32{0}, util::BitPack32{0}}; os::GenerateRandomBytes(uuid.data, sizeof(uuid.data)); /* Set version and reserved. */ uuid.data[1].Set<UuidImpl::Version>(Version); uuid.data[2].Set<UuidImpl::Reserved>(Reserved); /* Return the uuid. */ return uuid.Convert(); } } Uuid GenerateUuid() { return GenerateUuidVersion4(); } Uuid GenerateUuidVersion5(const void *sha1_hash) { constexpr u16 Version = 0x5; constexpr u8 Reserved = 0x1; /* Generate a uuid from a SHA1 hash. */ UuidImpl uuid = {util::BitPack32{0}, util::BitPack32{0}, util::BitPack32{0}, util::BitPack32{0}}; std::memcpy(uuid.data, sha1_hash, sizeof(uuid.data)); /* Set version and reserved. */ uuid.data[1].Set<UuidImpl::Version>(Version); uuid.data[2].Set<UuidImpl::Reserved>(Reserved); /* Return the uuid. */ return uuid.Convert(); } }
4,844
C++
.cpp
81
49.469136
128
0.587154
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,327
util_compression.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/util/util_compression.cpp
/* * Copyright (c) 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 "lz4.h" namespace ams::util { /* Compression utilities. */ int CompressLZ4(void *dst, size_t dst_size, const void *src, size_t src_size) { /* Size checks. */ AMS_ABORT_UNLESS(dst_size <= std::numeric_limits<int>::max()); AMS_ABORT_UNLESS(src_size <= std::numeric_limits<int>::max()); /* This is just a thin wrapper around LZ4. */ return LZ4_compress_default(reinterpret_cast<const char *>(src), reinterpret_cast<char *>(dst), static_cast<int>(src_size), static_cast<int>(dst_size)); } /* Decompression utilities. */ int DecompressLZ4(void *dst, size_t dst_size, const void *src, size_t src_size) { /* Size checks. */ AMS_ABORT_UNLESS(dst_size <= std::numeric_limits<int>::max()); AMS_ABORT_UNLESS(src_size <= std::numeric_limits<int>::max()); /* This is just a thin wrapper around LZ4. */ return LZ4_decompress_safe(reinterpret_cast<const char *>(src), reinterpret_cast<char *>(dst), static_cast<int>(src_size), static_cast<int>(dst_size)); } }
1,726
C++
.cpp
35
44.8
160
0.685053
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,328
psc_pm_module.os.horizon.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/psc/psc_pm_module.os.horizon.cpp
/* * Copyright (c) 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 "psc_remote_pm_module.hpp" namespace ams::psc { /* TODO: Nintendo uses sf::ShimLobraryObjectHolder here, we should similarly consider switching. */ namespace { struct PscRemotePmModuleTag; using RemoteAllocator = ams::sf::ExpHeapStaticAllocator<2_KB, PscRemotePmModuleTag>; using RemoteObjectFactory = ams::sf::ObjectFactory<typename RemoteAllocator::Policy>; class StaticAllocatorInitializer { public: StaticAllocatorInitializer() { RemoteAllocator::Initialize(lmem::CreateOption_None); } } g_static_allocator_initializer; } PmModule::PmModule() : m_intf(nullptr), m_initialized(false), m_module_id(PmModuleId_Reserved0), m_reserved(0) { /* ... */ } PmModule::~PmModule() { if (m_initialized) { m_intf = nullptr; os::DestroySystemEvent(m_system_event.GetBase()); } } Result PmModule::Initialize(const PmModuleId mid, const PmModuleId *dependencies, u32 dependency_count, os::EventClearMode clear_mode) { R_UNLESS(!m_initialized, psc::ResultAlreadyInitialized()); static_assert(sizeof(*dependencies) == sizeof(u32)); ::PscPmModule module; R_TRY(::pscmGetPmModule(std::addressof(module), static_cast<::PscPmModuleId>(mid), reinterpret_cast<const u32 *>(dependencies), dependency_count, clear_mode == os::EventClearMode_AutoClear)); m_intf = RemoteObjectFactory::CreateSharedEmplaced<psc::sf::IPmModule, RemotePmModule>(module); m_system_event.AttachReadableHandle(module.event.revent, false, clear_mode); m_initialized = true; R_SUCCEED(); } Result PmModule::Finalize() { R_UNLESS(m_initialized, psc::ResultNotInitialized()); R_TRY(m_intf->Finalize()); m_intf = nullptr; os::DestroySystemEvent(m_system_event.GetBase()); m_initialized = false; R_SUCCEED(); } Result PmModule::GetRequest(PmState *out_state, PmFlagSet *out_flags) { R_UNLESS(m_initialized, psc::ResultNotInitialized()); R_RETURN(m_intf->GetRequest(out_state, out_flags)); } Result PmModule::Acknowledge(PmState state, Result res) { R_ABORT_UNLESS(res); R_UNLESS(m_initialized, psc::ResultNotInitialized()); if (hos::GetVersion() >= hos::Version_5_1_0) { R_RETURN(m_intf->AcknowledgeEx(state)); } else { R_RETURN(m_intf->Acknowledge()); } } os::SystemEvent *PmModule::GetEventPointer() { return std::addressof(m_system_event); } }
3,295
C++
.cpp
72
38.666667
199
0.673737
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,329
htc_htcmisc_impl.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htc/server/htc_htcmisc_impl.cpp
/* * Copyright (c) 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 "htc_htcmisc_impl.hpp" namespace ams::htc::server { namespace { alignas(os::ThreadStackAlignment) u8 g_client_thread_stack[os::MemoryPageSize]; alignas(os::ThreadStackAlignment) u8 g_server_thread_stack[os::MemoryPageSize]; } HtcmiscImpl::HtcmiscImpl(htclow::HtclowManager *htclow_manager) : m_htclow_driver(htclow_manager, htclow::ModuleId::Htcmisc), m_driver_manager(std::addressof(m_htclow_driver)), m_rpc_client(std::addressof(m_htclow_driver), HtcmiscClientChannelId), m_rpc_server(std::addressof(m_htclow_driver), HtcmiscServerChannelId), m_cancel_event(os::EventClearMode_ManualClear), m_cancelled(false), m_connection_event(os::EventClearMode_ManualClear), m_client_connected(false), m_server_connected(false), m_connected(false), m_connection_mutex() { /* Create the client thread. */ R_ABORT_UNLESS(os::CreateThread(std::addressof(m_client_thread), ClientThreadEntry, this, g_client_thread_stack, sizeof(g_client_thread_stack), AMS_GET_SYSTEM_THREAD_PRIORITY(htc, Htcmisc))); /* Set the client thread name. */ os::SetThreadNamePointer(std::addressof(m_client_thread), AMS_GET_SYSTEM_THREAD_NAME(htc, Htcmisc)); /* Start the client thread. */ os::StartThread(std::addressof(m_client_thread)); /* Create the server thread. */ R_ABORT_UNLESS(os::CreateThread(std::addressof(m_server_thread), ServerThreadEntry, this, g_server_thread_stack, sizeof(g_server_thread_stack), AMS_GET_SYSTEM_THREAD_PRIORITY(htc, Htcmisc))); /* Set the server thread name. */ os::SetThreadNamePointer(std::addressof(m_server_thread), AMS_GET_SYSTEM_THREAD_NAME(htc, Htcmisc)); /* Start the server thread. */ os::StartThread(std::addressof(m_server_thread)); } HtcmiscImpl::~HtcmiscImpl() { /* Cancel ourselves. */ this->Cancel(); /* Wait for our threads to be done, and destroy them. */ os::WaitThread(std::addressof(m_client_thread)); os::DestroyThread(std::addressof(m_client_thread)); os::WaitThread(std::addressof(m_server_thread)); os::DestroyThread(std::addressof(m_server_thread)); } void HtcmiscImpl::Cancel() { /* Set ourselves as cancelled. */ m_cancelled = true; /* Signal our cancel event. */ m_cancel_event.Signal(); } void HtcmiscImpl::WaitTask(u32 task_id) { return m_rpc_client.Wait(task_id); } Result HtcmiscImpl::GetEnvironmentVariable(size_t *out_size, char *dst, size_t dst_size, const char *name, size_t name_size) { /* Begin the task. */ u32 task_id{}; R_TRY(m_rpc_client.Begin<rpc::GetEnvironmentVariableTask>(std::addressof(task_id), name, name_size)); /* Wait for the task to complete. */ this->WaitTask(task_id); /* Finish the task. */ R_TRY(m_rpc_client.End<rpc::GetEnvironmentVariableTask>(task_id, out_size, dst, dst_size)); R_SUCCEED(); } Result HtcmiscImpl::GetEnvironmentVariableLength(size_t *out_size, const char *name, size_t name_size) { /* Begin the task. */ u32 task_id{}; R_TRY(m_rpc_client.Begin<rpc::GetEnvironmentVariableLengthTask>(std::addressof(task_id), name, name_size)); /* Wait for the task to complete. */ this->WaitTask(task_id); /* Finish the task. */ R_TRY(m_rpc_client.End<rpc::GetEnvironmentVariableLengthTask>(task_id, out_size)); R_SUCCEED(); } Result HtcmiscImpl::RunOnHostBegin(u32 *out_task_id, os::NativeHandle *out_event, const char *args, size_t args_size) { /* Begin the task. */ u32 task_id{}; R_TRY(m_rpc_client.Begin<rpc::RunOnHostTask>(std::addressof(task_id), args, args_size)); /* Detach the task. */ *out_task_id = task_id; *out_event = m_rpc_client.DetachReadableHandle(task_id); R_SUCCEED(); } Result HtcmiscImpl::RunOnHostEnd(s32 *out_result, u32 task_id) { /* Finish the task. */ s32 res; R_TRY(m_rpc_client.End<rpc::RunOnHostTask>(task_id, std::addressof(res))); /* Set output. */ *out_result = res; R_SUCCEED(); } void HtcmiscImpl::ClientThread() { /* Loop so long as we're not cancelled. */ while (!m_cancelled) { /* Open the rpc client. */ m_rpc_client.Open(); /* Ensure we close, if something goes wrong. */ auto client_guard = SCOPE_GUARD { m_rpc_client.Close(); }; /* Wait for the rpc client. */ if (m_rpc_client.WaitAny(htclow::ChannelState_Connectable, m_cancel_event.GetBase()) != 0) { break; } /* Start the rpc client. */ if (R_FAILED(m_rpc_client.Start())) { break; } /* We're connected! */ this->SetClientConnectionEvent(true); client_guard.Cancel(); /* We're connected, so we want to cleanup when we're done. */ ON_SCOPE_EXIT { m_rpc_client.Close(); m_rpc_client.Cancel(); m_rpc_client.Wait(); this->SetClientConnectionEvent(false); }; /* Wait to become disconnected. */ if (m_rpc_client.WaitAny(htclow::ChannelState_Disconnected, m_cancel_event.GetBase()) != 0) { break; } } } void HtcmiscImpl::ServerThread() { /* Loop so long as we're not cancelled. */ while (!m_cancelled) { /* Open the rpc server. */ m_rpc_server.Open(); /* Ensure we close, if something goes wrong. */ auto server_guard = SCOPE_GUARD { m_rpc_server.Close(); }; /* Wait for the rpc server. */ if (m_rpc_server.WaitAny(htclow::ChannelState_Connectable, m_cancel_event.GetBase()) != 0) { break; } /* Start the rpc server. */ if (R_FAILED(m_rpc_server.Start())) { break; } /* We're connected! */ this->SetServerConnectionEvent(true); server_guard.Cancel(); /* We're connected, so we want to cleanup when we're done. */ ON_SCOPE_EXIT { m_rpc_server.Close(); m_rpc_server.Cancel(); m_rpc_server.Wait(); this->SetServerConnectionEvent(false); }; /* Wait to become disconnected. */ if (m_rpc_server.WaitAny(htclow::ChannelState_Disconnected, m_cancel_event.GetBase()) != 0) { break; } } } void HtcmiscImpl::SetClientConnectionEvent(bool en) { /* Lock ourselves. */ std::scoped_lock lk(m_connection_mutex); /* Update our state. */ if (m_client_connected != en) { m_client_connected = en; this->UpdateConnectionEvent(); } } void HtcmiscImpl::SetServerConnectionEvent(bool en) { /* Lock ourselves. */ std::scoped_lock lk(m_connection_mutex); /* Update our state. */ if (m_server_connected != en) { m_server_connected = en; this->UpdateConnectionEvent(); } } void HtcmiscImpl::UpdateConnectionEvent() { /* Determine if we're connected. */ const bool connected = m_client_connected && m_server_connected; /* Update our state. */ if (m_connected != connected) { m_connected = connected; m_connection_event.Signal(); } } os::EventType *HtcmiscImpl::GetConnectionEvent() const { return m_connection_event.GetBase(); } bool HtcmiscImpl::IsConnected() const { /* Lock ourselves. */ std::scoped_lock lk(m_connection_mutex); return m_connected; } }
8,734
C++
.cpp
201
34
199
0.600472
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,330
htc_htcmisc_hipc_server.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htc/server/htc_htcmisc_hipc_server.cpp
/* * Copyright (c) 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 "htc_htc_service_object.hpp" #include "htc_htcmisc_manager.hpp" namespace ams::htc::server { namespace { static constexpr inline size_t NumServers = 1; static constexpr inline size_t MaxSessions = 30; static constexpr inline sm::ServiceName ServiceName = sm::ServiceName::Encode("htc"); using ServerOptions = sf::hipc::DefaultServerManagerOptions; using ServerManager = sf::hipc::ServerManager<NumServers, ServerOptions, MaxSessions>; constinit util::TypedStorage<ServerManager> g_server_manager_storage = {}; constinit ServerManager *g_server_manager = nullptr; constinit HtcmiscImpl *g_misc_impl = nullptr; } void InitializeHtcmiscServer(htclow::HtclowManager *htclow_manager) { /* Check that we haven't already initialized. */ AMS_ASSERT(g_server_manager == nullptr); /* Create/Set the server manager pointer. */ g_server_manager = util::ConstructAt(g_server_manager_storage); /* Create and register the htc manager object. */ HtcServiceObject *service_object; R_ABORT_UNLESS(g_server_manager->RegisterObjectForServer(CreateHtcmiscManager(std::addressof(service_object), htclow_manager), ServiceName, MaxSessions)); /* Set the misc impl. */ g_misc_impl = service_object->GetHtcmiscImpl(); /* Start the server. */ g_server_manager->ResumeProcessing(); } void FinalizeHtcmiscServer() { /* Check that we've already initialized. */ AMS_ASSERT(g_server_manager != nullptr); /* Clear the misc impl. */ g_misc_impl = nullptr; /* Clear and destroy. */ std::destroy_at(g_server_manager); g_server_manager = nullptr; } void LoopHtcmiscServer() { /* Check that we've already initialized. */ AMS_ASSERT(g_server_manager != nullptr); g_server_manager->LoopProcess(); } void RequestStopHtcmiscServer() { /* Check that we've already initialized. */ AMS_ASSERT(g_server_manager != nullptr); g_server_manager->RequestStopProcessing(); } HtcmiscImpl *GetHtcmiscImpl() { return g_misc_impl; } }
2,903
C++
.cpp
65
38.323077
162
0.683351
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,331
htc_observer.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htc/server/htc_observer.cpp
/* * Copyright (c) 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 "htc_observer.hpp" #include "../../htcs/impl/htcs_manager.hpp" namespace ams::htc::server { Observer::Observer(const HtcmiscImpl &misc_impl) : m_connect_event(os::EventClearMode_ManualClear, true), m_disconnect_event(os::EventClearMode_ManualClear, true), m_stop_event(os::EventClearMode_ManualClear), m_misc_impl(misc_impl), m_thread_running(false), m_stopped(false), m_connected(false), m_is_service_available(false) { /* Initialize htcs library. */ htcs::impl::HtcsManagerHolder::AddReference(); /* Update our event state. */ this->UpdateEvent(); /* Start. */ R_ABORT_UNLESS(this->Start()); } Result Observer::Start() { /* Check that we're not already running. */ AMS_ASSERT(!m_thread_running); /* Create the thread. */ R_TRY(os::CreateThread(std::addressof(m_observer_thread), ObserverThreadEntry, this, m_observer_thread_stack, sizeof(m_observer_thread_stack), AMS_GET_SYSTEM_THREAD_PRIORITY(htc, HtcObserver))); /* Set the thread name pointer. */ os::SetThreadNamePointer(std::addressof(m_observer_thread), AMS_GET_SYSTEM_THREAD_NAME(htc, HtcObserver)); /* Mark our thread as running. */ m_thread_running = true; m_stopped = false; /* Start our thread. */ os::StartThread(std::addressof(m_observer_thread)); R_SUCCEED(); } void Observer::UpdateEvent() { if (m_connected && m_is_service_available) { m_disconnect_event.Clear(); m_connect_event.Signal(); } else { m_connect_event.Clear(); m_disconnect_event.Signal(); } } void Observer::ObserverThreadBody() { /* When we're done observing, clear our state. */ ON_SCOPE_EXIT { m_connected = false; m_is_service_available = false; this->UpdateEvent(); }; /* Get the htcs manager. */ auto * const htcs_manager = htcs::impl::HtcsManagerHolder::GetHtcsManager(); /* Get the events we're waiting on. */ os::EventType * const stop_event = m_stop_event.GetBase(); os::EventType * const conn_event = m_misc_impl.GetConnectionEvent(); os::EventType * const htcs_event = htcs_manager->GetServiceAvailabilityEvent(); /* Loop until we're asked to stop. */ while (!m_stopped) { /* Wait for an event to be signaled. */ const auto index = os::WaitAny(stop_event, conn_event /*, htcs_event */); switch (index) { case 0: /* Stop event, just break out of the loop. */ os::ClearEvent(stop_event); break; case 1: /* Connection event, update our connection status. */ os::ClearEvent(conn_event); m_connected = m_misc_impl.IsConnected(); break; case 2: /* Htcs event, update our service status. */ os::ClearEvent(htcs_event); m_is_service_available = htcs_manager->IsServiceAvailable(); break; AMS_UNREACHABLE_DEFAULT_CASE(); } /* If the event was our stop event, break. */ if (index == 0) { break; } /* Update event status. */ this->UpdateEvent(); } } }
4,264
C++
.cpp
102
31.960784
202
0.584218
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,332
htc_htc_service_object.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htc/server/htc_htc_service_object.cpp
/* * Copyright (c) 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 "htc_htc_service_object.hpp" #include "../../htcfs/htcfs_working_directory.hpp" namespace ams::htc::server { HtcServiceObject::HtcServiceObject(htclow::HtclowManager *htclow_manager) : m_set(), m_misc_impl(htclow_manager), m_observer(m_misc_impl), m_mutex(){ /* Initialize our set. */ m_set.Initialize(MaxSetElements, m_set_memory, sizeof(m_set_memory)); } HtcmiscImpl *HtcServiceObject::GetHtcmiscImpl() { return std::addressof(m_misc_impl); } Result HtcServiceObject::GetEnvironmentVariable(sf::Out<s32> out_size, const sf::OutBuffer &out, const sf::InBuffer &name) { /* Get the variable. */ size_t var_size = std::numeric_limits<size_t>::max(); R_TRY(m_misc_impl.GetEnvironmentVariable(std::addressof(var_size), reinterpret_cast<char *>(out.GetPointer()), out.GetSize(), reinterpret_cast<const char *>(name.GetPointer()), name.GetSize())); /* Check the output size. */ R_UNLESS(util::IsIntValueRepresentable<s32>(var_size), htc::ResultUnknown()); /* Set the output size. */ *out_size = static_cast<s32>(var_size); R_SUCCEED(); } Result HtcServiceObject::GetEnvironmentVariableLength(sf::Out<s32> out_size, const sf::InBuffer &name) { /* Get the variable. */ size_t var_size = std::numeric_limits<size_t>::max(); R_TRY(m_misc_impl.GetEnvironmentVariableLength(std::addressof(var_size), reinterpret_cast<const char *>(name.GetPointer()), name.GetSize())); /* Check the output size. */ R_UNLESS(util::IsIntValueRepresentable<s32>(var_size), htc::ResultUnknown()); /* Set the output size. */ *out_size = static_cast<s32>(var_size); R_SUCCEED(); } Result HtcServiceObject::GetHostConnectionEvent(sf::OutCopyHandle out) { /* Set the output handle. */ out.SetValue(m_observer.GetConnectEvent()->GetReadableHandle(), false); R_SUCCEED(); } Result HtcServiceObject::GetHostDisconnectionEvent(sf::OutCopyHandle out) { /* Set the output handle. */ out.SetValue(m_observer.GetDisconnectEvent()->GetReadableHandle(), false); R_SUCCEED(); } Result HtcServiceObject::GetHostConnectionEventForSystem(sf::OutCopyHandle out) { /* NOTE: Nintendo presumably reserved this command in case they need it, but they haven't implemented it yet. */ AMS_UNUSED(out); AMS_ABORT("HostEventForSystem not implemented."); } Result HtcServiceObject::GetHostDisconnectionEventForSystem(sf::OutCopyHandle out) { /* NOTE: Nintendo presumably reserved this command in case they need it, but they haven't implemented it yet. */ AMS_UNUSED(out); AMS_ABORT("HostEventForSystem not implemented."); } Result HtcServiceObject::GetWorkingDirectoryPath(const sf::OutBuffer &out, s32 max_len) { R_RETURN(htcfs::GetWorkingDirectory(reinterpret_cast<char *>(out.GetPointer()), max_len)); } Result HtcServiceObject::GetWorkingDirectoryPathSize(sf::Out<s32> out_size) { R_RETURN(htcfs::GetWorkingDirectorySize(out_size.GetPointer())); } Result HtcServiceObject::RunOnHostStart(sf::Out<u32> out_id, sf::OutCopyHandle out, const sf::InBuffer &args) { /* Begin the run on host task. */ os::NativeHandle event_handle; R_TRY(m_misc_impl.RunOnHostBegin(out_id.GetPointer(), std::addressof(event_handle), reinterpret_cast<const char *>(args.GetPointer()), args.GetSize())); /* Add the task id to our set. */ { std::scoped_lock lk(m_mutex); m_set.insert(*out_id); } /* Set the output event. */ out.SetValue(event_handle, true); R_SUCCEED(); } Result HtcServiceObject::RunOnHostResults(sf::Out<s32> out_result, u32 id) { /* Verify that we have the task. */ { std::scoped_lock lk(m_mutex); R_UNLESS(m_set.erase(id), htc::ResultInvalidTaskId()); } /* Finish the run on host task. */ R_RETURN(m_misc_impl.RunOnHostEnd(out_result.GetPointer(), id)); } Result HtcServiceObject::GetBridgeIpAddress(const sf::OutBuffer &out) { /* NOTE: Atmosphere does not support HostBridge, and it's unclear if we ever will. */ AMS_UNUSED(out); AMS_ABORT("HostBridge currently not supported."); } Result HtcServiceObject::GetBridgePort(const sf::OutBuffer &out) { /* NOTE: Atmosphere does not support HostBridge, and it's unclear if we ever will. */ AMS_UNUSED(out); AMS_ABORT("HostBridge currently not supported."); } Result HtcServiceObject::SetCradleAttached(bool attached) { /* NOTE: Atmosphere does not support HostBridge, and it's unclear if we ever will. */ AMS_UNUSED(attached); AMS_ABORT("HostBridge currently not supported."); } Result HtcServiceObject::GetBridgeSubnetMask(const sf::OutBuffer &out) { /* NOTE: Atmosphere does not support HostBridge, and it's unclear if we ever will. */ AMS_UNUSED(out); AMS_ABORT("HostBridge currently not supported."); } Result HtcServiceObject::GetBridgeMacAddress(const sf::OutBuffer &out) { /* NOTE: Atmosphere does not support HostBridge, and it's unclear if we ever will. */ AMS_UNUSED(out); AMS_ABORT("HostBridge currently not supported."); } Result HtcServiceObject::SetBridgeIpAddress(const sf::InBuffer &arg) { /* NOTE: Atmosphere does not support HostBridge, and it's unclear if we ever will. */ AMS_UNUSED(arg); AMS_ABORT("HostBridge currently not supported."); } Result HtcServiceObject::SetBridgeSubnetMask(const sf::InBuffer &arg) { /* NOTE: Atmosphere does not support HostBridge, and it's unclear if we ever will. */ AMS_UNUSED(arg); AMS_ABORT("HostBridge currently not supported."); } Result HtcServiceObject::SetBridgePort(const sf::InBuffer &arg) { /* NOTE: Atmosphere does not support HostBridge, and it's unclear if we ever will. */ AMS_UNUSED(arg); AMS_ABORT("HostBridge currently not supported."); } }
6,870
C++
.cpp
135
43.814815
202
0.67651
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,333
htc_htcmisc_manager.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htc/server/htc_htcmisc_manager.cpp
/* * Copyright (c) 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 "htc_htcmisc_manager.hpp" namespace ams::htc::server { namespace { mem::StandardAllocator g_allocator; sf::StandardAllocatorMemoryResource g_sf_resource(std::addressof(g_allocator)); alignas(os::MemoryPageSize) constinit u8 g_heap[util::AlignUp(sizeof(HtcServiceObject), os::MemoryPageSize) + 12_KB]; class StaticAllocatorInitializer { public: StaticAllocatorInitializer() { g_allocator.Initialize(g_heap, sizeof(g_heap)); } } g_static_allocator_initializer; using ObjectFactory = sf::ObjectFactory<sf::MemoryResourceAllocationPolicy>; } sf::SharedPointer<tma::IHtcManager> CreateHtcmiscManager(HtcServiceObject **out, htclow::HtclowManager *htclow_manager) { auto obj = ObjectFactory::CreateSharedEmplaced<tma::IHtcManager, HtcServiceObject>(std::addressof(g_sf_resource), htclow_manager); *out = std::addressof(obj.GetImpl()); return obj; } }
1,679
C++
.cpp
36
40.75
138
0.714636
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,334
htc_power_state_control.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htc/server/htc_power_state_control.cpp
/* * Copyright (c) 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 "../../htclow/htclow_manager.hpp" namespace ams::htc::server { namespace { constinit htclow::HtclowManager *g_htclow_manager = nullptr; constexpr const psc::PmModuleId PscModuleDependencies[] = { psc::PmModuleId_Pcie, psc::PmModuleId_Usb }; psc::PmModule g_pm_module; constinit bool g_is_asleep = false; constinit bool g_is_suspended = false; } void InitializePowerStateMonitor(htclow::impl::DriverType driver_type, htclow::HtclowManager *htclow_manager) { AMS_UNUSED(driver_type); /* Set the htclow manager. */ g_htclow_manager = htclow_manager; /* Initialize pm module. */ R_ABORT_UNLESS(g_pm_module.Initialize(psc::PmModuleId_TmaHostIo, PscModuleDependencies, util::size(PscModuleDependencies), os::EventClearMode_AutoClear)); /* We're neither asleep nor suspended. */ g_is_asleep = false; g_is_suspended = false; } void FinalizePowerStateMonitor() { R_ABORT_UNLESS(g_pm_module.Finalize()); } void LoopMonitorPowerState() { /* Get the psc module's event pointer. */ auto *event = g_pm_module.GetEventPointer(); while (true) { /* Wait for a new power state event. */ event->Wait(); /* Get the power state. */ psc::PmState pm_state; psc::PmFlagSet pm_flags; R_ABORT_UNLESS(g_pm_module.GetRequest(std::addressof(pm_state), std::addressof(pm_flags))); /* Update sleeping state. */ switch (pm_state) { case psc::PmState_FullAwake: if (g_is_asleep) { g_htclow_manager->NotifyAwake(); g_is_asleep = false; } break; case psc::PmState_MinimumAwake: case psc::PmState_SleepReady: case psc::PmState_EssentialServicesSleepReady: case psc::PmState_EssentialServicesAwake: if (!g_is_asleep) { g_htclow_manager->NotifyAsleep(); g_is_asleep = true; } break; default: break; } /* Update suspend state. */ switch (pm_state) { case psc::PmState_FullAwake: case psc::PmState_MinimumAwake: if (g_is_suspended) { g_htclow_manager->Resume(); g_is_suspended = false; } break; case psc::PmState_SleepReady: case psc::PmState_EssentialServicesSleepReady: case psc::PmState_EssentialServicesAwake: if (!g_is_suspended) { g_htclow_manager->Suspend(); g_is_suspended = true; } break; default: break; } /* Acknowledge the pm request. */ R_ABORT_UNLESS(g_pm_module.Acknowledge(pm_state, ResultSuccess())); } } }
3,890
C++
.cpp
93
29.655914
162
0.559259
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,335
htc_htclow_driver.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htc/server/driver/htc_htclow_driver.cpp
/* * Copyright (c) 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 "htc_htclow_driver.hpp" namespace ams::htc::server::driver { namespace { constexpr ALWAYS_INLINE htclow::impl::ChannelInternalType GetHtclowChannel(htclow::ChannelId channel_id, htclow::ModuleId module_id) { return { .channel_id = channel_id, .reserved = 0, .module_id = module_id, }; } } void HtclowDriver::WaitTask(u32 task_id) { os::WaitEvent(m_manager->GetTaskEvent(task_id)); } void HtclowDriver::SetDisconnectionEmulationEnabled(bool en) { /* NOTE: Nintendo ignores the input, here. */ AMS_UNUSED(en); m_disconnection_emulation_enabled = false; } Result HtclowDriver::Open(htclow::ChannelId channel) { /* Check the channel/module combination. */ if (m_module_id == htclow::ModuleId::Htcmisc) { AMS_ABORT_UNLESS(channel == HtcmiscClientChannelId ); } else if (m_module_id == htclow::ModuleId::Htcs) { AMS_ABORT_UNLESS(channel == 0); } else { AMS_ABORT("Unsupported channel"); } R_RETURN(this->Open(channel, m_default_receive_buffer, sizeof(m_default_receive_buffer), m_default_send_buffer, sizeof(m_default_send_buffer))); } Result HtclowDriver::Open(htclow::ChannelId channel, void *receive_buffer, size_t receive_buffer_size, void *send_buffer, size_t send_buffer_size) { /* Open the channel. */ R_TRY(m_manager->Open(GetHtclowChannel(channel, m_module_id))); /* Set the send/receive buffers. */ m_manager->SetReceiveBuffer(GetHtclowChannel(channel, m_module_id), receive_buffer, receive_buffer_size); m_manager->SetSendBuffer(GetHtclowChannel(channel, m_module_id), send_buffer, send_buffer_size); R_SUCCEED(); } void HtclowDriver::Close(htclow::ChannelId channel) { /* Close the channel. */ const auto result = m_manager->Close(GetHtclowChannel(channel, m_module_id)); R_ASSERT(result); } Result HtclowDriver::Connect(htclow::ChannelId channel) { /* Check if we should emulate disconnection. */ R_UNLESS(!m_disconnection_emulation_enabled, htclow::ResultConnectionFailure()); /* Begin connecting. */ u32 task_id{}; R_TRY(m_manager->ConnectBegin(std::addressof(task_id), GetHtclowChannel(channel, m_module_id))); /* Wait for the task to complete. */ this->WaitTask(task_id); /* Finish connecting. */ R_TRY(m_manager->ConnectEnd(GetHtclowChannel(channel, m_module_id), task_id)); R_SUCCEED(); } void HtclowDriver::Shutdown(htclow::ChannelId channel) { /* Shut down the channel. */ m_manager->Shutdown(GetHtclowChannel(channel, m_module_id)); } Result HtclowDriver::Send(s64 *out, const void *src, s64 src_size, htclow::ChannelId channel) { /* Check if we should emulate disconnection. */ R_UNLESS(!m_disconnection_emulation_enabled, htclow::ResultConnectionFailure()); /* Validate that dst_size is okay. */ R_UNLESS(util::IsIntValueRepresentable<size_t>(src_size), htclow::ResultOverflow()); /* Repeatedly send until we're done. */ size_t cur_send; size_t sent; for (sent = 0; sent < static_cast<size_t>(src_size); sent += cur_send) { /* Begin sending. */ u32 task_id{}; R_TRY(m_manager->SendBegin(std::addressof(task_id), std::addressof(cur_send), static_cast<const u8 *>(src) + sent, static_cast<size_t>(src_size) - sent, GetHtclowChannel(channel, m_module_id))); /* Wait for the task to complete. */ this->WaitTask(task_id); /* Finish sending. */ R_ABORT_UNLESS(m_manager->SendEnd(task_id)); } /* Set the output sent size. */ *out = static_cast<s64>(sent); R_SUCCEED(); } Result HtclowDriver::ReceiveInternal(size_t *out, void *dst, size_t dst_size, htclow::ChannelId channel, htclow::ReceiveOption option) { /* Determine whether we're blocking. */ const bool blocking = option != htclow::ReceiveOption_NonBlocking; /* Begin receiving. */ u32 task_id{}; R_TRY(m_manager->ReceiveBegin(std::addressof(task_id), GetHtclowChannel(channel, m_module_id), blocking ? 1 : 0)); /* Wait for the task to complete. */ this->WaitTask(task_id); /* Finish receiving. */ R_RETURN(m_manager->ReceiveEnd(out, dst, dst_size, GetHtclowChannel(channel, m_module_id), task_id)); } Result HtclowDriver::Receive(s64 *out, void *dst, s64 dst_size, htclow::ChannelId channel, htclow::ReceiveOption option) { /* Check if we should emulate disconnection. */ R_UNLESS(!m_disconnection_emulation_enabled, htclow::ResultConnectionFailure()); /* Validate that dst_size is okay. */ R_UNLESS(util::IsIntValueRepresentable<size_t>(dst_size), htclow::ResultOverflow()); /* Determine the minimum allowable receive size. */ size_t min_size; switch (option) { case htclow::ReceiveOption_NonBlocking: min_size = 0; break; case htclow::ReceiveOption_ReceiveAnyData: min_size = 1; break; case htclow::ReceiveOption_ReceiveAllData: min_size = dst_size; break; AMS_UNREACHABLE_DEFAULT_CASE(); } /* Repeatedly receive. */ size_t received = 0; do { size_t cur_received; const Result result = this->ReceiveInternal(std::addressof(cur_received), static_cast<u8 *>(dst) + received, static_cast<size_t>(dst_size) - received, channel, option); if (R_FAILED(result)) { if (htclow::ResultChannelReceiveBufferEmpty::Includes(result)) { R_UNLESS(option != htclow::ReceiveOption_NonBlocking, htclow::ResultNonBlockingReceiveFailed()); } if (htclow::ResultChannelNotExist::Includes(result)) { *out = received; } R_RETURN(result); } received += cur_received; } while (received < min_size); /* Set the output received size. */ *out = static_cast<s64>(received); R_SUCCEED(); } htclow::ChannelState HtclowDriver::GetChannelState(htclow::ChannelId channel) { return m_manager->GetChannelState(GetHtclowChannel(channel, m_module_id)); } os::EventType *HtclowDriver::GetChannelStateEvent(htclow::ChannelId channel) { return m_manager->GetChannelStateEvent(GetHtclowChannel(channel, m_module_id)); } }
7,358
C++
.cpp
147
41.258503
206
0.641751
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,336
htc_htcmisc_rpc_tasks.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htc/server/rpc/htc_htcmisc_rpc_tasks.cpp
/* * Copyright (c) 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 "htc_htcmisc_rpc_tasks.hpp" namespace ams::htc::server::rpc { Result GetEnvironmentVariableTask::SetArguments(const char *args, size_t size) { /* Copy to our name. */ const size_t copied = util::Strlcpy(m_name, args, sizeof(m_name)); m_name_size = copied; /* Require that the size be correct. */ R_UNLESS(size == copied || size == copied + 1, htc::ResultUnknown()); R_SUCCEED(); } void GetEnvironmentVariableTask::Complete(HtcmiscResult result, const char *data, size_t size) { /* Sanity check input. */ if (size < sizeof(m_value)) { /* Convert the result. */ switch (result) { case HtcmiscResult::Success: /* Copy to our value. */ std::memcpy(m_value, data, size); m_value[size] = '\x00'; m_value_size = size + 1; m_result = ResultSuccess(); break; case HtcmiscResult::UnknownError: m_result = htc::ResultUnknown(); break; case HtcmiscResult::UnsupportedVersion: m_result = htc::ResultConnectionFailure(); break; case HtcmiscResult::InvalidRequest: m_result = htc::ResultNotFound(); break; } } else { m_result = htc::ResultUnknown(); } /* Complete the task. */ Task::Complete(); } Result GetEnvironmentVariableTask::GetResult(size_t *out, char *dst, size_t size) const { /* Check our task state. */ AMS_ASSERT(this->GetTaskState() == RpcTaskState::Completed); /* Check that we succeeded. */ R_TRY(m_result); /* Check that we can convert successfully. */ R_UNLESS(util::IsIntValueRepresentable<int>(size), htc::ResultUnknown()); /* Copy out. */ const auto copied = util::Strlcpy(dst, m_value, size); R_UNLESS(copied < static_cast<int>(size), htc::ResultNotEnoughBuffer()); /* Set the output size. */ *out = m_value_size; R_SUCCEED(); } Result GetEnvironmentVariableTask::CreateRequest(size_t *out, char *data, size_t size, u32 task_id) { /* Validate pre-conditions. */ AMS_ASSERT(size >= sizeof(HtcmiscRpcPacket)); AMS_UNUSED(size); /* Create the packet. */ auto *packet = reinterpret_cast<HtcmiscRpcPacket *>(data); *packet = { .protocol = HtcmiscProtocol, .version = HtcmiscMaxVersion, .category = HtcmiscPacketCategory::Request, .type = HtcmiscPacketType::GetEnvironmentVariable, .body_size = this->GetNameSize(), .task_id = task_id, .params = { /* ... */ }, }; /* Set the packet body. */ std::memcpy(packet->data, this->GetName(), this->GetNameSize()); /* Set the output size. */ *out = sizeof(*packet) + this->GetNameSize(); R_SUCCEED(); } Result GetEnvironmentVariableTask::ProcessResponse(const char *data, size_t size) { /* Convert the input to a packet. */ auto *packet = reinterpret_cast<const HtcmiscRpcPacket *>(data); /* Process the packet. */ this->Complete(static_cast<HtcmiscResult>(packet->params[0]), data + sizeof(*packet), size - sizeof(*packet)); /* Complete the task. */ Task::Complete(); R_SUCCEED(); } Result GetEnvironmentVariableLengthTask::SetArguments(const char *args, size_t size) { /* Copy to our name. */ const size_t copied = util::Strlcpy(m_name, args, sizeof(m_name)); m_name_size = copied; /* Require that the size be correct. */ R_UNLESS(size == copied || size == copied + 1, htc::ResultUnknown()); R_SUCCEED(); } void GetEnvironmentVariableLengthTask::Complete(HtcmiscResult result, const char *data, size_t size) { /* Sanity check input. */ if (size == sizeof(s64)) { /* Convert the result. */ switch (result) { case HtcmiscResult::Success: /* Copy to our value. */ s64 tmp; std::memcpy(std::addressof(tmp), data, sizeof(tmp)); if (util::IsIntValueRepresentable<size_t>(tmp)) { m_value_size = static_cast<size_t>(tmp); } m_result = ResultSuccess(); break; case HtcmiscResult::UnknownError: m_result = htc::ResultUnknown(); break; case HtcmiscResult::UnsupportedVersion: m_result = htc::ResultConnectionFailure(); break; case HtcmiscResult::InvalidRequest: m_result = htc::ResultNotFound(); break; } } else { m_result = htc::ResultUnknown(); } /* Complete the task. */ Task::Complete(); } Result GetEnvironmentVariableLengthTask::GetResult(size_t *out) const { /* Check our task state. */ AMS_ASSERT(this->GetTaskState() == RpcTaskState::Completed); /* Check that we succeeded. */ R_TRY(m_result); /* Set the output size. */ *out = m_value_size; R_SUCCEED(); } Result GetEnvironmentVariableLengthTask::CreateRequest(size_t *out, char *data, size_t size, u32 task_id) { /* Validate pre-conditions. */ AMS_ASSERT(size >= sizeof(HtcmiscRpcPacket)); AMS_UNUSED(size); /* Create the packet. */ auto *packet = reinterpret_cast<HtcmiscRpcPacket *>(data); *packet = { .protocol = HtcmiscProtocol, .version = HtcmiscMaxVersion, .category = HtcmiscPacketCategory::Request, .type = HtcmiscPacketType::GetEnvironmentVariableLength, .body_size = this->GetNameSize(), .task_id = task_id, .params = { /* ... */ }, }; /* Set the packet body. */ std::memcpy(packet->data, this->GetName(), this->GetNameSize()); /* Set the output size. */ *out = sizeof(*packet) + this->GetNameSize(); R_SUCCEED(); } Result GetEnvironmentVariableLengthTask::ProcessResponse(const char *data, size_t size) { /* Convert the input to a packet. */ auto *packet = reinterpret_cast<const HtcmiscRpcPacket *>(data); /* Process the packet. */ this->Complete(static_cast<HtcmiscResult>(packet->params[0]), data + sizeof(*packet), size - sizeof(*packet)); /* Complete the task. */ Task::Complete(); R_SUCCEED(); } Result RunOnHostTask::SetArguments(const char *args, size_t size) { /* Verify command fits in our buffer. */ R_UNLESS(size < sizeof(m_command), htc::ResultNotEnoughBuffer()); /* Set our command. */ std::memcpy(m_command, args, size); m_command_size = size; R_SUCCEED(); } void RunOnHostTask::Complete(int host_result) { /* Set our host result. */ m_host_result = host_result; /* Signal. */ m_system_event.Signal(); /* Complete the task. */ Task::Complete(); } Result RunOnHostTask::GetResult(int *out) const { *out = m_host_result; R_SUCCEED(); } void RunOnHostTask::Cancel(RpcTaskCancelReason reason) { /* Cancel the task. */ Task::Cancel(reason); /* Signal our event. */ m_system_event.Signal(); } Result RunOnHostTask::CreateRequest(size_t *out, char *data, size_t size, u32 task_id) { /* Validate pre-conditions. */ AMS_ASSERT(size >= sizeof(HtcmiscRpcPacket)); AMS_UNUSED(size); /* Create the packet. */ auto *packet = reinterpret_cast<HtcmiscRpcPacket *>(data); *packet = { .protocol = HtcmiscProtocol, .version = HtcmiscMaxVersion, .category = HtcmiscPacketCategory::Request, .type = HtcmiscPacketType::RunOnHost, .body_size = this->GetCommandSize(), .task_id = task_id, .params = { /* ... */ }, }; /* Set the packet body. */ std::memcpy(packet->data, this->GetCommand(), this->GetCommandSize()); /* Set the output size. */ *out = sizeof(*packet) + this->GetCommandSize(); R_SUCCEED(); } Result RunOnHostTask::ProcessResponse(const char *data, size_t size) { /* Validate pre-conditions. */ AMS_ASSERT(size >= sizeof(HtcmiscRpcPacket)); AMS_UNUSED(size); this->Complete(reinterpret_cast<const HtcmiscRpcPacket *>(data)->params[0]); R_SUCCEED(); } os::SystemEventType *RunOnHostTask::GetSystemEvent() { return m_system_event.GetBase(); } }
9,883
C++
.cpp
239
31.016736
118
0.565376
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,337
htc_rpc_client.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htc/server/rpc/htc_rpc_client.cpp
/* * Copyright (c) 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 "htc_rpc_client.hpp" namespace ams::htc::server::rpc { namespace { constexpr inline size_t ThreadStackSize = os::MemoryPageSize; alignas(os::ThreadStackAlignment) constinit u8 g_receive_thread_stack[ThreadStackSize]; alignas(os::ThreadStackAlignment) constinit u8 g_send_thread_stack[ThreadStackSize]; constinit os::SdkMutex g_rpc_mutex; constinit RpcTaskIdFreeList g_task_id_free_list; constinit RpcTaskTable g_task_table; } RpcClient::RpcClient(driver::IDriver *driver, htclow::ChannelId channel) : m_allocator(nullptr), m_driver(driver), m_channel_id(channel), m_receive_thread_stack(g_receive_thread_stack), m_send_thread_stack(g_send_thread_stack), m_mutex(g_rpc_mutex), m_task_id_free_list(g_task_id_free_list), m_task_table(g_task_table), m_task_active(), m_is_htcs_task(), m_task_queue(), m_cancelled(false), m_thread_running(false) { /* Initialize all events. */ for (size_t i = 0; i < MaxRpcCount; ++i) { os::InitializeEvent(std::addressof(m_receive_buffer_available_events[i]), false, os::EventClearMode_AutoClear); os::InitializeEvent(std::addressof(m_send_buffer_available_events[i]), false, os::EventClearMode_AutoClear); } } RpcClient::RpcClient(mem::StandardAllocator *allocator, driver::IDriver *driver, htclow::ChannelId channel) : m_allocator(allocator), m_driver(driver), m_channel_id(channel), m_receive_thread_stack(m_allocator->Allocate(ThreadStackSize, os::ThreadStackAlignment)), m_send_thread_stack(m_allocator->Allocate(ThreadStackSize, os::ThreadStackAlignment)), m_mutex(g_rpc_mutex), m_task_id_free_list(g_task_id_free_list), m_task_table(g_task_table), m_task_active(), m_is_htcs_task(), m_task_queue(), m_cancelled(false), m_thread_running(false) { /* Initialize all events. */ for (size_t i = 0; i < MaxRpcCount; ++i) { os::InitializeEvent(std::addressof(m_receive_buffer_available_events[i]), false, os::EventClearMode_AutoClear); os::InitializeEvent(std::addressof(m_send_buffer_available_events[i]), false, os::EventClearMode_AutoClear); } } RpcClient::~RpcClient() { /* Finalize all events. */ for (size_t i = 0; i < MaxRpcCount; ++i) { os::FinalizeEvent(std::addressof(m_receive_buffer_available_events[i])); os::FinalizeEvent(std::addressof(m_send_buffer_available_events[i])); } /* Free the thread stacks. */ if (m_allocator != nullptr) { m_allocator->Free(m_receive_thread_stack); m_allocator->Free(m_send_thread_stack); } m_receive_thread_stack = nullptr; m_send_thread_stack = nullptr; /* Free all tasks. */ for (u32 i = 0; i < MaxRpcCount; ++i) { if (m_task_active[i]) { std::scoped_lock lk(m_mutex); m_task_table.Delete(i); m_task_id_free_list.Free(i); } } } void RpcClient::Open() { R_ABORT_UNLESS(m_driver->Open(m_channel_id)); } void RpcClient::Close() { m_driver->Close(m_channel_id); } Result RpcClient::Start() { /* Connect. */ R_TRY(m_driver->Connect(m_channel_id)); /* Initialize our task queue. */ m_task_queue.Initialize(); /* Create our threads. */ R_ABORT_UNLESS(os::CreateThread(std::addressof(m_receive_thread), ReceiveThreadEntry, this, m_receive_thread_stack, ThreadStackSize, AMS_GET_SYSTEM_THREAD_PRIORITY(htc, HtcmiscReceive))); R_ABORT_UNLESS(os::CreateThread(std::addressof(m_send_thread), SendThreadEntry, this, m_send_thread_stack, ThreadStackSize, AMS_GET_SYSTEM_THREAD_PRIORITY(htc, HtcmiscSend))); /* Set thread name pointers. */ os::SetThreadNamePointer(std::addressof(m_receive_thread), AMS_GET_SYSTEM_THREAD_NAME(htc, HtcmiscReceive)); os::SetThreadNamePointer(std::addressof(m_send_thread), AMS_GET_SYSTEM_THREAD_NAME(htc, HtcmiscSend)); /* Start threads. */ os::StartThread(std::addressof(m_receive_thread)); os::StartThread(std::addressof(m_send_thread)); /* Set initial state. */ m_cancelled = false; m_thread_running = true; /* Clear events. */ for (size_t i = 0; i < MaxRpcCount; ++i) { os::ClearEvent(std::addressof(m_receive_buffer_available_events[i])); os::ClearEvent(std::addressof(m_send_buffer_available_events[i])); } R_SUCCEED(); } void RpcClient::Cancel() { /* Set cancelled. */ m_cancelled = true; /* Signal all events. */ for (size_t i = 0; i < MaxRpcCount; ++i) { os::SignalEvent(std::addressof(m_receive_buffer_available_events[i])); os::SignalEvent(std::addressof(m_send_buffer_available_events[i])); } /* Cancel our queue. */ m_task_queue.Cancel(); } void RpcClient::Wait() { /* Wait for thread to not be running. */ if (m_thread_running) { os::WaitThread(std::addressof(m_receive_thread)); os::WaitThread(std::addressof(m_send_thread)); os::DestroyThread(std::addressof(m_receive_thread)); os::DestroyThread(std::addressof(m_send_thread)); } m_thread_running = false; /* Lock ourselves. */ std::scoped_lock lk(m_mutex); /* Finalize the task queue. */ m_task_queue.Finalize(); /* Cancel all tasks. */ for (size_t i = 0; i < MaxRpcCount; ++i) { if (m_task_active[i]) { m_task_table.Get<Task>(i)->Cancel(RpcTaskCancelReason::ClientFinalized); } } } int RpcClient::WaitAny(htclow::ChannelState state, os::EventType *event) { /* Check if we're already signaled. */ if (os::TryWaitEvent(event)) { return 1; } /* Wait. */ while (m_driver->GetChannelState(m_channel_id) != state) { const auto idx = os::WaitAny(m_driver->GetChannelStateEvent(m_channel_id), event); if (idx != 0) { return idx; } /* Clear the channel state event. */ os::ClearEvent(m_driver->GetChannelStateEvent(m_channel_id)); } return 0; } Result RpcClient::ReceiveThread() { /* Loop forever. */ auto *header = reinterpret_cast<RpcPacket *>(m_receive_buffer); while (true) { /* Try to receive a packet header. */ R_TRY(this->ReceiveHeader(header)); /* Track how much we've received. */ size_t received = sizeof(*header); /* If the packet has one, receive its body. */ if (header->body_size > 0) { /* Sanity check the task id. */ AMS_ABORT_UNLESS(header->task_id < static_cast<int>(MaxRpcCount)); /* Sanity check the body size. */ AMS_ABORT_UNLESS(util::IsIntValueRepresentable<size_t>(header->body_size)); AMS_ABORT_UNLESS(static_cast<size_t>(header->body_size) <= sizeof(m_receive_buffer) - received); /* Receive the body. */ R_TRY(this->ReceiveBody(header->data, header->body_size)); /* Note that we received the body. */ received += header->body_size; } /* Acquire exclusive access to the task tables. */ std::scoped_lock lk(m_mutex); /* Get the specified task. */ Task *task = m_task_table.Get<Task>(header->task_id); R_UNLESS(task != nullptr, htc::ResultInvalidTaskId()); /* If the task is canceled, free it. */ if (task->GetTaskState() == RpcTaskState::Cancelled) { m_task_active[header->task_id] = false; m_is_htcs_task[header->task_id] = false; m_task_table.Delete(header->task_id); m_task_id_free_list.Free(header->task_id); continue; } /* Handle the packet. */ switch (header->category) { case PacketCategory::Response: R_TRY(task->ProcessResponse(m_receive_buffer, received)); break; case PacketCategory::Notification: R_TRY(task->ProcessNotification(m_receive_buffer, received)); break; default: R_THROW(htc::ResultInvalidCategory()); } /* If we used the receive buffer, signal that we're done with it. */ if (task->IsReceiveBufferRequired()) { os::SignalEvent(std::addressof(m_receive_buffer_available_events[header->task_id])); } } } Result RpcClient::ReceiveHeader(RpcPacket *header) { /* Receive. */ s64 received; R_TRY(m_driver->Receive(std::addressof(received), reinterpret_cast<char *>(header), sizeof(*header), m_channel_id, htclow::ReceiveOption_ReceiveAllData)); /* Check size. */ R_UNLESS(static_cast<size_t>(received) == sizeof(*header), htc::ResultInvalidSize()); R_SUCCEED(); } Result RpcClient::ReceiveBody(char *dst, size_t size) { /* Receive. */ s64 received; R_TRY(m_driver->Receive(std::addressof(received), dst, size, m_channel_id, htclow::ReceiveOption_ReceiveAllData)); /* Check size. */ R_UNLESS(static_cast<size_t>(received) == size, htc::ResultInvalidSize()); R_SUCCEED(); } Result RpcClient::SendThread() { while (true) { /* Get a task. */ Task *task; u32 task_id{}; PacketCategory category{}; do { /* Dequeue a task. */ R_TRY(m_task_queue.Take(std::addressof(task_id), std::addressof(category))); /* Get the task from the table. */ std::scoped_lock lk(m_mutex); task = m_task_table.Get<Task>(task_id); } while (task == nullptr); /* If required, wait for the send buffer to become available. */ if (task->IsSendBufferRequired()) { os::WaitEvent(std::addressof(m_send_buffer_available_events[task_id])); /* Check if we've been cancelled. */ if (m_cancelled) { break; } } /* Handle the task. */ size_t packet_size; switch (category) { case PacketCategory::Request: R_TRY(task->CreateRequest(std::addressof(packet_size), m_send_buffer, sizeof(m_send_buffer), task_id)); break; case PacketCategory::Notification: R_TRY(task->CreateNotification(std::addressof(packet_size), m_send_buffer, sizeof(m_send_buffer), task_id)); break; AMS_UNREACHABLE_DEFAULT_CASE(); } /* Send the request. */ R_TRY(this->SendRequest(m_send_buffer, packet_size)); } R_THROW(htc::ResultCancelled()); } Result RpcClient::SendRequest(const char *src, size_t size) { /* Sanity check our size. */ AMS_ASSERT(util::IsIntValueRepresentable<s64>(size)); /* Send the data. */ s64 sent; R_TRY(m_driver->Send(std::addressof(sent), src, static_cast<s64>(size), m_channel_id)); /* Check that we sent the right amount. */ R_UNLESS(sent == static_cast<s64>(size), htc::ResultInvalidSize()); R_SUCCEED(); } void RpcClient::CancelBySocket(s32 handle) { /* Check if we need to cancel each task. */ for (size_t i = 0; i < MaxRpcCount; ++i) { /* Lock ourselves. */ std::scoped_lock lk(m_mutex); /* Check that the task is active and is an htcs task. */ if (!m_task_active[i] || !m_is_htcs_task[i]) { continue; } /* Get the htcs task. */ auto *htcs_task = m_task_table.Get<htcs::impl::rpc::HtcsTask>(i); /* Handle the case where the task handle is the one we're cancelling. */ if (this->GetTaskHandle(i) == handle) { /* If the task is complete, free it. */ if (htcs_task->GetTaskState() == RpcTaskState::Completed) { m_task_active[i] = false; m_is_htcs_task[i] = false; m_task_table.Delete(i); m_task_id_free_list.Free(i); } else { /* If the task is a send task, notify. */ if (htcs_task->GetTaskType() == htcs::impl::rpc::HtcsTaskType::Send) { m_task_queue.Add(i, PacketCategory::Notification); } /* Cancel the task. */ htcs_task->Cancel(RpcTaskCancelReason::BySocket); } /* The task has been cancelled, so we can move on. */ continue; } /* Handle the case where the task is a select task. */ if (htcs_task->GetTaskType() == htcs::impl::rpc::HtcsTaskType::Select) { /* Get the select task. */ auto *select_task = m_task_table.Get<htcs::impl::rpc::SelectTask>(i); /* Get the handle counts. */ const auto num_read = select_task->GetReadHandleCount(); const auto num_write = select_task->GetWriteHandleCount(); const auto num_exception = select_task->GetExceptionHandleCount(); const auto total = num_read + num_write + num_exception; /* Get the handle array. */ const auto *handles = select_task->GetHandles(); /* Check each handle. */ for (auto handle_idx = 0; handle_idx < total; ++handle_idx) { if (handles[handle_idx] == handle) { /* If the select is complete, free it. */ if (select_task->GetTaskState() == RpcTaskState::Completed) { m_task_active[i] = false; m_is_htcs_task[i] = false; m_task_table.Delete(i); m_task_id_free_list.Free(i); } else { /* Cancel the task. */ select_task->Cancel(RpcTaskCancelReason::BySocket); } } } } } } s32 RpcClient::GetTaskHandle(u32 task_id) { /* TODO: Why is this necessary to avoid a bogus array-bounds warning? */ AMS_ASSUME(task_id < MaxRpcCount); /* Check pre-conditions. */ AMS_ASSERT(m_task_active[task_id]); AMS_ASSERT(m_is_htcs_task[task_id]); /* Get the htcs task. */ auto *task = m_task_table.Get<htcs::impl::rpc::HtcsTask>(task_id); /* Check that the task has a handle. */ if (!m_task_active[task_id] || !m_is_htcs_task[task_id] || task == nullptr) { return -1; } /* Get the task's type. */ const auto type = task->GetTaskType(); /* Check that the task is new enough. */ if (task->GetVersion() == 3) { if (type == htcs::impl::rpc::HtcsTaskType::Receive || type == htcs::impl::rpc::HtcsTaskType::Send) { return -1; } } /* Get the handle from the task. */ switch (type) { case htcs::impl::rpc::HtcsTaskType::Receive: return static_cast<htcs::impl::rpc::ReceiveTask *>(task)->GetHandle(); case htcs::impl::rpc::HtcsTaskType::Send: return static_cast<htcs::impl::rpc::SendTask *>(task)->GetHandle(); case htcs::impl::rpc::HtcsTaskType::Shutdown: return static_cast<htcs::impl::rpc::ShutdownTask *>(task)->GetHandle(); case htcs::impl::rpc::HtcsTaskType::Close: return -1; case htcs::impl::rpc::HtcsTaskType::Connect: return static_cast<htcs::impl::rpc::ConnectTask *>(task)->GetHandle(); case htcs::impl::rpc::HtcsTaskType::Listen: return static_cast<htcs::impl::rpc::ListenTask *>(task)->GetHandle(); case htcs::impl::rpc::HtcsTaskType::Accept: return static_cast<htcs::impl::rpc::AcceptTask *>(task)->GetServerHandle(); case htcs::impl::rpc::HtcsTaskType::Socket: return -1; case htcs::impl::rpc::HtcsTaskType::Bind: return static_cast<htcs::impl::rpc::BindTask *>(task)->GetHandle(); case htcs::impl::rpc::HtcsTaskType::Fcntl: return static_cast<htcs::impl::rpc::FcntlTask *>(task)->GetHandle(); case htcs::impl::rpc::HtcsTaskType::ReceiveSmall: return static_cast<htcs::impl::rpc::ReceiveSmallTask *>(task)->GetHandle(); case htcs::impl::rpc::HtcsTaskType::SendSmall: return static_cast<htcs::impl::rpc::SendSmallTask *>(task)->GetHandle(); case htcs::impl::rpc::HtcsTaskType::Select: return -1; AMS_UNREACHABLE_DEFAULT_CASE(); } } }
18,455
C++
.cpp
391
35.102302
195
0.558138
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,338
htc_htcmisc_rpc_server.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htc/server/rpc/htc_htcmisc_rpc_server.cpp
/* * Copyright (c) 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 "htc_htcmisc_rpc_server.hpp" namespace ams::htc::server::rpc { namespace { constexpr inline size_t ReceiveThreadStackSize = os::MemoryPageSize; alignas(os::ThreadStackAlignment) constinit u8 g_receive_thread_stack[ReceiveThreadStackSize]; } HtcmiscRpcServer::HtcmiscRpcServer(driver::IDriver *driver, htclow::ChannelId channel) : m_allocator(nullptr), m_driver(driver), m_channel_id(channel), m_receive_thread_stack(g_receive_thread_stack), m_cancelled(false), m_thread_running(false) { /* ... */ } void HtcmiscRpcServer::Open() { R_ABORT_UNLESS(m_driver->Open(m_channel_id, m_driver_receive_buffer, sizeof(m_driver_receive_buffer), m_driver_send_buffer, sizeof(m_driver_send_buffer))); } void HtcmiscRpcServer::Close() { m_driver->Close(m_channel_id); } Result HtcmiscRpcServer::Start() { /* Connect. */ R_TRY(m_driver->Connect(m_channel_id)); /* Create our thread. */ R_ABORT_UNLESS(os::CreateThread(std::addressof(m_receive_thread), ReceiveThreadEntry, this, m_receive_thread_stack, ReceiveThreadStackSize, AMS_GET_SYSTEM_THREAD_PRIORITY(htc, HtcmiscReceive))); /* Set thread name pointer. */ os::SetThreadNamePointer(std::addressof(m_receive_thread), AMS_GET_SYSTEM_THREAD_NAME(htc, HtcmiscReceive)); /* Start thread. */ os::StartThread(std::addressof(m_receive_thread)); /* Set initial state. */ m_cancelled = false; m_thread_running = true; R_SUCCEED(); } void HtcmiscRpcServer::Cancel() { /* Set cancelled. */ m_cancelled = true; } void HtcmiscRpcServer::Wait() { /* Wait for thread to not be running. */ if (m_thread_running) { os::WaitThread(std::addressof(m_receive_thread)); os::DestroyThread(std::addressof(m_receive_thread)); } m_thread_running = false; } int HtcmiscRpcServer::WaitAny(htclow::ChannelState state, os::EventType *event) { /* Check if we're already signaled. */ if (os::TryWaitEvent(event)) { return 1; } /* Wait. */ while (m_driver->GetChannelState(m_channel_id) != state) { const auto idx = os::WaitAny(m_driver->GetChannelStateEvent(m_channel_id), event); if (idx != 0) { return idx; } /* Clear the channel state event. */ os::ClearEvent(m_driver->GetChannelStateEvent(m_channel_id)); } return 0; } Result HtcmiscRpcServer::ReceiveThread() { /* Loop forever. */ auto *header = reinterpret_cast<HtcmiscRpcPacket *>(m_receive_buffer); while (true) { /* Try to receive a packet header. */ R_TRY(this->ReceiveHeader(header)); /* Track how much we've received. */ size_t received = sizeof(*header); /* If the packet has one, receive its body. */ if (header->body_size > 0) { /* Sanity check the body size. */ AMS_ABORT_UNLESS(util::IsIntValueRepresentable<size_t>(header->body_size)); AMS_ABORT_UNLESS(static_cast<size_t>(header->body_size) <= sizeof(m_receive_buffer) - received); /* Receive the body. */ R_TRY(this->ReceiveBody(header->data, header->body_size)); /* Note that we received the body. */ received += header->body_size; } /* Check that the packet is a request packet. */ R_UNLESS(header->category == HtcmiscPacketCategory::Request, htc::ResultInvalidCategory()); /* Handle specific requests. */ if (header->type == HtcmiscPacketType::SetTargetName) { R_TRY(this->ProcessSetTargetNameRequest(header->data, header->body_size, header->task_id)); } } } Result HtcmiscRpcServer::ProcessSetTargetNameRequest(const char *name, size_t size, u32 task_id) { /* TODO: we need to use settings::fwdbg::SetSettingsItemValue here, but this will require ams support for set:fd re-enable? */ /* Needs some thought. */ AMS_UNUSED(name, size, task_id); AMS_ABORT("HtcmiscRpcServer::ProcessSetTargetNameRequest"); } Result HtcmiscRpcServer::ReceiveHeader(HtcmiscRpcPacket *header) { /* Receive. */ s64 received; R_TRY(m_driver->Receive(std::addressof(received), reinterpret_cast<char *>(header), sizeof(*header), m_channel_id, htclow::ReceiveOption_ReceiveAllData)); /* Check size. */ R_UNLESS(static_cast<size_t>(received) == sizeof(*header), htc::ResultInvalidSize()); R_SUCCEED(); } Result HtcmiscRpcServer::ReceiveBody(char *dst, size_t size) { /* Receive. */ s64 received; R_TRY(m_driver->Receive(std::addressof(received), dst, size, m_channel_id, htclow::ReceiveOption_ReceiveAllData)); /* Check size. */ R_UNLESS(static_cast<size_t>(received) == size, htc::ResultInvalidSize()); R_SUCCEED(); } Result HtcmiscRpcServer::SendRequest(const char *src, size_t size) { /* Sanity check our size. */ AMS_ASSERT(util::IsIntValueRepresentable<s64>(size)); /* Send the data. */ s64 sent; R_TRY(m_driver->Send(std::addressof(sent), src, static_cast<s64>(size), m_channel_id)); /* Check that we sent the right amount. */ R_UNLESS(sent == static_cast<s64>(size), htc::ResultInvalidSize()); R_SUCCEED(); } }
6,350
C++
.cpp
139
37.007194
202
0.626053
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,339
htc_tenv_service.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htc/tenv/htc_tenv_service.cpp
/* * Copyright (c) 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 "htc_tenv_service.hpp" namespace ams::htc::tenv { Result Service::GetVariable(sf::Out<s64> out_size, const sf::OutBuffer &out_buffer, const htc::tenv::VariableName &name) { /* TODO */ AMS_UNUSED(out_size, out_buffer, name); AMS_ABORT("Service::GetVariable"); } Result Service::GetVariableLength(sf::Out<s64> out_size, const htc::tenv::VariableName &name) { /* TODO */ AMS_UNUSED(out_size, name); AMS_ABORT("Service::GetVariableLength"); } Result Service::WaitUntilVariableAvailable(s64 timeout_ms) { /* TODO */ AMS_UNUSED(timeout_ms); AMS_ABORT("Service::WaitUntilVariableAvailable"); } }
1,362
C++
.cpp
34
35.676471
126
0.701436
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,340
htc_tenv_service_manager.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htc/tenv/htc_tenv_service_manager.cpp
/* * Copyright (c) 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 "impl/htc_tenv_allocator.hpp" #include "htc_tenv_service.hpp" namespace ams::htc::tenv { Result ServiceManager::GetServiceInterface(sf::Out<sf::SharedPointer<htc::tenv::IService>> out, const sf::ClientProcessId &process_id) { *out = impl::SfObjectFactory::CreateSharedEmplaced<htc::tenv::IService, Service>(process_id.GetValue()); R_SUCCEED(); } }
1,047
C++
.cpp
24
40.916667
140
0.746078
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,341
htc_tenv.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htc/tenv/htc_tenv.cpp
/* * Copyright (c) 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 "impl/htc_tenv_allocator.hpp" #include "impl/htc_tenv_impl.hpp" namespace ams::htc::tenv { void Initialize(AllocateFunction allocate, DeallocateFunction deallocate) { /* Initialize the library allocator. */ impl::InitializeAllocator(allocate, deallocate); } void UnregisterDefinitionFilePath(os::ProcessId process_id) { return impl::UnregisterDefinitionFilePath(process_id.value); } }
1,101
C++
.cpp
27
37.62963
79
0.752336
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,342
htc_tenv_allocator.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htc/tenv/impl/htc_tenv_allocator.cpp
/* * Copyright (c) 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 "htc_tenv_allocator.hpp" namespace ams::htc::tenv::impl { namespace { constinit AllocateFunction g_allocate = nullptr; constinit DeallocateFunction g_deallocate = nullptr; } void InitializeAllocator(AllocateFunction allocate, DeallocateFunction deallocate) { /* Check that we don't already have allocator functions. */ AMS_ASSERT(g_allocate == nullptr); AMS_ASSERT(g_deallocate == nullptr); /* Set our allocator functions. */ g_allocate = allocate; g_deallocate = deallocate; /* Check that we have allocator functions. */ AMS_ASSERT(g_allocate != nullptr); AMS_ASSERT(g_deallocate != nullptr); } void *Allocate(size_t size) { /* Check that we have an allocator. */ AMS_ASSERT(g_allocate != nullptr); return g_allocate(size); } void Deallocate(void *p, size_t size) { /* Check that we have a deallocator. */ AMS_ASSERT(g_deallocate != nullptr); return g_deallocate(p, size); } }
1,734
C++
.cpp
44
34
88
0.684148
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,343
htc_tenv_impl.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htc/tenv/impl/htc_tenv_impl.cpp
/* * Copyright (c) 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 "htc_tenv_impl.hpp" #include "htc_tenv_definition_file_info.hpp" namespace ams::htc::tenv::impl { namespace { class DefinitionFileInfoManager { private: using DefinitionFileInfoList = util::IntrusiveListBaseTraits<DefinitionFileInfo>::ListType; private: DefinitionFileInfoList m_list; os::SdkMutex m_mutex; public: constexpr DefinitionFileInfoManager() = default; ~DefinitionFileInfoManager() { while (!m_list.empty()) { auto *p = std::addressof(*m_list.rbegin()); m_list.erase(m_list.iterator_to(*p)); delete p; } } void Remove(DefinitionFileInfo *info) { std::scoped_lock lk(m_mutex); m_list.erase(m_list.iterator_to(*info)); delete info; } DefinitionFileInfo *GetInfo(u64 process_id) { std::scoped_lock lk(m_mutex); for (auto &info : m_list) { if (info.process_id == process_id) { return std::addressof(info); } } return nullptr; } }; constinit DefinitionFileInfoManager g_definition_file_info_manager; ALWAYS_INLINE DefinitionFileInfoManager &GetDefinitionFileInfoManager() { return g_definition_file_info_manager; } } void UnregisterDefinitionFilePath(u64 process_id) { /* Require the process id to be valid. */ if (process_id == 0) { return; } /* Remove the definition file info, if we have one. */ if (auto *info = GetDefinitionFileInfoManager().GetInfo(process_id); info != nullptr) { GetDefinitionFileInfoManager().Remove(info); } } }
2,695
C++
.cpp
66
29.333333
107
0.576511
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,344
fssystem_buffered_storage.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssystem/fssystem_buffered_storage.cpp
/* * Copyright (c) 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 { namespace { constexpr inline uintptr_t InvalidAddress = 0; constexpr inline s64 InvalidOffset = std::numeric_limits<s64>::max(); } class BufferedStorage::Cache : public ::ams::fs::impl::Newable { private: struct FetchParameter { s64 offset; void *buffer; size_t size; }; static_assert(util::is_pod<FetchParameter>::value); private: BufferedStorage *m_buffered_storage; std::pair<uintptr_t, size_t> m_memory_range; fs::IBufferManager::CacheHandle m_cache_handle; s64 m_offset; std::atomic<bool> m_is_valid; std::atomic<bool> m_is_dirty; u8 m_reserved[2]; s32 m_reference_count; Cache *m_next; Cache *m_prev; public: Cache() : m_buffered_storage(nullptr), m_memory_range(InvalidAddress, 0), m_cache_handle(), m_offset(InvalidOffset), m_is_valid(false), m_is_dirty(false), m_reference_count(1), m_next(nullptr), m_prev(nullptr) { /* ... */ } ~Cache() { this->Finalize(); } void Initialize(BufferedStorage *bs) { AMS_ASSERT(bs != nullptr); AMS_ASSERT(m_buffered_storage == nullptr); m_buffered_storage = bs; this->Link(); } void Finalize() { AMS_ASSERT(m_buffered_storage != nullptr); AMS_ASSERT(m_buffered_storage->m_buffer_manager != nullptr); AMS_ASSERT(m_reference_count == 0); /* If we're valid, acquire our cache handle and free our buffer. */ if (this->IsValid()) { const auto buffer_manager = m_buffered_storage->m_buffer_manager; if (!m_is_dirty) { AMS_ASSERT(m_memory_range.first == InvalidAddress); m_memory_range = buffer_manager->AcquireCache(m_cache_handle); } if (m_memory_range.first != InvalidAddress) { buffer_manager->DeallocateBuffer(m_memory_range.first, m_memory_range.second); m_memory_range.first = InvalidAddress; m_memory_range.second = 0; } } /* Clear all our members. */ m_buffered_storage = nullptr; m_offset = InvalidOffset; m_is_valid = false; m_is_dirty = false; m_next = nullptr; m_prev = nullptr; } void Link() { AMS_ASSERT(m_buffered_storage != nullptr); AMS_ASSERT(m_buffered_storage->m_buffer_manager != nullptr); AMS_ASSERT(m_reference_count > 0); if ((--m_reference_count) == 0) { AMS_ASSERT(m_next == nullptr); AMS_ASSERT(m_prev == nullptr); if (m_buffered_storage->m_next_fetch_cache == nullptr) { m_buffered_storage->m_next_fetch_cache = this; m_next = this; m_prev = this; } else { /* Check against a cache being registered twice. */ { auto cache = m_buffered_storage->m_next_fetch_cache; do { if (cache->IsValid() && this->Hits(cache->m_offset, m_buffered_storage->m_block_size)) { m_is_valid = false; break; } cache = cache->m_next; } while (cache != m_buffered_storage->m_next_fetch_cache); } /* Link into the fetch list. */ { AMS_ASSERT(m_buffered_storage->m_next_fetch_cache->m_prev != nullptr); AMS_ASSERT(m_buffered_storage->m_next_fetch_cache->m_prev->m_next == m_buffered_storage->m_next_fetch_cache); m_next = m_buffered_storage->m_next_fetch_cache; m_prev = m_buffered_storage->m_next_fetch_cache->m_prev; m_next->m_prev = this; m_prev->m_next = this; } /* Insert invalid caches at the start of the list. */ if (!this->IsValid()) { m_buffered_storage->m_next_fetch_cache = this; } } /* If we're not valid, clear our offset. */ if (!this->IsValid()) { m_offset = InvalidOffset; m_is_dirty = false; } /* Ensure our buffer state is coherent. */ if (m_memory_range.first != InvalidAddress && !m_is_dirty) { if (this->IsValid()) { m_cache_handle = m_buffered_storage->m_buffer_manager->RegisterCache(m_memory_range.first, m_memory_range.second, fs::IBufferManager::BufferAttribute()); } else { m_buffered_storage->m_buffer_manager->DeallocateBuffer(m_memory_range.first, m_memory_range.second); } m_memory_range.first = InvalidAddress; m_memory_range.second = 0; } } } void Unlink() { AMS_ASSERT(m_buffered_storage != nullptr); AMS_ASSERT(m_reference_count >= 0); if ((++m_reference_count) == 1) { AMS_ASSERT(m_next != nullptr); AMS_ASSERT(m_prev != nullptr); AMS_ASSERT(m_next->m_prev == this); AMS_ASSERT(m_prev->m_next == this); if (m_buffered_storage->m_next_fetch_cache == this) { if (m_next != this) { m_buffered_storage->m_next_fetch_cache = m_next; } else { m_buffered_storage->m_next_fetch_cache = nullptr; } } m_buffered_storage->m_next_acquire_cache = this; m_next->m_prev = m_prev; m_prev->m_next = m_next; m_next = nullptr; m_prev = nullptr; } else { AMS_ASSERT(m_next == nullptr); AMS_ASSERT(m_prev == nullptr); } } void Read(s64 offset, void *buffer, size_t size) const { AMS_ASSERT(m_buffered_storage != nullptr); AMS_ASSERT(m_next == nullptr); AMS_ASSERT(m_prev == nullptr); AMS_ASSERT(this->IsValid()); AMS_ASSERT(this->Hits(offset, 1)); AMS_ASSERT(m_memory_range.first != InvalidAddress); const auto read_offset = offset - m_offset; const auto readable_offset_max = m_buffered_storage->m_block_size - size; const auto cache_buffer = reinterpret_cast<u8 *>(m_memory_range.first) + read_offset; AMS_ASSERT(read_offset >= 0); AMS_ASSERT(static_cast<size_t>(read_offset) <= readable_offset_max); AMS_UNUSED(readable_offset_max); std::memcpy(buffer, cache_buffer, size); } void Write(s64 offset, const void *buffer, size_t size) { AMS_ASSERT(m_buffered_storage != nullptr); AMS_ASSERT(m_next == nullptr); AMS_ASSERT(m_prev == nullptr); AMS_ASSERT(this->IsValid()); AMS_ASSERT(this->Hits(offset, 1)); AMS_ASSERT(m_memory_range.first != InvalidAddress); const auto write_offset = offset - m_offset; const auto writable_offset_max = m_buffered_storage->m_block_size - size; const auto cache_buffer = reinterpret_cast<u8 *>(m_memory_range.first) + write_offset; AMS_ASSERT(write_offset >= 0); AMS_ASSERT(static_cast<size_t>(write_offset) <= writable_offset_max); AMS_UNUSED(writable_offset_max); std::memcpy(cache_buffer, buffer, size); m_is_dirty = true; } Result Flush() { AMS_ASSERT(m_buffered_storage != nullptr); AMS_ASSERT(m_next == nullptr); AMS_ASSERT(m_prev == nullptr); AMS_ASSERT(this->IsValid()); if (m_is_dirty) { AMS_ASSERT(m_memory_range.first != InvalidAddress); const auto base_size = m_buffered_storage->m_base_storage_size; const auto block_size = static_cast<s64>(m_buffered_storage->m_block_size); const auto flush_size = static_cast<size_t>(std::min(block_size, base_size - m_offset)); auto &base_storage = m_buffered_storage->m_base_storage; const auto cache_buffer = reinterpret_cast<void *>(m_memory_range.first); R_TRY(base_storage.Write(m_offset, cache_buffer, flush_size)); m_is_dirty = false; buffers::EnableBlockingBufferManagerAllocation(); } R_SUCCEED(); } const std::pair<Result, bool> PrepareFetch() { AMS_ASSERT(m_buffered_storage != nullptr); AMS_ASSERT(m_buffered_storage->m_buffer_manager != nullptr); AMS_ASSERT(m_next == nullptr); AMS_ASSERT(m_prev == nullptr); AMS_ASSERT(this->IsValid()); AMS_ASSERT(m_buffered_storage->m_mutex.IsLockedByCurrentThread()); std::pair<Result, bool> result(ResultSuccess(), false); if (m_reference_count == 1) { result.first = this->Flush(); if (R_SUCCEEDED(result.first)) { m_is_valid = false; m_reference_count = 0; result.second = true; } } return result; } void UnprepareFetch() { AMS_ASSERT(m_buffered_storage != nullptr); AMS_ASSERT(m_buffered_storage->m_buffer_manager != nullptr); AMS_ASSERT(m_next == nullptr); AMS_ASSERT(m_prev == nullptr); AMS_ASSERT(!this->IsValid()); AMS_ASSERT(!m_is_dirty); AMS_ASSERT(m_buffered_storage->m_mutex.IsLockedByCurrentThread()); m_is_valid = true; m_reference_count = 1; } Result Fetch(s64 offset) { AMS_ASSERT(m_buffered_storage != nullptr); AMS_ASSERT(m_buffered_storage->m_buffer_manager != nullptr); AMS_ASSERT(m_next == nullptr); AMS_ASSERT(m_prev == nullptr); AMS_ASSERT(!this->IsValid()); AMS_ASSERT(!m_is_dirty); if (m_memory_range.first == InvalidAddress) { R_TRY(this->AllocateFetchBuffer()); } FetchParameter fetch_param = {}; this->CalcFetchParameter(std::addressof(fetch_param), offset); auto &base_storage = m_buffered_storage->m_base_storage; R_TRY(base_storage.Read(fetch_param.offset, fetch_param.buffer, fetch_param.size)); m_offset = fetch_param.offset; AMS_ASSERT(this->Hits(offset, 1)); R_SUCCEED(); } Result FetchFromBuffer(s64 offset, const void *buffer, size_t buffer_size) { AMS_ASSERT(m_buffered_storage != nullptr); AMS_ASSERT(m_buffered_storage->m_buffer_manager != nullptr); AMS_ASSERT(m_next == nullptr); AMS_ASSERT(m_prev == nullptr); AMS_ASSERT(!this->IsValid()); AMS_ASSERT(!m_is_dirty); AMS_ASSERT(util::IsAligned(offset, m_buffered_storage->m_block_size)); if (m_memory_range.first == InvalidAddress) { R_TRY(this->AllocateFetchBuffer()); } FetchParameter fetch_param = {}; this->CalcFetchParameter(std::addressof(fetch_param), offset); AMS_ASSERT(fetch_param.offset == offset); AMS_ASSERT(fetch_param.size <= buffer_size); AMS_UNUSED(buffer_size); std::memcpy(fetch_param.buffer, buffer, fetch_param.size); m_offset = fetch_param.offset; AMS_ASSERT(this->Hits(offset, 1)); R_SUCCEED(); } bool TryAcquireCache() { AMS_ASSERT(m_buffered_storage != nullptr); AMS_ASSERT(m_buffered_storage->m_buffer_manager != nullptr); AMS_ASSERT(this->IsValid()); if (m_memory_range.first != InvalidAddress) { return true; } else { m_memory_range = m_buffered_storage->m_buffer_manager->AcquireCache(m_cache_handle); m_is_valid = m_memory_range.first != InvalidAddress; return m_is_valid; } } void Invalidate() { AMS_ASSERT(m_buffered_storage != nullptr); m_is_valid = false; } bool IsValid() const { AMS_ASSERT(m_buffered_storage != nullptr); return m_is_valid || m_reference_count > 0; } bool IsDirty() const { AMS_ASSERT(m_buffered_storage != nullptr); return m_is_dirty; } bool Hits(s64 offset, s64 size) const { AMS_ASSERT(m_buffered_storage != nullptr); const auto block_size = static_cast<s64>(m_buffered_storage->m_block_size); return (offset < m_offset + block_size) && (m_offset < offset + size); } private: Result AllocateFetchBuffer() { fs::IBufferManager *buffer_manager = m_buffered_storage->m_buffer_manager; AMS_ASSERT(buffer_manager->AcquireCache(m_cache_handle).first == InvalidAddress); auto range_guard = SCOPE_GUARD { m_memory_range.first = InvalidAddress; }; R_TRY(buffers::AllocateBufferUsingBufferManagerContext(std::addressof(m_memory_range), buffer_manager, m_buffered_storage->m_block_size, fs::IBufferManager::BufferAttribute(), [](const std::pair<uintptr_t, size_t> &buffer) { return buffer.first != 0; }, AMS_CURRENT_FUNCTION_NAME)); range_guard.Cancel(); R_SUCCEED(); } void CalcFetchParameter(FetchParameter *out, s64 offset) const { AMS_ASSERT(out != nullptr); const auto block_size = static_cast<s64>(m_buffered_storage->m_block_size); const auto cache_offset = util::AlignDown(offset, m_buffered_storage->m_block_size); const auto base_size = m_buffered_storage->m_base_storage_size; const auto cache_size = static_cast<size_t>(std::min(block_size, base_size - cache_offset)); const auto cache_buffer = reinterpret_cast<void *>(m_memory_range.first); AMS_ASSERT(offset >= 0); AMS_ASSERT(offset < base_size); out->offset = cache_offset; out->buffer = cache_buffer; out->size = cache_size; } }; class BufferedStorage::SharedCache { NON_COPYABLE(SharedCache); NON_MOVEABLE(SharedCache); friend class UniqueCache; private: Cache *m_cache; Cache *m_start_cache; BufferedStorage *m_buffered_storage; public: explicit SharedCache(BufferedStorage *bs) : m_cache(nullptr), m_start_cache(bs->m_next_acquire_cache), m_buffered_storage(bs) { AMS_ASSERT(m_buffered_storage != nullptr); } ~SharedCache() { std::scoped_lock lk(m_buffered_storage->m_mutex); this->Release(); } bool AcquireNextOverlappedCache(s64 offset, s64 size) { AMS_ASSERT(m_buffered_storage != nullptr); auto is_first = m_cache == nullptr; const auto start = is_first ? m_start_cache : m_cache + 1; AMS_ASSERT(start >= m_buffered_storage->m_caches.get()); AMS_ASSERT(start <= m_buffered_storage->m_caches.get() + m_buffered_storage->m_cache_count); std::scoped_lock lk(m_buffered_storage->m_mutex); this->Release(); AMS_ASSERT(m_cache == nullptr); for (auto cache = start; true; ++cache) { if (m_buffered_storage->m_caches.get() + m_buffered_storage->m_cache_count <= cache) { cache = m_buffered_storage->m_caches.get(); } if (!is_first && cache == m_start_cache) { break; } if (cache->IsValid() && cache->Hits(offset, size) && cache->TryAcquireCache()) { cache->Unlink(); m_cache = cache; return true; } is_first = false; } m_cache = nullptr; return false; } bool AcquireNextDirtyCache() { AMS_ASSERT(m_buffered_storage != nullptr); const auto start = m_cache != nullptr ? m_cache + 1 : m_buffered_storage->m_caches.get(); const auto end = m_buffered_storage->m_caches.get() + m_buffered_storage->m_cache_count; AMS_ASSERT(start >= m_buffered_storage->m_caches.get()); AMS_ASSERT(start <= end); this->Release(); AMS_ASSERT(m_cache == nullptr); for (auto cache = start; cache < end; ++cache) { if (cache->IsValid() && cache->IsDirty() && cache->TryAcquireCache()) { cache->Unlink(); m_cache = cache; return true; } } m_cache = nullptr; return false; } bool AcquireNextValidCache() { AMS_ASSERT(m_buffered_storage != nullptr); const auto start = m_cache != nullptr ? m_cache + 1 : m_buffered_storage->m_caches.get(); const auto end = m_buffered_storage->m_caches.get() + m_buffered_storage->m_cache_count; AMS_ASSERT(start >= m_buffered_storage->m_caches.get()); AMS_ASSERT(start <= end); this->Release(); AMS_ASSERT(m_cache == nullptr); for (auto cache = start; cache < end; ++cache) { if (cache->IsValid() && cache->TryAcquireCache()) { cache->Unlink(); m_cache = cache; return true; } } m_cache = nullptr; return false; } bool AcquireFetchableCache() { AMS_ASSERT(m_buffered_storage != nullptr); std::scoped_lock lk(m_buffered_storage->m_mutex); this->Release(); AMS_ASSERT(m_cache == nullptr); m_cache = m_buffered_storage->m_next_fetch_cache; if (m_cache != nullptr) { if (m_cache->IsValid()) { m_cache->TryAcquireCache(); } m_cache->Unlink(); } return m_cache != nullptr; } void Read(s64 offset, void *buffer, size_t size) { AMS_ASSERT(m_cache != nullptr); m_cache->Read(offset, buffer, size); } void Write(s64 offset, const void *buffer, size_t size) { AMS_ASSERT(m_cache != nullptr); m_cache->Write(offset, buffer, size); } Result Flush() { AMS_ASSERT(m_cache != nullptr); R_RETURN(m_cache->Flush()); } void Invalidate() { AMS_ASSERT(m_cache != nullptr); return m_cache->Invalidate(); } bool Hits(s64 offset, s64 size) const { AMS_ASSERT(m_cache != nullptr); return m_cache->Hits(offset, size); } private: void Release() { if (m_cache != nullptr) { AMS_ASSERT(m_buffered_storage->m_caches.get() <= m_cache); AMS_ASSERT(m_cache <= m_buffered_storage->m_caches.get() + m_buffered_storage->m_cache_count); m_cache->Link(); m_cache = nullptr; } } }; class BufferedStorage::UniqueCache { NON_COPYABLE(UniqueCache); NON_MOVEABLE(UniqueCache); private: Cache *m_cache; BufferedStorage *m_buffered_storage; public: explicit UniqueCache(BufferedStorage *bs) : m_cache(nullptr), m_buffered_storage(bs) { AMS_ASSERT(m_buffered_storage != nullptr); } ~UniqueCache() { if (m_cache != nullptr) { std::scoped_lock lk(m_buffered_storage->m_mutex); m_cache->UnprepareFetch(); } } const std::pair<Result, bool> Upgrade(const SharedCache &shared_cache) { AMS_ASSERT(m_buffered_storage == shared_cache.m_buffered_storage); AMS_ASSERT(shared_cache.m_cache != nullptr); std::scoped_lock lk(m_buffered_storage->m_mutex); const auto result = shared_cache.m_cache->PrepareFetch(); if (R_SUCCEEDED(result.first) && result.second) { m_cache = shared_cache.m_cache; } return result; } Result Fetch(s64 offset) { AMS_ASSERT(m_cache != nullptr); R_RETURN(m_cache->Fetch(offset)); } Result FetchFromBuffer(s64 offset, const void *buffer, size_t buffer_size) { AMS_ASSERT(m_cache != nullptr); R_TRY(m_cache->FetchFromBuffer(offset, buffer, buffer_size)); R_SUCCEED(); } }; BufferedStorage::BufferedStorage() : m_base_storage(), m_buffer_manager(), m_block_size(), m_base_storage_size(), m_caches(), m_cache_count(), m_next_acquire_cache(), m_next_fetch_cache(), m_mutex(), m_bulk_read_enabled() { /* ... */ } BufferedStorage::~BufferedStorage() { this->Finalize(); } Result BufferedStorage::Initialize(fs::SubStorage base_storage, fs::IBufferManager *buffer_manager, size_t block_size, s32 buffer_count) { AMS_ASSERT(buffer_manager != nullptr); AMS_ASSERT(block_size > 0); AMS_ASSERT(util::IsPowerOfTwo(block_size)); AMS_ASSERT(buffer_count > 0); /* Get the base storage size. */ R_TRY(base_storage.GetSize(std::addressof(m_base_storage_size))); /* Set members. */ m_base_storage = base_storage; m_buffer_manager = buffer_manager; m_block_size = block_size; m_cache_count = buffer_count; /* Allocate the caches. */ m_caches.reset(new Cache[buffer_count]); R_UNLESS(m_caches != nullptr, fs::ResultAllocationMemoryFailedInBufferedStorageA()); /* Initialize the caches. */ for (auto i = 0; i < buffer_count; i++) { m_caches[i].Initialize(this); } m_next_acquire_cache = std::addressof(m_caches[0]); R_SUCCEED(); } void BufferedStorage::Finalize() { m_base_storage = fs::SubStorage(); m_base_storage_size = 0; m_caches.reset(); m_cache_count = 0; m_next_fetch_cache = nullptr; } Result BufferedStorage::Read(s64 offset, void *buffer, size_t size) { AMS_ASSERT(this->IsInitialized()); /* Succeed if zero size. */ R_SUCCEED_IF(size == 0); /* Validate arguments. */ R_UNLESS(buffer != nullptr, fs::ResultNullptrArgument()); /* Do the read. */ R_TRY(this->ReadCore(offset, buffer, size)); R_SUCCEED(); } Result BufferedStorage::Write(s64 offset, const void *buffer, size_t size) { AMS_ASSERT(this->IsInitialized()); /* Succeed if zero size. */ R_SUCCEED_IF(size == 0); /* Validate arguments. */ R_UNLESS(buffer != nullptr, fs::ResultNullptrArgument()); /* Do the write. */ R_TRY(this->WriteCore(offset, buffer, size)); R_SUCCEED(); } Result BufferedStorage::GetSize(s64 *out) { AMS_ASSERT(out != nullptr); AMS_ASSERT(this->IsInitialized()); *out = m_base_storage_size; R_SUCCEED(); } Result BufferedStorage::SetSize(s64 size) { AMS_ASSERT(this->IsInitialized()); const s64 prev_size = m_base_storage_size; if (prev_size < size) { /* Prepare to expand. */ if (!util::IsAligned(prev_size, m_block_size)) { SharedCache cache(this); const auto invalidate_offset = prev_size; const auto invalidate_size = size - prev_size; if (cache.AcquireNextOverlappedCache(invalidate_offset, invalidate_size)) { R_TRY(cache.Flush()); cache.Invalidate(); } AMS_ASSERT(!cache.AcquireNextOverlappedCache(invalidate_offset, invalidate_size)); } } else if (size < prev_size) { /* Prepare to do a shrink. */ SharedCache cache(this); const auto invalidate_offset = prev_size; const auto invalidate_size = size - prev_size; const auto is_fragment = util::IsAligned(size, m_block_size); while (cache.AcquireNextOverlappedCache(invalidate_offset, invalidate_size)) { if (is_fragment && cache.Hits(invalidate_offset, 1)) { R_TRY(cache.Flush()); } cache.Invalidate(); } } /* Set the size. */ R_TRY(m_base_storage.SetSize(size)); /* Get our new size. */ s64 new_size = 0; R_TRY(m_base_storage.GetSize(std::addressof(new_size))); m_base_storage_size = new_size; R_SUCCEED(); } Result BufferedStorage::Flush() { AMS_ASSERT(this->IsInitialized()); /* Flush caches. */ SharedCache cache(this); while (cache.AcquireNextDirtyCache()) { R_TRY(cache.Flush()); } /* Flush the base storage. */ R_TRY(m_base_storage.Flush()); R_SUCCEED(); } Result BufferedStorage::OperateRange(void *dst, size_t dst_size, fs::OperationId op_id, s64 offset, s64 size, const void *src, size_t src_size) { AMS_ASSERT(this->IsInitialized()); /* Invalidate caches, if we should. */ if (op_id == fs::OperationId::Invalidate) { this->InvalidateCaches(); } R_RETURN(m_base_storage.OperateRange(dst, dst_size, op_id, offset, size, src, src_size)); } void BufferedStorage::InvalidateCaches() { AMS_ASSERT(this->IsInitialized()); SharedCache cache(this); while (cache.AcquireNextValidCache()) { cache.Invalidate(); } } Result BufferedStorage::PrepareAllocation() { const auto flush_threshold = m_buffer_manager->GetTotalSize() / 8; if (m_buffer_manager->GetTotalAllocatableSize() < flush_threshold) { R_TRY(this->Flush()); } R_SUCCEED(); } Result BufferedStorage::ControlDirtiness() { const auto flush_threshold = m_buffer_manager->GetTotalSize() / 4; if (m_buffer_manager->GetTotalAllocatableSize() < flush_threshold) { s32 dirty_count = 0; SharedCache cache(this); while (cache.AcquireNextDirtyCache()) { if ((++dirty_count) > 1) { R_TRY(cache.Flush()); cache.Invalidate(); } } } R_SUCCEED(); } Result BufferedStorage::ReadCore(s64 offset, void *buffer, size_t size) { AMS_ASSERT(m_caches != nullptr); AMS_ASSERT(buffer != nullptr); /* Validate the offset. */ const auto base_storage_size = m_base_storage_size; R_UNLESS(offset >= 0, fs::ResultInvalidOffset()); R_UNLESS(offset <= base_storage_size, fs::ResultInvalidOffset()); /* Setup tracking variables. */ size_t remaining_size = static_cast<size_t>(std::min<s64>(size, base_storage_size - offset)); s64 cur_offset = offset; s64 buf_offset = 0; /* Determine what caches are needed, if we have bulk read set. */ if (m_bulk_read_enabled) { /* Check head cache. */ const auto head_cache_needed = this->ReadHeadCache(std::addressof(cur_offset), buffer, std::addressof(remaining_size), std::addressof(buf_offset)); R_SUCCEED_IF(remaining_size == 0); /* Check tail cache. */ const auto tail_cache_needed = this->ReadTailCache(cur_offset, buffer, std::addressof(remaining_size), buf_offset); R_SUCCEED_IF(remaining_size == 0); /* Perform bulk reads. */ constexpr size_t BulkReadSizeMax = 2_MB; if (remaining_size <= BulkReadSizeMax) { do { /* Try to do a bulk read. */ R_TRY_CATCH(this->BulkRead(cur_offset, static_cast<u8 *>(buffer) + buf_offset, remaining_size, head_cache_needed, tail_cache_needed)) { R_CATCH(fs::ResultAllocationPooledBufferNotEnoughSize) { /* If the read fails due to insufficient pooled buffer size, */ /* then we want to fall back to the normal read path. */ break; } } R_END_TRY_CATCH; R_SUCCEED(); } while(0); } } /* Repeatedly read until we're done. */ while (remaining_size > 0) { /* Determine how much to read this iteration. */ auto *cur_dst = static_cast<u8 *>(buffer) + buf_offset; size_t cur_size = 0; if (!util::IsAligned(cur_offset, m_block_size)) { const size_t aligned_size = m_block_size - (cur_offset & (m_block_size - 1)); cur_size = std::min(aligned_size, remaining_size); } else if (remaining_size < m_block_size) { cur_size = remaining_size; } else { cur_size = util::AlignDown(remaining_size, m_block_size); } if (cur_size <= m_block_size) { SharedCache cache(this); if (!cache.AcquireNextOverlappedCache(cur_offset, cur_size)) { R_TRY(this->PrepareAllocation()); while (true) { R_UNLESS(cache.AcquireFetchableCache(), fs::ResultOutOfResource()); UniqueCache fetch_cache(this); const auto upgrade_result = fetch_cache.Upgrade(cache); R_TRY(upgrade_result.first); if (upgrade_result.second) { R_TRY(fetch_cache.Fetch(cur_offset)); break; } } R_TRY(this->ControlDirtiness()); } cache.Read(cur_offset, cur_dst, cur_size); } else { { SharedCache cache(this); while (cache.AcquireNextOverlappedCache(cur_offset, cur_size)) { R_TRY(cache.Flush()); cache.Invalidate(); } } R_TRY(m_base_storage.Read(cur_offset, cur_dst, cur_size)); } remaining_size -= cur_size; cur_offset += cur_size; buf_offset += cur_size; } R_SUCCEED(); } bool BufferedStorage::ReadHeadCache(s64 *offset, void *buffer, size_t *size, s64 *buffer_offset) { AMS_ASSERT(offset != nullptr); AMS_ASSERT(buffer != nullptr); AMS_ASSERT(size != nullptr); AMS_ASSERT(buffer_offset != nullptr); bool is_cache_needed = !util::IsAligned(*offset, m_block_size); while (*size > 0) { size_t cur_size = 0; if (!util::IsAligned(*offset, m_block_size)) { const s64 aligned_size = util::AlignUp(*offset, m_block_size) - *offset; cur_size = std::min(aligned_size, static_cast<s64>(*size)); } else if (*size < m_block_size) { cur_size = *size; } else { cur_size = m_block_size; } SharedCache cache(this); if (!cache.AcquireNextOverlappedCache(*offset, cur_size)) { break; } cache.Read(*offset, static_cast<u8 *>(buffer) + *buffer_offset, cur_size); *offset += cur_size; *buffer_offset += cur_size; *size -= cur_size; is_cache_needed = false; } return is_cache_needed; } bool BufferedStorage::ReadTailCache(s64 offset, void *buffer, size_t *size, s64 buffer_offset) { AMS_ASSERT(buffer != nullptr); AMS_ASSERT(size != nullptr); bool is_cache_needed = !util::IsAligned(offset + *size, m_block_size); while (*size > 0) { const s64 cur_offset_end = offset + *size; size_t cur_size = 0; if (!util::IsAligned(cur_offset_end, m_block_size)) { const s64 aligned_size = cur_offset_end - util::AlignDown(cur_offset_end, m_block_size); cur_size = std::min(aligned_size, static_cast<s64>(*size)); } else if (*size < m_block_size) { cur_size = *size; } else { cur_size = m_block_size; } const s64 cur_offset = cur_offset_end - static_cast<s64>(cur_size); AMS_ASSERT(cur_offset >= 0); SharedCache cache(this); if (!cache.AcquireNextOverlappedCache(cur_offset, cur_size)) { break; } cache.Read(cur_offset, static_cast<u8 *>(buffer) + buffer_offset + cur_offset - offset, cur_size); *size -= cur_size; is_cache_needed = false; } return is_cache_needed; } Result BufferedStorage::BulkRead(s64 offset, void *buffer, size_t size, bool head_cache_needed, bool tail_cache_needed) { /* Determine aligned extents. */ const s64 aligned_offset = util::AlignDown(offset, m_block_size); const s64 aligned_offset_end = std::min(util::AlignUp(offset + static_cast<s64>(size), m_block_size), m_base_storage_size); const s64 aligned_size = aligned_offset_end - aligned_offset; /* Allocate a work buffer. */ char *work_buffer = nullptr; PooledBuffer pooled_buffer; if (offset == aligned_offset && size == static_cast<size_t>(aligned_size)) { work_buffer = static_cast<char *>(buffer); } else { pooled_buffer.AllocateParticularlyLarge(static_cast<size_t>(aligned_size), 1); R_UNLESS(static_cast<s64>(pooled_buffer.GetSize()) >= aligned_size, fs::ResultAllocationPooledBufferNotEnoughSize()); work_buffer = pooled_buffer.GetBuffer(); } /* Ensure cache is coherent. */ { SharedCache cache(this); while (cache.AcquireNextOverlappedCache(aligned_offset, aligned_size)) { R_TRY(cache.Flush()); cache.Invalidate(); } } /* Read from the base storage. */ R_TRY(m_base_storage.Read(aligned_offset, work_buffer, static_cast<size_t>(aligned_size))); if (work_buffer != static_cast<char *>(buffer)) { std::memcpy(buffer, work_buffer + offset - aligned_offset, size); } bool cached = false; /* Handle head cache if needed. */ if (head_cache_needed) { R_TRY(this->PrepareAllocation()); SharedCache cache(this); while (true) { R_UNLESS(cache.AcquireFetchableCache(), fs::ResultOutOfResource()); UniqueCache fetch_cache(this); const auto upgrade_result = fetch_cache.Upgrade(cache); R_TRY(upgrade_result.first); if (upgrade_result.second) { R_TRY(fetch_cache.FetchFromBuffer(aligned_offset, work_buffer, static_cast<size_t>(aligned_size))); break; } } cached = true; } /* Handle tail cache if needed. */ if (tail_cache_needed && (!head_cache_needed || aligned_size > static_cast<s64>(m_block_size))) { if (!cached) { R_TRY(this->PrepareAllocation()); } SharedCache cache(this); while (true) { R_UNLESS(cache.AcquireFetchableCache(), fs::ResultOutOfResource()); UniqueCache fetch_cache(this); const auto upgrade_result = fetch_cache.Upgrade(cache); R_TRY(upgrade_result.first); if (upgrade_result.second) { const s64 tail_cache_offset = util::AlignDown(offset + static_cast<s64>(size), m_block_size); const size_t tail_cache_size = static_cast<size_t>(aligned_size - tail_cache_offset + aligned_offset); R_TRY(fetch_cache.FetchFromBuffer(tail_cache_offset, work_buffer + tail_cache_offset - aligned_offset, tail_cache_size)); break; } } } if (cached) { R_TRY(this->ControlDirtiness()); } R_SUCCEED(); } Result BufferedStorage::WriteCore(s64 offset, const void *buffer, size_t size) { AMS_ASSERT(m_caches != nullptr); AMS_ASSERT(buffer != nullptr); /* Validate the offset. */ const auto base_storage_size = m_base_storage_size; R_UNLESS(offset >= 0, fs::ResultInvalidOffset()); R_UNLESS(offset <= base_storage_size, fs::ResultInvalidOffset()); /* Setup tracking variables. */ size_t remaining_size = static_cast<size_t>(std::min<s64>(size, base_storage_size - offset)); s64 cur_offset = offset; s64 buf_offset = 0; /* Repeatedly read until we're done. */ while (remaining_size > 0) { /* Determine how much to read this iteration. */ const auto *cur_src = static_cast<const u8 *>(buffer) + buf_offset; size_t cur_size = 0; if (!util::IsAligned(cur_offset, m_block_size)) { const size_t aligned_size = m_block_size - (cur_offset & (m_block_size - 1)); cur_size = std::min(aligned_size, remaining_size); } else if (remaining_size < m_block_size) { cur_size = remaining_size; } else { cur_size = util::AlignDown(remaining_size, m_block_size); } if (cur_size <= m_block_size) { SharedCache cache(this); if (!cache.AcquireNextOverlappedCache(cur_offset, cur_size)) { R_TRY(this->PrepareAllocation()); while (true) { R_UNLESS(cache.AcquireFetchableCache(), fs::ResultOutOfResource()); UniqueCache fetch_cache(this); const auto upgrade_result = fetch_cache.Upgrade(cache); R_TRY(upgrade_result.first); if (upgrade_result.second) { R_TRY(fetch_cache.Fetch(cur_offset)); break; } } } cache.Write(cur_offset, cur_src, cur_size); buffers::EnableBlockingBufferManagerAllocation(); R_TRY(this->ControlDirtiness()); } else { { SharedCache cache(this); while (cache.AcquireNextOverlappedCache(cur_offset, cur_size)) { R_TRY(cache.Flush()); cache.Invalidate(); } } R_TRY(m_base_storage.Write(cur_offset, cur_src, cur_size)); buffers::EnableBlockingBufferManagerAllocation(); } remaining_size -= cur_size; cur_offset += cur_size; buf_offset += cur_size; } R_SUCCEED(); } }
43,133
C++
.cpp
895
32.922905
240
0.511664
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,345
fssystem_speed_emulation_configuration.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssystem/fssystem_speed_emulation_configuration.cpp
/* * Copyright (c) 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 { namespace { std::atomic<::ams::fs::SpeedEmulationMode> g_speed_emulation_mode = ::ams::fs::SpeedEmulationMode::None; } void SpeedEmulationConfiguration::SetSpeedEmulationMode(::ams::fs::SpeedEmulationMode mode) { g_speed_emulation_mode = mode; } ::ams::fs::SpeedEmulationMode SpeedEmulationConfiguration::GetSpeedEmulationMode() { return g_speed_emulation_mode; } }
1,110
C++
.cpp
27
37.555556
112
0.739777
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,346
fssystem_service_context.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssystem/fssystem_service_context.cpp
/* * Copyright (c) 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 { namespace { os::SdkThreadLocalStorage g_tls_service_context; } void RegisterServiceContext(ServiceContext *context) { /* Check pre-conditions. */ AMS_ASSERT(context != nullptr); AMS_ASSERT(g_tls_service_context.GetValue() == 0); /* Register context. */ g_tls_service_context.SetValue(reinterpret_cast<uintptr_t>(context)); } void UnregisterServiceContext() { /* Unregister context. */ g_tls_service_context.SetValue(0); } ServiceContext *GetServiceContext() { /* Get context. */ auto * const context = reinterpret_cast<ServiceContext *>(g_tls_service_context.GetValue()); AMS_ASSERT(context != nullptr); return context; } }
1,451
C++
.cpp
38
33.184211
100
0.695652
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,347
fssystem_nca_header.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssystem/fssystem_nca_header.cpp
/* * Copyright (c) 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 { u8 NcaHeader::GetProperKeyGeneration() const { return std::max(this->key_generation, this->key_generation_2); } bool NcaPatchInfo::HasIndirectTable() const { return this->indirect_size != 0; } bool NcaPatchInfo::HasAesCtrExTable() const { return this->aes_ctr_ex_size != 0; } }
1,020
C++
.cpp
27
34.296296
76
0.724696
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,348
fssystem_integrity_verification_storage.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssystem/fssystem_integrity_verification_storage.cpp
/* * Copyright (c) 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 { void IntegrityVerificationStorage::Initialize(fs::SubStorage hs, fs::SubStorage ds, s64 verif_block_size, s64 upper_layer_verif_block_size, fs::IBufferManager *bm, fssystem::IHash256GeneratorFactory *hgf, const util::optional<fs::HashSalt> &salt, bool is_real_data, bool is_writable, bool allow_cleared_blocks) { /* Validate preconditions. */ AMS_ASSERT(verif_block_size >= HashSize); AMS_ASSERT(bm != nullptr); AMS_ASSERT(hgf != nullptr); /* Set storages. */ m_hash_storage = hs; m_data_storage = ds; /* Set hash generator factory. */ m_hash_generator_factory = hgf; /* Set verification block sizes. */ m_verification_block_size = verif_block_size; m_verification_block_order = ILog2(static_cast<u32>(verif_block_size)); AMS_ASSERT(m_verification_block_size == (1l << m_verification_block_order)); /* Set buffer manager. */ m_buffer_manager = bm; /* Set upper layer block sizes. */ upper_layer_verif_block_size = std::max(upper_layer_verif_block_size, HashSize); m_upper_layer_verification_block_size = upper_layer_verif_block_size; m_upper_layer_verification_block_order = ILog2(static_cast<u32>(upper_layer_verif_block_size)); AMS_ASSERT(m_upper_layer_verification_block_size == (1l << m_upper_layer_verification_block_order)); /* Validate sizes. */ { s64 hash_size = 0; s64 data_size = 0; AMS_ASSERT(R_SUCCEEDED(m_hash_storage.GetSize(std::addressof(hash_size)))); AMS_ASSERT(R_SUCCEEDED(m_data_storage.GetSize(std::addressof(data_size)))); AMS_ASSERT(((hash_size / HashSize) * m_verification_block_size) >= data_size); AMS_UNUSED(hash_size, data_size); } /* Set salt. */ m_salt = salt; /* Set data, writable, and allow cleared. */ m_is_real_data = is_real_data; m_is_writable = is_writable; m_allow_cleared_blocks = allow_cleared_blocks; } void IntegrityVerificationStorage::Finalize() { if (m_buffer_manager != nullptr) { m_hash_storage = fs::SubStorage(); m_data_storage = fs::SubStorage(); m_buffer_manager = nullptr; } } Result IntegrityVerificationStorage::Read(s64 offset, void *buffer, size_t size) { /* Although we support zero-size reads, we expect non-zero sizes. */ AMS_ASSERT(size != 0); /* Validate other preconditions. */ AMS_ASSERT(util::IsAligned(offset, static_cast<size_t>(m_verification_block_size))); AMS_ASSERT(util::IsAligned(size, static_cast<size_t>(m_verification_block_size))); /* Succeed if zero size. */ R_SUCCEED_IF(size == 0); /* Validate arguments. */ R_UNLESS(buffer != nullptr, fs::ResultNullptrArgument()); /* Validate the offset. */ s64 data_size; R_TRY(m_data_storage.GetSize(std::addressof(data_size))); R_UNLESS(offset <= data_size, fs::ResultInvalidOffset()); /* Validate the access range. */ R_TRY(IStorage::CheckAccessRange(offset, size, util::AlignUp(data_size, static_cast<size_t>(m_verification_block_size)))); /* Determine the read extents. */ size_t read_size = size; if (static_cast<s64>(offset + read_size) > data_size) { /* Determine the padding sizes. */ s64 padding_offset = data_size - offset; size_t padding_size = static_cast<size_t>(m_verification_block_size - (padding_offset & (m_verification_block_size - 1))); AMS_ASSERT(static_cast<s64>(padding_size) < m_verification_block_size); /* Clear the padding. */ std::memset(static_cast<u8 *>(buffer) + padding_offset, 0, padding_size); /* Set the new in-bounds size. */ read_size = static_cast<size_t>(data_size - offset); } /* Perform the read. */ { auto clear_guard = SCOPE_GUARD { std::memset(buffer, 0, size); }; R_TRY(m_data_storage.Read(offset, buffer, read_size)); clear_guard.Cancel(); } /* Verify the signatures. */ Result verify_hash_result = ResultSuccess(); /* Create hash generator. */ std::unique_ptr<IHash256Generator> generator = nullptr; R_TRY(m_hash_generator_factory->Create(std::addressof(generator))); /* Prepare to validate the signatures. */ const auto signature_count = size >> m_verification_block_order; PooledBuffer signature_buffer(signature_count * sizeof(BlockHash), sizeof(BlockHash)); const auto buffer_count = std::min(signature_count, signature_buffer.GetSize() / sizeof(BlockHash)); size_t verified_count = 0; while (verified_count < signature_count) { /* Read the current signatures. */ const auto cur_count = std::min(buffer_count, signature_count - verified_count); auto cur_result = this->ReadBlockSignature(signature_buffer.GetBuffer(), signature_buffer.GetSize(), offset + (verified_count << m_verification_block_order), cur_count << m_verification_block_order); /* Temporarily increase our priority. */ ScopedThreadPriorityChanger cp(+1, ScopedThreadPriorityChanger::Mode::Relative); /* Loop over each signature we read. */ for (size_t i = 0; i < cur_count && R_SUCCEEDED(cur_result); ++i) { const auto verified_size = (verified_count + i) << m_verification_block_order; u8 *cur_buf = static_cast<u8 *>(buffer) + verified_size; cur_result = this->VerifyHash(cur_buf, reinterpret_cast<BlockHash *>(signature_buffer.GetBuffer()) + i, generator); /* If the data is corrupted, clear the corrupted parts. */ if (fs::ResultIntegrityVerificationStorageCorrupted::Includes(cur_result)) { std::memset(cur_buf, 0, m_verification_block_size); /* Set the result if we should. */ if (!fs::ResultClearedRealDataVerificationFailed::Includes(cur_result) && !m_allow_cleared_blocks) { verify_hash_result = cur_result; } cur_result = ResultSuccess(); } } /* If we failed, clear and return. */ if (R_FAILED(cur_result)) { std::memset(buffer, 0, size); R_THROW(cur_result); } /* Advance. */ verified_count += cur_count; } R_RETURN(verify_hash_result); } Result IntegrityVerificationStorage::Write(s64 offset, const void *buffer, size_t size) { /* Succeed if zero size. */ R_SUCCEED_IF(size == 0); /* Validate arguments. */ R_UNLESS(buffer != nullptr, fs::ResultNullptrArgument()); /* Check the offset/size. */ R_TRY(IStorage::CheckOffsetAndSize(offset, size)); /* Validate the offset. */ s64 data_size; R_TRY(m_data_storage.GetSize(std::addressof(data_size))); R_UNLESS(offset < data_size, fs::ResultInvalidOffset()); /* Validate the access range. */ R_TRY(IStorage::CheckAccessRange(offset, size, util::AlignUp(data_size, static_cast<size_t>(m_verification_block_size)))); /* Validate preconditions. */ AMS_ASSERT(util::IsAligned(offset, m_verification_block_size)); AMS_ASSERT(util::IsAligned(size, m_verification_block_size)); AMS_ASSERT(offset <= data_size); AMS_ASSERT(static_cast<s64>(offset + size) < data_size + m_verification_block_size); /* Validate that if writing past the end, all extra data is zero padding. */ if (static_cast<s64>(offset + size) > data_size) { const u8 *padding_cur = static_cast<const u8 *>(buffer) + data_size - offset; const u8 *padding_end = padding_cur + (offset + size - data_size); while (padding_cur < padding_end) { AMS_ASSERT((*padding_cur) == 0); ++padding_cur; } } /* Determine the unpadded size to write. */ auto write_size = size; if (static_cast<s64>(offset + write_size) > data_size) { write_size = static_cast<size_t>(data_size - offset); R_SUCCEED_IF(write_size == 0); } /* Determine the size we're writing in blocks. */ const auto aligned_write_size = util::AlignUp(write_size, m_verification_block_size); /* Write the updated block signatures. */ Result update_result = ResultSuccess(); size_t updated_count = 0; { const auto signature_count = aligned_write_size >> m_verification_block_order; PooledBuffer signature_buffer(signature_count * sizeof(BlockHash), sizeof(BlockHash)); const auto buffer_count = std::min(signature_count, signature_buffer.GetSize() / sizeof(BlockHash)); /* Create hash generator. */ std::unique_ptr<IHash256Generator> generator = nullptr; R_TRY(m_hash_generator_factory->Create(std::addressof(generator))); while (updated_count < signature_count) { const auto cur_count = std::min(buffer_count, signature_count - updated_count); /* Calculate the hash with temporarily increased priority. */ { ScopedThreadPriorityChanger cp(+1, ScopedThreadPriorityChanger::Mode::Relative); for (size_t i = 0; i < cur_count; ++i) { const auto updated_size = (updated_count + i) << m_verification_block_order; this->CalcBlockHash(reinterpret_cast<BlockHash *>(signature_buffer.GetBuffer()) + i, reinterpret_cast<const u8 *>(buffer) + updated_size, generator); } } /* Write the new block signatures. */ if (R_FAILED((update_result = this->WriteBlockSignature(signature_buffer.GetBuffer(), signature_buffer.GetSize(), offset + (updated_count << m_verification_block_order), cur_count << m_verification_block_order)))) { break; } /* Advance. */ updated_count += cur_count; } } /* Write the data. */ R_TRY(m_data_storage.Write(offset, buffer, std::min(write_size, updated_count << m_verification_block_order))); R_RETURN(update_result); } Result IntegrityVerificationStorage::GetSize(s64 *out) { R_RETURN(m_data_storage.GetSize(out)); } Result IntegrityVerificationStorage::Flush() { /* Flush both storages. */ R_TRY(m_hash_storage.Flush()); R_TRY(m_data_storage.Flush()); R_SUCCEED(); } Result IntegrityVerificationStorage::OperateRange(void *dst, size_t dst_size, fs::OperationId op_id, s64 offset, s64 size, const void *src, size_t src_size) { /* Validate preconditions. */ if (op_id != fs::OperationId::Invalidate) { AMS_ASSERT(util::IsAligned(offset, static_cast<size_t>(m_verification_block_size))); AMS_ASSERT(util::IsAligned(size, static_cast<size_t>(m_verification_block_size))); } switch (op_id) { case fs::OperationId::FillZero: { /* FillZero should only be called for writable storages. */ AMS_ASSERT(m_is_writable); /* Validate the range. */ s64 data_size = 0; R_TRY(m_data_storage.GetSize(std::addressof(data_size))); R_UNLESS(0 <= offset && offset <= data_size, fs::ResultInvalidOffset()); /* Determine the extents to clear. */ const auto sign_offset = (offset >> m_verification_block_order) * HashSize; const auto sign_size = (std::min(size, data_size - offset) >> m_verification_block_order) * HashSize; /* Allocate a work buffer. */ const auto buf_size = static_cast<size_t>(std::min(sign_size, static_cast<s64>(1) << (m_upper_layer_verification_block_order + 2))); std::unique_ptr<char[], fs::impl::Deleter> buf = fs::impl::MakeUnique<char[]>(buf_size); R_UNLESS(buf != nullptr, fs::ResultAllocationMemoryFailedInIntegrityVerificationStorageA()); /* Clear the work buffer. */ std::memset(buf.get(), 0, buf_size); /* Clear in chunks. */ auto remaining_size = sign_size; while (remaining_size > 0) { const auto cur_size = static_cast<size_t>(std::min(remaining_size, static_cast<s64>(buf_size))); R_TRY(m_hash_storage.Write(sign_offset + sign_size - remaining_size, buf.get(), cur_size)); remaining_size -= cur_size; } R_SUCCEED(); } case fs::OperationId::DestroySignature: { /* DestroySignature should only be called for save data. */ AMS_ASSERT(m_is_writable); /* Validate the range. */ s64 data_size = 0; R_TRY(m_data_storage.GetSize(std::addressof(data_size))); R_UNLESS(0 <= offset && offset <= data_size, fs::ResultInvalidOffset()); /* Determine the extents to clear the signature for. */ const auto sign_offset = (offset >> m_verification_block_order) * HashSize; const auto sign_size = (std::min(size, data_size - offset) >> m_verification_block_order) * HashSize; /* Allocate a work buffer. */ std::unique_ptr<char[], fs::impl::Deleter> buf = fs::impl::MakeUnique<char[]>(sign_size); R_UNLESS(buf != nullptr, fs::ResultAllocationMemoryFailedInIntegrityVerificationStorageB()); /* Read the existing signature. */ R_TRY(m_hash_storage.Read(sign_offset, buf.get(), sign_size)); /* Clear the signature. */ /* This flips all bits other than the verification bit. */ for (auto i = 0; i < sign_size; ++i) { buf[i] ^= ((i + 1) % HashSize == 0 ? 0x7F : 0xFF); } /* Write the cleared signature. */ R_RETURN(m_hash_storage.Write(sign_offset, buf.get(), sign_size)); } case fs::OperationId::Invalidate: { /* Only allow cache invalidation read-only storages. */ R_UNLESS(!m_is_writable, fs::ResultUnsupportedOperateRangeForWritableIntegrityVerificationStorage()); /* Operate on our storages. */ R_TRY(m_hash_storage.OperateRange(op_id, 0, std::numeric_limits<s64>::max())); R_TRY(m_data_storage.OperateRange(op_id, offset, size)); R_SUCCEED(); } case fs::OperationId::QueryRange: { /* Validate the range. */ s64 data_size = 0; R_TRY(m_data_storage.GetSize(std::addressof(data_size))); R_UNLESS(0 <= offset && offset <= data_size, fs::ResultInvalidOffset()); /* Determine the real size to query. */ const auto actual_size = std::min(size, data_size - offset); /* Query the data storage. */ R_RETURN(m_data_storage.OperateRange(dst, dst_size, op_id, offset, actual_size, src, src_size)); } default: R_THROW(fs::ResultUnsupportedOperateRangeForIntegrityVerificationStorage()); } } void IntegrityVerificationStorage::CalcBlockHash(BlockHash *out, const void *buffer, size_t block_size, std::unique_ptr<fssystem::IHash256Generator> &generator) const { /* Hash procedure depends on whether or not we're writable. */ if (m_is_writable) { /* Compute the hash with or without the hash salt, if we have one. */ if (m_salt.has_value()) { /* Initialize the generator. */ generator->Initialize(); /* Hash the salt. */ generator->Update(m_salt->value, sizeof(m_salt->value)); /* Update with the buffer and get the hash. */ generator->Update(buffer, block_size); generator->GetHash(out, sizeof(*out)); } else { /* If we have no hash salt, just calculate the hash. */ m_hash_generator_factory->GenerateHash(out, sizeof(*out), buffer, block_size); } /* Set the validation bit. */ SetValidationBit(out); } else { /* If we're not writable, just calculate the hash. */ m_hash_generator_factory->GenerateHash(out, sizeof(*out), buffer, block_size); } } Result IntegrityVerificationStorage::ReadBlockSignature(void *dst, size_t dst_size, s64 offset, size_t size) { /* Validate preconditions. */ AMS_ASSERT(dst != nullptr); AMS_ASSERT(util::IsAligned(offset, static_cast<size_t>(m_verification_block_size))); AMS_ASSERT(util::IsAligned(size, static_cast<size_t>(m_verification_block_size))); /* Determine where to read the signature. */ const s64 sign_offset = (offset >> m_verification_block_order) * HashSize; const auto sign_size = static_cast<size_t>((size >> m_verification_block_order) * HashSize); AMS_ASSERT(dst_size >= sign_size); AMS_UNUSED(dst_size); /* Create a guard in the event of failure. */ auto clear_guard = SCOPE_GUARD { std::memset(dst, 0, sign_size); }; /* Validate that we can read the signature. */ s64 hash_size; R_TRY(m_hash_storage.GetSize(std::addressof(hash_size))); const bool range_valid = static_cast<s64>(sign_offset + sign_size) <= hash_size; AMS_ASSERT(range_valid); R_UNLESS(range_valid, fs::ResultOutOfRange()); /* Read the signature. */ R_TRY(m_hash_storage.Read(sign_offset, dst, sign_size)); /* We succeeded. */ clear_guard.Cancel(); R_SUCCEED(); } Result IntegrityVerificationStorage::WriteBlockSignature(const void *src, size_t src_size, s64 offset, size_t size) { /* Validate preconditions. */ AMS_ASSERT(src != nullptr); AMS_ASSERT(util::IsAligned(offset, static_cast<size_t>(m_verification_block_size))); /* Determine where to write the signature. */ const s64 sign_offset = (offset >> m_verification_block_order) * HashSize; const auto sign_size = static_cast<size_t>((size >> m_verification_block_order) * HashSize); AMS_ASSERT(src_size >= sign_size); AMS_UNUSED(src_size); /* Write the signature. */ R_TRY(m_hash_storage.Write(sign_offset, src, sign_size)); /* We succeeded. */ R_SUCCEED(); } Result IntegrityVerificationStorage::VerifyHash(const void *buf, BlockHash *hash, std::unique_ptr<fssystem::IHash256Generator> &generator) { /* Validate preconditions. */ AMS_ASSERT(buf != nullptr); AMS_ASSERT(hash != nullptr); /* Get the comparison hash. */ auto &cmp_hash = *hash; /* If writable, check if the data is uninitialized. */ if (m_is_writable) { bool is_cleared = false; R_TRY(this->IsCleared(std::addressof(is_cleared), cmp_hash)); R_UNLESS(!is_cleared, fs::ResultClearedRealDataVerificationFailed()); } /* Get the calculated hash. */ BlockHash calc_hash; this->CalcBlockHash(std::addressof(calc_hash), buf, generator); /* Check that the signatures are equal. */ if (!crypto::IsSameBytes(std::addressof(cmp_hash), std::addressof(calc_hash), sizeof(BlockHash))) { /* Clear the comparison hash. */ std::memset(std::addressof(cmp_hash), 0, sizeof(cmp_hash)); /* Return the appropriate result. */ if (m_is_real_data) { R_THROW(fs::ResultUnclearedRealDataVerificationFailed()); } else { R_THROW(fs::ResultNonRealDataVerificationFailed()); } } R_SUCCEED(); } Result IntegrityVerificationStorage::IsCleared(bool *is_cleared, const BlockHash &hash) { /* Validate preconditions. */ AMS_ASSERT(is_cleared != nullptr); AMS_ASSERT(m_is_writable); /* Default to uncleared. */ *is_cleared = false; /* Succeed if the validation bit is set. */ R_SUCCEED_IF(IsValidationBit(std::addressof(hash))); /* Otherwise, we expect the hash to be all zero. */ for (size_t i = 0; i < sizeof(hash.hash); ++i) { R_UNLESS(hash.hash[i] == 0, fs::ResultInvalidZeroHash()); } /* Set cleared. */ *is_cleared = true; R_SUCCEED(); } }
22,209
C++
.cpp
399
43.295739
316
0.585932
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,349
fssystem_thread_priority_changer.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssystem/fssystem_thread_priority_changer.cpp
/* * Copyright (c) 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 { s32 ScopedThreadPriorityChangerByAccessPriority::GetThreadPriorityByAccessPriority(AccessMode mode) { /* TODO: Actually implement this for real. */ AMS_UNUSED(mode); return os::GetThreadPriority(os::GetCurrentThread()); } }
948
C++
.cpp
23
38.086957
105
0.750542
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,350
fssystem_nca_file_system_driver.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssystem/fssystem_nca_file_system_driver.cpp
/* * Copyright (c) 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 "fssystem_read_only_block_cache_storage.hpp" #include "fssystem_hierarchical_sha256_storage.hpp" #include "fssystem_memory_resource_buffer_hold_storage.hpp" namespace ams::fssystem { namespace { constexpr inline s32 AesCtrExTableCacheBlockSize = AesCtrCounterExtendedStorage::NodeSize; constexpr inline s32 AesCtrExTableCacheCount = 8; constexpr inline s32 IndirectTableCacheBlockSize = IndirectStorage::NodeSize; constexpr inline s32 IndirectTableCacheCount = 8; constexpr inline s32 IndirectDataCacheBlockSize = 32_KB; constexpr inline s32 IndirectDataCacheCount = 16; constexpr inline s32 SparseTableCacheBlockSize = SparseStorage::NodeSize; constexpr inline s32 SparseTableCacheCount = 4; constexpr inline s32 IntegrityDataCacheCount = 24; constexpr inline s32 IntegrityHashCacheCount = 8; constexpr inline s32 IntegrityDataCacheCountForMeta = 16; constexpr inline s32 IntegrityHashCacheCountForMeta = 2; //TODO: Better names for these? //constexpr inline s32 CompressedDataBlockSize = 64_KB; //constexpr inline s32 CompressedContinuousReadingSizeMax = 640_KB; //constexpr inline s32 CompressedCacheBlockSize = 16_KB; //constexpr inline s32 CompressedCacheCount = 32; constexpr inline s32 AesCtrStorageCacheBlockSize = 0x200; constexpr inline s32 AesCtrStorageCacheCount = 9; class SharedNcaBodyStorage : public ::ams::fs::IStorage, public ::ams::fs::impl::Newable { NON_COPYABLE(SharedNcaBodyStorage); NON_MOVEABLE(SharedNcaBodyStorage); private: std::shared_ptr<fs::IStorage> m_storage; std::shared_ptr<fssystem::NcaReader> m_nca_reader; public: SharedNcaBodyStorage(std::shared_ptr<fs::IStorage> s, std::shared_ptr<fssystem::NcaReader> r) : m_storage(std::move(s)), m_nca_reader(std::move(r)) { /* ... */ } virtual Result Read(s64 offset, void *buffer, size_t size) override { /* Validate pre-conditions. */ AMS_ASSERT(m_storage != nullptr); /* Read from the base storage. */ R_RETURN(m_storage->Read(offset, buffer, size)); } virtual Result GetSize(s64 *out) override { /* Validate pre-conditions. */ AMS_ASSERT(m_storage != nullptr); R_RETURN(m_storage->GetSize(out)); } virtual Result Flush() override { /* Validate pre-conditions. */ AMS_ASSERT(m_storage != nullptr); R_RETURN(m_storage->Flush()); } virtual Result Write(s64 offset, const void *buffer, size_t size) override { /* Validate pre-conditions. */ AMS_ASSERT(m_storage != nullptr); /* Read from the base storage. */ R_RETURN(m_storage->Write(offset, buffer, size)); } virtual Result SetSize(s64 size) override { /* Validate pre-conditions. */ AMS_ASSERT(m_storage != nullptr); R_RETURN(m_storage->SetSize(size)); } virtual Result OperateRange(void *dst, size_t dst_size, fs::OperationId op_id, s64 offset, s64 size, const void *src, size_t src_size) override { /* Validate pre-conditions. */ AMS_ASSERT(m_storage != nullptr); R_RETURN(m_storage->OperateRange(dst, dst_size, op_id, offset, size, src, src_size)); } }; inline s64 GetFsOffset(const NcaReader &reader, s32 fs_index) { return static_cast<s64>(reader.GetFsOffset(fs_index)); } inline s64 GetFsEndOffset(const NcaReader &reader, s32 fs_index) { return static_cast<s64>(reader.GetFsEndOffset(fs_index)); } inline bool IsUsingHwAesCtrForSpeedEmulation() { auto mode = fssystem::SpeedEmulationConfiguration::GetSpeedEmulationMode(); return mode == fs::SpeedEmulationMode::None || mode == fs::SpeedEmulationMode::Slower; } using Sha256DataRegion = NcaFsHeader::Region; using IntegrityLevelInfo = NcaFsHeader::HashData::IntegrityMetaInfo::LevelHashInfo; using IntegrityDataInfo = IntegrityLevelInfo::HierarchicalIntegrityVerificationLevelInformation; } Result NcaFileSystemDriver::OpenStorageWithContext(std::shared_ptr<fs::IStorage> *out, std::shared_ptr<IAsynchronousAccessSplitter> *out_splitter, NcaFsHeaderReader *out_header_reader, s32 fs_index, StorageContext *ctx) { /* Open storage. */ R_TRY(this->OpenStorageImpl(out, out_header_reader, fs_index, ctx)); /* If we have a compressed storage, use it as splitter. */ if (ctx->compressed_storage != nullptr) { *out_splitter = ctx->compressed_storage; } else { /* Otherwise, allocate a default splitter. */ *out_splitter = fssystem::AllocateShared<DefaultAsynchronousAccessSplitter>(); R_UNLESS(*out_splitter != nullptr, fs::ResultAllocationMemoryFailedAllocateShared()); } R_SUCCEED(); } Result NcaFileSystemDriver::OpenStorageImpl(std::shared_ptr<fs::IStorage> *out, NcaFsHeaderReader *out_header_reader, s32 fs_index, StorageContext *ctx) { /* Validate preconditions. */ AMS_ASSERT(out != nullptr); AMS_ASSERT(out_header_reader != nullptr); AMS_ASSERT(0 <= fs_index && fs_index < NcaHeader::FsCountMax); /* Validate the fs index. */ R_UNLESS(m_reader->HasFsInfo(fs_index), fs::ResultPartitionNotFound()); /* Initialize our header reader for the fs index. */ R_TRY(out_header_reader->Initialize(*m_reader, fs_index)); /* Declare the storage we're opening. */ std::shared_ptr<fs::IStorage> storage; /* Process sparse layer. */ s64 fs_data_offset = 0; if (out_header_reader->ExistsSparseLayer()) { /* Get the sparse info. */ const auto &sparse_info = out_header_reader->GetSparseInfo(); /* Create based on whether we have a meta hash layer. */ if (out_header_reader->ExistsSparseMetaHashLayer()) { /* Create the sparse storage with verification. */ R_TRY(this->CreateSparseStorageWithVerification(std::addressof(storage), std::addressof(fs_data_offset), ctx != nullptr ? std::addressof(ctx->current_sparse_storage) : nullptr, ctx != nullptr ? std::addressof(ctx->sparse_storage_meta_storage) : nullptr, ctx != nullptr ? std::addressof(ctx->sparse_layer_info_storage) : nullptr, fs_index, out_header_reader->GetAesCtrUpperIv(), sparse_info, out_header_reader->GetSparseMetaDataHashDataInfo(), out_header_reader->GetSparseMetaHashType())); } else { /* Create the sparse storage. */ R_TRY(this->CreateSparseStorage(std::addressof(storage), std::addressof(fs_data_offset), ctx != nullptr ? std::addressof(ctx->current_sparse_storage) : nullptr, ctx != nullptr ? std::addressof(ctx->sparse_storage_meta_storage) : nullptr, fs_index, out_header_reader->GetAesCtrUpperIv(), sparse_info)); } } else { /* Get the data offsets. */ fs_data_offset = GetFsOffset(*m_reader, fs_index); const auto fs_end_offset = GetFsEndOffset(*m_reader, fs_index); /* Validate that we're within range. */ const auto data_size = fs_end_offset - fs_data_offset; R_UNLESS(data_size > 0, fs::ResultInvalidNcaHeader()); /* Create the body substorage. */ R_TRY(this->CreateBodySubStorage(std::addressof(storage), fs_data_offset, data_size)); /* Potentially save the body substorage to our context. */ if (ctx != nullptr) { ctx->body_substorage = storage; } } /* Process patch layer. */ const auto &patch_info = out_header_reader->GetPatchInfo(); std::shared_ptr<fs::IStorage> patch_meta_aes_ctr_ex_meta_storage; std::shared_ptr<fs::IStorage> patch_meta_indirect_meta_storage; if (out_header_reader->ExistsPatchMetaHashLayer()) { /* Check the meta hash type. */ R_UNLESS(out_header_reader->GetPatchMetaHashType() == NcaFsHeader::MetaDataHashType::HierarchicalIntegrity, fs::ResultRomNcaInvalidPatchMetaDataHashType()); /* Create the patch meta storage. */ R_TRY(this->CreatePatchMetaStorage(std::addressof(patch_meta_aes_ctr_ex_meta_storage), std::addressof(patch_meta_indirect_meta_storage), ctx != nullptr ? std::addressof(ctx->patch_layer_info_storage) : nullptr, storage, fs_data_offset, out_header_reader->GetAesCtrUpperIv(), patch_info, out_header_reader->GetPatchMetaDataHashDataInfo(), m_hash_generator_factory_selector->GetFactory(fssystem::HashAlgorithmType_Sha2))); } if (patch_info.HasAesCtrExTable()) { /* Check the encryption type. */ AMS_ASSERT(out_header_reader->GetEncryptionType() == NcaFsHeader::EncryptionType::None || out_header_reader->GetEncryptionType() == NcaFsHeader::EncryptionType::AesCtrEx || out_header_reader->GetEncryptionType() == NcaFsHeader::EncryptionType::AesCtrExSkipLayerHash); /* Create the ex meta storage. */ std::shared_ptr<fs::IStorage> aes_ctr_ex_storage_meta_storage = patch_meta_aes_ctr_ex_meta_storage; if (aes_ctr_ex_storage_meta_storage == nullptr) { /* If we don't have a meta storage, we must not have a patch meta hash layer. */ AMS_ASSERT(!out_header_reader->ExistsPatchMetaHashLayer()); R_TRY(this->CreateAesCtrExStorageMetaStorage(std::addressof(aes_ctr_ex_storage_meta_storage), storage, fs_data_offset, out_header_reader->GetEncryptionType(), out_header_reader->GetAesCtrUpperIv(), patch_info)); } /* Create the ex storage. */ std::shared_ptr<fs::IStorage> aes_ctr_ex_storage; R_TRY(this->CreateAesCtrExStorage(std::addressof(aes_ctr_ex_storage), ctx != nullptr ? std::addressof(ctx->aes_ctr_ex_storage) : nullptr, std::move(storage), aes_ctr_ex_storage_meta_storage, fs_data_offset, out_header_reader->GetAesCtrUpperIv(), patch_info)); /* Set the base storage as the ex storage. */ storage = std::move(aes_ctr_ex_storage); /* Potentially save storages to our context. */ if (ctx != nullptr) { ctx->aes_ctr_ex_storage_meta_storage = aes_ctr_ex_storage_meta_storage; ctx->aes_ctr_ex_storage_data_storage = storage; ctx->fs_data_storage = storage; } } else { /* Create the appropriate storage for the encryption type. */ switch (out_header_reader->GetEncryptionType()) { case NcaFsHeader::EncryptionType::None: /* If there's no encryption, use the base storage we made previously. */ break; case NcaFsHeader::EncryptionType::AesXts: R_TRY(this->CreateAesXtsStorage(std::addressof(storage), std::move(storage), fs_data_offset)); break; case NcaFsHeader::EncryptionType::AesCtr: R_TRY(this->CreateAesCtrStorage(std::addressof(storage), std::move(storage), fs_data_offset, out_header_reader->GetAesCtrUpperIv(), AlignmentStorageRequirement_None)); break; case NcaFsHeader::EncryptionType::AesCtrSkipLayerHash: { /* Create the aes ctr storage. */ std::shared_ptr<fs::IStorage> aes_ctr_storage; R_TRY(this->CreateAesCtrStorage(std::addressof(aes_ctr_storage), storage, fs_data_offset, out_header_reader->GetAesCtrUpperIv(), AlignmentStorageRequirement_None)); /* Create region switch storage. */ R_TRY(this->CreateRegionSwitchStorage(std::addressof(storage), out_header_reader, std::move(storage), std::move(aes_ctr_storage))); } break; default: R_THROW(fs::ResultInvalidNcaFsHeaderEncryptionType()); } /* Potentially save storages to our context. */ if (ctx != nullptr) { ctx->fs_data_storage = storage; } } /* Process indirect layer. */ if (patch_info.HasIndirectTable()) { /* Create the indirect meta storage. */ std::shared_ptr<fs::IStorage> indirect_storage_meta_storage = patch_meta_indirect_meta_storage; if (indirect_storage_meta_storage == nullptr) { /* If we don't have a meta storage, we must not have a patch meta hash layer. */ AMS_ASSERT(!out_header_reader->ExistsPatchMetaHashLayer()); R_TRY(this->CreateIndirectStorageMetaStorage(std::addressof(indirect_storage_meta_storage), storage, patch_info)); } /* Potentially save the indirect meta storage to our context. */ if (ctx != nullptr) { ctx->indirect_storage_meta_storage = indirect_storage_meta_storage; } /* Get the original indirectable storage. */ std::shared_ptr<fs::IStorage> original_indirectable_storage; if (m_original_reader != nullptr && m_original_reader->HasFsInfo(fs_index)) { /* Create a driver for the original. */ NcaFileSystemDriver original_driver(m_original_reader, m_allocator, m_buffer_manager, m_hash_generator_factory_selector); /* Create a header reader for the original. */ NcaFsHeaderReader original_header_reader; R_TRY(original_header_reader.Initialize(*m_original_reader, fs_index)); /* Open original indirectable storage. */ R_TRY(original_driver.OpenIndirectableStorageAsOriginal(std::addressof(original_indirectable_storage), std::addressof(original_header_reader), ctx)); } else if (ctx != nullptr && ctx->external_original_storage != nullptr) { /* Use the external original storage. */ original_indirectable_storage = ctx->external_original_storage; } else { /* Allocate a dummy memory storage as original storage. */ original_indirectable_storage = fssystem::AllocateShared<fs::MemoryStorage>(nullptr, 0); R_UNLESS(original_indirectable_storage != nullptr, fs::ResultAllocationMemoryFailedAllocateShared()); } /* Create the indirect storage. */ std::shared_ptr<fs::IStorage> indirect_storage; R_TRY(this->CreateIndirectStorage(std::addressof(indirect_storage), ctx != nullptr ? std::addressof(ctx->indirect_storage) : nullptr, std::move(storage), std::move(original_indirectable_storage), std::move(indirect_storage_meta_storage), patch_info)); /* Set storage as the indirect storage. */ storage = std::move(indirect_storage); } /* Check if we're sparse or requested to skip the integrity layer. */ if (out_header_reader->ExistsSparseLayer() || (ctx != nullptr && ctx->open_raw_storage)) { *out = std::move(storage); R_SUCCEED(); } /* Create the non-raw storage. */ R_RETURN(this->CreateStorageByRawStorage(out, out_header_reader, std::move(storage), ctx)); } Result NcaFileSystemDriver::CreateStorageByRawStorage(std::shared_ptr<fs::IStorage> *out, const NcaFsHeaderReader *header_reader, std::shared_ptr<fs::IStorage> raw_storage, StorageContext *ctx) { /* Initialize storage as raw storage. */ std::shared_ptr<fs::IStorage> storage = std::move(raw_storage); /* Process hash/integrity layer. */ switch (header_reader->GetHashType()) { case NcaFsHeader::HashType::HierarchicalSha256Hash: R_TRY(this->CreateSha256Storage(std::addressof(storage), std::move(storage), header_reader->GetHashData().hierarchical_sha256_data, m_hash_generator_factory_selector->GetFactory(fssystem::HashAlgorithmType_Sha2))); break; case NcaFsHeader::HashType::HierarchicalIntegrityHash: R_TRY(this->CreateIntegrityVerificationStorage(std::addressof(storage), std::move(storage), header_reader->GetHashData().integrity_meta_info, m_hash_generator_factory_selector->GetFactory(fssystem::HashAlgorithmType_Sha2))); break; default: R_THROW(fs::ResultInvalidNcaFsHeaderHashType()); } /* Process compression layer. */ if (header_reader->ExistsCompressionLayer()) { R_TRY(this->CreateCompressedStorage(std::addressof(storage), ctx != nullptr ? std::addressof(ctx->compressed_storage) : nullptr, ctx != nullptr ? std::addressof(ctx->compressed_storage_meta_storage) : nullptr, std::move(storage), header_reader->GetCompressionInfo())); } /* Set output storage. */ *out = std::move(storage); R_SUCCEED(); } Result NcaFileSystemDriver::OpenIndirectableStorageAsOriginal(std::shared_ptr<fs::IStorage> *out, const NcaFsHeaderReader *header_reader, StorageContext *ctx) { /* Get the fs index. */ const auto fs_index = header_reader->GetFsIndex(); /* Declare the storage we're opening. */ std::shared_ptr<fs::IStorage> storage; /* Process sparse layer. */ s64 fs_data_offset = 0; if (header_reader->ExistsSparseLayer()) { /* Get the sparse info. */ const auto &sparse_info = header_reader->GetSparseInfo(); /* Create based on whether we have a meta hash layer. */ if (header_reader->ExistsSparseMetaHashLayer()) { /* Create the sparse storage with verification. */ R_TRY(this->CreateSparseStorageWithVerification(std::addressof(storage), std::addressof(fs_data_offset), ctx != nullptr ? std::addressof(ctx->original_sparse_storage) : nullptr, ctx != nullptr ? std::addressof(ctx->sparse_storage_meta_storage) : nullptr, ctx != nullptr ? std::addressof(ctx->sparse_layer_info_storage) : nullptr, fs_index, header_reader->GetAesCtrUpperIv(), sparse_info, header_reader->GetSparseMetaDataHashDataInfo(), header_reader->GetSparseMetaHashType())); } else { /* Create the sparse storage. */ R_TRY(this->CreateSparseStorage(std::addressof(storage), std::addressof(fs_data_offset), ctx != nullptr ? std::addressof(ctx->original_sparse_storage) : nullptr, ctx != nullptr ? std::addressof(ctx->sparse_storage_meta_storage) : nullptr, fs_index, header_reader->GetAesCtrUpperIv(), sparse_info)); } } else { /* Get the data offsets. */ fs_data_offset = GetFsOffset(*m_reader, fs_index); const auto fs_end_offset = GetFsEndOffset(*m_reader, fs_index); /* Validate that we're within range. */ const auto data_size = fs_end_offset - fs_data_offset; R_UNLESS(data_size > 0, fs::ResultInvalidNcaHeader()); /* Create the body substorage. */ R_TRY(this->CreateBodySubStorage(std::addressof(storage), fs_data_offset, data_size)); } /* Create the appropriate storage for the encryption type. */ switch (header_reader->GetEncryptionType()) { case NcaFsHeader::EncryptionType::None: /* If there's no encryption, use the base storage we made previously. */ break; case NcaFsHeader::EncryptionType::AesXts: R_TRY(this->CreateAesXtsStorage(std::addressof(storage), std::move(storage), fs_data_offset)); break; case NcaFsHeader::EncryptionType::AesCtr: R_TRY(this->CreateAesCtrStorage(std::addressof(storage), std::move(storage), fs_data_offset, header_reader->GetAesCtrUpperIv(), AlignmentStorageRequirement_CacheBlockSize)); break; default: R_THROW(fs::ResultInvalidNcaFsHeaderEncryptionType()); } /* Set output storage. */ *out = std::move(storage); R_SUCCEED(); } Result NcaFileSystemDriver::CreateBodySubStorage(std::shared_ptr<fs::IStorage> *out, s64 offset, s64 size) { /* Create the body storage. */ auto body_storage = fssystem::AllocateShared<SharedNcaBodyStorage>(m_reader->GetSharedBodyStorage(), m_reader); R_UNLESS(body_storage != nullptr, fs::ResultAllocationMemoryFailedAllocateShared()); /* Get the body storage size. */ s64 body_size = 0; R_TRY(body_storage->GetSize(std::addressof(body_size))); /* Check that we're within range. */ R_UNLESS(offset + size <= body_size, fs::ResultNcaBaseStorageOutOfRangeB()); /* Create substorage. */ auto body_substorage = fssystem::AllocateShared<fs::SubStorage>(std::move(body_storage), offset, size); R_UNLESS(body_substorage != nullptr, fs::ResultAllocationMemoryFailedAllocateShared()); /* Set the output storage. */ *out = std::move(body_substorage); R_SUCCEED(); } Result NcaFileSystemDriver::CreateAesCtrStorage(std::shared_ptr<fs::IStorage> *out, std::shared_ptr<fs::IStorage> base_storage, s64 offset, const NcaAesCtrUpperIv &upper_iv, AlignmentStorageRequirement alignment_storage_requirement) { /* Check pre-conditions. */ AMS_ASSERT(out != nullptr); AMS_ASSERT(base_storage != nullptr); /* Enforce alignment of accesses to base storage. */ switch (alignment_storage_requirement) { case AlignmentStorageRequirement_CacheBlockSize: { /* Get the base storage's size. */ s64 base_size; R_TRY(base_storage->GetSize(std::addressof(base_size))); /* Create buffered storage. */ auto buffered_storage = fssystem::AllocateShared<BufferedStorage>(); R_UNLESS(buffered_storage != nullptr, fs::ResultAllocationMemoryFailedAllocateShared()); /* Initialize the buffered storage. */ R_TRY(buffered_storage->Initialize(fs::SubStorage(std::move(base_storage), 0, base_size), m_buffer_manager, AesCtrStorageCacheBlockSize, AesCtrStorageCacheCount)); /* Enable bulk read in the buffered storage. */ buffered_storage->EnableBulkRead(); /* Use the buffered storage in place of our base storage. */ base_storage = std::move(buffered_storage); } break; case AlignmentStorageRequirement_None: default: /* No alignment enforcing is required. */ break; } /* Create the iv. */ u8 iv[AesCtrStorageBySharedPointer::IvSize] = {}; AesCtrStorageBySharedPointer::MakeIv(iv, sizeof(iv), upper_iv.value, offset); /* Create the ctr storage. */ std::shared_ptr<fs::IStorage> aes_ctr_storage; if (m_reader->HasExternalDecryptionKey()) { aes_ctr_storage = fssystem::AllocateShared<AesCtrStorageExternal>(std::move(base_storage), m_reader->GetExternalDecryptionKey(), AesCtrStorageExternal::KeySize, iv, AesCtrStorageExternal::IvSize, m_reader->GetExternalDecryptAesCtrFunctionForExternalKey(), -1, -1); R_UNLESS(aes_ctr_storage != nullptr, fs::ResultAllocationMemoryFailedAllocateShared()); } else { /* Create software decryption storage. */ auto sw_storage = fssystem::AllocateShared<AesCtrStorageBySharedPointer>(base_storage, m_reader->GetDecryptionKey(NcaHeader::DecryptionKey_AesCtr), AesCtrStorageBySharedPointer::KeySize, iv, AesCtrStorageBySharedPointer::IvSize); R_UNLESS(sw_storage != nullptr, fs::ResultAllocationMemoryFailedAllocateShared()); /* If we have a hardware key and should use it, make the hardware decryption storage. */ if (m_reader->HasInternalDecryptionKeyForAesHw() && !m_reader->IsSoftwareAesPrioritized()) { auto hw_storage = fssystem::AllocateShared<AesCtrStorageExternal>(base_storage, m_reader->GetDecryptionKey(NcaHeader::DecryptionKey_AesCtrHw), AesCtrStorageExternal::KeySize, iv, AesCtrStorageExternal::IvSize, m_reader->GetExternalDecryptAesCtrFunction(), m_reader->GetKeyIndex(), m_reader->GetKeyGeneration()); R_UNLESS(hw_storage != nullptr, fs::ResultAllocationMemoryFailedAllocateShared()); /* Create the selection storage. */ auto switch_storage = fssystem::AllocateShared<SwitchStorage<bool (*)()>>(std::move(hw_storage), std::move(sw_storage), IsUsingHwAesCtrForSpeedEmulation); R_UNLESS(switch_storage != nullptr, fs::ResultAllocationMemoryFailedAllocateShared()); /* Use the selection storage. */ aes_ctr_storage = std::move(switch_storage); } else { /* Otherwise, just use the software decryption storage. */ aes_ctr_storage = std::move(sw_storage); } } /* Create alignment matching storage. */ auto aligned_storage = fssystem::AllocateShared<AlignmentMatchingStorage<NcaHeader::CtrBlockSize, 1>>(std::move(aes_ctr_storage)); R_UNLESS(aligned_storage != nullptr, fs::ResultAllocationMemoryFailedAllocateShared()); /* Set the out storage. */ *out = std::move(aligned_storage); R_SUCCEED(); } Result NcaFileSystemDriver::CreateAesXtsStorage(std::shared_ptr<fs::IStorage> *out, std::shared_ptr<fs::IStorage> base_storage, s64 offset) { /* Check pre-conditions. */ AMS_ASSERT(out != nullptr); AMS_ASSERT(base_storage != nullptr); /* Create the iv. */ u8 iv[AesXtsStorageBySharedPointer::IvSize] = {}; AesXtsStorageBySharedPointer::MakeAesXtsIv(iv, sizeof(iv), offset, NcaHeader::XtsBlockSize); /* Make the aes xts storage. */ const auto * const key1 = m_reader->GetDecryptionKey(NcaHeader::DecryptionKey_AesXts1); const auto * const key2 = m_reader->GetDecryptionKey(NcaHeader::DecryptionKey_AesXts2); auto xts_storage = fssystem::AllocateShared<AesXtsStorageBySharedPointer>(std::move(base_storage), key1, key2, AesXtsStorageBySharedPointer::KeySize, iv, AesXtsStorageBySharedPointer::IvSize, NcaHeader::XtsBlockSize); R_UNLESS(xts_storage != nullptr, fs::ResultAllocationMemoryFailedAllocateShared()); /* Create alignment matching storage. */ auto aligned_storage = fssystem::AllocateShared<AlignmentMatchingStorage<NcaHeader::XtsBlockSize, 1>>(std::move(xts_storage)); R_UNLESS(aligned_storage != nullptr, fs::ResultAllocationMemoryFailedAllocateShared()); /* Set the out storage. */ *out = std::move(aligned_storage); R_SUCCEED(); } Result NcaFileSystemDriver::CreateSparseStorageMetaStorage(std::shared_ptr<fs::IStorage> *out, std::shared_ptr<fs::IStorage> base_storage, s64 offset, const NcaAesCtrUpperIv &upper_iv, const NcaSparseInfo &sparse_info) { /* Validate preconditions. */ AMS_ASSERT(out != nullptr); AMS_ASSERT(base_storage != nullptr); /* Get the base storage size. */ s64 base_size = 0; R_TRY(base_storage->GetSize(std::addressof(base_size))); /* Get the meta extents. */ const auto meta_offset = sparse_info.bucket.offset; const auto meta_size = sparse_info.bucket.size; R_UNLESS(meta_offset + meta_size - offset <= base_size, fs::ResultNcaBaseStorageOutOfRangeB()); /* Create the encrypted storage. */ auto enc_storage = fssystem::AllocateShared<fs::SubStorage>(std::move(base_storage), meta_offset, meta_size); R_UNLESS(enc_storage != nullptr, fs::ResultAllocationMemoryFailedAllocateShared()); /* Create the decrypted storage. */ std::shared_ptr<fs::IStorage> decrypted_storage; R_TRY(this->CreateAesCtrStorage(std::addressof(decrypted_storage), std::move(enc_storage), offset + meta_offset, sparse_info.MakeAesCtrUpperIv(upper_iv), AlignmentStorageRequirement_None)); /* Create meta storage. */ auto meta_storage = fssystem::AllocateShared<BufferedStorage>(); R_UNLESS(meta_storage != nullptr, fs::ResultAllocationMemoryFailedAllocateShared()); /* Initialize the meta storage. */ R_TRY(meta_storage->Initialize(fs::SubStorage(std::move(decrypted_storage), 0, meta_size), m_buffer_manager, SparseTableCacheBlockSize, SparseTableCacheCount)); /* Set the output. */ *out = std::move(meta_storage); R_SUCCEED(); } Result NcaFileSystemDriver::CreateSparseStorageCore(std::shared_ptr<fssystem::SparseStorage> *out, std::shared_ptr<fs::IStorage> base_storage, s64 base_size, std::shared_ptr<fs::IStorage> meta_storage, const NcaSparseInfo &sparse_info, bool external_info) { /* Validate preconditions. */ AMS_ASSERT(out != nullptr); AMS_ASSERT(base_storage != nullptr); AMS_ASSERT(meta_storage != nullptr); /* Read and verify the bucket tree header. */ BucketTree::Header header; std::memcpy(std::addressof(header), sparse_info.bucket.header, sizeof(header)); R_TRY(header.Verify()); /* Determine storage extents. */ const auto node_offset = 0; const auto node_size = SparseStorage::QueryNodeStorageSize(header.entry_count); const auto entry_offset = node_offset + node_size; const auto entry_size = SparseStorage::QueryEntryStorageSize(header.entry_count); /* Create the sparse storage. */ auto sparse_storage = fssystem::AllocateShared<fssystem::SparseStorage>(); R_UNLESS(sparse_storage != nullptr, fs::ResultAllocationMemoryFailedAllocateShared()); /* Sanity check that we can be doing this. */ AMS_ASSERT(header.entry_count != 0); /* Initialize the sparse storage. */ R_TRY(sparse_storage->Initialize(m_allocator, fs::SubStorage(meta_storage, node_offset, node_size), fs::SubStorage(meta_storage, entry_offset, entry_size), header.entry_count)); /* If not external, set the data storage. */ if (!external_info) { sparse_storage->SetDataStorage(fs::SubStorage(std::move(base_storage), 0, base_size)); } /* Set the output. */ *out = std::move(sparse_storage); R_SUCCEED(); } Result NcaFileSystemDriver::CreateSparseStorage(std::shared_ptr<fs::IStorage> *out, s64 *out_fs_data_offset, std::shared_ptr<fssystem::SparseStorage> *out_sparse_storage, std::shared_ptr<fs::IStorage> *out_meta_storage, s32 index, const NcaAesCtrUpperIv &upper_iv, const NcaSparseInfo &sparse_info) { /* Validate preconditions. */ AMS_ASSERT(out != nullptr); AMS_ASSERT(out_fs_data_offset != nullptr); /* Check the sparse info generation. */ R_UNLESS(sparse_info.generation != 0, fs::ResultInvalidNcaHeader()); /* Read and verify the bucket tree header. */ BucketTree::Header header; std::memcpy(std::addressof(header), sparse_info.bucket.header, sizeof(header)); R_TRY(header.Verify()); /* Determine the storage extents. */ const auto fs_offset = GetFsOffset(*m_reader, index); const auto fs_end_offset = GetFsEndOffset(*m_reader, index); const auto fs_size = fs_end_offset - fs_offset; /* Create the sparse storage. */ std::shared_ptr<fssystem::SparseStorage> sparse_storage; if (header.entry_count != 0) { /* Create the body substorage. */ std::shared_ptr<fs::IStorage> body_substorage; R_TRY(this->CreateBodySubStorage(std::addressof(body_substorage), sparse_info.physical_offset, sparse_info.GetPhysicalSize())); /* Create the meta storage. */ std::shared_ptr<fs::IStorage> meta_storage; R_TRY(this->CreateSparseStorageMetaStorage(std::addressof(meta_storage), body_substorage, sparse_info.physical_offset, upper_iv, sparse_info)); /* Potentially set the output meta storage. */ if (out_meta_storage != nullptr) { *out_meta_storage = meta_storage; } /* Create the sparse storage. */ R_TRY(this->CreateSparseStorageCore(std::addressof(sparse_storage), body_substorage, sparse_info.GetPhysicalSize(), std::move(meta_storage), sparse_info, false)); } else { /* If there are no entries, there's nothing to actually do. */ sparse_storage = fssystem::AllocateShared<fssystem::SparseStorage>(); R_UNLESS(sparse_storage != nullptr, fs::ResultAllocationMemoryFailedAllocateShared()); sparse_storage->Initialize(fs_size); } /* Potentially set the output sparse storage. */ if (out_sparse_storage != nullptr) { *out_sparse_storage = sparse_storage; } /* Set the output fs data offset. */ *out_fs_data_offset = fs_offset; /* Set the output storage. */ *out = std::move(sparse_storage); R_SUCCEED(); } Result NcaFileSystemDriver::CreateSparseStorageMetaStorageWithVerification(std::shared_ptr<fs::IStorage> *out, std::shared_ptr<fs::IStorage> *out_layer_info_storage, std::shared_ptr<fs::IStorage> base_storage, s64 offset, const NcaAesCtrUpperIv &upper_iv, const NcaSparseInfo &sparse_info, const NcaMetaDataHashDataInfo &meta_data_hash_data_info, IHash256GeneratorFactory *hgf) { /* Validate preconditions. */ AMS_ASSERT(out != nullptr); AMS_ASSERT(base_storage != nullptr); AMS_ASSERT(hgf != nullptr); /* Get the base storage size. */ s64 base_size = 0; R_TRY(base_storage->GetSize(std::addressof(base_size))); /* Get the meta extents. */ const auto meta_offset = sparse_info.bucket.offset; const auto meta_size = sparse_info.bucket.size; R_UNLESS(meta_offset + meta_size - offset <= base_size, fs::ResultNcaBaseStorageOutOfRangeB()); /* Get the meta data hash data extents. */ const s64 meta_data_hash_data_offset = meta_data_hash_data_info.offset; const s64 meta_data_hash_data_size = util::AlignUp<s64>(meta_data_hash_data_info.size, NcaHeader::CtrBlockSize); R_UNLESS(meta_data_hash_data_offset + meta_data_hash_data_size <= base_size, fs::ResultNcaBaseStorageOutOfRangeB()); /* Check that the meta is before the hash data. */ R_UNLESS(meta_offset + meta_size <= meta_data_hash_data_offset, fs::ResultRomNcaInvalidSparseMetaDataHashDataOffset()); /* Check that offsets are appropriately aligned. */ R_UNLESS(util::IsAligned<s64>(meta_data_hash_data_offset, NcaHeader::CtrBlockSize), fs::ResultRomNcaInvalidSparseMetaDataHashDataOffset()); R_UNLESS(util::IsAligned<s64>(meta_offset, NcaHeader::CtrBlockSize), fs::ResultInvalidNcaFsHeader()); /* Create the meta storage. */ auto enc_storage = fssystem::AllocateShared<fs::SubStorage>(std::move(base_storage), meta_offset, meta_data_hash_data_offset + meta_data_hash_data_size - meta_offset); R_UNLESS(enc_storage != nullptr, fs::ResultAllocationMemoryFailedAllocateShared()); /* Create the decrypted storage. */ std::shared_ptr<fs::IStorage> decrypted_storage; R_TRY(this->CreateAesCtrStorage(std::addressof(decrypted_storage), std::move(enc_storage), offset + meta_offset, sparse_info.MakeAesCtrUpperIv(upper_iv), AlignmentStorageRequirement_None)); /* Create the verification storage. */ std::shared_ptr<fs::IStorage> integrity_storage; R_TRY_CATCH(this->CreateIntegrityVerificationStorageForMeta(std::addressof(integrity_storage), out_layer_info_storage, std::move(decrypted_storage), meta_offset, meta_data_hash_data_info, hgf)) { R_CONVERT(fs::ResultInvalidNcaMetaDataHashDataSize, fs::ResultRomNcaInvalidSparseMetaDataHashDataSize()) R_CONVERT(fs::ResultInvalidNcaMetaDataHashDataHash, fs::ResultRomNcaInvalidSparseMetaDataHashDataHash()) } R_END_TRY_CATCH; /* Create the meta storage. */ auto meta_storage = fssystem::AllocateShared<fs::SubStorage>(std::move(integrity_storage), 0, meta_size); R_UNLESS(meta_storage != nullptr, fs::ResultAllocationMemoryFailedAllocateShared()); /* Set the output. */ *out = std::move(meta_storage); R_SUCCEED(); } Result NcaFileSystemDriver::CreateSparseStorageWithVerification(std::shared_ptr<fs::IStorage> *out, s64 *out_fs_data_offset, std::shared_ptr<fssystem::SparseStorage> *out_sparse_storage, std::shared_ptr<fs::IStorage> *out_meta_storage, std::shared_ptr<fs::IStorage> *out_layer_info_storage, s32 index, const NcaAesCtrUpperIv &upper_iv, const NcaSparseInfo &sparse_info, const NcaMetaDataHashDataInfo &meta_data_hash_data_info, NcaFsHeader::MetaDataHashType meta_data_hash_type) { /* Validate preconditions. */ AMS_ASSERT(out != nullptr); AMS_ASSERT(out_fs_data_offset != nullptr); /* Check the sparse info generation. */ R_UNLESS(sparse_info.generation != 0, fs::ResultInvalidNcaHeader()); /* Read and verify the bucket tree header. */ BucketTree::Header header; std::memcpy(std::addressof(header), sparse_info.bucket.header, sizeof(header)); R_TRY(header.Verify()); /* Determine the storage extents. */ const auto fs_offset = GetFsOffset(*m_reader, index); const auto fs_end_offset = GetFsEndOffset(*m_reader, index); const auto fs_size = fs_end_offset - fs_offset; /* Create the sparse storage. */ std::shared_ptr<fssystem::SparseStorage> sparse_storage; if (header.entry_count != 0) { /* Create the body substorage. */ std::shared_ptr<fs::IStorage> body_substorage; R_TRY(this->CreateBodySubStorage(std::addressof(body_substorage), sparse_info.physical_offset, util::AlignUp<s64>(static_cast<s64>(meta_data_hash_data_info.offset) + static_cast<s64>(meta_data_hash_data_info.size), NcaHeader::CtrBlockSize))); /* Check the meta data hash type. */ R_UNLESS(meta_data_hash_type == NcaFsHeader::MetaDataHashType::HierarchicalIntegrity, fs::ResultRomNcaInvalidSparseMetaDataHashType()); /* Create the meta storage. */ std::shared_ptr<fs::IStorage> meta_storage; R_TRY(this->CreateSparseStorageMetaStorageWithVerification(std::addressof(meta_storage), out_layer_info_storage, body_substorage, sparse_info.physical_offset, upper_iv, sparse_info, meta_data_hash_data_info, m_hash_generator_factory_selector->GetFactory(fssystem::HashAlgorithmType_Sha2))); /* Potentially set the output meta storage. */ if (out_meta_storage != nullptr) { *out_meta_storage = meta_storage; } /* Create the sparse storage. */ R_TRY(this->CreateSparseStorageCore(std::addressof(sparse_storage), body_substorage, sparse_info.GetPhysicalSize(), std::move(meta_storage), sparse_info, false)); } else { /* If there are no entries, there's nothing to actually do. */ sparse_storage = fssystem::AllocateShared<fssystem::SparseStorage>(); R_UNLESS(sparse_storage != nullptr, fs::ResultAllocationMemoryFailedAllocateShared()); sparse_storage->Initialize(fs_size); } /* Potentially set the output sparse storage. */ if (out_sparse_storage != nullptr) { *out_sparse_storage = sparse_storage; } /* Set the output fs data offset. */ *out_fs_data_offset = fs_offset; /* Set the output storage. */ *out = std::move(sparse_storage); R_SUCCEED(); } Result NcaFileSystemDriver::CreateAesCtrExStorageMetaStorage(std::shared_ptr<fs::IStorage> *out, std::shared_ptr<fs::IStorage> base_storage, s64 offset, NcaFsHeader::EncryptionType encryption_type, const NcaAesCtrUpperIv &upper_iv, const NcaPatchInfo &patch_info) { /* Validate preconditions. */ AMS_ASSERT(out != nullptr); AMS_ASSERT(base_storage != nullptr); AMS_ASSERT(encryption_type == NcaFsHeader::EncryptionType::None || encryption_type == NcaFsHeader::EncryptionType::AesCtrEx || encryption_type == NcaFsHeader::EncryptionType::AesCtrExSkipLayerHash); AMS_ASSERT(patch_info.HasAesCtrExTable()); /* Validate patch info extents. */ R_UNLESS(patch_info.indirect_size > 0, fs::ResultInvalidNcaPatchInfoIndirectSize()); R_UNLESS(patch_info.aes_ctr_ex_size > 0, fs::ResultInvalidNcaPatchInfoAesCtrExSize()); R_UNLESS(patch_info.indirect_size + patch_info.indirect_offset <= patch_info.aes_ctr_ex_offset, fs::ResultInvalidNcaPatchInfoAesCtrExOffset()); /* Get the base storage size. */ s64 base_size; R_TRY(base_storage->GetSize(std::addressof(base_size))); /* Get and validate the meta extents. */ const s64 meta_offset = patch_info.aes_ctr_ex_offset; const s64 meta_size = util::AlignUp(static_cast<s64>(patch_info.aes_ctr_ex_size), NcaHeader::XtsBlockSize); R_UNLESS(meta_offset + meta_size <= base_size, fs::ResultNcaBaseStorageOutOfRangeB()); /* Create the encrypted storage. */ auto enc_storage = fssystem::AllocateShared<fs::SubStorage>(std::move(base_storage), meta_offset, meta_size); R_UNLESS(enc_storage != nullptr, fs::ResultAllocationMemoryFailedAllocateShared()); /* Create the decrypted storage. */ std::shared_ptr<fs::IStorage> decrypted_storage; if (encryption_type != NcaFsHeader::EncryptionType::None) { R_TRY(this->CreateAesCtrStorage(std::addressof(decrypted_storage), std::move(enc_storage), offset + meta_offset, upper_iv, AlignmentStorageRequirement_None)); } else { /* If encryption type is none, don't do any decryption. */ decrypted_storage = std::move(enc_storage); } /* Create meta storage. */ auto meta_storage = fssystem::AllocateShared<BufferedStorage>(); R_UNLESS(meta_storage != nullptr, fs::ResultAllocationMemoryFailedAllocateShared()); /* Initialize the meta storage. */ R_TRY(meta_storage->Initialize(fs::SubStorage(std::move(decrypted_storage), 0, meta_size), m_buffer_manager, AesCtrExTableCacheBlockSize, AesCtrExTableCacheCount)); /* Create an alignment-matching storage. */ using AlignedStorage = AlignmentMatchingStorage<NcaHeader::CtrBlockSize, 1>; auto aligned_storage = fssystem::AllocateShared<AlignedStorage>(std::move(meta_storage)); R_UNLESS(aligned_storage != nullptr, fs::ResultAllocationMemoryFailedAllocateShared()); /* Set the output. */ *out = std::move(aligned_storage); R_SUCCEED(); } Result NcaFileSystemDriver::CreateAesCtrExStorage(std::shared_ptr<fs::IStorage> *out, std::shared_ptr<fssystem::AesCtrCounterExtendedStorage> *out_ext, std::shared_ptr<fs::IStorage> base_storage, std::shared_ptr<fs::IStorage> meta_storage, s64 counter_offset, const NcaAesCtrUpperIv &upper_iv, const NcaPatchInfo &patch_info) { /* Validate pre-conditions. */ AMS_ASSERT(out != nullptr); AMS_ASSERT(base_storage != nullptr); AMS_ASSERT(meta_storage != nullptr); AMS_ASSERT(patch_info.HasAesCtrExTable()); /* Read the bucket tree header. */ BucketTree::Header header; std::memcpy(std::addressof(header), patch_info.aes_ctr_ex_header, sizeof(header)); R_TRY(header.Verify()); /* Determine the bucket extents. */ const auto entry_count = header.entry_count; const s64 data_offset = 0; const s64 data_size = patch_info.aes_ctr_ex_offset; const s64 node_offset = 0; const s64 node_size = AesCtrCounterExtendedStorage::QueryNodeStorageSize(entry_count); const s64 entry_offset = node_offset + node_size; const s64 entry_size = AesCtrCounterExtendedStorage::QueryEntryStorageSize(entry_count); /* Create bucket storages. */ fs::SubStorage data_storage(std::move(base_storage), data_offset, data_size); fs::SubStorage node_storage(meta_storage, node_offset, node_size); fs::SubStorage entry_storage(meta_storage, entry_offset, entry_size); /* Get the secure value. */ const auto secure_value = upper_iv.part.secure_value; /* Create the aes ctr ex storage. */ std::shared_ptr<fs::IStorage> aes_ctr_ex_storage; if (m_reader->HasExternalDecryptionKey()) { /* Create the decryptor. */ std::unique_ptr<AesCtrCounterExtendedStorage::IDecryptor> decryptor; R_TRY(AesCtrCounterExtendedStorage::CreateExternalDecryptor(std::addressof(decryptor), m_reader->GetExternalDecryptAesCtrFunctionForExternalKey(), -1, -1)); /* Create the aes ctr ex storage. */ auto impl_storage = fssystem::AllocateShared<AesCtrCounterExtendedStorage>(); R_UNLESS(impl_storage != nullptr, fs::ResultAllocationMemoryFailedAllocateShared()); /* Initialize the aes ctr ex storage. */ R_TRY(impl_storage->Initialize(m_allocator, m_reader->GetExternalDecryptionKey(), AesCtrStorageBySharedPointer::KeySize, secure_value, counter_offset, data_storage, node_storage, entry_storage, entry_count, std::move(decryptor))); /* Potentially set the output implementation storage. */ if (out_ext != nullptr) { *out_ext = impl_storage; } /* Set the implementation storage. */ aes_ctr_ex_storage = std::move(impl_storage); } else { /* Create the software decryptor. */ std::unique_ptr<AesCtrCounterExtendedStorage::IDecryptor> sw_decryptor; R_TRY(AesCtrCounterExtendedStorage::CreateSoftwareDecryptor(std::addressof(sw_decryptor))); /* Make the software storage. */ auto sw_storage = fssystem::AllocateShared<AesCtrCounterExtendedStorage>(); R_UNLESS(sw_storage != nullptr, fs::ResultAllocationMemoryFailedAllocateShared()); /* Initialize the software storage. */ R_TRY(sw_storage->Initialize(m_allocator, m_reader->GetDecryptionKey(NcaHeader::DecryptionKey_AesCtr), AesCtrStorageBySharedPointer::KeySize, secure_value, counter_offset, data_storage, node_storage, entry_storage, entry_count, std::move(sw_decryptor))); /* Potentially set the output implementation storage. */ if (out_ext != nullptr) { *out_ext = sw_storage; } /* If we have a hardware key and should use it, make the hardware decryption storage. */ if (m_reader->HasInternalDecryptionKeyForAesHw() && !m_reader->IsSoftwareAesPrioritized()) { /* Create the hardware decryptor. */ std::unique_ptr<AesCtrCounterExtendedStorage::IDecryptor> hw_decryptor; R_TRY(AesCtrCounterExtendedStorage::CreateExternalDecryptor(std::addressof(hw_decryptor), m_reader->GetExternalDecryptAesCtrFunction(), m_reader->GetKeyIndex(), m_reader->GetKeyGeneration())); /* Create the hardware storage. */ auto hw_storage = fssystem::AllocateShared<AesCtrCounterExtendedStorage>(); R_UNLESS(hw_storage != nullptr, fs::ResultAllocationMemoryFailedAllocateShared()); /* Initialize the hardware storage. */ R_TRY(hw_storage->Initialize(m_allocator, m_reader->GetDecryptionKey(NcaHeader::DecryptionKey_AesCtrHw), AesCtrStorageBySharedPointer::KeySize, secure_value, counter_offset, data_storage, node_storage, entry_storage, entry_count, std::move(hw_decryptor))); /* Create the selection storage. */ auto switch_storage = fssystem::AllocateShared<SwitchStorage<bool (*)()>>(std::move(hw_storage), std::move(sw_storage), IsUsingHwAesCtrForSpeedEmulation); R_UNLESS(switch_storage != nullptr, fs::ResultAllocationMemoryFailedAllocateShared()); /* Set the implementation storage. */ aes_ctr_ex_storage = std::move(switch_storage); } else { /* Set the implementation storage. */ aes_ctr_ex_storage = std::move(sw_storage); } } /* Create an alignment-matching storage. */ using AlignedStorage = AlignmentMatchingStorage<NcaHeader::CtrBlockSize, 1>; auto aligned_storage = fssystem::AllocateShared<AlignedStorage>(std::move(aes_ctr_ex_storage)); R_UNLESS(aligned_storage != nullptr, fs::ResultAllocationMemoryFailedAllocateShared()); /* Set the output. */ *out = std::move(aligned_storage); R_SUCCEED(); } Result NcaFileSystemDriver::CreateIndirectStorageMetaStorage(std::shared_ptr<fs::IStorage> *out, std::shared_ptr<fs::IStorage> base_storage, const NcaPatchInfo &patch_info) { /* Validate preconditions. */ AMS_ASSERT(out != nullptr); AMS_ASSERT(base_storage != nullptr); AMS_ASSERT(patch_info.HasIndirectTable()); /* Get the base storage size. */ s64 base_size = 0; R_TRY(base_storage->GetSize(std::addressof(base_size))); /* Check that we're within range. */ R_UNLESS(patch_info.indirect_offset + patch_info.indirect_size <= base_size, fs::ResultNcaBaseStorageOutOfRangeE()); /* Allocate the meta storage. */ auto meta_storage = fssystem::AllocateShared<BufferedStorage>(); R_UNLESS(meta_storage != nullptr, fs::ResultAllocationMemoryFailedAllocateShared()); /* Initialize the meta storage. */ R_TRY(meta_storage->Initialize(fs::SubStorage(base_storage, patch_info.indirect_offset, patch_info.indirect_size), m_buffer_manager, IndirectTableCacheBlockSize, IndirectTableCacheCount)); /* Set the output. */ *out = std::move(meta_storage); R_SUCCEED(); } Result NcaFileSystemDriver::CreateIndirectStorage(std::shared_ptr<fs::IStorage> *out, std::shared_ptr<fssystem::IndirectStorage> *out_ind, std::shared_ptr<fs::IStorage> base_storage, std::shared_ptr<fs::IStorage> original_data_storage, std::shared_ptr<fs::IStorage> meta_storage, const NcaPatchInfo &patch_info) { /* Validate preconditions. */ AMS_ASSERT(out != nullptr); AMS_ASSERT(base_storage != nullptr); AMS_ASSERT(meta_storage != nullptr); AMS_ASSERT(patch_info.HasIndirectTable()); /* Read the bucket tree header. */ BucketTree::Header header; std::memcpy(std::addressof(header), patch_info.indirect_header, sizeof(header)); R_TRY(header.Verify()); /* Determine the storage sizes. */ const auto node_size = IndirectStorage::QueryNodeStorageSize(header.entry_count); const auto entry_size = IndirectStorage::QueryEntryStorageSize(header.entry_count); R_UNLESS(node_size + entry_size <= patch_info.indirect_size, fs::ResultInvalidNcaIndirectStorageOutOfRange()); /* Get the indirect data size. */ const s64 indirect_data_size = patch_info.indirect_offset; AMS_ASSERT(util::IsAligned(indirect_data_size, NcaHeader::XtsBlockSize)); /* Create the indirect data storage. */ auto indirect_data_storage = fssystem::AllocateShared<BufferedStorage>(); R_UNLESS(indirect_data_storage != nullptr, fs::ResultAllocationMemoryFailedAllocateShared()); /* Initialize the indirect data storage. */ R_TRY(indirect_data_storage->Initialize(fs::SubStorage(base_storage, 0, indirect_data_size), m_buffer_manager, IndirectDataCacheBlockSize, IndirectDataCacheCount)); /* Enable bulk read on the data storage. */ indirect_data_storage->EnableBulkRead(); /* Create the indirect storage. */ auto indirect_storage = fssystem::AllocateShared<IndirectStorage>(); R_UNLESS(indirect_storage != nullptr, fs::ResultAllocationMemoryFailedAllocateShared()); /* Initialize the indirect storage. */ R_TRY(indirect_storage->Initialize(m_allocator, fs::SubStorage(meta_storage, 0, node_size), fs::SubStorage(meta_storage, node_size, entry_size), header.entry_count)); /* Get the original data size. */ s64 original_data_size; R_TRY(original_data_storage->GetSize(std::addressof(original_data_size))); /* Set the indirect storages. */ indirect_storage->SetStorage(0, fs::SubStorage(original_data_storage, 0, original_data_size)); indirect_storage->SetStorage(1, fs::SubStorage(indirect_data_storage, 0, indirect_data_size)); /* If necessary, set the output indirect storage. */ if (out_ind != nullptr) { *out_ind = indirect_storage; } /* Set the output. */ *out = std::move(indirect_storage); R_SUCCEED(); } Result NcaFileSystemDriver::CreatePatchMetaStorage(std::shared_ptr<fs::IStorage> *out_aes_ctr_ex_meta, std::shared_ptr<fs::IStorage> *out_indirect_meta, std::shared_ptr<fs::IStorage> *out_layer_info_storage, std::shared_ptr<fs::IStorage> base_storage, s64 offset, const NcaAesCtrUpperIv &upper_iv, const NcaPatchInfo &patch_info, const NcaMetaDataHashDataInfo &meta_data_hash_data_info, IHash256GeneratorFactory *hgf) { /* Validate preconditions. */ AMS_ASSERT(out_aes_ctr_ex_meta != nullptr); AMS_ASSERT(out_indirect_meta != nullptr); AMS_ASSERT(base_storage != nullptr); AMS_ASSERT(patch_info.HasAesCtrExTable()); AMS_ASSERT(patch_info.HasIndirectTable()); AMS_ASSERT(util::IsAligned<s64>(patch_info.aes_ctr_ex_size, NcaHeader::XtsBlockSize)); /* Validate patch info extents. */ R_UNLESS(patch_info.indirect_size > 0, fs::ResultInvalidNcaPatchInfoIndirectSize()); R_UNLESS(patch_info.aes_ctr_ex_size >= 0, fs::ResultInvalidNcaPatchInfoAesCtrExSize()); R_UNLESS(patch_info.indirect_size + patch_info.indirect_offset <= patch_info.aes_ctr_ex_offset, fs::ResultInvalidNcaPatchInfoAesCtrExOffset()); R_UNLESS(patch_info.aes_ctr_ex_offset + patch_info.aes_ctr_ex_size <= meta_data_hash_data_info.offset, fs::ResultRomNcaInvalidPatchMetaDataHashDataOffset()); /* Get the base storage size. */ s64 base_size; R_TRY(base_storage->GetSize(std::addressof(base_size))); /* Check that extents remain within range. */ R_UNLESS(patch_info.indirect_offset + patch_info.indirect_size <= base_size, fs::ResultNcaBaseStorageOutOfRangeE()); R_UNLESS(patch_info.aes_ctr_ex_offset + patch_info.aes_ctr_ex_size <= base_size, fs::ResultNcaBaseStorageOutOfRangeB()); /* Check that metadata hash data extents remain within range. */ const s64 meta_data_hash_data_offset = meta_data_hash_data_info.offset; const s64 meta_data_hash_data_size = util::AlignUp<s64>(meta_data_hash_data_info.size, NcaHeader::CtrBlockSize); R_UNLESS(meta_data_hash_data_offset + meta_data_hash_data_size <= base_size, fs::ResultNcaBaseStorageOutOfRangeB()); /* Create the encrypted storage. */ auto enc_storage = fssystem::AllocateShared<fs::SubStorage>(std::move(base_storage), patch_info.indirect_offset, meta_data_hash_data_offset + meta_data_hash_data_size - patch_info.indirect_offset); R_UNLESS(enc_storage != nullptr, fs::ResultAllocationMemoryFailedAllocateShared()); /* Create the decrypted storage. */ std::shared_ptr<fs::IStorage> decrypted_storage; R_TRY(this->CreateAesCtrStorage(std::addressof(decrypted_storage), std::move(enc_storage), offset + patch_info.indirect_offset, upper_iv, AlignmentStorageRequirement_None)); /* Create the verification storage. */ std::shared_ptr<fs::IStorage> integrity_storage; R_TRY_CATCH(this->CreateIntegrityVerificationStorageForMeta(std::addressof(integrity_storage), out_layer_info_storage, std::move(decrypted_storage), patch_info.indirect_offset, meta_data_hash_data_info, hgf)) { R_CONVERT(fs::ResultInvalidNcaMetaDataHashDataSize, fs::ResultRomNcaInvalidPatchMetaDataHashDataSize()) R_CONVERT(fs::ResultInvalidNcaMetaDataHashDataHash, fs::ResultRomNcaInvalidPatchMetaDataHashDataHash()) } R_END_TRY_CATCH; /* Create the indirect meta storage. */ auto indirect_meta_storage = fssystem::AllocateShared<fs::SubStorage>(integrity_storage, patch_info.indirect_offset - patch_info.indirect_offset, patch_info.indirect_size); R_UNLESS(indirect_meta_storage != nullptr, fs::ResultAllocationMemoryFailedAllocateShared()); /* Create the aes ctr ex meta storage. */ auto aes_ctr_ex_meta_storage = fssystem::AllocateShared<fs::SubStorage>(integrity_storage, patch_info.aes_ctr_ex_offset - patch_info.indirect_offset, patch_info.aes_ctr_ex_size); R_UNLESS(aes_ctr_ex_meta_storage != nullptr, fs::ResultAllocationMemoryFailedAllocateShared()); /* Set the output. */ *out_aes_ctr_ex_meta = std::move(aes_ctr_ex_meta_storage); *out_indirect_meta = std::move(indirect_meta_storage); R_SUCCEED(); } Result NcaFileSystemDriver::CreateSha256Storage(std::shared_ptr<fs::IStorage> *out, std::shared_ptr<fs::IStorage> base_storage, const NcaFsHeader::HashData::HierarchicalSha256Data &hash_data, IHash256GeneratorFactory *hgf) { /* Validate preconditions. */ AMS_ASSERT(out != nullptr); AMS_ASSERT(base_storage != nullptr); /* Define storage types. */ using VerificationStorage = HierarchicalSha256Storage<fs::SubStorage>; using CacheStorage = ReadOnlyBlockCacheStorage; using AlignedStorage = AlignmentMatchingStoragePooledBuffer<std::shared_ptr<fs::IStorage>, 1>; /* Validate the hash data. */ R_UNLESS(util::IsPowerOfTwo(hash_data.hash_block_size), fs::ResultInvalidHierarchicalSha256BlockSize()); R_UNLESS(hash_data.hash_layer_count == VerificationStorage::LayerCount - 1, fs::ResultInvalidHierarchicalSha256LayerCount()); /* Get the regions. */ const auto &hash_region = hash_data.hash_layer_region[0]; const auto &data_region = hash_data.hash_layer_region[1]; /* Determine buffer sizes. */ constexpr s32 CacheBlockCount = 2; const auto hash_buffer_size = static_cast<size_t>(hash_region.size); const auto cache_buffer_size = CacheBlockCount * hash_data.hash_block_size; const auto total_buffer_size = hash_buffer_size + cache_buffer_size; /* Make a buffer holder storage. */ auto buffer_hold_storage = fssystem::AllocateShared<MemoryResourceBufferHoldStorage>(std::move(base_storage), m_allocator, total_buffer_size); R_UNLESS(buffer_hold_storage != nullptr, fs::ResultAllocationMemoryFailedAllocateShared()); R_UNLESS(buffer_hold_storage->IsValid(), fs::ResultAllocationMemoryFailedInNcaFileSystemDriverI()); /* Get storage size. */ s64 base_size; R_TRY(buffer_hold_storage->GetSize(std::addressof(base_size))); /* Check that we're within range. */ R_UNLESS(hash_region.offset + hash_region.size <= base_size, fs::ResultNcaBaseStorageOutOfRangeC()); R_UNLESS(data_region.offset + data_region.size <= base_size, fs::ResultNcaBaseStorageOutOfRangeC()); /* Create the master hash storage. */ fs::MemoryStorage master_hash_storage(const_cast<Hash *>(std::addressof(hash_data.fs_data_master_hash)), sizeof(Hash)); /* Make the verification storage. */ auto verification_storage = fssystem::AllocateShared<VerificationStorage>(); R_UNLESS(verification_storage != nullptr, fs::ResultAllocationMemoryFailedAllocateShared()); /* Make layer storages. */ fs::SubStorage layer_storages[VerificationStorage::LayerCount] = { fs::SubStorage(std::addressof(master_hash_storage), 0, sizeof(Hash)), fs::SubStorage(buffer_hold_storage.get(), hash_region.offset, hash_region.size), fs::SubStorage(buffer_hold_storage, data_region.offset, data_region.size) }; /* Initialize the verification storage. */ R_TRY(verification_storage->Initialize(layer_storages, util::size(layer_storages), hash_data.hash_block_size, buffer_hold_storage->GetBuffer(), hash_buffer_size, hgf)); /* Make the cache storage. */ auto cache_storage = fssystem::AllocateShared<CacheStorage>(std::move(verification_storage), hash_data.hash_block_size, static_cast<char *>(buffer_hold_storage->GetBuffer()) + hash_buffer_size, cache_buffer_size, CacheBlockCount); R_UNLESS(cache_storage != nullptr, fs::ResultAllocationMemoryFailedAllocateShared()); /* Make the aligned storage. */ auto aligned_storage = fssystem::AllocateShared<AlignedStorage>(std::move(cache_storage), hash_data.hash_block_size); R_UNLESS(aligned_storage != nullptr, fs::ResultAllocationMemoryFailedAllocateShared()); /* Set the output. */ *out = std::move(aligned_storage); R_SUCCEED(); } Result NcaFileSystemDriver::CreateIntegrityVerificationStorage(std::shared_ptr<fs::IStorage> *out, std::shared_ptr<fs::IStorage> base_storage, const NcaFsHeader::HashData::IntegrityMetaInfo &meta_info, IHash256GeneratorFactory *hgf) { R_RETURN(this->CreateIntegrityVerificationStorageImpl(out, base_storage, meta_info, 0, IntegrityDataCacheCount, IntegrityHashCacheCount, fssystem::HierarchicalIntegrityVerificationStorage::GetDefaultDataCacheBufferLevel(meta_info.level_hash_info.max_layers), hgf)); } Result NcaFileSystemDriver::CreateIntegrityVerificationStorageForMeta(std::shared_ptr<fs::IStorage> *out, std::shared_ptr<fs::IStorage> *out_layer_info_storage, std::shared_ptr<fs::IStorage> base_storage, s64 offset, const NcaMetaDataHashDataInfo &meta_data_hash_data_info, IHash256GeneratorFactory *hgf) { /* Validate preconditions. */ AMS_ASSERT(out != nullptr); /* Check the meta data hash data size. */ R_UNLESS(meta_data_hash_data_info.size == sizeof(NcaMetaDataHashData), fs::ResultInvalidNcaMetaDataHashDataSize()); /* Read the meta data hash data. */ NcaMetaDataHashData meta_data_hash_data; R_TRY(base_storage->Read(meta_data_hash_data_info.offset - offset, std::addressof(meta_data_hash_data), sizeof(meta_data_hash_data))); /* Check the meta data hash data hash. */ u8 meta_data_hash_data_hash[IHash256Generator::HashSize]; m_hash_generator_factory_selector->GetFactory(fssystem::HashAlgorithmType_Sha2)->GenerateHash(meta_data_hash_data_hash, sizeof(meta_data_hash_data_hash), std::addressof(meta_data_hash_data), sizeof(meta_data_hash_data)); R_UNLESS(crypto::IsSameBytes(meta_data_hash_data_hash, std::addressof(meta_data_hash_data_info.hash), sizeof(meta_data_hash_data_hash)), fs::ResultInvalidNcaMetaDataHashDataHash()); /* Set the out layer info storage, if necessary. */ if (out_layer_info_storage != nullptr) { auto layer_info_storage = fssystem::AllocateShared<fs::SubStorage>(base_storage, meta_data_hash_data.layer_info_offset - offset, meta_data_hash_data_info.offset + meta_data_hash_data_info.size - meta_data_hash_data.layer_info_offset); R_UNLESS(layer_info_storage != nullptr, fs::ResultAllocationMemoryFailedAllocateShared()); *out_layer_info_storage = std::move(layer_info_storage); } /* Create the meta storage. */ auto meta_storage = fssystem::AllocateShared<fs::SubStorage>(std::move(base_storage), 0, meta_data_hash_data_info.offset - offset); R_UNLESS(meta_storage != nullptr, fs::ResultAllocationMemoryFailedAllocateShared()); /* Create the integrity verification storage. */ R_RETURN(this->CreateIntegrityVerificationStorageImpl(out, std::move(meta_storage), meta_data_hash_data.integrity_meta_info, meta_data_hash_data.layer_info_offset - offset, IntegrityDataCacheCountForMeta, IntegrityHashCacheCountForMeta, 0, hgf)); } Result NcaFileSystemDriver::CreateIntegrityVerificationStorageImpl(std::shared_ptr<fs::IStorage> *out, std::shared_ptr<fs::IStorage> base_storage, const NcaFsHeader::HashData::IntegrityMetaInfo &meta_info, s64 layer_info_offset, int max_data_cache_entries, int max_hash_cache_entries, s8 buffer_level, IHash256GeneratorFactory *hgf) { /* Validate preconditions. */ AMS_ASSERT(out != nullptr); AMS_ASSERT(base_storage != nullptr); AMS_ASSERT(layer_info_offset >= 0); /* Define storage types. */ using VerificationStorage = HierarchicalIntegrityVerificationStorage; using StorageInfo = VerificationStorage::HierarchicalStorageInformation; /* Validate the meta info. */ HierarchicalIntegrityVerificationInformation level_hash_info; std::memcpy(std::addressof(level_hash_info), std::addressof(meta_info.level_hash_info), sizeof(level_hash_info)); R_UNLESS(IntegrityMinLayerCount <= level_hash_info.max_layers, fs::ResultInvalidNcaHierarchicalIntegrityVerificationLayerCount()); R_UNLESS(level_hash_info.max_layers <= IntegrityMaxLayerCount, fs::ResultInvalidNcaHierarchicalIntegrityVerificationLayerCount()); /* Get the base storage size. */ s64 base_storage_size; R_TRY(base_storage->GetSize(std::addressof(base_storage_size))); /* Create storage info. */ StorageInfo storage_info; for (s32 i = 0; i < static_cast<s32>(level_hash_info.max_layers - 2); ++i) { const auto &layer_info = level_hash_info.info[i]; R_UNLESS(layer_info_offset + layer_info.offset + layer_info.size <= base_storage_size, fs::ResultNcaBaseStorageOutOfRangeD()); storage_info[i + 1] = fs::SubStorage(base_storage, layer_info_offset + layer_info.offset, layer_info.size); } /* Set the last layer info. */ const auto &layer_info = level_hash_info.info[level_hash_info.max_layers - 2]; const s64 last_layer_info_offset = layer_info_offset > 0 ? 0 : layer_info.offset; R_UNLESS(last_layer_info_offset + layer_info.size <= base_storage_size, fs::ResultNcaBaseStorageOutOfRangeD()); if (layer_info_offset > 0) { R_UNLESS(last_layer_info_offset + layer_info.size <= layer_info_offset, fs::ResultRomNcaInvalidIntegrityLayerInfoOffset()); } storage_info.SetDataStorage(fs::SubStorage(std::move(base_storage), last_layer_info_offset, layer_info.size)); /* Make the integrity romfs storage. */ auto integrity_storage = fssystem::AllocateShared<fssystem::IntegrityRomFsStorage>(); R_UNLESS(integrity_storage != nullptr, fs::ResultAllocationMemoryFailedAllocateShared()); /* Initialize the integrity storage. */ R_TRY(integrity_storage->Initialize(level_hash_info, meta_info.master_hash, storage_info, m_buffer_manager, max_data_cache_entries, max_hash_cache_entries, buffer_level, hgf)); /* Set the output. */ *out = std::move(integrity_storage); R_SUCCEED(); } Result NcaFileSystemDriver::CreateRegionSwitchStorage(std::shared_ptr<fs::IStorage> *out, const NcaFsHeaderReader *header_reader, std::shared_ptr<fs::IStorage> inside_storage, std::shared_ptr<fs::IStorage> outside_storage) { /* Check pre-conditions. */ AMS_ASSERT(header_reader->GetHashType() == NcaFsHeader::HashType::HierarchicalIntegrityHash); /* Create the region. */ fssystem::RegionSwitchStorage::Region region = {}; R_TRY(header_reader->GetHashTargetOffset(std::addressof(region.size))); /* Create the region switch storage. */ auto region_switch_storage = fssystem::AllocateShared<fssystem::RegionSwitchStorage>(std::move(inside_storage), std::move(outside_storage), region); R_UNLESS(region_switch_storage != nullptr, fs::ResultAllocationMemoryFailedAllocateShared()); /* Set the output. */ *out = std::move(region_switch_storage); R_SUCCEED(); } Result NcaFileSystemDriver::CreateCompressedStorage(std::shared_ptr<fs::IStorage> *out, std::shared_ptr<fssystem::CompressedStorage> *out_cmp, std::shared_ptr<fs::IStorage> *out_meta, std::shared_ptr<fs::IStorage> base_storage, const NcaCompressionInfo &compression_info) { R_RETURN(this->CreateCompressedStorage(out, out_cmp, out_meta, std::move(base_storage), compression_info, m_reader->GetDecompressor(), m_allocator, m_buffer_manager)); } Result NcaFileSystemDriver::CreateCompressedStorage(std::shared_ptr<fs::IStorage> *out, std::shared_ptr<fssystem::CompressedStorage> *out_cmp, std::shared_ptr<fs::IStorage> *out_meta, std::shared_ptr<fs::IStorage> base_storage, const NcaCompressionInfo &compression_info, GetDecompressorFunction get_decompressor, MemoryResource *allocator, fs::IBufferManager *buffer_manager) { /* Check pre-conditions. */ AMS_ASSERT(out != nullptr); AMS_ASSERT(base_storage != nullptr); AMS_ASSERT(get_decompressor != nullptr); /* Read and verify the bucket tree header. */ BucketTree::Header header; std::memcpy(std::addressof(header), compression_info.bucket.header, sizeof(header)); R_TRY(header.Verify()); /* Determine the storage extents. */ const auto table_offset = compression_info.bucket.offset; const auto table_size = compression_info.bucket.size; const auto node_size = CompressedStorage::QueryNodeStorageSize(header.entry_count); const auto entry_size = CompressedStorage::QueryEntryStorageSize(header.entry_count); R_UNLESS(node_size + entry_size <= table_size, fs::ResultInvalidCompressedStorageSize()); /* If we should, set the output meta storage. */ if (out_meta != nullptr) { auto meta_storage = fssystem::AllocateShared<fs::SubStorage>(base_storage, table_offset, table_size); R_UNLESS(meta_storage != nullptr, fs::ResultAllocationMemoryFailedAllocateShared()); *out_meta = std::move(meta_storage); } /* Allocate the compressed storage. */ auto compressed_storage = fssystem::AllocateShared<fssystem::CompressedStorage>(); R_UNLESS(compressed_storage != nullptr, fs::ResultAllocationMemoryFailedAllocateShared()); /* Initialize the compressed storage. */ R_TRY(compressed_storage->Initialize(allocator, buffer_manager, fs::SubStorage(base_storage, 0, table_offset), fs::SubStorage(base_storage, table_offset, node_size), fs::SubStorage(base_storage, table_offset + node_size, entry_size), header.entry_count, 64_KB, 640_KB, get_decompressor, 16_KB, 16_KB, 32)); /* Potentially set the output compressed storage. */ if (out_cmp) { *out_cmp = compressed_storage; } /* Set the output. */ *out = std::move(compressed_storage); R_SUCCEED(); } }
72,992
C++
.cpp
1,004
61.660359
504
0.666513
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,351
fssystem_indirect_storage.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssystem/fssystem_indirect_storage.cpp
/* * Copyright (c) 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 { Result IndirectStorage::Initialize(IAllocator *allocator, fs::SubStorage table_storage) { /* Read and verify the bucket tree header. */ BucketTree::Header header; R_TRY(table_storage.Read(0, std::addressof(header), sizeof(header))); R_TRY(header.Verify()); /* Determine extents. */ const auto node_storage_size = QueryNodeStorageSize(header.entry_count); const auto entry_storage_size = QueryEntryStorageSize(header.entry_count); const auto node_storage_offset = QueryHeaderStorageSize(); const auto entry_storage_offset = node_storage_offset + node_storage_size; /* Initialize. */ R_RETURN(this->Initialize(allocator, fs::SubStorage(std::addressof(table_storage), node_storage_offset, node_storage_size), fs::SubStorage(std::addressof(table_storage), entry_storage_offset, entry_storage_size), header.entry_count)); } void IndirectStorage::Finalize() { if (this->IsInitialized()) { m_table.Finalize(); for (auto i = 0; i < StorageCount; i++) { m_data_storage[i] = fs::SubStorage(); } } } Result IndirectStorage::GetEntryList(Entry *out_entries, s32 *out_entry_count, s32 entry_count, s64 offset, s64 size) { /* Validate pre-conditions. */ AMS_ASSERT(offset >= 0); AMS_ASSERT(size >= 0); AMS_ASSERT(this->IsInitialized()); /* Clear the out count. */ R_UNLESS(out_entry_count != nullptr, fs::ResultNullptrArgument()); *out_entry_count = 0; /* Succeed if there's no range. */ R_SUCCEED_IF(size == 0); /* If we have an output array, we need it to be non-null. */ R_UNLESS(out_entries != nullptr || entry_count == 0, fs::ResultNullptrArgument()); /* Check that our range is valid. */ BucketTree::Offsets table_offsets; R_TRY(m_table.GetOffsets(std::addressof(table_offsets))); R_UNLESS(table_offsets.IsInclude(offset, size), fs::ResultOutOfRange()); /* Find the offset in our tree. */ BucketTree::Visitor visitor; R_TRY(m_table.Find(std::addressof(visitor), offset)); { const auto entry_offset = visitor.Get<Entry>()->GetVirtualOffset(); R_UNLESS(0 <= entry_offset && table_offsets.IsInclude(entry_offset), fs::ResultInvalidIndirectEntryOffset()); } /* Prepare to loop over entries. */ const auto end_offset = offset + static_cast<s64>(size); s32 count = 0; auto cur_entry = *visitor.Get<Entry>(); while (cur_entry.GetVirtualOffset() < end_offset) { /* Try to write the entry to the out list. */ if (entry_count != 0) { if (count >= entry_count) { break; } std::memcpy(out_entries + count, std::addressof(cur_entry), sizeof(Entry)); } count++; /* Advance. */ if (visitor.CanMoveNext()) { R_TRY(visitor.MoveNext()); cur_entry = *visitor.Get<Entry>(); } else { break; } } /* Write the output count. */ *out_entry_count = count; R_SUCCEED(); } Result IndirectStorage::Read(s64 offset, void *buffer, size_t size) { /* Validate pre-conditions. */ AMS_ASSERT(offset >= 0); AMS_ASSERT(this->IsInitialized()); /* Succeed if there's nothing to read. */ R_SUCCEED_IF(size == 0); /* Ensure that we have a buffer to read to. */ R_UNLESS(buffer != nullptr, fs::ResultNullptrArgument()); R_TRY((this->OperatePerEntry<true, true>(offset, size, [=](fs::IStorage *storage, s64 data_offset, s64 cur_offset, s64 cur_size) -> Result { R_TRY(storage->Read(data_offset, reinterpret_cast<u8 *>(buffer) + (cur_offset - offset), static_cast<size_t>(cur_size))); R_SUCCEED(); }))); R_SUCCEED(); } Result IndirectStorage::OperateRange(void *dst, size_t dst_size, fs::OperationId op_id, s64 offset, s64 size, const void *src, size_t src_size) { /* Validate pre-conditions. */ AMS_ASSERT(offset >= 0); AMS_ASSERT(size >= 0); AMS_ASSERT(this->IsInitialized()); switch (op_id) { case fs::OperationId::Invalidate: { if (!m_table.IsEmpty()) { /* Invalidate our table's cache. */ R_TRY(m_table.InvalidateCache()); /* Invalidate our storages. */ for (auto &storage : m_data_storage) { R_TRY(storage.OperateRange(fs::OperationId::Invalidate, 0, std::numeric_limits<s64>::max())); } } R_SUCCEED(); } case fs::OperationId::QueryRange: { /* Validate that we have an output range info. */ R_UNLESS(dst != nullptr, fs::ResultNullptrArgument()); R_UNLESS(dst_size == sizeof(fs::QueryRangeInfo), fs::ResultInvalidSize()); if (size > 0) { /* Validate arguments. */ BucketTree::Offsets table_offsets; R_TRY(m_table.GetOffsets(std::addressof(table_offsets))); R_UNLESS(table_offsets.IsInclude(offset, size), fs::ResultOutOfRange()); if (!m_table.IsEmpty()) { /* Create a new info. */ fs::QueryRangeInfo merged_info; merged_info.Clear(); /* Operate on our entries. */ R_TRY((this->OperatePerEntry<false, true>(offset, size, [=, &merged_info](fs::IStorage *storage, s64 data_offset, s64 cur_offset, s64 cur_size) -> Result { AMS_UNUSED(cur_offset); fs::QueryRangeInfo cur_info; R_TRY(storage->OperateRange(std::addressof(cur_info), sizeof(cur_info), op_id, data_offset, cur_size, src, src_size)); merged_info.Merge(cur_info); R_SUCCEED(); }))); /* Write the merged info. */ *reinterpret_cast<fs::QueryRangeInfo *>(dst) = merged_info; } } R_SUCCEED(); } default: R_THROW(fs::ResultUnsupportedOperateRangeForIndirectStorage()); } R_SUCCEED(); } }
7,542
C++
.cpp
152
36.493421
242
0.55036
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,352
fssystem_block_cache_buffered_storage.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssystem/fssystem_block_cache_buffered_storage.cpp
/* * Copyright (c) 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 { BlockCacheBufferedStorage::BlockCacheBufferedStorage() : m_mutex(), m_data_storage(), m_last_result(ResultSuccess()), m_data_size(), m_verification_block_size(), m_verification_block_shift(), m_flags(), m_buffer_level(-1), m_block_cache_manager() { /* ... */ } BlockCacheBufferedStorage::~BlockCacheBufferedStorage() { this->Finalize(); } Result BlockCacheBufferedStorage::Initialize(fs::IBufferManager *bm, os::SdkRecursiveMutex *mtx, IStorage *data, s64 data_size, size_t verif_block_size, s32 max_cache_entries, bool is_real_data, s8 buffer_level, bool is_keep_burst_mode, bool is_writable) { /* Validate preconditions. */ AMS_ASSERT(data != nullptr); AMS_ASSERT(bm != nullptr); AMS_ASSERT(mtx != nullptr); AMS_ASSERT(m_mutex == nullptr); AMS_ASSERT(m_data_storage == nullptr); AMS_ASSERT(max_cache_entries > 0); /* Initialize our manager. */ R_TRY(m_block_cache_manager.Initialize(bm, max_cache_entries)); /* Set members. */ m_mutex = mtx; m_data_storage = data; m_data_size = data_size; m_verification_block_size = verif_block_size; m_last_result = ResultSuccess(); m_flags = 0; m_buffer_level = buffer_level; m_is_writable = is_writable; /* Calculate block shift. */ m_verification_block_shift = ILog2(static_cast<u32>(verif_block_size)); AMS_ASSERT(static_cast<size_t>(UINT64_C(1) << m_verification_block_shift) == m_verification_block_size); /* Set burst mode. */ this->SetKeepBurstMode(is_keep_burst_mode); /* Set real data cache. */ this->SetRealDataCache(is_real_data); R_SUCCEED(); } void BlockCacheBufferedStorage::Finalize() { if (m_block_cache_manager.IsInitialized()) { /* Invalidate all cache entries. */ this->InvalidateAllCacheEntries(); /* Finalize our block cache manager. */ m_block_cache_manager.Finalize(); /* Clear members. */ m_mutex = nullptr; m_data_storage = nullptr; m_data_size = 0; m_verification_block_size = 0; m_verification_block_shift = 0; } } Result BlockCacheBufferedStorage::Read(s64 offset, void *buffer, size_t size) { /* Validate pre-conditions. */ AMS_ASSERT(m_data_storage != nullptr); AMS_ASSERT(m_block_cache_manager.IsInitialized()); /* Ensure we aren't already in a failed state. */ R_TRY(m_last_result); /* Succeed if zero-size. */ R_SUCCEED_IF(size == 0); /* Validate arguments. */ R_UNLESS(buffer != nullptr, fs::ResultNullptrArgument()); /* Determine the extents to read. */ s64 read_offset = offset; size_t read_size = size; R_UNLESS(read_offset < m_data_size, fs::ResultInvalidOffset()); if (static_cast<s64>(read_offset + read_size) > m_data_size) { read_size = static_cast<size_t>(m_data_size - read_offset); } /* Determine the aligned range to read. */ const size_t block_alignment = m_verification_block_size; s64 aligned_offset = util::AlignDown(read_offset, block_alignment); s64 aligned_offset_end = util::AlignUp(read_offset + read_size, block_alignment); AMS_ASSERT(0 <= aligned_offset && aligned_offset_end <= static_cast<s64>(util::AlignUp(m_data_size, block_alignment))); /* Try to read using cache. */ char *dst = static_cast<char *>(buffer); { /* Determine if we can do bulk reads. */ constexpr s64 BulkReadSizeMax = 2_MB; const bool bulk_read_enabled = (read_offset != aligned_offset || static_cast<s64>(read_offset + read_size) != aligned_offset_end) && aligned_offset_end - aligned_offset <= BulkReadSizeMax; /* Read the head cache. */ CacheEntry head_entry = {}; MemoryRange head_range = {}; bool head_cache_needed = true; R_TRY(this->ReadHeadCache(std::addressof(head_range), std::addressof(head_entry), std::addressof(head_cache_needed), std::addressof(read_offset), std::addressof(aligned_offset), aligned_offset_end, std::addressof(dst), std::addressof(read_size))); /* We may be done after reading the head cache, so check if we are. */ R_SUCCEED_IF(aligned_offset >= aligned_offset_end); /* Ensure we destroy the head buffer. */ auto head_guard = SCOPE_GUARD { m_block_cache_manager.ReleaseCacheEntry(std::addressof(head_entry), head_range); }; /* Read the tail cache. */ CacheEntry tail_entry = {}; MemoryRange tail_range = {}; bool tail_cache_needed = true; R_TRY(this->ReadTailCache(std::addressof(tail_range), std::addressof(tail_entry), std::addressof(tail_cache_needed), read_offset, aligned_offset, std::addressof(aligned_offset_end), dst, std::addressof(read_size))); /* We may be done after reading the tail cache, so check if we are. */ R_SUCCEED_IF(aligned_offset >= aligned_offset_end); /* Ensure that we destroy the tail buffer. */ auto tail_guard = SCOPE_GUARD { m_block_cache_manager.ReleaseCacheEntry(std::addressof(tail_entry), tail_range); }; /* Try to do a bulk read. */ if (bulk_read_enabled) { /* The bulk read will destroy our head/tail buffers. */ head_guard.Cancel(); tail_guard.Cancel(); do { /* Do the bulk read. If we fail due to pooled buffer allocation failing, fall back to the normal read codepath. */ R_TRY_CATCH(this->BulkRead(read_offset, dst, read_size, std::addressof(head_range), std::addressof(tail_range), std::addressof(head_entry), std::addressof(tail_entry), head_cache_needed, tail_cache_needed)) { R_CATCH(fs::ResultAllocationPooledBufferNotEnoughSize) { break; } } R_END_TRY_CATCH; /* Se successfully did a bulk read, so we're done. */ R_SUCCEED(); } while (0); } } /* Read the data using non-bulk reads. */ while (aligned_offset < aligned_offset_end) { /* Ensure that there is data for us to read. */ AMS_ASSERT(read_size > 0); /* If conditions allow us to, read in burst mode. This doesn't use the cache. */ if (this->IsEnabledKeepBurstMode() && read_offset == aligned_offset && (block_alignment * 2 <= read_size)) { const size_t aligned_size = util::AlignDown(read_size, block_alignment); /* Flush the entries. */ R_TRY(this->UpdateLastResult(this->FlushRangeCacheEntries(read_offset, aligned_size, false))); /* Read the data. */ R_TRY(this->UpdateLastResult(m_data_storage->Read(read_offset, dst, aligned_size))); /* Advance. */ dst += aligned_size; read_offset += aligned_size; read_size -= aligned_size; aligned_offset += aligned_size; } else { /* Get the buffer associated with what we're reading. */ CacheEntry entry; MemoryRange range; R_TRY(this->UpdateLastResult(this->GetAssociateBuffer(std::addressof(range), std::addressof(entry), aligned_offset, static_cast<size_t>(aligned_offset_end - aligned_offset), true))); /* Determine where to read data into, and ensure that our entry is aligned. */ char *src = reinterpret_cast<char *>(range.first); AMS_ASSERT(util::IsAligned(entry.range.size, block_alignment)); /* If the entry isn't cached, read the data. */ if (!entry.is_cached) { if (const Result result = m_data_storage->Read(entry.range.offset, src, entry.range.size); R_FAILED(result)) { m_block_cache_manager.ReleaseCacheEntry(std::addressof(entry), range); R_RETURN(this->UpdateLastResult(result)); } entry.is_cached = true; } /* Validate the entry extents. */ AMS_ASSERT(static_cast<s64>(entry.range.offset) <= aligned_offset); AMS_ASSERT(aligned_offset < entry.range.GetEndOffset()); AMS_ASSERT(aligned_offset <= read_offset); /* Copy the data. */ { /* Determine where and how much to copy. */ const s64 buffer_offset = read_offset - entry.range.offset; const size_t copy_size = std::min(read_size, static_cast<size_t>(entry.range.GetEndOffset() - read_offset)); /* Actually copy the data. */ std::memcpy(dst, src + buffer_offset, copy_size); /* Advance. */ dst += copy_size; read_offset += copy_size; read_size -= copy_size; } /* Release the cache entry. */ R_TRY(this->UpdateLastResult(this->StoreOrDestroyBuffer(range, std::addressof(entry)))); aligned_offset = entry.range.GetEndOffset(); } } /* Ensure that we read all the data. */ AMS_ASSERT(read_size == 0); R_SUCCEED(); } Result BlockCacheBufferedStorage::Write(s64 offset, const void *buffer, size_t size) { /* Validate pre-conditions. */ AMS_ASSERT(m_data_storage != nullptr); AMS_ASSERT(m_block_cache_manager.IsInitialized()); /* Ensure we aren't already in a failed state. */ R_TRY(m_last_result); /* Succeed if zero-size. */ R_SUCCEED_IF(size == 0); /* Validate arguments. */ R_UNLESS(buffer != nullptr, fs::ResultNullptrArgument()); /* Determine the extents to read. */ R_UNLESS(offset < m_data_size, fs::ResultInvalidOffset()); if (static_cast<s64>(offset + size) > m_data_size) { size = static_cast<size_t>(m_data_size - offset); } /* The actual extents may be zero-size, so succeed if that's the case. */ R_SUCCEED_IF(size == 0); /* Determine the aligned range to read. */ const size_t block_alignment = m_verification_block_size; s64 aligned_offset = util::AlignDown(offset, block_alignment); const s64 aligned_offset_end = util::AlignUp(offset + size, block_alignment); AMS_ASSERT(0 <= aligned_offset && aligned_offset_end <= static_cast<s64>(util::AlignUp(m_data_size, block_alignment))); /* Write the data. */ const u8 *src = static_cast<const u8 *>(buffer); while (aligned_offset < aligned_offset_end) { /* If conditions allow us to, write in burst mode. This doesn't use the cache. */ if (this->IsEnabledKeepBurstMode() && offset == aligned_offset && (block_alignment * 2 <= size)) { const size_t aligned_size = util::AlignDown(size, block_alignment); /* Flush the entries. */ R_TRY(this->UpdateLastResult(this->FlushRangeCacheEntries(offset, aligned_size, true))); /* Read the data. */ R_TRY(this->UpdateLastResult(m_data_storage->Write(offset, src, aligned_size))); /* Set blocking buffer manager allocations. */ buffers::EnableBlockingBufferManagerAllocation(); /* Advance. */ src += aligned_size; offset += aligned_size; size -= aligned_size; aligned_offset += aligned_size; } else { /* Get the buffer associated with what we're writing. */ CacheEntry entry; MemoryRange range; R_TRY(this->UpdateLastResult(this->GetAssociateBuffer(std::addressof(range), std::addressof(entry), aligned_offset, static_cast<size_t>(aligned_offset_end - aligned_offset), true))); /* Determine where to write data into. */ char *dst = reinterpret_cast<char *>(range.first); /* If the entry isn't cached and we're writing a partial entry, read in the entry. */ if (!entry.is_cached && ((offset != entry.range.offset) || (offset + size < static_cast<size_t>(entry.range.GetEndOffset())))) { if (Result result = m_data_storage->Read(entry.range.offset, dst, entry.range.size); R_FAILED(result)) { m_block_cache_manager.ReleaseCacheEntry(std::addressof(entry), range); R_RETURN(this->UpdateLastResult(result)); } } entry.is_cached = true; /* Validate the entry extents. */ AMS_ASSERT(static_cast<s64>(entry.range.offset) <= aligned_offset); AMS_ASSERT(aligned_offset < entry.range.GetEndOffset()); AMS_ASSERT(aligned_offset <= offset); /* Copy the data. */ { /* Determine where and how much to copy. */ const s64 buffer_offset = offset - entry.range.offset; const size_t copy_size = std::min(size, static_cast<size_t>(entry.range.GetEndOffset() - offset)); /* Actually copy the data. */ std::memcpy(dst + buffer_offset, src, copy_size); /* Advance. */ src += copy_size; offset += copy_size; size -= copy_size; } /* Set the entry as write-back. */ entry.is_write_back = true; /* Set blocking buffer manager allocations. */ buffers::EnableBlockingBufferManagerAllocation(); /* Store the associated buffer. */ CacheIndex index; R_TRY(this->UpdateLastResult(this->StoreOrDestroyBuffer(std::addressof(index), range, std::addressof(entry)))); /* Set the after aligned offset. */ aligned_offset = entry.range.GetEndOffset(); /* If we need to, flush the cache entry. */ if (index >= 0 && IsEnabledKeepBurstMode() && offset == aligned_offset && (block_alignment * 2 <= size)) { R_TRY(this->UpdateLastResult(this->FlushCacheEntry(index, false))); } } } /* Ensure that didn't end up in a failure state. */ R_TRY(m_last_result); R_SUCCEED(); } Result BlockCacheBufferedStorage::GetSize(s64 *out) { /* Validate pre-conditions. */ AMS_ASSERT(out != nullptr); AMS_ASSERT(m_data_storage != nullptr); /* Set the size. */ *out = m_data_size; R_SUCCEED(); } Result BlockCacheBufferedStorage::Flush() { /* Validate pre-conditions. */ AMS_ASSERT(m_data_storage != nullptr); AMS_ASSERT(m_block_cache_manager.IsInitialized()); /* Ensure we aren't already in a failed state. */ R_TRY(m_last_result); /* Flush all cache entries. */ R_TRY(this->UpdateLastResult(this->FlushAllCacheEntries())); /* Flush the data storage. */ R_TRY(this->UpdateLastResult(m_data_storage->Flush())); /* Set blocking buffer manager allocations. */ buffers::EnableBlockingBufferManagerAllocation(); R_SUCCEED(); } Result BlockCacheBufferedStorage::OperateRange(void *dst, size_t dst_size, fs::OperationId op_id, s64 offset, s64 size, const void *src, size_t src_size) { AMS_UNUSED(src, src_size); /* Validate pre-conditions. */ AMS_ASSERT(m_data_storage != nullptr); switch (op_id) { case fs::OperationId::FillZero: { R_RETURN(this->FillZeroImpl(offset, size)); } case fs::OperationId::DestroySignature: { R_RETURN(this->DestroySignatureImpl(offset, size)); } case fs::OperationId::Invalidate: { R_UNLESS(!m_is_writable, fs::ResultUnsupportedOperateRangeForWritableBlockCacheBufferedStorage()); R_RETURN(this->InvalidateImpl()); } case fs::OperationId::QueryRange: { R_RETURN(this->QueryRangeImpl(dst, dst_size, offset, size)); } default: R_THROW(fs::ResultUnsupportedOperateRangeForBlockCacheBufferedStorage()); } } Result BlockCacheBufferedStorage::Commit() { /* Validate pre-conditions. */ AMS_ASSERT(m_data_storage != nullptr); AMS_ASSERT(m_block_cache_manager.IsInitialized()); /* Ensure we aren't already in a failed state. */ R_TRY(m_last_result); /* Flush all cache entries. */ R_TRY(this->UpdateLastResult(this->FlushAllCacheEntries())); R_SUCCEED(); } Result BlockCacheBufferedStorage::OnRollback() { /* Validate pre-conditions. */ AMS_ASSERT(m_block_cache_manager.IsInitialized()); /* Ensure we aren't already in a failed state. */ R_TRY(m_last_result); /* Release all valid entries back to the buffer manager. */ const auto max_cache_entry_count = m_block_cache_manager.GetCount(); for (auto index = 0; index < max_cache_entry_count; index++) { if (const auto &entry = m_block_cache_manager[index]; entry.is_valid) { m_block_cache_manager.InvalidateCacheEntry(index); } } R_SUCCEED(); } Result BlockCacheBufferedStorage::FillZeroImpl(s64 offset, s64 size) { /* Ensure we aren't already in a failed state. */ R_TRY(m_last_result); /* Get our storage size. */ s64 storage_size = 0; R_TRY(this->UpdateLastResult(m_data_storage->GetSize(std::addressof(storage_size)))); /* Check the access range. */ R_UNLESS(0 <= offset && offset < storage_size, fs::ResultInvalidOffset()); /* Determine the extents to data signature for. */ auto start_offset = util::AlignDown(offset, m_verification_block_size); auto end_offset = util::AlignUp(std::min(offset + size, storage_size), m_verification_block_size); /* Flush the entries. */ R_TRY(this->UpdateLastResult(this->FlushRangeCacheEntries(offset, size, true))); /* Handle any data before or after the aligned range. */ if (start_offset < offset || offset + size < end_offset) { /* Allocate a work buffer. */ std::unique_ptr<char[], fs::impl::Deleter> work = fs::impl::MakeUnique<char[]>(m_verification_block_size); R_UNLESS(work != nullptr, fs::ResultAllocationMemoryFailedInBlockCacheBufferedStorageB()); /* Handle data before the aligned range. */ if (start_offset < offset) { /* Read the block. */ R_TRY(this->UpdateLastResult(m_data_storage->Read(start_offset, work.get(), m_verification_block_size))); /* Determine the partial extents to clear. */ const auto clear_offset = static_cast<size_t>(offset - start_offset); const auto clear_size = static_cast<size_t>(std::min(static_cast<s64>(m_verification_block_size - clear_offset), size)); /* Clear the partial block. */ std::memset(work.get() + clear_offset, 0, clear_size); /* Write the partially cleared block. */ R_TRY(this->UpdateLastResult(m_data_storage->Write(start_offset, work.get(), m_verification_block_size))); /* Update the start offset. */ start_offset += m_verification_block_size; /* Set blocking buffer manager allocations. */ buffers::EnableBlockingBufferManagerAllocation(); } /* Handle data after the aligned range. */ if (start_offset < offset + size && offset + size < end_offset) { /* Read the block. */ const auto last_offset = end_offset - m_verification_block_size; R_TRY(this->UpdateLastResult(m_data_storage->Read(last_offset, work.get(), m_verification_block_size))); /* Clear the partial block. */ const auto clear_size = static_cast<size_t>((offset + size) - last_offset); std::memset(work.get(), 0, clear_size); /* Write the partially cleared block. */ R_TRY(this->UpdateLastResult(m_data_storage->Write(last_offset, work.get(), m_verification_block_size))); /* Update the end offset. */ end_offset -= m_verification_block_size; /* Set blocking buffer manager allocations. */ buffers::EnableBlockingBufferManagerAllocation(); } } /* We're done if there's no data to clear. */ R_SUCCEED_IF(start_offset == end_offset); /* Clear the signature for the aligned range. */ R_TRY(this->UpdateLastResult(m_data_storage->OperateRange(fs::OperationId::FillZero, start_offset, end_offset - start_offset))); /* Set blocking buffer manager allocations. */ buffers::EnableBlockingBufferManagerAllocation(); R_SUCCEED(); } Result BlockCacheBufferedStorage::DestroySignatureImpl(s64 offset, s64 size) { /* Ensure we aren't already in a failed state. */ R_TRY(m_last_result); /* Get our storage size. */ s64 storage_size = 0; R_TRY(this->UpdateLastResult(m_data_storage->GetSize(std::addressof(storage_size)))); /* Check the access range. */ R_UNLESS(0 <= offset && offset < storage_size, fs::ResultInvalidOffset()); /* Determine the extents to clear signature for. */ const auto start_offset = util::AlignUp(offset, m_verification_block_size); const auto end_offset = util::AlignDown(std::min(offset + size, storage_size), m_verification_block_size); /* Flush the entries. */ R_TRY(this->UpdateLastResult(this->FlushRangeCacheEntries(offset, size, true))); /* Clear the signature for the aligned range. */ R_TRY(this->UpdateLastResult(m_data_storage->OperateRange(fs::OperationId::DestroySignature, start_offset, end_offset - start_offset))); /* Set blocking buffer manager allocations. */ buffers::EnableBlockingBufferManagerAllocation(); R_SUCCEED(); } Result BlockCacheBufferedStorage::InvalidateImpl() { /* Invalidate cache entries. */ { std::scoped_lock lk(*m_mutex); m_block_cache_manager.Invalidate(); } /* Invalidate the aligned range. */ { Result result = m_data_storage->OperateRange(fs::OperationId::Invalidate, 0, std::numeric_limits<s64>::max()); AMS_ASSERT(!fs::ResultBufferAllocationFailed::Includes(result)); R_TRY(result); } /* Clear our last result if we should. */ if (fs::ResultIntegrityVerificationStorageCorrupted::Includes(m_last_result)) { m_last_result = ResultSuccess(); } R_SUCCEED(); } Result BlockCacheBufferedStorage::QueryRangeImpl(void *dst, size_t dst_size, s64 offset, s64 size) { /* Get our storage size. */ s64 storage_size = 0; R_TRY(this->GetSize(std::addressof(storage_size))); /* Determine the extents we can actually query. */ const auto actual_size = std::min(size, storage_size - offset); const auto aligned_offset = util::AlignDown(offset, m_verification_block_size); const auto aligned_offset_end = util::AlignUp(offset + actual_size, m_verification_block_size); const auto aligned_size = aligned_offset_end - aligned_offset; /* Query the aligned range. */ R_TRY(this->UpdateLastResult(m_data_storage->OperateRange(dst, dst_size, fs::OperationId::QueryRange, aligned_offset, aligned_size, nullptr, 0))); R_SUCCEED(); } Result BlockCacheBufferedStorage::GetAssociateBuffer(MemoryRange *out_range, CacheEntry *out_entry, s64 offset, size_t ideal_size, bool is_allocate_for_write) { AMS_UNUSED(is_allocate_for_write); /* Validate pre-conditions. */ AMS_ASSERT(m_data_storage != nullptr); AMS_ASSERT(m_block_cache_manager.IsInitialized()); AMS_ASSERT(out_range != nullptr); AMS_ASSERT(out_entry != nullptr); /* Lock our mutex. */ std::scoped_lock lk(*m_mutex); /* Get the maximum cache entry count. */ const CacheIndex max_cache_entry_count = m_block_cache_manager.GetCount(); /* Locate the index of the cache entry, if present. */ CacheIndex index; size_t actual_size = ideal_size; for (index = 0; index < max_cache_entry_count; ++index) { if (const auto &entry = m_block_cache_manager[index]; entry.IsAllocated()) { if (entry.range.IsIncluded(offset)) { break; } if (offset <= entry.range.offset && entry.range.offset < static_cast<s64>(offset + actual_size)) { actual_size = static_cast<s64>(entry.range.offset - offset); } } } /* Clear the out range. */ out_range->first = 0; out_range->second = 0; /* If we located an entry, use it. */ if (index != max_cache_entry_count) { m_block_cache_manager.AcquireCacheEntry(out_entry, out_range, index); actual_size = out_entry->range.size - (offset - out_entry->range.offset); } /* If we don't have an out entry, allocate one. */ if (out_range->first == 0) { /* Ensure that the allocatable size is above a threshold. */ const auto size_threshold = m_block_cache_manager.GetAllocator()->GetTotalSize() / 8; if (m_block_cache_manager.GetAllocator()->GetTotalAllocatableSize() < size_threshold) { R_TRY(this->FlushAllCacheEntries()); } /* Decide in advance on a block alignment. */ const size_t block_alignment = m_verification_block_size; /* Ensure that the size we request is valid. */ { AMS_ASSERT(actual_size >= 1); actual_size = std::min(actual_size, block_alignment * 2); } AMS_ASSERT(actual_size >= block_alignment); /* Allocate a buffer. */ R_TRY(buffers::AllocateBufferUsingBufferManagerContext(out_range, m_block_cache_manager.GetAllocator(), actual_size, fs::IBufferManager::BufferAttribute(m_buffer_level), [=](const MemoryRange &buffer) { return buffer.first != 0 && block_alignment <= buffer.second; }, AMS_CURRENT_FUNCTION_NAME)); /* Ensure our size is accurate. */ actual_size = std::min(actual_size, out_range->second); /* Set the output entry. */ out_entry->is_valid = true; out_entry->is_write_back = false; out_entry->is_cached = false; out_entry->is_flushing = false; out_entry->handle = 0; out_entry->memory_address = 0; out_entry->memory_size = 0; out_entry->range.offset = offset; out_entry->range.size = actual_size; out_entry->lru_counter = 0; } /* Check that we ended up with a coherent out range. */ AMS_ASSERT(out_range->second >= out_entry->range.size); R_SUCCEED(); } Result BlockCacheBufferedStorage::StoreOrDestroyBuffer(CacheIndex *out, const MemoryRange &range, CacheEntry *entry) { /* Validate pre-conditions. */ AMS_ASSERT(out != nullptr); /* Lock our mutex. */ std::scoped_lock lk(*m_mutex); /* In the event that we fail, release our buffer. */ ON_RESULT_FAILURE { m_block_cache_manager.ReleaseCacheEntry(entry, range); }; /* If the entry is write-back, ensure we don't exceed certain dirtiness thresholds. */ if (entry->is_write_back) { R_TRY(this->ControlDirtiness()); } /* Get unused cache entry index. */ CacheIndex empty_index, lru_index; m_block_cache_manager.GetEmptyCacheEntryIndex(std::addressof(empty_index), std::addressof(lru_index)); /* If all entries are valid, we need to invalidate one. */ if (empty_index == BlockCacheManager::InvalidCacheIndex) { /* Invalidate the lease recently used entry. */ empty_index = lru_index; /* Get the entry to invalidate, sanity check that we can invalidate it. */ const CacheEntry &entry_to_invalidate = m_block_cache_manager[empty_index]; AMS_ASSERT(entry_to_invalidate.is_valid); AMS_ASSERT(!entry_to_invalidate.is_flushing); AMS_UNUSED(entry_to_invalidate); /* Invalidate the entry. */ R_TRY(this->FlushCacheEntry(empty_index, true)); /* Check that the entry was invalidated successfully. */ AMS_ASSERT(!entry_to_invalidate.is_valid); AMS_ASSERT(!entry_to_invalidate.is_flushing); } /* Store the entry. */ if (m_block_cache_manager.SetCacheEntry(empty_index, *entry, range, fs::IBufferManager::BufferAttribute(m_buffer_level))) { *out = empty_index; } else { *out = BlockCacheManager::InvalidCacheIndex; } R_SUCCEED(); } Result BlockCacheBufferedStorage::FlushCacheEntry(CacheIndex index, bool invalidate) { /* Lock our mutex. */ std::scoped_lock lk(*m_mutex); /* Get the entry, sanity check that the entry's state allows for flush. */ auto &entry = m_block_cache_manager[index]; AMS_ASSERT(entry.is_valid); AMS_ASSERT(!entry.is_flushing); /* If we're not write back (i.e. an invalidate is happening), just release the buffer. */ if (!entry.is_write_back) { AMS_ASSERT(invalidate); m_block_cache_manager.InvalidateCacheEntry(index); R_SUCCEED(); } /* Note that we've started flushing, while we process. */ m_block_cache_manager.SetFlushing(index, true); ON_SCOPE_EXIT { m_block_cache_manager.SetFlushing(index, false); }; /* Create and check our memory range. */ MemoryRange memory_range = fs::IBufferManager::MakeMemoryRange(entry.memory_address, entry.memory_size); AMS_ASSERT(memory_range.first != 0); AMS_ASSERT(memory_range.second >= entry.range.size); /* Validate the entry's offset. */ AMS_ASSERT(entry.range.offset >= 0); AMS_ASSERT(entry.range.offset < m_data_size); AMS_ASSERT(util::IsAligned(entry.range.offset, m_verification_block_size)); /* Write back the data. */ Result result = ResultSuccess(); size_t write_size = entry.range.size; if (R_SUCCEEDED(m_last_result)) { /* Set blocking buffer manager allocations. */ result = m_data_storage->Write(entry.range.offset, reinterpret_cast<const void *>(memory_range.first), write_size); /* Check the result. */ AMS_ASSERT(!fs::ResultBufferAllocationFailed::Includes(result)); } else { result = m_last_result; } /* Set that we're not write-back. */ m_block_cache_manager.SetWriteBack(index, false); /* If we're invalidating, release the buffer. Otherwise, register the flushed data. */ if (invalidate) { m_block_cache_manager.ReleaseCacheEntry(index, memory_range); } else { AMS_ASSERT(entry.is_valid); m_block_cache_manager.RegisterCacheEntry(index, memory_range, fs::IBufferManager::BufferAttribute(m_buffer_level)); } /* Try to succeed. */ R_TRY(result); /* We succeeded. */ R_SUCCEED(); } Result BlockCacheBufferedStorage::FlushRangeCacheEntries(s64 offset, s64 size, bool invalidate) { /* Validate pre-conditions. */ AMS_ASSERT(m_data_storage != nullptr); AMS_ASSERT(m_block_cache_manager.IsInitialized()); /* Iterate over all entries that fall within the range. */ Result result = ResultSuccess(); const auto max_cache_entry_count = m_block_cache_manager.GetCount(); for (auto i = 0; i < max_cache_entry_count; ++i) { auto &entry = m_block_cache_manager[i]; if (entry.is_valid && (entry.is_write_back || invalidate) && (entry.range.offset < (offset + size)) && (offset < entry.range.GetEndOffset())) { const auto cur_result = this->FlushCacheEntry(i, invalidate); if (R_FAILED(cur_result) && R_SUCCEEDED(result)) { result = cur_result; } } } /* Try to succeed. */ R_TRY(result); /* We succeeded. */ R_SUCCEED(); } Result BlockCacheBufferedStorage::FlushAllCacheEntries() { R_TRY(this->FlushRangeCacheEntries(0, std::numeric_limits<s64>::max(), false)); R_SUCCEED(); } Result BlockCacheBufferedStorage::InvalidateAllCacheEntries() { R_TRY(this->FlushRangeCacheEntries(0, std::numeric_limits<s64>::max(), true)); R_SUCCEED(); } Result BlockCacheBufferedStorage::ControlDirtiness() { /* Get and validate the max cache entry count. */ const auto max_cache_entry_count = m_block_cache_manager.GetCount(); AMS_ASSERT(max_cache_entry_count > 0); /* Get size metrics from the buffer manager. */ const auto total_size = m_block_cache_manager.GetAllocator()->GetTotalSize(); const auto allocatable_size = m_block_cache_manager.GetAllocator()->GetTotalAllocatableSize(); /* If we have enough allocatable space, we don't need to do anything. */ R_SUCCEED_IF(allocatable_size >= total_size / 4); /* Iterate over all entries (up to the threshold) and flush the least recently used dirty entry. */ constexpr auto Threshold = 2; for (int n = 0; n < Threshold; ++n) { auto flushed_index = BlockCacheManager::InvalidCacheIndex; for (auto index = 0; index < max_cache_entry_count; ++index) { if (auto &entry = m_block_cache_manager[index]; entry.is_valid && entry.is_write_back) { if (flushed_index == BlockCacheManager::InvalidCacheIndex || m_block_cache_manager[flushed_index].lru_counter < entry.lru_counter) { flushed_index = index; } } } /* If we can't flush anything, break. */ if (flushed_index == BlockCacheManager::InvalidCacheIndex) { break; } R_TRY(this->FlushCacheEntry(flushed_index, false)); } R_SUCCEED(); } Result BlockCacheBufferedStorage::UpdateLastResult(Result result) { /* Update the last result. */ if (R_FAILED(result) && !fs::ResultBufferAllocationFailed::Includes(result) && R_SUCCEEDED(m_last_result)) { m_last_result = result; } /* Try to succeed with the result. */ R_TRY(result); /* We succeeded. */ R_SUCCEED(); } Result BlockCacheBufferedStorage::ReadHeadCache(MemoryRange *out_range, CacheEntry *out_entry, bool *out_cache_needed, s64 *offset, s64 *aligned_offset, s64 aligned_offset_end, char **buffer, size_t *size) { /* Valdiate pre-conditions. */ AMS_ASSERT(out_range != nullptr); AMS_ASSERT(out_entry != nullptr); AMS_ASSERT(out_cache_needed != nullptr); AMS_ASSERT(offset != nullptr); AMS_ASSERT(aligned_offset != nullptr); AMS_ASSERT(buffer != nullptr); AMS_ASSERT(*buffer != nullptr); AMS_ASSERT(size != nullptr); AMS_ASSERT(*aligned_offset < aligned_offset_end); /* Iterate over the region. */ CacheEntry entry = {}; MemoryRange memory_range = {}; *out_cache_needed = true; while (*aligned_offset < aligned_offset_end) { /* Get the associated buffer for the offset. */ R_TRY(this->UpdateLastResult(this->GetAssociateBuffer(std::addressof(memory_range), std::addressof(entry), *aligned_offset, m_verification_block_size, true))); /* If the entry isn't cached, we're done. */ if (!entry.is_cached) { break; } /* Set cache not needed. */ *out_cache_needed = false; /* Determine the size to copy. */ const s64 buffer_offset = *offset - entry.range.offset; const size_t copy_size = std::min(*size, static_cast<size_t>(entry.range.GetEndOffset() - *offset)); /* Copy data from the entry. */ std::memcpy(*buffer, reinterpret_cast<const void *>(memory_range.first + buffer_offset), copy_size); /* Advance. */ *buffer += copy_size; *offset += copy_size; *size -= copy_size; *aligned_offset = entry.range.GetEndOffset(); /* Handle the buffer. */ R_TRY(this->UpdateLastResult(this->StoreOrDestroyBuffer(memory_range, std::addressof(entry)))); } /* Set the output entry. */ *out_entry = entry; *out_range = memory_range; R_SUCCEED(); } Result BlockCacheBufferedStorage::ReadTailCache(MemoryRange *out_range, CacheEntry *out_entry, bool *out_cache_needed, s64 offset, s64 aligned_offset, s64 *aligned_offset_end, char *buffer, size_t *size) { /* Valdiate pre-conditions. */ AMS_ASSERT(out_range != nullptr); AMS_ASSERT(out_entry != nullptr); AMS_ASSERT(out_cache_needed != nullptr); AMS_ASSERT(aligned_offset_end != nullptr); AMS_ASSERT(buffer != nullptr); AMS_ASSERT(size != nullptr); AMS_ASSERT(aligned_offset < *aligned_offset_end); /* Iterate over the region. */ CacheEntry entry = {}; MemoryRange memory_range = {}; *out_cache_needed = true; while (aligned_offset < *aligned_offset_end) { /* Get the associated buffer for the offset. */ R_TRY(this->UpdateLastResult(this->GetAssociateBuffer(std::addressof(memory_range), std::addressof(entry), *aligned_offset_end - m_verification_block_size, m_verification_block_size, true))); /* If the entry isn't cached, we're done. */ if (!entry.is_cached) { break; } /* Set cache not needed. */ *out_cache_needed = false; /* Determine the size to copy. */ const s64 buffer_offset = std::max(static_cast<s64>(0), offset - entry.range.offset); const size_t copy_size = std::min(*size, static_cast<size_t>(offset + *size - entry.range.offset)); /* Copy data from the entry. */ std::memcpy(buffer + *size - copy_size, reinterpret_cast<const void *>(memory_range.first + buffer_offset), copy_size); /* Advance. */ *size -= copy_size; *aligned_offset_end = entry.range.offset; /* Handle the buffer. */ R_TRY(this->UpdateLastResult(this->StoreOrDestroyBuffer(memory_range, std::addressof(entry)))); } /* Set the output entry. */ *out_entry = entry; *out_range = memory_range; R_SUCCEED(); } Result BlockCacheBufferedStorage::BulkRead(s64 offset, void *buffer, size_t size, MemoryRange *range_head, MemoryRange *range_tail, CacheEntry *entry_head, CacheEntry *entry_tail, bool head_cache_needed, bool tail_cache_needed) { /* Validate pre-conditions. */ AMS_ASSERT(buffer != nullptr); AMS_ASSERT(range_head != nullptr); AMS_ASSERT(range_tail != nullptr); AMS_ASSERT(entry_head != nullptr); AMS_ASSERT(entry_tail != nullptr); /* Determine bulk read offsets. */ const s64 read_offset = offset; const size_t read_size = size; const s64 aligned_offset = util::AlignDown(read_offset, m_verification_block_size); const s64 aligned_offset_end = util::AlignUp(read_offset + read_size, m_verification_block_size); char *dst = static_cast<char *>(buffer); /* Prepare to do our reads. */ auto head_guard = SCOPE_GUARD { m_block_cache_manager.ReleaseCacheEntry(entry_head, *range_head); }; auto tail_guard = SCOPE_GUARD { m_block_cache_manager.ReleaseCacheEntry(entry_tail, *range_tail); }; /* Flush the entries. */ R_TRY(this->UpdateLastResult(this->FlushRangeCacheEntries(aligned_offset, aligned_offset_end - aligned_offset, false))); /* Determine the buffer to read into. */ PooledBuffer pooled_buffer; const size_t buffer_size = static_cast<size_t>(aligned_offset_end - aligned_offset); char *read_buffer = nullptr; if (read_offset == aligned_offset && read_size == buffer_size) { read_buffer = dst; } else if (tail_cache_needed && entry_tail->range.offset == aligned_offset && entry_tail->range.size == buffer_size) { read_buffer = reinterpret_cast<char *>(range_tail->first); } else if (head_cache_needed && entry_head->range.offset == aligned_offset && entry_head->range.size == buffer_size) { read_buffer = reinterpret_cast<char *>(range_head->first); } else { pooled_buffer.AllocateParticularlyLarge(buffer_size, 1); R_UNLESS(pooled_buffer.GetSize() >= buffer_size, fs::ResultAllocationPooledBufferNotEnoughSize()); read_buffer = pooled_buffer.GetBuffer(); } /* Read the data. */ R_TRY(m_data_storage->Read(aligned_offset, read_buffer, buffer_size)); /* Copy the data out. */ if (dst != read_buffer) { std::memcpy(dst, read_buffer + read_offset - aligned_offset, read_size); } /* Create a helper to populate our caches. */ const auto PopulateCacheFromPooledBuffer = [&](CacheEntry *entry, MemoryRange *range) { AMS_ASSERT(entry != nullptr); AMS_ASSERT(range != nullptr); if (aligned_offset <= entry->range.offset && entry->range.GetEndOffset() <= static_cast<s64>(aligned_offset + buffer_size)) { AMS_ASSERT(!entry->is_cached); if (reinterpret_cast<void *>(range->first) != read_buffer) { std::memcpy(reinterpret_cast<void *>(range->first), read_buffer + entry->range.offset - aligned_offset, entry->range.size); } entry->is_cached = true; } }; /* Populate tail cache if needed. */ if (tail_cache_needed) { PopulateCacheFromPooledBuffer(entry_tail, range_tail); } /* Populate head cache if needed. */ if (head_cache_needed) { PopulateCacheFromPooledBuffer(entry_head, range_head); } /* If both entries are cached, one may contain the other; in that case, we need only the larger entry. */ if (entry_head->is_cached && entry_tail->is_cached) { if (entry_tail->range.offset <= entry_head->range.offset && entry_head->range.GetEndOffset() <= entry_tail->range.GetEndOffset()) { entry_head->is_cached = false; } else if (entry_head->range.offset <= entry_tail->range.offset && entry_tail->range.GetEndOffset() <= entry_head->range.GetEndOffset()) { entry_tail->is_cached = false; } } /* Destroy the tail cache. */ tail_guard.Cancel(); if (entry_tail->is_cached) { R_TRY(this->UpdateLastResult(this->StoreOrDestroyBuffer(*range_tail, entry_tail))); } else { m_block_cache_manager.ReleaseCacheEntry(entry_tail, *range_tail); } /* Destroy the head cache. */ head_guard.Cancel(); if (entry_head->is_cached) { R_TRY(this->UpdateLastResult(this->StoreOrDestroyBuffer(*range_head, entry_head))); } else { m_block_cache_manager.ReleaseCacheEntry(entry_head, *range_head); } R_SUCCEED(); } }
46,146
C++
.cpp
838
43.328162
260
0.590741
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,353
fssystem_utility.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssystem/fssystem_utility.cpp
/* * Copyright (c) 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 { namespace { Result EnsureDirectoryImpl(fs::fsa::IFileSystem *fs, const fs::Path &path) { /* Create work path. */ fs::Path work_path; R_TRY(work_path.Initialize(path)); /* Create a directory path parser. */ fs::DirectoryPathParser parser; R_TRY(parser.Initialize(std::addressof(work_path))); bool is_finished; do { /* Get the current path. */ const fs::Path &cur_path = parser.GetCurrentPath(); /* Get the entry type for the current path. */ fs::DirectoryEntryType type; R_TRY_CATCH(fs->GetEntryType(std::addressof(type), cur_path)) { R_CATCH(fs::ResultPathNotFound) { /* The path doesn't exist. We should create it. */ R_TRY(fs->CreateDirectory(cur_path)); /* Get the updated entry type. */ R_TRY(fs->GetEntryType(std::addressof(type), cur_path)); } } R_END_TRY_CATCH; /* Verify that the current entry isn't a file. */ R_UNLESS(type != fs::DirectoryEntryType_File, fs::ResultPathAlreadyExists()); /* Advance to the next part of the path. */ R_TRY(parser.ReadNext(std::addressof(is_finished))); } while (!is_finished); R_SUCCEED(); } Result HasEntry(bool *out, fs::fsa::IFileSystem *fsa, const fs::Path &path, fs::DirectoryEntryType type) { /* Set out to false initially. */ *out = false; /* Try to get the entry type. */ fs::DirectoryEntryType entry_type; R_TRY_CATCH(fsa->GetEntryType(std::addressof(entry_type), path)) { /* If the path doesn't exist, nothing has gone wrong. */ R_CONVERT(fs::ResultPathNotFound, ResultSuccess()); } R_END_TRY_CATCH; /* We succeeded. */ *out = entry_type == type; R_SUCCEED(); } } Result CopyFile(fs::fsa::IFileSystem *dst_fs, fs::fsa::IFileSystem *src_fs, const fs::Path &dst_path, const fs::Path &src_path, void *work_buf, size_t work_buf_size) { /* Open source file. */ std::unique_ptr<fs::fsa::IFile> src_file; R_TRY(src_fs->OpenFile(std::addressof(src_file), src_path, fs::OpenMode_Read)); /* Get the file size. */ s64 file_size; R_TRY(src_file->GetSize(std::addressof(file_size))); /* Open dst file. */ std::unique_ptr<fs::fsa::IFile> dst_file; R_TRY(dst_fs->CreateFile(dst_path, file_size)); R_TRY(dst_fs->OpenFile(std::addressof(dst_file), dst_path, fs::OpenMode_Write)); /* Read/Write file in work buffer sized chunks. */ s64 remaining = file_size; s64 offset = 0; while (remaining > 0) { size_t read_size; R_TRY(src_file->Read(std::addressof(read_size), offset, work_buf, work_buf_size, fs::ReadOption())); R_TRY(dst_file->Write(offset, work_buf, read_size, fs::WriteOption())); remaining -= read_size; offset += read_size; } R_SUCCEED(); } Result CopyDirectoryRecursively(fs::fsa::IFileSystem *dst_fs, fs::fsa::IFileSystem *src_fs, const fs::Path &dst_path, const fs::Path &src_path, fs::DirectoryEntry *entry, void *work_buf, size_t work_buf_size) { /* Set up the destination work path to point at the target directory. */ fs::Path dst_work_path; R_TRY(dst_work_path.Initialize(dst_path)); /* Iterate, copying files. */ R_RETURN(IterateDirectoryRecursively(src_fs, src_path, entry, [&](const fs::Path &path, const fs::DirectoryEntry &entry) -> Result { /* On Enter Directory */ AMS_UNUSED(path, entry); /* Append the current entry to the dst work path. */ R_TRY(dst_work_path.AppendChild(entry.name)); /* Create the directory. */ R_RETURN(dst_fs->CreateDirectory(dst_work_path)); }, [&](const fs::Path &path, const fs::DirectoryEntry &entry) -> Result { /* On Exit Directory */ AMS_UNUSED(path, entry); /* Remove the directory we're leaving from the dst work path. */ R_RETURN(dst_work_path.RemoveChild()); }, [&](const fs::Path &path, const fs::DirectoryEntry &entry) -> Result { /* On File */ /* Append the current entry to the dst work path. */ R_TRY(dst_work_path.AppendChild(entry.name)); /* Copy the file. */ R_TRY(fssystem::CopyFile(dst_fs, src_fs, dst_work_path, path, work_buf, work_buf_size)); /* Remove the current entry from the dst work path. */ R_RETURN(dst_work_path.RemoveChild()); } )); } Result HasFile(bool *out, fs::fsa::IFileSystem *fs, const fs::Path &path) { R_RETURN(HasEntry(out, fs, path, fs::DirectoryEntryType_File)); } Result HasDirectory(bool *out, fs::fsa::IFileSystem *fs, const fs::Path &path) { R_RETURN(HasEntry(out, fs, path, fs::DirectoryEntryType_Directory)); } Result EnsureDirectory(fs::fsa::IFileSystem *fs, const fs::Path &path) { /* First, check if the directory already exists. If it does, we're good to go. */ fs::DirectoryEntryType type; R_TRY_CATCH(fs->GetEntryType(std::addressof(type), path)) { /* If the directory doesn't already exist, we should create it. */ R_CATCH(fs::ResultPathNotFound) { R_TRY(EnsureDirectoryImpl(fs, path)); } } R_END_TRY_CATCH; R_SUCCEED(); } Result TryAcquireCountSemaphore(util::unique_lock<SemaphoreAdaptor> *out, SemaphoreAdaptor *adaptor) { /* Create deferred unique lock. */ util::unique_lock<SemaphoreAdaptor> lock(*adaptor, std::defer_lock); /* Try to lock. */ R_UNLESS(lock.try_lock(), fs::ResultOpenCountLimit()); /* Set the output lock. */ *out = std::move(lock); R_SUCCEED(); } void AddCounter(void *_counter, size_t counter_size, u64 value) { u8 *counter = static_cast<u8 *>(_counter); u64 remaining = value; u8 carry = 0; for (size_t i = 0; i < counter_size; i++) { auto sum = counter[counter_size - 1 - i] + (remaining & 0xFF) + carry; carry = static_cast<u8>(sum >> BITSIZEOF(u8)); auto sum8 = static_cast<u8>(sum & 0xFF); counter[counter_size - 1 - i] = sum8; remaining >>= BITSIZEOF(u8); if (carry == 0 && remaining == 0) { break; } } } }
7,605
C++
.cpp
153
38.633987
214
0.575745
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,354
fssystem_sparse_storage.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssystem/fssystem_sparse_storage.cpp
/* * Copyright (c) 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 { Result SparseStorage::Read(s64 offset, void *buffer, size_t size) { /* Validate preconditions. */ AMS_ASSERT(offset >= 0); AMS_ASSERT(this->IsInitialized()); /* Allow zero size. */ R_SUCCEED_IF(size == 0); /* Validate arguments. */ R_UNLESS(buffer != nullptr, fs::ResultNullptrArgument()); if (this->GetEntryTable().IsEmpty()) { BucketTree::Offsets table_offsets; R_TRY(this->GetEntryTable().GetOffsets(std::addressof(table_offsets))); R_UNLESS(table_offsets.IsInclude(offset, size), fs::ResultOutOfRange()); std::memset(buffer, 0, size); } else { R_TRY((this->OperatePerEntry<false, true>(offset, size, [=](fs::IStorage *storage, s64 data_offset, s64 cur_offset, s64 cur_size) -> Result { R_TRY(storage->Read(data_offset, reinterpret_cast<u8 *>(buffer) + (cur_offset - offset), static_cast<size_t>(cur_size))); R_SUCCEED(); }))); } R_SUCCEED(); } }
1,748
C++
.cpp
39
38.102564
153
0.649412
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,355
fssystem_bucket_tree.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssystem/fssystem_bucket_tree.cpp
/* * Copyright (c) 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 { namespace { using Node = impl::BucketTreeNode<const s64 *>; static_assert(sizeof(Node) == sizeof(BucketTree::NodeHeader)); static_assert(util::is_pod<Node>::value); constexpr inline s32 NodeHeaderSize = sizeof(BucketTree::NodeHeader); class StorageNode { private: class Offset { public: using difference_type = s64; private: s64 m_offset; s32 m_stride; public: constexpr Offset(s64 offset, s32 stride) : m_offset(offset), m_stride(stride) { /* ... */ } constexpr Offset &operator++() { m_offset += m_stride; return *this; } constexpr Offset operator++(int) { Offset ret(*this); m_offset += m_stride; return ret; } constexpr Offset &operator--() { m_offset -= m_stride; return *this; } constexpr Offset operator--(int) { Offset ret(*this); m_offset -= m_stride; return ret; } constexpr difference_type operator-(const Offset &rhs) const { return (m_offset - rhs.m_offset) / m_stride; } constexpr Offset operator+(difference_type ofs) const { return Offset(m_offset + ofs * m_stride, m_stride); } constexpr Offset operator-(difference_type ofs) const { return Offset(m_offset - ofs * m_stride, m_stride); } constexpr Offset &operator+=(difference_type ofs) { m_offset += ofs * m_stride; return *this; } constexpr Offset &operator-=(difference_type ofs) { m_offset -= ofs * m_stride; return *this; } constexpr bool operator==(const Offset &rhs) const { return m_offset == rhs.m_offset; } constexpr bool operator!=(const Offset &rhs) const { return m_offset != rhs.m_offset; } constexpr s64 Get() const { return m_offset; } }; private: const Offset m_start; const s32 m_count; s32 m_index; public: StorageNode(size_t size, s32 count) : m_start(NodeHeaderSize, static_cast<s32>(size)), m_count(count), m_index(-1) { /* ... */ } StorageNode(s64 ofs, size_t size, s32 count) : m_start(NodeHeaderSize + ofs, static_cast<s32>(size)), m_count(count), m_index(-1) { /* ... */ } s32 GetIndex() const { return m_index; } void Find(const char *buffer, s64 virtual_address) { s32 end = m_count; auto pos = m_start; while (end > 0) { auto half = end / 2; auto mid = pos + half; s64 offset = 0; std::memcpy(std::addressof(offset), buffer + mid.Get(), sizeof(s64)); if (offset <= virtual_address) { pos = mid + 1; end -= half + 1; } else { end = half; } } m_index = static_cast<s32>(pos - m_start) - 1; } Result Find(fs::SubStorage &storage, s64 virtual_address) { s32 end = m_count; auto pos = m_start; while (end > 0) { auto half = end / 2; auto mid = pos + half; s64 offset = 0; R_TRY(storage.Read(mid.Get(), std::addressof(offset), sizeof(s64))); if (offset <= virtual_address) { pos = mid + 1; end -= half + 1; } else { end = half; } } m_index = static_cast<s32>(pos - m_start) - 1; R_SUCCEED(); } }; } void BucketTree::Header::Format(s32 entry_count) { AMS_ASSERT(entry_count >= 0); this->magic = Magic; this->version = Version; this->entry_count = entry_count; this->reserved = 0; } Result BucketTree::Header::Verify() const { R_UNLESS(this->magic == Magic, fs::ResultInvalidBucketTreeSignature()); R_UNLESS(this->entry_count >= 0, fs::ResultInvalidBucketTreeEntryCount()); R_UNLESS(this->version <= Version, fs::ResultUnsupportedVersion()); R_SUCCEED(); } Result BucketTree::NodeHeader::Verify(s32 node_index, size_t node_size, size_t entry_size) const { R_UNLESS(this->index == node_index, fs::ResultInvalidBucketTreeNodeIndex()); R_UNLESS(entry_size != 0 && node_size >= entry_size + NodeHeaderSize, fs::ResultInvalidSize()); const size_t max_entry_count = (node_size - NodeHeaderSize) / entry_size; R_UNLESS(this->count > 0 && static_cast<size_t>(this->count) <= max_entry_count, fs::ResultInvalidBucketTreeNodeEntryCount()); R_UNLESS(this->offset >= 0, fs::ResultInvalidBucketTreeNodeOffset()); R_SUCCEED(); } Result BucketTree::Initialize(IAllocator *allocator, fs::SubStorage node_storage, fs::SubStorage entry_storage, size_t node_size, size_t entry_size, s32 entry_count) { /* Validate preconditions. */ AMS_ASSERT(allocator != nullptr); AMS_ASSERT(entry_size >= sizeof(s64)); AMS_ASSERT(node_size >= entry_size + sizeof(NodeHeader)); AMS_ASSERT(NodeSizeMin <= node_size && node_size <= NodeSizeMax); AMS_ASSERT(util::IsPowerOfTwo(node_size)); AMS_ASSERT(!this->IsInitialized()); /* Ensure valid entry count. */ R_UNLESS(entry_count > 0, fs::ResultInvalidArgument()); /* Allocate node. */ R_UNLESS(m_node_l1.Allocate(allocator, node_size), fs::ResultBufferAllocationFailed()); ON_RESULT_FAILURE { m_node_l1.Free(node_size); }; /* Read node. */ R_TRY(node_storage.Read(0, m_node_l1.Get(), node_size)); /* Verify node. */ R_TRY(m_node_l1->Verify(0, node_size, sizeof(s64))); /* Validate offsets. */ const auto offset_count = GetOffsetCount(node_size); const auto entry_set_count = GetEntrySetCount(node_size, entry_size, entry_count); const auto * const node = m_node_l1.Get<Node>(); s64 start_offset; if (offset_count < entry_set_count && node->GetCount() < offset_count) { start_offset = *node->GetEnd(); } else { start_offset = *node->GetBegin(); } const auto end_offset = node->GetEndOffset(); R_UNLESS(0 <= start_offset && start_offset <= node->GetBeginOffset(), fs::ResultInvalidBucketTreeEntryOffset()); R_UNLESS(start_offset < end_offset, fs::ResultInvalidBucketTreeEntryOffset()); /* Set member variables. */ m_node_storage = node_storage; m_entry_storage = entry_storage; m_node_size = node_size; m_entry_size = entry_size; m_entry_count = entry_count; m_offset_count = offset_count; m_entry_set_count = entry_set_count; m_offset_cache.offsets.start_offset = start_offset; m_offset_cache.offsets.end_offset = end_offset; m_offset_cache.is_initialized = true; /* We succeeded. */ R_SUCCEED(); } void BucketTree::Initialize(size_t node_size, s64 end_offset) { AMS_ASSERT(NodeSizeMin <= node_size && node_size <= NodeSizeMax); AMS_ASSERT(util::IsPowerOfTwo(node_size)); AMS_ASSERT(end_offset > 0); AMS_ASSERT(!this->IsInitialized()); m_node_size = node_size; m_offset_cache.offsets.start_offset = 0; m_offset_cache.offsets.end_offset = end_offset; m_offset_cache.is_initialized = true; } void BucketTree::Finalize() { if (this->IsInitialized()) { m_node_storage = fs::SubStorage(); m_entry_storage = fs::SubStorage(); m_node_l1.Free(m_node_size); m_node_size = 0; m_entry_size = 0; m_entry_count = 0; m_offset_count = 0; m_entry_set_count = 0; m_offset_cache.offsets.start_offset = 0; m_offset_cache.offsets.end_offset = 0; m_offset_cache.is_initialized = false; } } Result BucketTree::Find(Visitor *visitor, s64 virtual_address) { AMS_ASSERT(visitor != nullptr); AMS_ASSERT(this->IsInitialized()); R_UNLESS(virtual_address >= 0, fs::ResultInvalidOffset()); R_UNLESS(!this->IsEmpty(), fs::ResultOutOfRange()); BucketTree::Offsets offsets; R_TRY(this->GetOffsets(std::addressof(offsets))); R_TRY(visitor->Initialize(this, offsets)); R_RETURN(visitor->Find(virtual_address)); } Result BucketTree::InvalidateCache() { /* Invalidate the node storage cache. */ R_TRY(m_node_storage.OperateRange(fs::OperationId::Invalidate, 0, std::numeric_limits<s64>::max())); /* Invalidate the entry storage cache. */ R_TRY(m_entry_storage.OperateRange(fs::OperationId::Invalidate, 0, std::numeric_limits<s64>::max())); /* Reset our offsets. */ m_offset_cache.is_initialized = false; R_SUCCEED(); } Result BucketTree::EnsureOffsetCache() { /* If we already have an offset cache, we're good. */ R_SUCCEED_IF(m_offset_cache.is_initialized); /* Acquire exclusive right to edit the offset cache. */ std::scoped_lock lk(m_offset_cache.mutex); /* Check again, to be sure. */ R_SUCCEED_IF(m_offset_cache.is_initialized); /* Read/verify L1. */ R_TRY(m_node_storage.Read(0, m_node_l1.Get(), m_node_size)); R_TRY(m_node_l1->Verify(0, m_node_size, sizeof(s64))); /* Get the node. */ auto * const node = m_node_l1.Get<Node>(); s64 start_offset; if (m_offset_count < m_entry_set_count && node->GetCount() < m_offset_count) { start_offset = *node->GetEnd(); } else { start_offset = *node->GetBegin(); } const auto end_offset = node->GetEndOffset(); R_UNLESS(0 <= start_offset && start_offset <= node->GetBeginOffset(), fs::ResultInvalidBucketTreeEntryOffset()); R_UNLESS(start_offset < end_offset, fs::ResultInvalidBucketTreeEntryOffset()); m_offset_cache.offsets.start_offset = start_offset; m_offset_cache.offsets.end_offset = end_offset; m_offset_cache.is_initialized = true; R_SUCCEED(); } Result BucketTree::Visitor::Initialize(const BucketTree *tree, const BucketTree::Offsets &offsets) { AMS_ASSERT(tree != nullptr); AMS_ASSERT(m_tree == nullptr || m_tree == tree); if (m_entry == nullptr) { m_entry = tree->GetAllocator()->Allocate(tree->m_entry_size); R_UNLESS(m_entry != nullptr, fs::ResultBufferAllocationFailed()); m_tree = tree; m_offsets = offsets; } R_SUCCEED(); } Result BucketTree::Visitor::MoveNext() { R_UNLESS(this->IsValid(), fs::ResultOutOfRange()); /* Invalidate our index, and read the header for the next index. */ auto entry_index = m_entry_index + 1; if (entry_index == m_entry_set.info.count) { const auto entry_set_index = m_entry_set.info.index + 1; R_UNLESS(entry_set_index < m_entry_set_count, fs::ResultOutOfRange()); m_entry_index = -1; const auto end = m_entry_set.info.end; const auto entry_set_size = m_tree->m_node_size; const auto entry_set_offset = entry_set_index * static_cast<s64>(entry_set_size); R_TRY(m_tree->m_entry_storage.Read(entry_set_offset, std::addressof(m_entry_set), sizeof(EntrySetHeader))); R_TRY(m_entry_set.header.Verify(entry_set_index, entry_set_size, m_tree->m_entry_size)); R_UNLESS(m_entry_set.info.start == end && m_entry_set.info.start < m_entry_set.info.end, fs::ResultInvalidBucketTreeEntrySetOffset()); entry_index = 0; } else { m_entry_index = -1; } /* Read the new entry. */ const auto entry_size = m_tree->m_entry_size; const auto entry_offset = impl::GetBucketTreeEntryOffset(m_entry_set.info.index, m_tree->m_node_size, entry_size, entry_index); R_TRY(m_tree->m_entry_storage.Read(entry_offset, m_entry, entry_size)); /* Note that we changed index. */ m_entry_index = entry_index; R_SUCCEED(); } Result BucketTree::Visitor::MovePrevious() { R_UNLESS(this->IsValid(), fs::ResultOutOfRange()); /* Invalidate our index, and read the heasder for the previous index. */ auto entry_index = m_entry_index; if (entry_index == 0) { R_UNLESS(m_entry_set.info.index > 0, fs::ResultOutOfRange()); m_entry_index = -1; const auto start = m_entry_set.info.start; const auto entry_set_size = m_tree->m_node_size; const auto entry_set_index = m_entry_set.info.index - 1; const auto entry_set_offset = entry_set_index * static_cast<s64>(entry_set_size); R_TRY(m_tree->m_entry_storage.Read(entry_set_offset, std::addressof(m_entry_set), sizeof(EntrySetHeader))); R_TRY(m_entry_set.header.Verify(entry_set_index, entry_set_size, m_tree->m_entry_size)); R_UNLESS(m_entry_set.info.end == start && m_entry_set.info.start < m_entry_set.info.end, fs::ResultInvalidBucketTreeEntrySetOffset()); entry_index = m_entry_set.info.count; } else { m_entry_index = -1; } --entry_index; /* Read the new entry. */ const auto entry_size = m_tree->m_entry_size; const auto entry_offset = impl::GetBucketTreeEntryOffset(m_entry_set.info.index, m_tree->m_node_size, entry_size, entry_index); R_TRY(m_tree->m_entry_storage.Read(entry_offset, m_entry, entry_size)); /* Note that we changed index. */ m_entry_index = entry_index; R_SUCCEED(); } Result BucketTree::Visitor::Find(s64 virtual_address) { AMS_ASSERT(m_tree != nullptr); /* Get the node. */ const auto * const node = m_tree->m_node_l1.Get<Node>(); R_UNLESS(virtual_address < node->GetEndOffset(), fs::ResultOutOfRange()); /* Get the entry set index. */ s32 entry_set_index = -1; if (m_tree->IsExistOffsetL2OnL1() && virtual_address < node->GetBeginOffset()) { const auto start = node->GetEnd(); const auto end = node->GetBegin() + m_tree->m_offset_count; auto pos = std::upper_bound(start, end, virtual_address); R_UNLESS(start < pos, fs::ResultOutOfRange()); --pos; entry_set_index = static_cast<s32>(pos - start); } else { const auto start = node->GetBegin(); const auto end = node->GetEnd(); auto pos = std::upper_bound(start, end, virtual_address); R_UNLESS(start < pos, fs::ResultOutOfRange()); --pos; if (m_tree->IsExistL2()) { const auto node_index = static_cast<s32>(pos - start); R_UNLESS(0 <= node_index && node_index < m_tree->m_offset_count, fs::ResultInvalidBucketTreeNodeOffset()); R_TRY(this->FindEntrySet(std::addressof(entry_set_index), virtual_address, node_index)); } else { entry_set_index = static_cast<s32>(pos - start); } } /* Validate the entry set index. */ R_UNLESS(0 <= entry_set_index && entry_set_index < m_tree->m_entry_set_count, fs::ResultInvalidBucketTreeNodeOffset()); /* Find the entry. */ R_TRY(this->FindEntry(virtual_address, entry_set_index)); /* Set count. */ m_entry_set_count = m_tree->m_entry_set_count; R_SUCCEED(); } Result BucketTree::Visitor::FindEntrySet(s32 *out_index, s64 virtual_address, s32 node_index) { const auto node_size = m_tree->m_node_size; PooledBuffer pool(node_size, 1); if (node_size <= pool.GetSize()) { R_RETURN(this->FindEntrySetWithBuffer(out_index, virtual_address, node_index, pool.GetBuffer())); } else { pool.Deallocate(); R_RETURN(this->FindEntrySetWithoutBuffer(out_index, virtual_address, node_index)); } } Result BucketTree::Visitor::FindEntrySetWithBuffer(s32 *out_index, s64 virtual_address, s32 node_index, char *buffer) { /* Calculate node extents. */ const auto node_size = m_tree->m_node_size; const auto node_offset = (node_index + 1) * static_cast<s64>(node_size); fs::SubStorage &storage = m_tree->m_node_storage; /* Read the node. */ R_TRY(storage.Read(node_offset, buffer, node_size)); /* Validate the header. */ NodeHeader header; std::memcpy(std::addressof(header), buffer, NodeHeaderSize); R_TRY(header.Verify(node_index, node_size, sizeof(s64))); /* Create the node, and find. */ StorageNode node(sizeof(s64), header.count); node.Find(buffer, virtual_address); R_UNLESS(node.GetIndex() >= 0, fs::ResultInvalidBucketTreeVirtualOffset()); /* Return the index. */ *out_index = m_tree->GetEntrySetIndex(header.index, node.GetIndex()); R_SUCCEED(); } Result BucketTree::Visitor::FindEntrySetWithoutBuffer(s32 *out_index, s64 virtual_address, s32 node_index) { /* Calculate node extents. */ const auto node_size = m_tree->m_node_size; const auto node_offset = (node_index + 1) * static_cast<s64>(node_size); fs::SubStorage &storage = m_tree->m_node_storage; /* Read and validate the header. */ NodeHeader header; R_TRY(storage.Read(node_offset, std::addressof(header), NodeHeaderSize)); R_TRY(header.Verify(node_index, node_size, sizeof(s64))); /* Create the node, and find. */ StorageNode node(node_offset, sizeof(s64), header.count); R_TRY(node.Find(storage, virtual_address)); R_UNLESS(node.GetIndex() >= 0, fs::ResultOutOfRange()); /* Return the index. */ *out_index = m_tree->GetEntrySetIndex(header.index, node.GetIndex()); R_SUCCEED(); } Result BucketTree::Visitor::FindEntry(s64 virtual_address, s32 entry_set_index) { const auto entry_set_size = m_tree->m_node_size; PooledBuffer pool(entry_set_size, 1); if (entry_set_size <= pool.GetSize()) { R_RETURN(this->FindEntryWithBuffer(virtual_address, entry_set_index, pool.GetBuffer())); } else { pool.Deallocate(); R_RETURN(this->FindEntryWithoutBuffer(virtual_address, entry_set_index)); } } Result BucketTree::Visitor::FindEntryWithBuffer(s64 virtual_address, s32 entry_set_index, char *buffer) { /* Calculate entry set extents. */ const auto entry_size = m_tree->m_entry_size; const auto entry_set_size = m_tree->m_node_size; const auto entry_set_offset = entry_set_index * static_cast<s64>(entry_set_size); fs::SubStorage &storage = m_tree->m_entry_storage; /* Read the entry set. */ R_TRY(storage.Read(entry_set_offset, buffer, entry_set_size)); /* Validate the entry_set. */ EntrySetHeader entry_set; std::memcpy(std::addressof(entry_set), buffer, sizeof(EntrySetHeader)); R_TRY(entry_set.header.Verify(entry_set_index, entry_set_size, entry_size)); /* Create the node, and find. */ StorageNode node(entry_size, entry_set.info.count); node.Find(buffer, virtual_address); R_UNLESS(node.GetIndex() >= 0, fs::ResultOutOfRange()); /* Copy the data into entry. */ const auto entry_index = node.GetIndex(); const auto entry_offset = impl::GetBucketTreeEntryOffset(0, entry_size, entry_index); std::memcpy(m_entry, buffer + entry_offset, entry_size); /* Set our entry set/index. */ m_entry_set = entry_set; m_entry_index = entry_index; R_SUCCEED(); } Result BucketTree::Visitor::FindEntryWithoutBuffer(s64 virtual_address, s32 entry_set_index) { /* Calculate entry set extents. */ const auto entry_size = m_tree->m_entry_size; const auto entry_set_size = m_tree->m_node_size; const auto entry_set_offset = entry_set_index * static_cast<s64>(entry_set_size); fs::SubStorage &storage = m_tree->m_entry_storage; /* Read and validate the entry_set. */ EntrySetHeader entry_set; R_TRY(storage.Read(entry_set_offset, std::addressof(entry_set), sizeof(EntrySetHeader))); R_TRY(entry_set.header.Verify(entry_set_index, entry_set_size, entry_size)); /* Create the node, and find. */ StorageNode node(entry_set_offset, entry_size, entry_set.info.count); R_TRY(node.Find(storage, virtual_address)); R_UNLESS(node.GetIndex() >= 0, fs::ResultOutOfRange()); /* Copy the data into entry. */ const auto entry_index = node.GetIndex(); const auto entry_offset = impl::GetBucketTreeEntryOffset(entry_set_offset, entry_size, entry_index); R_TRY(storage.Read(entry_offset, m_entry, entry_size)); /* Set our entry set/index. */ m_entry_set = entry_set; m_entry_index = entry_index; R_SUCCEED(); } }
22,898
C++
.cpp
430
41.951163
171
0.581666
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,356
fssystem_external_code.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssystem/fssystem_external_code.cpp
/* * Copyright (c) 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 { #if defined(ATMOSPHERE_BOARD_NINTENDO_NX) namespace { constexpr inline size_t MaxExternalCodeFileSystem = 0x10; util::BoundedMap<ncm::ProgramId, fs::RemoteFileSystem, MaxExternalCodeFileSystem> g_ecs_map; util::BoundedMap<ncm::ProgramId, os::NativeHandle, MaxExternalCodeFileSystem> g_hnd_map; } fs::fsa::IFileSystem *GetExternalCodeFileSystem(ncm::ProgramId program_id) { /* Return a fs from the map if one exists. */ if (auto *fs = g_ecs_map.Find(program_id); fs != nullptr) { return fs; } /* Otherwise, we may have a handle. */ if (auto *hnd = g_hnd_map.Find(program_id); hnd != nullptr) { /* Create a service using libnx bindings. */ Service srv; serviceCreate(std::addressof(srv), *hnd); g_hnd_map.Remove(program_id); /* Create a remote filesystem. */ const FsFileSystem fs = { srv }; g_ecs_map.Emplace(program_id, fs); /* Return the created filesystem. */ return g_ecs_map.Find(program_id); } /* Otherwise, we have no filesystem. */ return nullptr; } Result CreateExternalCode(os::NativeHandle *out, ncm::ProgramId program_id) { /* Create a handle pair. */ os::NativeHandle server, client; R_TRY(svc::CreateSession(std::addressof(server), std::addressof(client), false, 0)); /* Insert the handle into the map. */ g_hnd_map.Emplace(program_id, client); *out = server; R_SUCCEED(); } void DestroyExternalCode(ncm::ProgramId program_id) { g_ecs_map.Remove(program_id); if (auto *hnd = g_hnd_map.Find(program_id); hnd != nullptr) { os::CloseNativeHandle(*hnd); g_hnd_map.Remove(program_id); } } #else fs::fsa::IFileSystem *GetExternalCodeFileSystem(ncm::ProgramId program_id) { AMS_UNUSED(program_id); return nullptr; } Result CreateExternalCode(os::NativeHandle *out, ncm::ProgramId program_id) { AMS_UNUSED(out, program_id); R_THROW(fs::ResultNotImplemented()); } void DestroyExternalCode(ncm::ProgramId program_id) { AMS_UNUSED(program_id); } #endif }
2,990
C++
.cpp
73
33.739726
100
0.645841
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,357
fssystem_nca_reader.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssystem/fssystem_nca_reader.cpp
/* * Copyright (c) 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 { namespace { constexpr inline u32 SdkAddonVersionMin = 0x000B0000; constexpr Result CheckNcaMagic(u32 magic) { /* Verify the magic is not a deprecated one. */ R_UNLESS(magic != NcaHeader::Magic0, fs::ResultUnsupportedSdkVersion()); R_UNLESS(magic != NcaHeader::Magic1, fs::ResultUnsupportedSdkVersion()); R_UNLESS(magic != NcaHeader::Magic2, fs::ResultUnsupportedSdkVersion()); /* Verify the magic is the current one. */ R_UNLESS(magic == NcaHeader::Magic3, fs::ResultInvalidNcaSignature()); R_SUCCEED(); } } NcaReader::NcaReader() : m_body_storage(), m_header_storage(), m_decrypt_aes_ctr(), m_decrypt_aes_ctr_external(), m_is_software_aes_prioritized(false), m_is_available_sw_key(false), m_header_encryption_type(NcaHeader::EncryptionType::Auto), m_get_decompressor(), m_hash_generator_factory_selector() { std::memset(std::addressof(m_header), 0, sizeof(m_header)); std::memset(std::addressof(m_decryption_keys), 0, sizeof(m_decryption_keys)); std::memset(std::addressof(m_external_decryption_key), 0, sizeof(m_external_decryption_key)); } NcaReader::~NcaReader() { /* ... */ } Result NcaReader::Initialize(std::shared_ptr<fs::IStorage> base_storage, const NcaCryptoConfiguration &crypto_cfg, const NcaCompressionConfiguration &compression_cfg, IHash256GeneratorFactorySelector *hgf_selector) { /* Validate preconditions. */ AMS_ASSERT(base_storage != nullptr); AMS_ASSERT(hgf_selector != nullptr); AMS_ASSERT(m_body_storage == nullptr); /* Check that the crypto config is valid. */ R_UNLESS(crypto_cfg.verify_sign1 != nullptr, fs::ResultInvalidArgument()); /* Create the work header storage storage. */ std::unique_ptr<fs::IStorage> work_header_storage; if (crypto_cfg.is_available_sw_key) { /* If software key is available, we need to be able to generate keys. */ R_UNLESS(crypto_cfg.generate_key != nullptr, fs::ResultInvalidArgument()); /* Generate keys for header. */ using AesXtsStorageForNcaHeader = AesXtsStorageBySharedPointer; constexpr const s32 HeaderKeyTypeValues[NcaCryptoConfiguration::HeaderEncryptionKeyCount] = { static_cast<s32>(KeyType::NcaHeaderKey1), static_cast<s32>(KeyType::NcaHeaderKey2), }; u8 header_decryption_keys[NcaCryptoConfiguration::HeaderEncryptionKeyCount][NcaCryptoConfiguration::Aes128KeySize]; for (size_t i = 0; i < NcaCryptoConfiguration::HeaderEncryptionKeyCount; i++) { crypto_cfg.generate_key(header_decryption_keys[i], AesXtsStorageForNcaHeader::KeySize, crypto_cfg.header_encrypted_encryption_keys[i], AesXtsStorageForNcaHeader::KeySize, HeaderKeyTypeValues[i]); } /* Create the header storage. */ const u8 header_iv[AesXtsStorageForNcaHeader::IvSize] = {}; work_header_storage = std::make_unique<AesXtsStorageForNcaHeader>(base_storage, header_decryption_keys[0], header_decryption_keys[1], AesXtsStorageForNcaHeader::KeySize, header_iv, AesXtsStorageForNcaHeader::IvSize, NcaHeader::XtsBlockSize); } else { /* Software key isn't available, so we need to be able to decrypt externally. */ R_UNLESS(crypto_cfg.decrypt_aes_xts_external, fs::ResultInvalidArgument()); /* Create the header storage. */ using AesXtsStorageExternalForNcaHeader = AesXtsStorageExternalByPointer; const u8 header_iv[AesXtsStorageExternalForNcaHeader::IvSize] = {}; work_header_storage = std::make_unique<AesXtsStorageExternalForNcaHeader>(base_storage.get(), nullptr, nullptr, AesXtsStorageExternalForNcaHeader::KeySize, header_iv, AesXtsStorageExternalForNcaHeader::IvSize, NcaHeader::XtsBlockSize, crypto_cfg.encrypt_aes_xts_external, crypto_cfg.decrypt_aes_xts_external); } /* Check that we successfully created the storage. */ R_UNLESS(work_header_storage != nullptr, fs::ResultAllocationMemoryFailedInNcaReaderA()); /* Read the header. */ R_TRY(work_header_storage->Read(0, std::addressof(m_header), sizeof(m_header))); /* Validate the magic. */ if (const Result magic_result = CheckNcaMagic(m_header.magic); R_FAILED(magic_result)) { /* If we're not allowed to use plaintext headers, stop here. */ R_UNLESS(crypto_cfg.is_plaintext_header_available, magic_result); /* Try to use a plaintext header. */ R_TRY(base_storage->Read(0, std::addressof(m_header), sizeof(m_header))); R_UNLESS(R_SUCCEEDED(CheckNcaMagic(m_header.magic)), magic_result); /* Configure to use the plaintext header. */ s64 base_storage_size; R_TRY(base_storage->GetSize(std::addressof(base_storage_size))); work_header_storage.reset(new fs::SubStorage(base_storage, 0, base_storage_size)); R_UNLESS(work_header_storage != nullptr, fs::ResultAllocationMemoryFailedInNcaReaderA()); /* Set encryption type as plaintext. */ m_header_encryption_type = NcaHeader::EncryptionType::None; } /* Validate the fixed key signature. */ R_UNLESS(m_header.header1_signature_key_generation <= NcaCryptoConfiguration::Header1SignatureKeyGenerationMax, fs::ResultInvalidNcaHeader1SignatureKeyGeneration()); /* Verify the header sign1. */ { const u8 *sig = m_header.header_sign_1; const size_t sig_size = NcaHeader::HeaderSignSize; const u8 *msg = static_cast<const u8 *>(static_cast<const void *>(std::addressof(m_header.magic))); const size_t msg_size = NcaHeader::Size - NcaHeader::HeaderSignSize * NcaHeader::HeaderSignCount; m_is_header_sign1_signature_valid = crypto_cfg.verify_sign1(sig, sig_size, msg, msg_size, m_header.header1_signature_key_generation); #if defined(ATMOSPHERE_BOARD_NINTENDO_NX) R_UNLESS(m_is_header_sign1_signature_valid, fs::ResultNcaHeaderSignature1VerificationFailed()); #else R_UNLESS(m_is_header_sign1_signature_valid || crypto_cfg.is_unsigned_header_available_for_host_tool, fs::ResultNcaHeaderSignature1VerificationFailed()); #endif } /* Validate the sdk version. */ R_UNLESS(m_header.sdk_addon_version >= SdkAddonVersionMin, fs::ResultUnsupportedSdkVersion()); /* Validate the key index. */ R_UNLESS(m_header.key_index < NcaCryptoConfiguration::KeyAreaEncryptionKeyIndexCount || m_header.key_index == NcaCryptoConfiguration::KeyAreaEncryptionKeyIndexZeroKey, fs::ResultInvalidNcaKeyIndex()); /* Set our hash generator factory selector. */ m_hash_generator_factory_selector = hgf_selector; /* Check if we have a rights id. */ constexpr const u8 ZeroRightsId[NcaHeader::RightsIdSize] = {}; if (crypto::IsSameBytes(ZeroRightsId, m_header.rights_id, NcaHeader::RightsIdSize)) { /* If we don't, then we don't have an external key, so we need to generate decryption keys if software keys are available. */ if (crypto_cfg.is_available_sw_key) { crypto_cfg.generate_key(m_decryption_keys[NcaHeader::DecryptionKey_AesCtr], crypto::AesDecryptor128::KeySize, m_header.encrypted_key_area + NcaHeader::DecryptionKey_AesCtr * crypto::AesDecryptor128::KeySize, crypto::AesDecryptor128::KeySize, GetKeyTypeValue(m_header.key_index, m_header.GetProperKeyGeneration())); /* If we're building for non-nx board (i.e., a host tool), generate all keys for debug. */ #if !defined(ATMOSPHERE_BOARD_NINTENDO_NX) crypto_cfg.generate_key(m_decryption_keys[NcaHeader::DecryptionKey_AesXts1], crypto::AesDecryptor128::KeySize, m_header.encrypted_key_area + NcaHeader::DecryptionKey_AesXts1 * crypto::AesDecryptor128::KeySize, crypto::AesDecryptor128::KeySize, GetKeyTypeValue(m_header.key_index, m_header.GetProperKeyGeneration())); crypto_cfg.generate_key(m_decryption_keys[NcaHeader::DecryptionKey_AesXts2], crypto::AesDecryptor128::KeySize, m_header.encrypted_key_area + NcaHeader::DecryptionKey_AesXts2 * crypto::AesDecryptor128::KeySize, crypto::AesDecryptor128::KeySize, GetKeyTypeValue(m_header.key_index, m_header.GetProperKeyGeneration())); crypto_cfg.generate_key(m_decryption_keys[NcaHeader::DecryptionKey_AesCtrEx], crypto::AesDecryptor128::KeySize, m_header.encrypted_key_area + NcaHeader::DecryptionKey_AesCtrEx * crypto::AesDecryptor128::KeySize, crypto::AesDecryptor128::KeySize, GetKeyTypeValue(m_header.key_index, m_header.GetProperKeyGeneration())); #endif } /* Copy the hardware speed emulation key. */ std::memcpy(m_decryption_keys[NcaHeader::DecryptionKey_AesCtrHw], m_header.encrypted_key_area + NcaHeader::DecryptionKey_AesCtrHw * crypto::AesDecryptor128::KeySize, crypto::AesDecryptor128::KeySize); } /* Clear the external decryption key. */ std::memset(m_external_decryption_key, 0, sizeof(m_external_decryption_key)); /* Set software key availability. */ m_is_available_sw_key = crypto_cfg.is_available_sw_key; /* Set our decryptor functions. */ m_decrypt_aes_ctr = crypto_cfg.decrypt_aes_ctr; m_decrypt_aes_ctr_external = crypto_cfg.decrypt_aes_ctr_external; /* Set our decompressor function getter. */ m_get_decompressor = compression_cfg.get_decompressor; /* Set our storages. */ m_header_storage = std::move(work_header_storage); m_body_storage = std::move(base_storage); R_SUCCEED(); } std::shared_ptr<fs::IStorage> NcaReader::GetSharedBodyStorage() { AMS_ASSERT(m_body_storage != nullptr); return m_body_storage; } u32 NcaReader::GetMagic() const { AMS_ASSERT(m_body_storage != nullptr); return m_header.magic; } NcaHeader::DistributionType NcaReader::GetDistributionType() const { AMS_ASSERT(m_body_storage != nullptr); return m_header.distribution_type; } NcaHeader::ContentType NcaReader::GetContentType() const { AMS_ASSERT(m_body_storage != nullptr); return m_header.content_type; } u8 NcaReader::GetHeaderSign1KeyGeneration() const { AMS_ASSERT(m_body_storage != nullptr); return m_header.header1_signature_key_generation; } u8 NcaReader::GetKeyGeneration() const { AMS_ASSERT(m_body_storage != nullptr); return m_header.GetProperKeyGeneration(); } u8 NcaReader::GetKeyIndex() const { AMS_ASSERT(m_body_storage != nullptr); return m_header.key_index; } u64 NcaReader::GetContentSize() const { AMS_ASSERT(m_body_storage != nullptr); return m_header.content_size; } u64 NcaReader::GetProgramId() const { AMS_ASSERT(m_body_storage != nullptr); return m_header.program_id; } u32 NcaReader::GetContentIndex() const { AMS_ASSERT(m_body_storage != nullptr); return m_header.content_index; } u32 NcaReader::GetSdkAddonVersion() const { AMS_ASSERT(m_body_storage != nullptr); return m_header.sdk_addon_version; } void NcaReader::GetRightsId(u8 *dst, size_t dst_size) const { AMS_ASSERT(dst != nullptr); AMS_ASSERT(dst_size >= NcaHeader::RightsIdSize); AMS_UNUSED(dst_size); std::memcpy(dst, m_header.rights_id, NcaHeader::RightsIdSize); } bool NcaReader::HasFsInfo(s32 index) const { AMS_ASSERT(0 <= index && index < NcaHeader::FsCountMax); return m_header.fs_info[index].start_sector != 0 || m_header.fs_info[index].end_sector != 0; } s32 NcaReader::GetFsCount() const { AMS_ASSERT(m_body_storage != nullptr); for (s32 i = 0; i < NcaHeader::FsCountMax; i++) { if (!this->HasFsInfo(i)) { return i; } } return NcaHeader::FsCountMax; } const Hash &NcaReader::GetFsHeaderHash(s32 index) const { AMS_ASSERT(m_body_storage != nullptr); AMS_ASSERT(0 <= index && index < NcaHeader::FsCountMax); return m_header.fs_header_hash[index]; } void NcaReader::GetFsHeaderHash(Hash *dst, s32 index) const { AMS_ASSERT(m_body_storage != nullptr); AMS_ASSERT(0 <= index && index < NcaHeader::FsCountMax); AMS_ASSERT(dst != nullptr); std::memcpy(dst, std::addressof(m_header.fs_header_hash[index]), sizeof(*dst)); } void NcaReader::GetFsInfo(NcaHeader::FsInfo *dst, s32 index) const { AMS_ASSERT(m_body_storage != nullptr); AMS_ASSERT(0 <= index && index < NcaHeader::FsCountMax); AMS_ASSERT(dst != nullptr); std::memcpy(dst, std::addressof(m_header.fs_info[index]), sizeof(*dst)); } u64 NcaReader::GetFsOffset(s32 index) const { AMS_ASSERT(m_body_storage != nullptr); AMS_ASSERT(0 <= index && index < NcaHeader::FsCountMax); return NcaHeader::SectorToByte(m_header.fs_info[index].start_sector); } u64 NcaReader::GetFsEndOffset(s32 index) const { AMS_ASSERT(m_body_storage != nullptr); AMS_ASSERT(0 <= index && index < NcaHeader::FsCountMax); return NcaHeader::SectorToByte(m_header.fs_info[index].end_sector); } u64 NcaReader::GetFsSize(s32 index) const { AMS_ASSERT(m_body_storage != nullptr); AMS_ASSERT(0 <= index && index < NcaHeader::FsCountMax); return NcaHeader::SectorToByte(m_header.fs_info[index].end_sector - m_header.fs_info[index].start_sector); } void NcaReader::GetEncryptedKey(void *dst, size_t size) const { AMS_ASSERT(m_body_storage != nullptr); AMS_ASSERT(dst != nullptr); AMS_ASSERT(size >= NcaHeader::EncryptedKeyAreaSize); AMS_UNUSED(size); std::memcpy(dst, m_header.encrypted_key_area, NcaHeader::EncryptedKeyAreaSize); } const void *NcaReader::GetDecryptionKey(s32 index) const { AMS_ASSERT(m_body_storage != nullptr); AMS_ASSERT(0 <= index && index < NcaHeader::DecryptionKey_Count); return m_decryption_keys[index]; } bool NcaReader::HasValidInternalKey() const { constexpr const u8 ZeroKey[crypto::AesDecryptor128::KeySize] = {}; for (s32 i = 0; i < NcaHeader::DecryptionKey_Count; i++) { if (!crypto::IsSameBytes(ZeroKey, m_header.encrypted_key_area + i * crypto::AesDecryptor128::KeySize, crypto::AesDecryptor128::KeySize)) { return true; } } return false; } bool NcaReader::HasInternalDecryptionKeyForAesHw() const { constexpr const u8 ZeroKey[crypto::AesDecryptor128::KeySize] = {}; return !crypto::IsSameBytes(ZeroKey, this->GetDecryptionKey(NcaHeader::DecryptionKey_AesCtrHw), crypto::AesDecryptor128::KeySize); } bool NcaReader::IsSoftwareAesPrioritized() const { return m_is_software_aes_prioritized; } void NcaReader::PrioritizeSoftwareAes() { m_is_software_aes_prioritized = true; } bool NcaReader::IsAvailableSwKey() const { return m_is_available_sw_key; } bool NcaReader::HasExternalDecryptionKey() const { constexpr const u8 ZeroKey[crypto::AesDecryptor128::KeySize] = {}; return !crypto::IsSameBytes(ZeroKey, this->GetExternalDecryptionKey(), crypto::AesDecryptor128::KeySize); } const void *NcaReader::GetExternalDecryptionKey() const { return m_external_decryption_key; } void NcaReader::SetExternalDecryptionKey(const void *src, size_t size) { AMS_ASSERT(src != nullptr); AMS_ASSERT(size == sizeof(m_external_decryption_key)); AMS_UNUSED(size); std::memcpy(m_external_decryption_key, src, sizeof(m_external_decryption_key)); } void NcaReader::GetRawData(void *dst, size_t dst_size) const { AMS_ASSERT(m_body_storage != nullptr); AMS_ASSERT(dst != nullptr); AMS_ASSERT(dst_size >= sizeof(NcaHeader)); AMS_UNUSED(dst_size); std::memcpy(dst, std::addressof(m_header), sizeof(NcaHeader)); } DecryptAesCtrFunction NcaReader::GetExternalDecryptAesCtrFunction() const { AMS_ASSERT(m_decrypt_aes_ctr != nullptr); return m_decrypt_aes_ctr; } DecryptAesCtrFunction NcaReader::GetExternalDecryptAesCtrFunctionForExternalKey() const { AMS_ASSERT(m_decrypt_aes_ctr_external != nullptr); return m_decrypt_aes_ctr_external; } GetDecompressorFunction NcaReader::GetDecompressor() const { AMS_ASSERT(m_get_decompressor != nullptr); return m_get_decompressor; } IHash256GeneratorFactorySelector *NcaReader::GetHashGeneratorFactorySelector() const { AMS_ASSERT(m_hash_generator_factory_selector != nullptr); return m_hash_generator_factory_selector; } NcaHeader::EncryptionType NcaReader::GetEncryptionType() const { return m_header_encryption_type; } Result NcaReader::ReadHeader(NcaFsHeader *dst, s32 index) const { AMS_ASSERT(dst != nullptr); AMS_ASSERT(0 <= index && index < NcaHeader::FsCountMax); const s64 offset = sizeof(NcaHeader) + sizeof(NcaFsHeader) * index; R_RETURN(m_header_storage->Read(offset, dst, sizeof(NcaFsHeader))); } bool NcaReader::GetHeaderSign1Valid() const { #if defined(ATMOSPHERE_BOARD_NINTENDO_NX) AMS_ABORT_UNLESS(m_is_header_sign1_signature_valid); #endif return m_is_header_sign1_signature_valid; } void NcaReader::GetHeaderSign2(void *dst, size_t size) const { AMS_ASSERT(dst != nullptr); AMS_ASSERT(size == NcaHeader::HeaderSignSize); std::memcpy(dst, m_header.header_sign_2, size); } void NcaReader::GetHeaderSign2TargetHash(void *dst, size_t size) const { AMS_ASSERT(m_hash_generator_factory_selector!= nullptr); AMS_ASSERT(dst != nullptr); AMS_ASSERT(size == IHash256Generator::HashSize); auto * const factory = m_hash_generator_factory_selector->GetFactory(fssystem::HashAlgorithmType_Sha2); return factory->GenerateHash(dst, size, static_cast<const void *>(std::addressof(m_header.magic)), NcaHeader::Size - NcaHeader::HeaderSignSize * NcaHeader::HeaderSignCount); } Result NcaFsHeaderReader::Initialize(const NcaReader &reader, s32 index) { /* Reset ourselves to uninitialized. */ m_fs_index = -1; /* Read the header. */ R_TRY(reader.ReadHeader(std::addressof(m_data), index)); /* Generate the hash. */ Hash hash; crypto::GenerateSha256(std::addressof(hash), sizeof(hash), std::addressof(m_data), sizeof(NcaFsHeader)); /* Validate the hash. */ R_UNLESS(crypto::IsSameBytes(std::addressof(reader.GetFsHeaderHash(index)), std::addressof(hash), sizeof(Hash)), fs::ResultNcaFsHeaderHashVerificationFailed()); /* Set our index. */ m_fs_index = index; R_SUCCEED(); } void NcaFsHeaderReader::GetRawData(void *dst, size_t dst_size) const { AMS_ASSERT(this->IsInitialized()); AMS_ASSERT(dst != nullptr); AMS_ASSERT(dst_size >= sizeof(NcaFsHeader)); AMS_UNUSED(dst_size); std::memcpy(dst, std::addressof(m_data), sizeof(NcaFsHeader)); } NcaFsHeader::HashData &NcaFsHeaderReader::GetHashData() { AMS_ASSERT(this->IsInitialized()); return m_data.hash_data; } const NcaFsHeader::HashData &NcaFsHeaderReader::GetHashData() const { AMS_ASSERT(this->IsInitialized()); return m_data.hash_data; } u16 NcaFsHeaderReader::GetVersion() const { AMS_ASSERT(this->IsInitialized()); return m_data.version; } s32 NcaFsHeaderReader::GetFsIndex() const { AMS_ASSERT(this->IsInitialized()); return m_fs_index; } NcaFsHeader::FsType NcaFsHeaderReader::GetFsType() const { AMS_ASSERT(this->IsInitialized()); return m_data.fs_type; } NcaFsHeader::HashType NcaFsHeaderReader::GetHashType() const { AMS_ASSERT(this->IsInitialized()); return m_data.hash_type; } NcaFsHeader::EncryptionType NcaFsHeaderReader::GetEncryptionType() const { AMS_ASSERT(this->IsInitialized()); return m_data.encryption_type; } NcaPatchInfo &NcaFsHeaderReader::GetPatchInfo() { AMS_ASSERT(this->IsInitialized()); return m_data.patch_info; } const NcaPatchInfo &NcaFsHeaderReader::GetPatchInfo() const { AMS_ASSERT(this->IsInitialized()); return m_data.patch_info; } const NcaAesCtrUpperIv NcaFsHeaderReader::GetAesCtrUpperIv() const { AMS_ASSERT(this->IsInitialized()); return m_data.aes_ctr_upper_iv; } bool NcaFsHeaderReader::IsSkipLayerHashEncryption() const { AMS_ASSERT(this->IsInitialized()); return m_data.IsSkipLayerHashEncryption(); } Result NcaFsHeaderReader::GetHashTargetOffset(s64 *out) const { AMS_ASSERT(out != nullptr); AMS_ASSERT(this->IsInitialized()); R_RETURN(m_data.GetHashTargetOffset(out)); } bool NcaFsHeaderReader::ExistsSparseLayer() const { AMS_ASSERT(this->IsInitialized()); return m_data.sparse_info.generation != 0; } NcaSparseInfo &NcaFsHeaderReader::GetSparseInfo() { AMS_ASSERT(this->IsInitialized()); return m_data.sparse_info; } const NcaSparseInfo &NcaFsHeaderReader::GetSparseInfo() const { AMS_ASSERT(this->IsInitialized()); return m_data.sparse_info; } bool NcaFsHeaderReader::ExistsCompressionLayer() const { AMS_ASSERT(this->IsInitialized()); return m_data.compression_info.bucket.offset != 0 && m_data.compression_info.bucket.size != 0; } NcaCompressionInfo &NcaFsHeaderReader::GetCompressionInfo() { AMS_ASSERT(this->IsInitialized()); return m_data.compression_info; } const NcaCompressionInfo &NcaFsHeaderReader::GetCompressionInfo() const { AMS_ASSERT(this->IsInitialized()); return m_data.compression_info; } bool NcaFsHeaderReader::ExistsPatchMetaHashLayer() const { AMS_ASSERT(this->IsInitialized()); return m_data.meta_data_hash_data_info.size != 0 && this->GetPatchInfo().HasIndirectTable(); } NcaMetaDataHashDataInfo &NcaFsHeaderReader::GetPatchMetaDataHashDataInfo() { AMS_ASSERT(this->IsInitialized()); return m_data.meta_data_hash_data_info; } const NcaMetaDataHashDataInfo &NcaFsHeaderReader::GetPatchMetaDataHashDataInfo() const { AMS_ASSERT(this->IsInitialized()); return m_data.meta_data_hash_data_info; } NcaFsHeader::MetaDataHashType NcaFsHeaderReader::GetPatchMetaHashType() const { AMS_ASSERT(this->IsInitialized()); return m_data.meta_data_hash_type; } bool NcaFsHeaderReader::ExistsSparseMetaHashLayer() const { AMS_ASSERT(this->IsInitialized()); return m_data.meta_data_hash_data_info.size != 0 && this->ExistsSparseLayer(); } NcaMetaDataHashDataInfo &NcaFsHeaderReader::GetSparseMetaDataHashDataInfo() { AMS_ASSERT(this->IsInitialized()); return m_data.meta_data_hash_data_info; } const NcaMetaDataHashDataInfo &NcaFsHeaderReader::GetSparseMetaDataHashDataInfo() const { AMS_ASSERT(this->IsInitialized()); return m_data.meta_data_hash_data_info; } NcaFsHeader::MetaDataHashType NcaFsHeaderReader::GetSparseMetaHashType() const { AMS_ASSERT(this->IsInitialized()); return m_data.meta_data_hash_type; } }
24,689
C++
.cpp
459
45.361656
334
0.676567
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,358
fssystem_crypto_configuration.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssystem/fssystem_crypto_configuration.cpp
/* * Copyright (c) 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 "fssystem_key_slot_cache.hpp" namespace ams::fssystem { namespace { constexpr inline const size_t KeySize = crypto::AesDecryptor128::KeySize; constexpr inline const size_t NxAcidSignatureKeyGenerationMax = 1; constexpr inline const size_t NxAcidSignatureKeyModulusSize = NcaCryptoConfiguration::Rsa2048KeyModulusSize; constexpr inline const u8 NxAcidSignatureKeyModulusDev[NxAcidSignatureKeyGenerationMax + 1][NxAcidSignatureKeyModulusSize] = { { 0xD6, 0x34, 0xA5, 0x78, 0x6C, 0x68, 0xCE, 0x5A, 0xC2, 0x37, 0x17, 0xF3, 0x82, 0x45, 0xC6, 0x89, 0xE1, 0x2D, 0x06, 0x67, 0xBF, 0xB4, 0x06, 0x19, 0x55, 0x6B, 0x27, 0x66, 0x0C, 0xA4, 0xB5, 0x87, 0x81, 0x25, 0xF4, 0x30, 0xBC, 0x53, 0x08, 0x68, 0xA2, 0x48, 0x49, 0x8C, 0x3F, 0x38, 0x40, 0x9C, 0xC4, 0x26, 0xF4, 0x79, 0xE2, 0xA1, 0x85, 0xF5, 0x5C, 0x7F, 0x58, 0xBA, 0xA6, 0x1C, 0xA0, 0x8B, 0x84, 0x16, 0x14, 0x6F, 0x85, 0xD9, 0x7C, 0xE1, 0x3C, 0x67, 0x22, 0x1E, 0xFB, 0xD8, 0xA7, 0xA5, 0x9A, 0xBF, 0xEC, 0x0E, 0xCF, 0x96, 0x7E, 0x85, 0xC2, 0x1D, 0x49, 0x5D, 0x54, 0x26, 0xCB, 0x32, 0x7C, 0xF6, 0xBB, 0x58, 0x03, 0x80, 0x2B, 0x5D, 0xF7, 0xFB, 0xD1, 0x9D, 0xC7, 0xC6, 0x2E, 0x53, 0xC0, 0x6F, 0x39, 0x2C, 0x1F, 0xA9, 0x92, 0xF2, 0x4D, 0x7D, 0x4E, 0x74, 0xFF, 0xE4, 0xEF, 0xE4, 0x7C, 0x3D, 0x34, 0x2A, 0x71, 0xA4, 0x97, 0x59, 0xFF, 0x4F, 0xA2, 0xF4, 0x66, 0x78, 0xD8, 0xBA, 0x99, 0xE3, 0xE6, 0xDB, 0x54, 0xB9, 0xE9, 0x54, 0xA1, 0x70, 0xFC, 0x05, 0x1F, 0x11, 0x67, 0x4B, 0x26, 0x8C, 0x0C, 0x3E, 0x03, 0xD2, 0xA3, 0x55, 0x5C, 0x7D, 0xC0, 0x5D, 0x9D, 0xFF, 0x13, 0x2F, 0xFD, 0x19, 0xBF, 0xED, 0x44, 0xC3, 0x8C, 0xA7, 0x28, 0xCB, 0xE5, 0xE0, 0xB1, 0xA7, 0x9C, 0x33, 0x8D, 0xB8, 0x6E, 0xDE, 0x87, 0x18, 0x22, 0x60, 0xC4, 0xAE, 0xF2, 0x87, 0x9F, 0xCE, 0x09, 0x5C, 0xB5, 0x99, 0xA5, 0x9F, 0x49, 0xF2, 0xD7, 0x58, 0xFA, 0xF9, 0xC0, 0x25, 0x7D, 0xD6, 0xCB, 0xF3, 0xD8, 0x6C, 0xA2, 0x69, 0x91, 0x68, 0x73, 0xB1, 0x94, 0x6F, 0xA3, 0xF3, 0xB9, 0x7D, 0xF8, 0xE0, 0x72, 0x9E, 0x93, 0x7B, 0x7A, 0xA2, 0x57, 0x60, 0xB7, 0x5B, 0xA9, 0x84, 0xAE, 0x64, 0x88, 0x69 }, { 0xBC, 0xA5, 0x6A, 0x7E, 0xEA, 0x38, 0x34, 0x62, 0xA6, 0x10, 0x18, 0x3C, 0xE1, 0x63, 0x7B, 0xF0, 0xD3, 0x08, 0x8C, 0xF5, 0xC5, 0xC4, 0xC7, 0x93, 0xE9, 0xD9, 0xE6, 0x32, 0xF3, 0xA0, 0xF6, 0x6E, 0x8A, 0x98, 0x76, 0x47, 0x33, 0x47, 0x65, 0x02, 0x70, 0xDC, 0x86, 0x5F, 0x3D, 0x61, 0x5A, 0x70, 0xBC, 0x5A, 0xCA, 0xCA, 0x50, 0xAD, 0x61, 0x7E, 0xC9, 0xEC, 0x27, 0xFF, 0xE8, 0x64, 0x42, 0x9A, 0xEE, 0xBE, 0xC3, 0xD1, 0x0B, 0xC0, 0xE9, 0xBF, 0x83, 0x8D, 0xC0, 0x0C, 0xD8, 0x00, 0x5B, 0x76, 0x90, 0xD2, 0x4B, 0x30, 0x84, 0x35, 0x8B, 0x1E, 0x20, 0xB7, 0xE4, 0xDC, 0x63, 0xE5, 0xDF, 0xCD, 0x00, 0x5F, 0x81, 0x5F, 0x67, 0xC5, 0x8B, 0xDF, 0xFC, 0xE1, 0x37, 0x5F, 0x07, 0xD9, 0xDE, 0x4F, 0xE6, 0x7B, 0xF1, 0xFB, 0xA1, 0x5A, 0x71, 0x40, 0xFE, 0xBA, 0x1E, 0xAE, 0x13, 0x22, 0xD2, 0xFE, 0x37, 0xA2, 0xB6, 0x8B, 0xAB, 0xEB, 0x84, 0x81, 0x4E, 0x7C, 0x1E, 0x02, 0xD1, 0xFB, 0xD7, 0x5D, 0x11, 0x84, 0x64, 0xD2, 0x4D, 0xBB, 0x50, 0x00, 0x67, 0x54, 0xE2, 0x77, 0x89, 0xBA, 0x0B, 0xE7, 0x05, 0x57, 0x9A, 0x22, 0x5A, 0xEC, 0x76, 0x1C, 0xFD, 0xE8, 0xA8, 0x18, 0x16, 0x41, 0x65, 0x03, 0xFA, 0xC4, 0xA6, 0x31, 0x5C, 0x1A, 0x7F, 0xAB, 0x11, 0xC8, 0x4A, 0x99, 0xB9, 0xE6, 0xCF, 0x62, 0x21, 0xA6, 0x72, 0x47, 0xDB, 0xBA, 0x96, 0x26, 0x4E, 0x2E, 0xD4, 0x8C, 0x46, 0xD6, 0xA7, 0x1A, 0x6C, 0x32, 0xA7, 0xDF, 0x85, 0x1C, 0x03, 0xC3, 0x6D, 0xA9, 0xE9, 0x68, 0xF4, 0x17, 0x1E, 0xB2, 0x70, 0x2A, 0xA1, 0xE5, 0xE1, 0xF3, 0x8F, 0x6F, 0x63, 0xAC, 0xEB, 0x72, 0x0B, 0x4C, 0x4A, 0x36, 0x3C, 0x60, 0x91, 0x9F, 0x6E, 0x1C, 0x71, 0xEA, 0xD0, 0x78, 0x78, 0xA0, 0x2E, 0xC6, 0x32, 0x6B } }; constexpr inline const u8 NxAcidSignatureKeyModulusProd[NxAcidSignatureKeyGenerationMax + 1][NxAcidSignatureKeyModulusSize] = { { 0xDD, 0xC8, 0xDD, 0xF2, 0x4E, 0x6D, 0xF0, 0xCA, 0x9E, 0xC7, 0x5D, 0xC7, 0x7B, 0xAD, 0xFE, 0x7D, 0x23, 0x89, 0x69, 0xB6, 0xF2, 0x06, 0xA2, 0x02, 0x88, 0xE1, 0x55, 0x91, 0xAB, 0xCB, 0x4D, 0x50, 0x2E, 0xFC, 0x9D, 0x94, 0x76, 0xD6, 0x4C, 0xD8, 0xFF, 0x10, 0xFA, 0x5E, 0x93, 0x0A, 0xB4, 0x57, 0xAC, 0x51, 0xC7, 0x16, 0x66, 0xF4, 0x1A, 0x54, 0xC2, 0xC5, 0x04, 0x3D, 0x1B, 0xFE, 0x30, 0x20, 0x8A, 0xAC, 0x6F, 0x6F, 0xF5, 0xC7, 0xB6, 0x68, 0xB8, 0xC9, 0x40, 0x6B, 0x42, 0xAD, 0x11, 0x21, 0xE7, 0x8B, 0xE9, 0x75, 0x01, 0x86, 0xE4, 0x48, 0x9B, 0x0A, 0x0A, 0xF8, 0x7F, 0xE8, 0x87, 0xF2, 0x82, 0x01, 0xE6, 0xA3, 0x0F, 0xE4, 0x66, 0xAE, 0x83, 0x3F, 0x4E, 0x9F, 0x5E, 0x01, 0x30, 0xA4, 0x00, 0xB9, 0x9A, 0xAE, 0x5F, 0x03, 0xCC, 0x18, 0x60, 0xE5, 0xEF, 0x3B, 0x5E, 0x15, 0x16, 0xFE, 0x1C, 0x82, 0x78, 0xB5, 0x2F, 0x47, 0x7C, 0x06, 0x66, 0x88, 0x5D, 0x35, 0xA2, 0x67, 0x20, 0x10, 0xE7, 0x6C, 0x43, 0x68, 0xD3, 0xE4, 0x5A, 0x68, 0x2A, 0x5A, 0xE2, 0x6D, 0x73, 0xB0, 0x31, 0x53, 0x1C, 0x20, 0x09, 0x44, 0xF5, 0x1A, 0x9D, 0x22, 0xBE, 0x12, 0xA1, 0x77, 0x11, 0xE2, 0xA1, 0xCD, 0x40, 0x9A, 0xA2, 0x8B, 0x60, 0x9B, 0xEF, 0xA0, 0xD3, 0x48, 0x63, 0xA2, 0xF8, 0xA3, 0x2C, 0x08, 0x56, 0x52, 0x2E, 0x60, 0x19, 0x67, 0x5A, 0xA7, 0x9F, 0xDC, 0x3F, 0x3F, 0x69, 0x2B, 0x31, 0x6A, 0xB7, 0x88, 0x4A, 0x14, 0x84, 0x80, 0x33, 0x3C, 0x9D, 0x44, 0xB7, 0x3F, 0x4C, 0xE1, 0x75, 0xEA, 0x37, 0xEA, 0xE8, 0x1E, 0x7C, 0x77, 0xB7, 0xC6, 0x1A, 0xA2, 0xF0, 0x9F, 0x10, 0x61, 0xCD, 0x7B, 0x5B, 0x32, 0x4C, 0x37, 0xEF, 0xB1, 0x71, 0x68, 0x53, 0x0A, 0xED, 0x51, 0x7D, 0x35, 0x22, 0xFD }, { 0xE7, 0xAA, 0x25, 0xC8, 0x01, 0xA5, 0x14, 0x6B, 0x01, 0x60, 0x3E, 0xD9, 0x96, 0x5A, 0xBF, 0x90, 0xAC, 0xA7, 0xFD, 0x9B, 0x5B, 0xBD, 0x8A, 0x26, 0xB0, 0xCB, 0x20, 0x28, 0x9A, 0x72, 0x12, 0xF5, 0x20, 0x65, 0xB3, 0xB9, 0x84, 0x58, 0x1F, 0x27, 0xBC, 0x7C, 0xA2, 0xC9, 0x9E, 0x18, 0x95, 0xCF, 0xC2, 0x73, 0x2E, 0x74, 0x8C, 0x66, 0xE5, 0x9E, 0x79, 0x2B, 0xB8, 0x07, 0x0C, 0xB0, 0x4E, 0x8E, 0xAB, 0x85, 0x21, 0x42, 0xC4, 0xC5, 0x6D, 0x88, 0x9C, 0xDB, 0x15, 0x95, 0x3F, 0x80, 0xDB, 0x7A, 0x9A, 0x7D, 0x41, 0x56, 0x25, 0x17, 0x18, 0x42, 0x4D, 0x8C, 0xAC, 0xA5, 0x7B, 0xDB, 0x42, 0x5D, 0x59, 0x35, 0x45, 0x5D, 0x8A, 0x02, 0xB5, 0x70, 0xC0, 0x72, 0x35, 0x46, 0xD0, 0x1D, 0x60, 0x01, 0x4A, 0xCC, 0x1C, 0x46, 0xD3, 0xD6, 0x35, 0x52, 0xD6, 0xE1, 0xF8, 0x3B, 0x5D, 0xEA, 0xDD, 0xB8, 0xFE, 0x7D, 0x50, 0xCB, 0x35, 0x23, 0x67, 0x8B, 0xB6, 0xE4, 0x74, 0xD2, 0x60, 0xFC, 0xFD, 0x43, 0xBF, 0x91, 0x08, 0x81, 0xC5, 0x4F, 0x5D, 0x16, 0x9A, 0xC4, 0x9A, 0xC6, 0xF6, 0xF3, 0xE1, 0xF6, 0x5C, 0x07, 0xAA, 0x71, 0x6C, 0x13, 0xA4, 0xB1, 0xB3, 0x66, 0xBF, 0x90, 0x4C, 0x3D, 0xA2, 0xC4, 0x0B, 0xB8, 0x3D, 0x7A, 0x8C, 0x19, 0xFA, 0xFF, 0x6B, 0xB9, 0x1F, 0x02, 0xCC, 0xB6, 0xD3, 0x0C, 0x7D, 0x19, 0x1F, 0x47, 0xF9, 0xC7, 0x40, 0x01, 0xFA, 0x46, 0xEA, 0x0B, 0xD4, 0x02, 0xE0, 0x3D, 0x30, 0x9A, 0x1A, 0x0F, 0xEA, 0xA7, 0x66, 0x55, 0xF7, 0xCB, 0x28, 0xE2, 0xBB, 0x99, 0xE4, 0x83, 0xC3, 0x43, 0x03, 0xEE, 0xDC, 0x1F, 0x02, 0x23, 0xDD, 0xD1, 0x2D, 0x39, 0xA4, 0x65, 0x75, 0x03, 0xEF, 0x37, 0x9C, 0x06, 0xD6, 0xFA, 0xA1, 0x15, 0xF0, 0xDB, 0x17, 0x47, 0x26, 0x4F, 0x49, 0x03 } }; static_assert(sizeof(NxAcidSignatureKeyModulusProd) == sizeof(NxAcidSignatureKeyModulusDev)); constexpr inline const u8 AcidSignatureKeyPublicExponent[] = { 0x01, 0x00, 0x01 }; NcaCryptoConfiguration g_nca_crypto_configuration_dev; NcaCryptoConfiguration g_nca_crypto_configuration_prod; constexpr inline s32 KeySlotCacheEntryCount = 3; constinit KeySlotCache g_key_slot_cache; constinit util::optional<KeySlotCacheEntry> g_key_slot_cache_entry[KeySlotCacheEntryCount]; spl::AccessKey &GetNcaKekAccessKey(s32 key_type) { AMS_FUNCTION_LOCAL_STATIC_CONSTINIT(spl::AccessKey, s_nca_kek_access_key_array[KeyAreaEncryptionKeyCount]); AMS_FUNCTION_LOCAL_STATIC_CONSTINIT(spl::AccessKey, s_nca_header_kek_access_key); AMS_FUNCTION_LOCAL_STATIC_CONSTINIT(spl::AccessKey, s_invalid_nca_kek_access_key); if (key_type > static_cast<s32>(KeyType::NcaHeaderKey2) || IsInvalidKeyTypeValue(key_type)) { return s_invalid_nca_kek_access_key; } else if (key_type == static_cast<s32>(KeyType::NcaHeaderKey1) || key_type == static_cast<s32>(KeyType::NcaHeaderKey2)) { return s_nca_header_kek_access_key; } else { return s_nca_kek_access_key_array[key_type]; } } void GenerateNcaKey(void *dst, size_t dst_size, const void *src, size_t src_size, s32 key_type) { R_ABORT_UNLESS(spl::GenerateAesKey(dst, dst_size, GetNcaKekAccessKey(key_type), src, src_size)); } void ComputeCtr(void *dst, size_t dst_size, int key_slot_idx, const void *src, size_t src_size, const void *iv, size_t iv_size) { if (dst == src) { /* If the destination and source are the same, we'll use an intermediate buffer. */ constexpr size_t MinimumSizeToRequireLocking = 256_KB; constexpr size_t MinimumWorkBufferSize = 16_KB; /* If the request is large enough, acquire a lock to prevent too many large requests in flight simultaneously. */ static constinit os::SdkMutex s_large_work_buffer_mutex; util::optional<std::scoped_lock<os::SdkMutex>> lk = util::nullopt; if (dst_size >= MinimumSizeToRequireLocking) { lk.emplace(s_large_work_buffer_mutex); } /* Allocate a pooled buffer. */ PooledBuffer pooled_buffer; pooled_buffer.AllocateParticularlyLarge(dst_size, MinimumWorkBufferSize); /* Copy the iv locally. */ AMS_ASSERT(iv_size == crypto::Aes128CtrEncryptor::IvSize); u8 work_iv[crypto::Aes128CtrEncryptor::IvSize]; std::memcpy(work_iv, iv, sizeof(work_iv)); /* Process all data. */ size_t processed = 0; while (processed < dst_size) { /* Determine the currently processable size. */ const size_t cur_size = std::min<size_t>(dst_size - processed, pooled_buffer.GetSize()); /* Process. */ R_ABORT_UNLESS(spl::ComputeCtr(pooled_buffer.GetBuffer(), cur_size, key_slot_idx, static_cast<const u8 *>(src) + processed, cur_size, work_iv, sizeof(work_iv))); /* Copy to dst. */ std::memcpy(static_cast<u8 *>(dst) + processed, pooled_buffer.GetBuffer(), cur_size); /* Advance. */ processed += cur_size; /* Increment the counter. */ fssystem::AddCounter(work_iv, sizeof(work_iv), cur_size / crypto::Aes128CtrEncryptor::BlockSize); } } else { /* If the destination and source are different, we can just call ComputeCtr directly. */ R_ABORT_UNLESS(spl::ComputeCtr(dst, dst_size, key_slot_idx, src, src_size, iv, iv_size)); } } void DecryptAesCtr(void *dst, size_t dst_size, u8 key_index, u8 key_generation, const void *enc_key, size_t enc_key_size, const void *iv, size_t iv_size, const void *src, size_t src_size) { std::unique_ptr<KeySlotCacheAccessor> accessor; const s32 key_type = GetKeyTypeValue(key_index, key_generation); R_TRY_CATCH(g_key_slot_cache.Find(std::addressof(accessor), enc_key, enc_key_size, key_type)) { R_CATCH(fs::ResultTargetNotFound) { R_ABORT_UNLESS(g_key_slot_cache.AllocateHighPriority(std::addressof(accessor), enc_key, enc_key_size, key_type)); R_ABORT_UNLESS(spl::LoadAesKey(accessor->GetKeySlotIndex(), GetNcaKekAccessKey(key_type), enc_key, enc_key_size)); } } R_END_TRY_CATCH_WITH_ABORT_UNLESS; ComputeCtr(dst, dst_size, accessor->GetKeySlotIndex(), src, src_size, iv, iv_size); } void DecryptAesCtrForPreparedKey(void *dst, size_t dst_size, u8 key_index, u8 key_generation, const void *enc_key, size_t enc_key_size, const void *iv, size_t iv_size, const void *src, size_t src_size) { std::unique_ptr<KeySlotCacheAccessor> accessor; AMS_UNUSED(key_index, key_generation); const s32 key_type = static_cast<s32>(KeyType::NcaExternalKey); R_TRY_CATCH(g_key_slot_cache.Find(std::addressof(accessor), enc_key, enc_key_size, key_type)) { R_CATCH(fs::ResultTargetNotFound) { R_ABORT_UNLESS(g_key_slot_cache.AllocateHighPriority(std::addressof(accessor), enc_key, enc_key_size, key_type)); spl::AccessKey access_key; AMS_ABORT_UNLESS(enc_key_size == sizeof(access_key)); std::memcpy(std::addressof(access_key), enc_key, sizeof(access_key)); R_ABORT_UNLESS(spl::LoadPreparedAesKey(accessor->GetKeySlotIndex(), access_key)); } } R_END_TRY_CATCH_WITH_ABORT_UNLESS; ComputeCtr(dst, dst_size, accessor->GetKeySlotIndex(), src, src_size, iv, iv_size); } bool VerifySign1Prod(const void *sig, size_t sig_size, const void *data, size_t data_size, u8 generation) { const u8 *mod = g_nca_crypto_configuration_prod.header_1_sign_key_moduli[generation]; const size_t mod_size = NcaCryptoConfiguration::Rsa2048KeyModulusSize; const u8 *exp = g_nca_crypto_configuration_prod.header_1_sign_key_public_exponent; const size_t exp_size = NcaCryptoConfiguration::Rsa2048KeyPublicExponentSize; return crypto::VerifyRsa2048PssSha256(sig, sig_size, mod, mod_size, exp, exp_size, data, data_size); } bool VerifySign1Dev(const void *sig, size_t sig_size, const void *data, size_t data_size, u8 generation) { const u8 *mod = g_nca_crypto_configuration_dev.header_1_sign_key_moduli[generation]; const size_t mod_size = NcaCryptoConfiguration::Rsa2048KeyModulusSize; const u8 *exp = g_nca_crypto_configuration_dev.header_1_sign_key_public_exponent; const size_t exp_size = NcaCryptoConfiguration::Rsa2048KeyPublicExponentSize; return crypto::VerifyRsa2048PssSha256(sig, sig_size, mod, mod_size, exp, exp_size, data, data_size); } } const ::ams::fssystem::NcaCryptoConfiguration *GetNcaCryptoConfiguration(bool prod) { /* Decide which configuration to use. */ NcaCryptoConfiguration * const cfg = prod ? std::addressof(g_nca_crypto_configuration_prod) : std::addressof(g_nca_crypto_configuration_dev); std::memcpy(cfg, fssrv::GetDefaultNcaCryptoConfiguration(prod), sizeof(NcaCryptoConfiguration)); /* Set the key generation functions. */ cfg->generate_key = GenerateNcaKey; cfg->decrypt_aes_xts_external = nullptr; cfg->encrypt_aes_xts_external = nullptr; cfg->decrypt_aes_ctr = DecryptAesCtr; cfg->decrypt_aes_ctr_external = DecryptAesCtrForPreparedKey; cfg->verify_sign1 = prod ? VerifySign1Prod : VerifySign1Dev; cfg->is_plaintext_header_available = !prod; cfg->is_available_sw_key = true; /* TODO: Should this default to false for host tools with api to set explicitly? */ #if !defined(ATMOSPHERE_BOARD_NINTENDO_NX) cfg->is_unsigned_header_available_for_host_tool = true; #endif return cfg; } void SetUpKekAccessKeys(bool prod) { /* Get the crypto configuration. */ const NcaCryptoConfiguration *nca_crypto_cfg = GetNcaCryptoConfiguration(prod); /* Setup the nca keys. */ { constexpr s32 Option = 0; /* Setup the key area encryption keys. */ for (u8 i = 0; i < NcaCryptoConfiguration::KeyGenerationMax; ++i) { spl::GenerateAesKek(std::addressof(GetNcaKekAccessKey(GetKeyTypeValue(0, i))), nca_crypto_cfg->key_area_encryption_key_source[0], KeySize, i, Option); spl::GenerateAesKek(std::addressof(GetNcaKekAccessKey(GetKeyTypeValue(1, i))), nca_crypto_cfg->key_area_encryption_key_source[1], KeySize, i, Option); spl::GenerateAesKek(std::addressof(GetNcaKekAccessKey(GetKeyTypeValue(2, i))), nca_crypto_cfg->key_area_encryption_key_source[2], KeySize, i, Option); } /* Setup the header encryption key. */ R_ABORT_UNLESS(spl::GenerateAesKek(std::addressof(GetNcaKekAccessKey(static_cast<s32>(KeyType::NcaHeaderKey1))), nca_crypto_cfg->header_encryption_key_source, KeySize, 0, Option)); } /* TODO FS-REIMPL: Save stuff. */ /* Setup the keyslot cache. */ for (s32 i = 0; i < KeySlotCacheEntryCount; i++) { s32 slot_index = -1; R_ABORT_UNLESS(spl::AllocateAesKeySlot(std::addressof(slot_index))); g_key_slot_cache_entry[i].emplace(slot_index); g_key_slot_cache.AddEntry(std::addressof(g_key_slot_cache_entry[i].value())); } } void InvalidateHardwareAesKey() { constexpr u8 InvalidKey[KeySize] = {}; for (s32 i = 0; i < KeySlotCacheEntryCount; ++i) { std::unique_ptr<KeySlotCacheAccessor> accessor; R_ABORT_UNLESS(g_key_slot_cache.AllocateHighPriority(std::addressof(accessor), InvalidKey, KeySize, -1 - i)); } } bool IsValidSignatureKeyGeneration(ncm::ContentMetaPlatform platform, size_t key_generation) { switch (platform) { case ncm::ContentMetaPlatform::Nx: return key_generation <= NxAcidSignatureKeyGenerationMax; AMS_UNREACHABLE_DEFAULT_CASE(); } } const u8 *GetAcidSignatureKeyModulus(ncm::ContentMetaPlatform platform, bool prod, size_t key_generation, bool unk_unused) { AMS_ASSERT(IsValidSignatureKeyGeneration(platform, key_generation)); AMS_UNUSED(unk_unused); switch (platform) { case ncm::ContentMetaPlatform::Nx: { const size_t used_keygen = (key_generation % (NxAcidSignatureKeyGenerationMax + 1)); return prod ? NxAcidSignatureKeyModulusProd[used_keygen] : NxAcidSignatureKeyModulusDev[used_keygen]; } AMS_UNREACHABLE_DEFAULT_CASE(); } } size_t GetAcidSignatureKeyModulusSize(ncm::ContentMetaPlatform platform, bool unk_unused) { AMS_UNUSED(unk_unused); switch (platform) { case ncm::ContentMetaPlatform::Nx: return NxAcidSignatureKeyModulusSize; AMS_UNREACHABLE_DEFAULT_CASE(); } } const u8 *GetAcidSignatureKeyPublicExponent() { return AcidSignatureKeyPublicExponent; } }
20,506
C++
.cpp
281
59.985765
211
0.615518
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,359
fssystem_aes_ctr_counter_extended_storage.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssystem/fssystem_aes_ctr_counter_extended_storage.cpp
/* * Copyright (c) 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 { namespace { class SoftwareDecryptor final : public AesCtrCounterExtendedStorage::IDecryptor { public: virtual void Decrypt(void *buf, size_t buf_size, const void *enc_key, size_t enc_key_size, void *iv, size_t iv_size) override final; virtual bool HasExternalDecryptionKey() const override final { return false; } }; class ExternalDecryptor final : public AesCtrCounterExtendedStorage::IDecryptor { public: static constexpr size_t BlockSize = AesCtrCounterExtendedStorage::BlockSize; static constexpr size_t KeySize = AesCtrCounterExtendedStorage::KeySize; static constexpr size_t IvSize = AesCtrCounterExtendedStorage::IvSize; private: AesCtrCounterExtendedStorage::DecryptFunction m_decrypt_function; s32 m_key_index; s32 m_key_generation; public: ExternalDecryptor(AesCtrCounterExtendedStorage::DecryptFunction df, s32 key_idx, s32 key_gen) : m_decrypt_function(df), m_key_index(key_idx), m_key_generation(key_gen) { AMS_ASSERT(m_decrypt_function != nullptr); } public: virtual void Decrypt(void *buf, size_t buf_size, const void *enc_key, size_t enc_key_size, void *iv, size_t iv_size) override final; virtual bool HasExternalDecryptionKey() const override final { return m_key_index < 0; } }; } Result AesCtrCounterExtendedStorage::CreateExternalDecryptor(std::unique_ptr<IDecryptor> *out, DecryptFunction func, s32 key_index, s32 key_generation) { std::unique_ptr<IDecryptor> decryptor = std::make_unique<ExternalDecryptor>(func, key_index, key_generation); R_UNLESS(decryptor != nullptr, fs::ResultAllocationMemoryFailedInAesCtrCounterExtendedStorageA()); *out = std::move(decryptor); R_SUCCEED(); } Result AesCtrCounterExtendedStorage::CreateSoftwareDecryptor(std::unique_ptr<IDecryptor> *out) { std::unique_ptr<IDecryptor> decryptor = std::make_unique<SoftwareDecryptor>(); R_UNLESS(decryptor != nullptr, fs::ResultAllocationMemoryFailedInAesCtrCounterExtendedStorageA()); *out = std::move(decryptor); R_SUCCEED(); } Result AesCtrCounterExtendedStorage::Initialize(IAllocator *allocator, const void *key, size_t key_size, u32 secure_value, fs::SubStorage data_storage, fs::SubStorage table_storage) { /* Read and verify the bucket tree header. */ BucketTree::Header header; R_TRY(table_storage.Read(0, std::addressof(header), sizeof(header))); R_TRY(header.Verify()); /* Determine extents. */ const auto node_storage_size = QueryNodeStorageSize(header.entry_count); const auto entry_storage_size = QueryEntryStorageSize(header.entry_count); const auto node_storage_offset = QueryHeaderStorageSize(); const auto entry_storage_offset = node_storage_offset + node_storage_size; /* Create a software decryptor. */ std::unique_ptr<IDecryptor> sw_decryptor; R_TRY(CreateSoftwareDecryptor(std::addressof(sw_decryptor))); /* Initialize. */ R_RETURN(this->Initialize(allocator, key, key_size, secure_value, 0, data_storage, fs::SubStorage(std::addressof(table_storage), node_storage_offset, node_storage_size), fs::SubStorage(std::addressof(table_storage), entry_storage_offset, entry_storage_size), header.entry_count, std::move(sw_decryptor))); } Result AesCtrCounterExtendedStorage::Initialize(IAllocator *allocator, const void *key, size_t key_size, u32 secure_value, s64 counter_offset, fs::SubStorage data_storage, fs::SubStorage node_storage, fs::SubStorage entry_storage, s32 entry_count, std::unique_ptr<IDecryptor> &&decryptor) { /* Validate preconditions. */ AMS_ASSERT(key != nullptr); AMS_ASSERT(key_size == KeySize); AMS_ASSERT(counter_offset >= 0); AMS_ASSERT(decryptor != nullptr); /* Initialize the bucket tree table. */ if (entry_count > 0) { R_TRY(m_table.Initialize(allocator, node_storage, entry_storage, NodeSize, sizeof(Entry), entry_count)); } else { m_table.Initialize(NodeSize, 0); } /* Set members. */ m_data_storage = data_storage; std::memcpy(m_key, key, key_size); m_secure_value = secure_value; m_counter_offset = counter_offset; m_decryptor = std::move(decryptor); R_SUCCEED(); } void AesCtrCounterExtendedStorage::Finalize() { if (this->IsInitialized()) { m_table.Finalize(); m_data_storage = fs::SubStorage(); } } Result AesCtrCounterExtendedStorage::GetEntryList(Entry *out_entries, s32 *out_entry_count, s32 entry_count, s64 offset, s64 size) { /* Validate pre-conditions. */ AMS_ASSERT(offset >= 0); AMS_ASSERT(size >= 0); AMS_ASSERT(this->IsInitialized()); /* Clear the out count. */ R_UNLESS(out_entry_count != nullptr, fs::ResultNullptrArgument()); *out_entry_count = 0; /* Succeed if there's no range. */ R_SUCCEED_IF(size == 0); /* If we have an output array, we need it to be non-null. */ R_UNLESS(out_entries != nullptr || entry_count == 0, fs::ResultNullptrArgument()); /* Check that our range is valid. */ BucketTree::Offsets table_offsets; R_TRY(m_table.GetOffsets(std::addressof(table_offsets))); R_UNLESS(table_offsets.IsInclude(offset, size), fs::ResultOutOfRange()); /* Find the offset in our tree. */ BucketTree::Visitor visitor; R_TRY(m_table.Find(std::addressof(visitor), offset)); { const auto entry_offset = visitor.Get<Entry>()->GetOffset(); R_UNLESS(0 <= entry_offset && table_offsets.IsInclude(entry_offset), fs::ResultInvalidAesCtrCounterExtendedEntryOffset()); } /* Prepare to loop over entries. */ const auto end_offset = offset + static_cast<s64>(size); s32 count = 0; auto cur_entry = *visitor.Get<Entry>(); while (cur_entry.GetOffset() < end_offset) { /* Try to write the entry to the out list. */ if (entry_count != 0) { if (count >= entry_count) { break; } std::memcpy(out_entries + count, std::addressof(cur_entry), sizeof(Entry)); } count++; /* Advance. */ if (visitor.CanMoveNext()) { R_TRY(visitor.MoveNext()); cur_entry = *visitor.Get<Entry>(); } else { break; } } /* Write the output count. */ *out_entry_count = count; R_SUCCEED(); } Result AesCtrCounterExtendedStorage::Read(s64 offset, void *buffer, size_t size) { /* Validate preconditions. */ AMS_ASSERT(offset >= 0); AMS_ASSERT(this->IsInitialized()); /* Allow zero size. */ R_SUCCEED_IF(size == 0); /* Validate arguments. */ R_UNLESS(buffer != nullptr, fs::ResultNullptrArgument()); R_UNLESS(util::IsAligned(offset, BlockSize), fs::ResultInvalidOffset()); R_UNLESS(util::IsAligned(size, BlockSize), fs::ResultInvalidSize()); BucketTree::Offsets table_offsets; R_TRY(m_table.GetOffsets(std::addressof(table_offsets))); R_UNLESS(table_offsets.IsInclude(offset, size), fs::ResultOutOfRange()); /* Read the data. */ R_TRY(m_data_storage.Read(offset, buffer, size)); /* Temporarily increase our thread priority. */ ScopedThreadPriorityChanger cp(+1, ScopedThreadPriorityChanger::Mode::Relative); /* Find the offset in our tree. */ BucketTree::Visitor visitor; R_TRY(m_table.Find(std::addressof(visitor), offset)); { const auto entry_offset = visitor.Get<Entry>()->GetOffset(); R_UNLESS(util::IsAligned(entry_offset, BlockSize), fs::ResultInvalidAesCtrCounterExtendedEntryOffset()); R_UNLESS(0 <= entry_offset && table_offsets.IsInclude(entry_offset), fs::ResultInvalidAesCtrCounterExtendedEntryOffset()); } /* Prepare to read in chunks. */ u8 *cur_data = static_cast<u8 *>(buffer); auto cur_offset = offset; const auto end_offset = offset + static_cast<s64>(size); while (cur_offset < end_offset) { /* Get the current entry. */ const auto cur_entry = *visitor.Get<Entry>(); /* Get and validate the entry's offset. */ const auto cur_entry_offset = cur_entry.GetOffset(); R_UNLESS(cur_entry_offset <= cur_offset, fs::ResultInvalidAesCtrCounterExtendedEntryOffset()); /* Get and validate the next entry offset. */ s64 next_entry_offset; if (visitor.CanMoveNext()) { R_TRY(visitor.MoveNext()); next_entry_offset = visitor.Get<Entry>()->GetOffset(); R_UNLESS(table_offsets.IsInclude(next_entry_offset), fs::ResultInvalidAesCtrCounterExtendedEntryOffset()); } else { next_entry_offset = table_offsets.end_offset; } R_UNLESS(util::IsAligned(next_entry_offset, BlockSize), fs::ResultInvalidAesCtrCounterExtendedEntryOffset()); R_UNLESS(cur_offset < next_entry_offset, fs::ResultInvalidAesCtrCounterExtendedEntryOffset()); /* Get the offset of the entry in the data we read. */ const auto data_offset = cur_offset - cur_entry_offset; const auto data_size = (next_entry_offset - cur_entry_offset) - data_offset; AMS_ASSERT(data_size > 0); /* Determine how much is left. */ const auto remaining_size = end_offset - cur_offset; const auto cur_size = static_cast<size_t>(std::min(remaining_size, data_size)); AMS_ASSERT(cur_size <= size); /* If necessary, perform decryption. */ if (cur_entry.encryption_value == Entry::Encryption::Encrypted) { /* Make the CTR for the data we're decrypting. */ const auto counter_offset = m_counter_offset + cur_entry_offset + data_offset; NcaAesCtrUpperIv upper_iv = { .part = { .generation = static_cast<u32>(cur_entry.generation), .secure_value = m_secure_value } }; u8 iv[IvSize]; AesCtrStorageByPointer::MakeIv(iv, IvSize, upper_iv.value, counter_offset); /* Decrypt. */ m_decryptor->Decrypt(cur_data, cur_size, m_key, KeySize, iv, IvSize); } /* Advance. */ cur_data += cur_size; cur_offset += cur_size; } R_SUCCEED(); } Result AesCtrCounterExtendedStorage::OperateRange(void *dst, size_t dst_size, fs::OperationId op_id, s64 offset, s64 size, const void *src, size_t src_size) { switch (op_id) { case fs::OperationId::Invalidate: { /* Validate preconditions. */ AMS_ASSERT(this->IsInitialized()); /* Invalidate our table's cache. */ R_TRY(m_table.InvalidateCache()); /* Operate on our data storage. */ R_TRY(m_data_storage.OperateRange(fs::OperationId::Invalidate, 0, std::numeric_limits<s64>::max())); R_SUCCEED(); } case fs::OperationId::QueryRange: { /* Validate preconditions. */ AMS_ASSERT(offset >= 0); AMS_ASSERT(this->IsInitialized()); /* Validate that we have an output range info. */ R_UNLESS(dst != nullptr, fs::ResultNullptrArgument()); R_UNLESS(dst_size == sizeof(fs::QueryRangeInfo), fs::ResultInvalidSize()); /* Succeed if there's nothing to operate on. */ if (size == 0) { reinterpret_cast<fs::QueryRangeInfo *>(dst)->Clear(); R_SUCCEED(); } /* Validate arguments. */ R_UNLESS(util::IsAligned(offset, BlockSize), fs::ResultInvalidOffset()); R_UNLESS(util::IsAligned(size, BlockSize), fs::ResultInvalidSize()); BucketTree::Offsets table_offsets; R_TRY(m_table.GetOffsets(std::addressof(table_offsets))); R_UNLESS(table_offsets.IsInclude(offset, size), fs::ResultOutOfRange()); /* Operate on our data storage. */ R_TRY(m_data_storage.OperateRange(dst, dst_size, op_id, offset, size, src, src_size)); /* Add in new flags. */ fs::QueryRangeInfo new_info; new_info.Clear(); new_info.aes_ctr_key_type = static_cast<s32>(m_decryptor->HasExternalDecryptionKey() ? fs::AesCtrKeyTypeFlag::ExternalKeyForHardwareAes : fs::AesCtrKeyTypeFlag::InternalKeyForHardwareAes); /* Merge in the new info. */ reinterpret_cast<fs::QueryRangeInfo *>(dst)->Merge(new_info); R_SUCCEED(); } default: R_THROW(fs::ResultUnsupportedOperateRangeForAesCtrCounterExtendedStorage()); } } void SoftwareDecryptor::Decrypt(void *buf, size_t buf_size, const void *enc_key, size_t enc_key_size, void *iv, size_t iv_size) { crypto::DecryptAes128Ctr(buf, buf_size, enc_key, enc_key_size, iv, iv_size, buf, buf_size); } void ExternalDecryptor::Decrypt(void *buf, size_t buf_size, const void *enc_key, size_t enc_key_size, void *iv, size_t iv_size) { /* Validate preconditions. */ AMS_ASSERT(buf != nullptr); AMS_ASSERT(enc_key != nullptr); AMS_ASSERT(enc_key_size == KeySize); AMS_ASSERT(iv != nullptr); AMS_ASSERT(iv_size == IvSize); AMS_UNUSED(iv_size); /* Copy the ctr. */ u8 ctr[IvSize]; std::memcpy(ctr, iv, IvSize); /* Setup tracking. */ size_t remaining_size = buf_size; s64 cur_offset = 0; /* Allocate a pooled buffer for decryption. */ PooledBuffer pooled_buffer; pooled_buffer.AllocateParticularlyLarge(buf_size, BlockSize); AMS_ASSERT(pooled_buffer.GetSize() > 0 && util::IsAligned(pooled_buffer.GetSize(), BlockSize)); /* Read and decrypt in chunks. */ while (remaining_size > 0) { size_t cur_size = std::min(pooled_buffer.GetSize(), remaining_size); u8 *dst = static_cast<u8 *>(buf) + cur_offset; m_decrypt_function(pooled_buffer.GetBuffer(), cur_size, m_key_index, m_key_generation, enc_key, enc_key_size, ctr, IvSize, dst, cur_size); std::memcpy(dst, pooled_buffer.GetBuffer(), cur_size); cur_offset += cur_size; remaining_size -= cur_size; if (remaining_size > 0) { AddCounter(ctr, IvSize, cur_size / BlockSize); } } } }
16,192
C++
.cpp
293
43.542662
313
0.604562
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,360
fssystem_alignment_matching_storage_impl.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssystem/fssystem_alignment_matching_storage_impl.cpp
/* * Copyright (c) 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 { namespace { template<typename T> constexpr ALWAYS_INLINE size_t GetRoundDownDifference(T x, size_t align) { return static_cast<size_t>(x - util::AlignDown(x, align)); } template<typename T> constexpr ALWAYS_INLINE size_t GetRoundUpDifference(T x, size_t align) { return static_cast<size_t>(util::AlignUp(x, align) - x); } template<typename T> ALWAYS_INLINE size_t GetRoundUpDifference(T *x, size_t align) { return GetRoundUpDifference(reinterpret_cast<uintptr_t>(x), align); } } Result AlignmentMatchingStorageImpl::Read(fs::IStorage *base_storage, char *work_buf, size_t work_buf_size, size_t data_alignment, size_t buffer_alignment, s64 offset, char *buffer, size_t size) { /* Check preconditions. */ AMS_ASSERT(work_buf_size >= data_alignment); AMS_UNUSED(work_buf_size); /* Succeed if zero size. */ R_SUCCEED_IF(size == 0); /* Validate arguments. */ R_UNLESS(buffer != nullptr, fs::ResultNullptrArgument()); /* Determine extents. */ char *aligned_core_buffer; s64 core_offset; size_t core_size; size_t buffer_gap; size_t offset_gap; s64 covered_offset; const size_t offset_round_up_difference = GetRoundUpDifference(offset, data_alignment); if (util::IsAligned(reinterpret_cast<uintptr_t>(buffer) + offset_round_up_difference, buffer_alignment)) { aligned_core_buffer = buffer + offset_round_up_difference; core_offset = util::AlignUp(offset, data_alignment); core_size = (size < offset_round_up_difference) ? 0 : util::AlignDown(size - offset_round_up_difference, data_alignment); buffer_gap = 0; offset_gap = 0; covered_offset = core_size > 0 ? core_offset : offset; } else { const size_t buffer_round_up_difference = GetRoundUpDifference(buffer, buffer_alignment); aligned_core_buffer = buffer + buffer_round_up_difference; core_offset = util::AlignDown(offset, data_alignment); core_size = (size < buffer_round_up_difference) ? 0 : util::AlignDown(size - buffer_round_up_difference, data_alignment); buffer_gap = buffer_round_up_difference; offset_gap = GetRoundDownDifference(offset, data_alignment); covered_offset = offset; } /* Read the core portion. */ if (core_size > 0) { R_TRY(base_storage->Read(core_offset, aligned_core_buffer, core_size)); if (offset_gap != 0 || buffer_gap != 0) { std::memmove(aligned_core_buffer - buffer_gap, aligned_core_buffer + offset_gap, core_size - offset_gap); core_size -= offset_gap; } } /* Handle the head portion. */ if (offset < covered_offset) { const s64 head_offset = util::AlignDown(offset, data_alignment); const size_t head_size = static_cast<size_t>(covered_offset - offset); AMS_ASSERT(GetRoundDownDifference(offset, data_alignment) + head_size <= work_buf_size); R_TRY(base_storage->Read(head_offset, work_buf, data_alignment)); std::memcpy(buffer, work_buf + GetRoundDownDifference(offset, data_alignment), head_size); } /* Handle the tail portion. */ s64 tail_offset = covered_offset + core_size; size_t remaining_tail_size = static_cast<size_t>((offset + size) - tail_offset); while (remaining_tail_size > 0) { const auto aligned_tail_offset = util::AlignDown(tail_offset, data_alignment); const auto cur_size = std::min(static_cast<size_t>(aligned_tail_offset + data_alignment - tail_offset), remaining_tail_size); R_TRY(base_storage->Read(aligned_tail_offset, work_buf, data_alignment)); AMS_ASSERT((tail_offset - offset) + cur_size <= size); AMS_ASSERT((tail_offset - aligned_tail_offset) + cur_size <= data_alignment); std::memcpy(static_cast<char *>(buffer) + (tail_offset - offset), work_buf + (tail_offset - aligned_tail_offset), cur_size); remaining_tail_size -= cur_size; tail_offset += cur_size; } R_SUCCEED(); } Result AlignmentMatchingStorageImpl::Write(fs::IStorage *base_storage, char *work_buf, size_t work_buf_size, size_t data_alignment, size_t buffer_alignment, s64 offset, const char *buffer, size_t size) { /* Check preconditions. */ AMS_ASSERT(work_buf_size >= data_alignment); AMS_UNUSED(work_buf_size); /* Succeed if zero size. */ R_SUCCEED_IF(size == 0); /* Validate arguments. */ R_UNLESS(buffer != nullptr, fs::ResultNullptrArgument()); /* Determine extents. */ const char *aligned_core_buffer; s64 core_offset; size_t core_size; s64 covered_offset; const size_t offset_round_up_difference = GetRoundUpDifference(offset, data_alignment); if (util::IsAligned(reinterpret_cast<uintptr_t>(buffer) + offset_round_up_difference, buffer_alignment)) { aligned_core_buffer = buffer + offset_round_up_difference; core_offset = util::AlignUp(offset, data_alignment); core_size = (size < offset_round_up_difference) ? 0 : util::AlignDown(size - offset_round_up_difference, data_alignment); covered_offset = core_size > 0 ? core_offset : offset; } else { aligned_core_buffer = nullptr; core_offset = util::AlignDown(offset, data_alignment); core_size = 0; covered_offset = offset; } /* Write the core portion. */ if (core_size > 0) { R_TRY(base_storage->Write(core_offset, aligned_core_buffer, core_size)); } /* Handle the head portion. */ if (offset < covered_offset) { const s64 head_offset = util::AlignDown(offset, data_alignment); const size_t head_size = static_cast<size_t>(covered_offset - offset); AMS_ASSERT((offset - head_offset) + head_size <= data_alignment); R_TRY(base_storage->Read(head_offset, work_buf, data_alignment)); std::memcpy(work_buf + (offset - head_offset), buffer, head_size); R_TRY(base_storage->Write(head_offset, work_buf, data_alignment)); } /* Handle the tail portion. */ s64 tail_offset = covered_offset + core_size; size_t remaining_tail_size = static_cast<size_t>((offset + size) - tail_offset); while (remaining_tail_size > 0) { AMS_ASSERT(static_cast<size_t>(tail_offset - offset) < size); const auto aligned_tail_offset = util::AlignDown(tail_offset, data_alignment); const auto cur_size = std::min(static_cast<size_t>(aligned_tail_offset + data_alignment - tail_offset), remaining_tail_size); R_TRY(base_storage->Read(aligned_tail_offset, work_buf, data_alignment)); std::memcpy(work_buf + GetRoundDownDifference(tail_offset, data_alignment), buffer + (tail_offset - offset), cur_size); R_TRY(base_storage->Write(aligned_tail_offset, work_buf, data_alignment)); remaining_tail_size -= cur_size; tail_offset += cur_size; } R_SUCCEED(); } template<> Result AlignmentMatchingStorageInBulkRead<1>::Read(s64 offset, void *buffer, size_t size) { /* Succeed if zero size. */ R_SUCCEED_IF(size == 0); /* Validate arguments. */ R_UNLESS(buffer != nullptr, fs::ResultNullptrArgument()); s64 bs_size = 0; R_TRY(this->GetSize(std::addressof(bs_size))); R_TRY(fs::IStorage::CheckAccessRange(offset, size, bs_size)); /* Determine extents. */ const auto offset_end = offset + static_cast<s64>(size); const auto aligned_offset = util::AlignDown(offset, m_data_align); const auto aligned_offset_end = util::AlignUp(offset_end, m_data_align); const auto aligned_size = static_cast<size_t>(aligned_offset_end - aligned_offset); /* If we aren't aligned, we need to allocate a buffer. */ PooledBuffer pooled_buffer; if (aligned_offset != offset || aligned_size != size) { if (aligned_size <= pooled_buffer.GetAllocatableSizeMax()) { pooled_buffer.Allocate(aligned_size, m_data_align); if (aligned_size <= pooled_buffer.GetSize()) { R_TRY(m_base_storage->Read(aligned_offset, pooled_buffer.GetBuffer(), aligned_size)); std::memcpy(buffer, pooled_buffer.GetBuffer() + (offset - aligned_offset), size); R_SUCCEED(); } else { pooled_buffer.Shrink(m_data_align); } } else { pooled_buffer.Allocate(m_data_align, m_data_align); } AMS_ASSERT(pooled_buffer.GetSize() >= static_cast<size_t>(m_data_align)); } /* Determine read extents for the aligned portion. */ const auto core_offset = util::AlignUp(offset, m_data_align); const auto core_offset_end = util::AlignDown(offset_end, m_data_align); /* Handle any data before the aligned portion. */ if (offset < core_offset) { const auto head_size = static_cast<size_t>(core_offset - offset); AMS_ASSERT(head_size < size); R_TRY(m_base_storage->Read(aligned_offset, pooled_buffer.GetBuffer(), m_data_align)); std::memcpy(buffer, pooled_buffer.GetBuffer() + (offset - aligned_offset), head_size); } /* Handle the aligned portion. */ if (core_offset < core_offset_end) { const auto core_buffer = static_cast<char *>(buffer) + (core_offset - offset); const auto core_size = static_cast<size_t>(core_offset_end - core_offset); R_TRY(m_base_storage->Read(core_offset, core_buffer, core_size)); } /* Handle any data after the aligned portion. */ if (core_offset_end < offset_end) { const auto tail_buffer = static_cast<char *>(buffer) + (core_offset_end - offset); const auto tail_size = static_cast<size_t>(offset_end - core_offset_end); R_TRY(m_base_storage->Read(core_offset_end, pooled_buffer.GetBuffer(), m_data_align)); std::memcpy(tail_buffer, pooled_buffer.GetBuffer(), tail_size); } R_SUCCEED(); } }
11,376
C++
.cpp
204
45.416667
207
0.618444
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,361
fssystem_aes_xts_storage.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssystem/fssystem_aes_xts_storage.cpp
/* * Copyright (c) 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 { template<fs::PointerToStorage BasePointer> void AesXtsStorage<BasePointer>::MakeAesXtsIv(void *dst, size_t dst_size, s64 offset, size_t block_size) { AMS_ASSERT(dst != nullptr); AMS_ASSERT(dst_size == IvSize); AMS_ASSERT(offset >= 0); AMS_UNUSED(dst_size); const uintptr_t out_addr = reinterpret_cast<uintptr_t>(dst); util::StoreBigEndian<s64>(reinterpret_cast<s64 *>(out_addr + sizeof(s64)), offset / block_size); } template<fs::PointerToStorage BasePointer> AesXtsStorage<BasePointer>::AesXtsStorage(BasePointer base, const void *key1, const void *key2, size_t key_size, const void *iv, size_t iv_size, size_t block_size) : m_base_storage(std::move(base)), m_block_size(block_size), m_mutex() { AMS_ASSERT(m_base_storage != nullptr); AMS_ASSERT(key1 != nullptr); AMS_ASSERT(key2 != nullptr); AMS_ASSERT(iv != nullptr); AMS_ASSERT(key_size == KeySize); AMS_ASSERT(iv_size == IvSize); AMS_ASSERT(util::IsAligned(m_block_size, AesBlockSize)); AMS_UNUSED(key_size, iv_size); std::memcpy(m_key[0], key1, KeySize); std::memcpy(m_key[1], key2, KeySize); std::memcpy(m_iv, iv, IvSize); } template<fs::PointerToStorage BasePointer> Result AesXtsStorage<BasePointer>::Read(s64 offset, void *buffer, size_t size) { /* Allow zero-size reads. */ R_SUCCEED_IF(size == 0); /* Ensure buffer is valid. */ R_UNLESS(buffer != nullptr, fs::ResultNullptrArgument()); /* We can only read at block aligned offsets. */ R_UNLESS(util::IsAligned(offset, AesBlockSize), fs::ResultInvalidArgument()); R_UNLESS(util::IsAligned(size, AesBlockSize), fs::ResultInvalidArgument()); /* Read the data. */ R_TRY(m_base_storage->Read(offset, buffer, size)); /* Prepare to decrypt the data, with temporarily increased priority. */ ScopedThreadPriorityChanger cp(+1, ScopedThreadPriorityChanger::Mode::Relative); /* Setup the counter. */ char ctr[IvSize]; std::memcpy(ctr, m_iv, IvSize); AddCounter(ctr, IvSize, offset / m_block_size); /* Handle any unaligned data before the start. */ size_t processed_size = 0; if ((offset % m_block_size) != 0) { /* Determine the size of the pre-data read. */ const size_t skip_size = static_cast<size_t>(offset - util::AlignDown(offset, m_block_size)); const size_t data_size = std::min(size, m_block_size - skip_size); /* Decrypt into a pooled buffer. */ { PooledBuffer tmp_buf(m_block_size, m_block_size); AMS_ASSERT(tmp_buf.GetSize() >= m_block_size); std::memset(tmp_buf.GetBuffer(), 0, skip_size); std::memcpy(tmp_buf.GetBuffer() + skip_size, buffer, data_size); const size_t dec_size = crypto::DecryptAes128Xts(tmp_buf.GetBuffer(), m_block_size, m_key[0], m_key[1], KeySize, ctr, IvSize, tmp_buf.GetBuffer(), m_block_size); R_UNLESS(dec_size == m_block_size, fs::ResultUnexpectedInAesXtsStorageA()); std::memcpy(buffer, tmp_buf.GetBuffer() + skip_size, data_size); } AddCounter(ctr, IvSize, 1); processed_size += data_size; AMS_ASSERT(processed_size == std::min(size, m_block_size - skip_size)); } /* Decrypt aligned chunks. */ char *cur = static_cast<char *>(buffer) + processed_size; size_t remaining = size - processed_size; while (remaining > 0) { const size_t cur_size = std::min(m_block_size, remaining); const size_t dec_size = crypto::DecryptAes128Xts(cur, cur_size, m_key[0], m_key[1], KeySize, ctr, IvSize, cur, cur_size); R_UNLESS(cur_size == dec_size, fs::ResultUnexpectedInAesXtsStorageA()); remaining -= cur_size; cur += cur_size; AddCounter(ctr, IvSize, 1); } R_SUCCEED(); } template<fs::PointerToStorage BasePointer> Result AesXtsStorage<BasePointer>::Write(s64 offset, const void *buffer, size_t size) { /* Allow zero-size writes. */ R_SUCCEED_IF(size == 0); /* Ensure buffer is valid. */ R_UNLESS(buffer != nullptr, fs::ResultNullptrArgument()); /* We can only read at block aligned offsets. */ R_UNLESS(util::IsAligned(offset, AesBlockSize), fs::ResultInvalidArgument()); R_UNLESS(util::IsAligned(size, AesBlockSize), fs::ResultInvalidArgument()); /* Get a pooled buffer. */ PooledBuffer pooled_buffer; const bool use_work_buffer = !IsDeviceAddress(buffer); if (use_work_buffer) { pooled_buffer.Allocate(size, m_block_size); } /* Setup the counter. */ char ctr[IvSize]; std::memcpy(ctr, m_iv, IvSize); AddCounter(ctr, IvSize, offset / m_block_size); /* Handle any unaligned data before the start. */ size_t processed_size = 0; if ((offset % m_block_size) != 0) { /* Determine the size of the pre-data read. */ const size_t skip_size = static_cast<size_t>(offset - util::AlignDown(offset, m_block_size)); const size_t data_size = std::min(size, m_block_size - skip_size); /* Create an encryptor. */ /* NOTE: This is completely unnecessary, because crypto::EncryptAes128Xts is used below. */ /* However, Nintendo does it, so we will too. */ crypto::Aes128XtsEncryptor xts; xts.Initialize(m_key[0], m_key[1], KeySize, ctr, IvSize); /* Encrypt into a pooled buffer. */ { /* NOTE: Nintendo allocates a second pooled buffer here despite having one already allocated above. */ PooledBuffer tmp_buf(m_block_size, m_block_size); AMS_ASSERT(tmp_buf.GetSize() >= m_block_size); std::memset(tmp_buf.GetBuffer(), 0, skip_size); std::memcpy(tmp_buf.GetBuffer() + skip_size, buffer, data_size); const size_t enc_size = crypto::EncryptAes128Xts(tmp_buf.GetBuffer(), m_block_size, m_key[0], m_key[1], KeySize, ctr, IvSize, tmp_buf.GetBuffer(), m_block_size); R_UNLESS(enc_size == m_block_size, fs::ResultUnexpectedInAesXtsStorageA()); R_TRY(m_base_storage->Write(offset, tmp_buf.GetBuffer() + skip_size, data_size)); } AddCounter(ctr, IvSize, 1); processed_size += data_size; AMS_ASSERT(processed_size == std::min(size, m_block_size - skip_size)); } /* Encrypt aligned chunks. */ size_t remaining = size - processed_size; s64 cur_offset = offset + processed_size; while (remaining > 0) { /* Determine data we're writing and where. */ const size_t write_size = use_work_buffer ? std::min(pooled_buffer.GetSize(), remaining) : remaining; /* Encrypt the data, with temporarily increased priority. */ { ScopedThreadPriorityChanger cp(+1, ScopedThreadPriorityChanger::Mode::Relative); size_t remaining_write = write_size; size_t encrypt_offset = 0; while (remaining_write > 0) { const size_t cur_size = std::min(remaining_write, m_block_size); const void *src = static_cast<const char *>(buffer) + processed_size + encrypt_offset; void *dst = use_work_buffer ? pooled_buffer.GetBuffer() + encrypt_offset : const_cast<void *>(src); const size_t enc_size = crypto::EncryptAes128Xts(dst, cur_size, m_key[0], m_key[1], KeySize, ctr, IvSize, src, cur_size); R_UNLESS(enc_size == cur_size, fs::ResultUnexpectedInAesXtsStorageA()); AddCounter(ctr, IvSize, 1); encrypt_offset += cur_size; remaining_write -= cur_size; } } /* Write the encrypted data. */ const void *write_buf = use_work_buffer ? pooled_buffer.GetBuffer() : static_cast<const char *>(buffer) + processed_size; R_TRY(m_base_storage->Write(cur_offset, write_buf, write_size)); /* Advance. */ cur_offset += write_size; processed_size += write_size; remaining -= write_size; } R_SUCCEED(); } template<fs::PointerToStorage BasePointer> Result AesXtsStorage<BasePointer>::Flush() { R_RETURN(m_base_storage->Flush()); } template<fs::PointerToStorage BasePointer> Result AesXtsStorage<BasePointer>::SetSize(s64 size) { R_UNLESS(util::IsAligned(size, AesBlockSize), fs::ResultUnexpectedInAesXtsStorageA()); R_RETURN(m_base_storage->SetSize(size)); } template<fs::PointerToStorage BasePointer> Result AesXtsStorage<BasePointer>::GetSize(s64 *out) { R_RETURN(m_base_storage->GetSize(out)); } template<fs::PointerToStorage BasePointer> Result AesXtsStorage<BasePointer>::OperateRange(void *dst, size_t dst_size, fs::OperationId op_id, s64 offset, s64 size, const void *src, size_t src_size) { /* Unless invalidating cache, check the arguments. */ if (op_id != fs::OperationId::Invalidate) { /* Handle the zero size case. */ R_SUCCEED_IF(size == 0); /* Ensure alignment. */ R_UNLESS(util::IsAligned(offset, AesBlockSize), fs::ResultInvalidArgument()); R_UNLESS(util::IsAligned(size, AesBlockSize), fs::ResultInvalidArgument()); } R_RETURN(m_base_storage->OperateRange(dst, dst_size, op_id, offset, size, src, src_size)); } template class AesXtsStorage<fs::IStorage *>; template class AesXtsStorage<std::shared_ptr<fs::IStorage>>; }
10,705
C++
.cpp
195
44.553846
240
0.614267
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,362
fssystem_directory_savedata_filesystem.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssystem/fssystem_directory_savedata_filesystem.cpp
/* * Copyright (c) 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 { namespace { constexpr size_t IdealWorkBufferSize = 1_MB; constexpr size_t MinimumWorkBufferSize = 1_KB; constexpr const fs::Path CommittedDirectoryPath = fs::MakeConstantPath("/0"); constexpr const fs::Path WorkingDirectoryPath = fs::MakeConstantPath("/1"); constexpr const fs::Path SynchronizingDirectoryPath = fs::MakeConstantPath("/_"); constexpr const fs::Path LockFilePath = fs::MakeConstantPath("/.lock"); class DirectorySaveDataFile : public fs::fsa::IFile, public fs::impl::Newable { private: std::unique_ptr<fs::fsa::IFile> m_base_file; DirectorySaveDataFileSystem *m_parent_fs; fs::OpenMode m_open_mode; public: DirectorySaveDataFile(std::unique_ptr<fs::fsa::IFile> f, DirectorySaveDataFileSystem *p, fs::OpenMode m) : m_base_file(std::move(f)), m_parent_fs(p), m_open_mode(m) { /* ... */ } virtual ~DirectorySaveDataFile() { /* Observe closing of writable file. */ if (m_open_mode & fs::OpenMode_Write) { m_parent_fs->DecrementWriteOpenFileCount(); } } public: virtual Result DoRead(size_t *out, s64 offset, void *buffer, size_t size, const fs::ReadOption &option) override { R_RETURN(m_base_file->Read(out, offset, buffer, size, option)); } virtual Result DoGetSize(s64 *out) override { R_RETURN(m_base_file->GetSize(out)); } virtual Result DoFlush() override { R_RETURN(m_base_file->Flush()); } virtual Result DoWrite(s64 offset, const void *buffer, size_t size, const fs::WriteOption &option) override { R_RETURN(m_base_file->Write(offset, buffer, size, option)); } virtual Result DoSetSize(s64 size) override { R_RETURN(m_base_file->SetSize(size)); } virtual Result DoOperateRange(void *dst, size_t dst_size, fs::OperationId op_id, s64 offset, s64 size, const void *src, size_t src_size) override { R_RETURN(m_base_file->OperateRange(dst, dst_size, op_id, offset, size, src, src_size)); } public: virtual sf::cmif::DomainObjectId GetDomainObjectId() const override { return m_base_file->GetDomainObjectId(); } }; } Result DirectorySaveDataFileSystem::Initialize(bool journaling_supported, bool multi_commit_supported, bool journaling_enabled) { /* Configure ourselves. */ m_is_journaling_supported = journaling_supported; m_is_multi_commit_supported = multi_commit_supported; m_is_journaling_enabled = journaling_enabled; /* Ensure that we can initialize further by acquiring a lock on the filesystem. */ R_TRY(this->AcquireLockFile()); fs::DirectoryEntryType type; /* Check that the working directory exists. */ R_TRY_CATCH(m_base_fs->GetEntryType(std::addressof(type), WorkingDirectoryPath)) { /* If path isn't found, create working directory and committed directory. */ R_CATCH(fs::ResultPathNotFound) { R_TRY(m_base_fs->CreateDirectory(WorkingDirectoryPath)); if (m_is_journaling_supported) { R_TRY(m_base_fs->CreateDirectory(CommittedDirectoryPath)); } } } R_END_TRY_CATCH; /* If we support journaling, we need to set up the committed directory. */ if (m_is_journaling_supported) { /* Now check for the committed directory. */ R_TRY_CATCH(m_base_fs->GetEntryType(std::addressof(type), CommittedDirectoryPath)) { /* Committed doesn't exist, so synchronize and rename. */ R_CATCH(fs::ResultPathNotFound) { R_TRY(this->SynchronizeDirectory(SynchronizingDirectoryPath, WorkingDirectoryPath)); R_TRY(m_base_fs->RenameDirectory(SynchronizingDirectoryPath, CommittedDirectoryPath)); R_SUCCEED(); } } R_END_TRY_CATCH; /* The committed directory exists, so if we should, synchronize it to the working directory. */ if (m_is_journaling_enabled) { R_TRY(this->SynchronizeDirectory(WorkingDirectoryPath, CommittedDirectoryPath)); } } R_SUCCEED(); } Result DirectorySaveDataFileSystem::SynchronizeDirectory(const fs::Path &dst, const fs::Path &src) { /* Delete destination dir and recreate it. */ R_TRY_CATCH(m_base_fs->DeleteDirectoryRecursively(dst)) { R_CATCH(fs::ResultPathNotFound) { /* Nintendo returns error unconditionally, but I think that's a bug in their code. */} } R_END_TRY_CATCH; R_TRY(m_base_fs->CreateDirectory(dst)); /* Get a work buffer to work with. */ fssystem::PooledBuffer buffer; buffer.AllocateParticularlyLarge(IdealWorkBufferSize, MinimumWorkBufferSize); /* Copy the directory recursively. */ fs::DirectoryEntry dir_entry_buffer = {}; R_RETURN(fssystem::CopyDirectoryRecursively(m_base_fs, dst, src, std::addressof(dir_entry_buffer), buffer.GetBuffer(), buffer.GetSize())); } Result DirectorySaveDataFileSystem::ResolvePath(fs::Path *out, const fs::Path &path) { const fs::Path &directory = (m_is_journaling_supported && !m_is_journaling_enabled) ? CommittedDirectoryPath : WorkingDirectoryPath; R_RETURN(out->Combine(directory, path)); } Result DirectorySaveDataFileSystem::AcquireLockFile() { /* If we already have a lock file, we don't need to lock again. */ R_SUCCEED_IF(m_lock_file != nullptr); /* Open the lock file. */ std::unique_ptr<fs::fsa::IFile> file; R_TRY_CATCH(m_base_fs->OpenFile(std::addressof(file), LockFilePath, fs::OpenMode_ReadWrite)) { /* If the lock file doesn't yet exist, we may need to create it. */ R_CATCH(fs::ResultPathNotFound) { R_TRY(m_base_fs->CreateFile(LockFilePath, 0)); R_TRY(m_base_fs->OpenFile(std::addressof(file), LockFilePath, fs::OpenMode_ReadWrite)); } } R_END_TRY_CATCH; /* Set our lock file. */ m_lock_file = std::move(file); R_SUCCEED(); } void DirectorySaveDataFileSystem::DecrementWriteOpenFileCount() { std::scoped_lock lk(m_accessor_mutex); --m_open_writable_files; } Result DirectorySaveDataFileSystem::DoCreateFile(const fs::Path &path, s64 size, int option) { /* Resolve the final path. */ fs::Path resolved; R_TRY(this->ResolvePath(std::addressof(resolved), path)); /* Lock ourselves. */ std::scoped_lock lk(m_accessor_mutex); R_RETURN(m_base_fs->CreateFile(resolved, size, option)); } Result DirectorySaveDataFileSystem::DoDeleteFile(const fs::Path &path) { /* Resolve the final path. */ fs::Path resolved; R_TRY(this->ResolvePath(std::addressof(resolved), path)); /* Lock ourselves. */ std::scoped_lock lk(m_accessor_mutex); R_RETURN(m_base_fs->DeleteFile(resolved)); } Result DirectorySaveDataFileSystem::DoCreateDirectory(const fs::Path &path) { /* Resolve the final path. */ fs::Path resolved; R_TRY(this->ResolvePath(std::addressof(resolved), path)); /* Lock ourselves. */ std::scoped_lock lk(m_accessor_mutex); R_RETURN(m_base_fs->CreateDirectory(resolved)); } Result DirectorySaveDataFileSystem::DoDeleteDirectory(const fs::Path &path) { /* Resolve the final path. */ fs::Path resolved; R_TRY(this->ResolvePath(std::addressof(resolved), path)); /* Lock ourselves. */ std::scoped_lock lk(m_accessor_mutex); R_RETURN(m_base_fs->DeleteDirectory(resolved)); } Result DirectorySaveDataFileSystem::DoDeleteDirectoryRecursively(const fs::Path &path) { /* Resolve the final path. */ fs::Path resolved; R_TRY(this->ResolvePath(std::addressof(resolved), path)); /* Lock ourselves. */ std::scoped_lock lk(m_accessor_mutex); R_RETURN(m_base_fs->DeleteDirectoryRecursively(resolved)); } Result DirectorySaveDataFileSystem::DoRenameFile(const fs::Path &old_path, const fs::Path &new_path) { /* Resolve the final paths. */ fs::Path old_resolved; fs::Path new_resolved; R_TRY(this->ResolvePath(std::addressof(old_resolved), old_path)); R_TRY(this->ResolvePath(std::addressof(new_resolved), new_path)); /* Lock ourselves. */ std::scoped_lock lk(m_accessor_mutex); R_RETURN(m_base_fs->RenameFile(old_resolved, new_resolved)); } Result DirectorySaveDataFileSystem::DoRenameDirectory(const fs::Path &old_path, const fs::Path &new_path) { /* Resolve the final paths. */ fs::Path old_resolved; fs::Path new_resolved; R_TRY(this->ResolvePath(std::addressof(old_resolved), old_path)); R_TRY(this->ResolvePath(std::addressof(new_resolved), new_path)); /* Lock ourselves. */ std::scoped_lock lk(m_accessor_mutex); R_RETURN(m_base_fs->RenameDirectory(old_resolved, new_resolved)); } Result DirectorySaveDataFileSystem::DoGetEntryType(fs::DirectoryEntryType *out, const fs::Path &path) { /* Resolve the final path. */ fs::Path resolved; R_TRY(this->ResolvePath(std::addressof(resolved), path)); /* Lock ourselves. */ std::scoped_lock lk(m_accessor_mutex); R_RETURN(m_base_fs->GetEntryType(out, resolved)); } Result DirectorySaveDataFileSystem::DoOpenFile(std::unique_ptr<fs::fsa::IFile> *out_file, const fs::Path &path, fs::OpenMode mode) { /* Resolve the final path. */ fs::Path resolved; R_TRY(this->ResolvePath(std::addressof(resolved), path)); /* Lock ourselves. */ std::scoped_lock lk(m_accessor_mutex); /* Open base file. */ std::unique_ptr<fs::fsa::IFile> base_file; R_TRY(m_base_fs->OpenFile(std::addressof(base_file), resolved, mode)); /* Make DirectorySaveDataFile. */ std::unique_ptr<fs::fsa::IFile> file = std::make_unique<DirectorySaveDataFile>(std::move(base_file), this, mode); R_UNLESS(file != nullptr, fs::ResultAllocationMemoryFailedInDirectorySaveDataFileSystemA()); /* Increment our open writable files, if the file is writable. */ if (mode & fs::OpenMode_Write) { ++m_open_writable_files; } /* Set the output. */ *out_file = std::move(file); R_SUCCEED(); } Result DirectorySaveDataFileSystem::DoOpenDirectory(std::unique_ptr<fs::fsa::IDirectory> *out_dir, const fs::Path &path, fs::OpenDirectoryMode mode) { /* Resolve the final path. */ fs::Path resolved; R_TRY(this->ResolvePath(std::addressof(resolved), path)); /* Lock ourselves. */ std::scoped_lock lk(m_accessor_mutex); R_RETURN(m_base_fs->OpenDirectory(out_dir, resolved, mode)); } Result DirectorySaveDataFileSystem::DoCommit() { /* Lock ourselves. */ std::scoped_lock lk(m_accessor_mutex); /* If we aren't journaling, we don't need to do anything. */ R_SUCCEED_IF(!m_is_journaling_enabled); R_SUCCEED_IF(!m_is_journaling_supported); /* Check that there are no open files blocking the commit. */ R_UNLESS(m_open_writable_files == 0, fs::ResultWriteModeFileNotClosed()); /* Remove the previous commit by renaming the folder. */ R_TRY(fssystem::RetryFinitelyForTargetLocked([&] () ALWAYS_INLINE_LAMBDA { R_RETURN(m_base_fs->RenameDirectory(CommittedDirectoryPath, SynchronizingDirectoryPath)); })); /* Synchronize the working directory to the synchronizing directory. */ R_TRY(fssystem::RetryFinitelyForTargetLocked([&] () ALWAYS_INLINE_LAMBDA { R_RETURN(this->SynchronizeDirectory(SynchronizingDirectoryPath, WorkingDirectoryPath)); })); /* Rename the synchronized directory to commit it. */ R_TRY(fssystem::RetryFinitelyForTargetLocked([&] () ALWAYS_INLINE_LAMBDA { R_RETURN(m_base_fs->RenameDirectory(SynchronizingDirectoryPath, CommittedDirectoryPath)); })); R_SUCCEED(); } Result DirectorySaveDataFileSystem::DoGetFreeSpaceSize(s64 *out, const fs::Path &path) { /* Lock ourselves. */ std::scoped_lock lk(m_accessor_mutex); /* Get the free space size in our working directory. */ AMS_UNUSED(path); R_RETURN(m_base_fs->GetFreeSpaceSize(out, WorkingDirectoryPath)); } Result DirectorySaveDataFileSystem::DoGetTotalSpaceSize(s64 *out, const fs::Path &path) { /* Lock ourselves. */ std::scoped_lock lk(m_accessor_mutex); /* Get the free space size in our working directory. */ AMS_UNUSED(path); R_RETURN(m_base_fs->GetTotalSpaceSize(out, WorkingDirectoryPath)); } Result DirectorySaveDataFileSystem::DoCleanDirectoryRecursively(const fs::Path &path) { /* Resolve the final path. */ fs::Path resolved; R_TRY(this->ResolvePath(std::addressof(resolved), path)); /* Lock ourselves. */ std::scoped_lock lk(m_accessor_mutex); R_RETURN(m_base_fs->CleanDirectoryRecursively(resolved)); } Result DirectorySaveDataFileSystem::DoCommitProvisionally(s64 counter) { /* Check that we support multi-commit. */ R_UNLESS(m_is_multi_commit_supported, fs::ResultUnsupportedCommitProvisionallyForDirectorySaveDataFileSystem()); /* Do nothing. */ AMS_UNUSED(counter); R_SUCCEED(); } Result DirectorySaveDataFileSystem::DoRollback() { /* On non-journaled savedata, there's nothing to roll back to. */ R_SUCCEED_IF(!m_is_journaling_supported); /* Perform a re-initialize. */ R_RETURN(this->Initialize(m_is_journaling_supported, m_is_multi_commit_supported, m_is_journaling_enabled)); } }
15,182
C++
.cpp
285
43.277193
182
0.636609
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,363
fssystem_romfs_filesystem.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssystem/fssystem_romfs_filesystem.cpp
/* * Copyright (c) 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 { namespace { constexpr size_t CalculateRequiredWorkingMemorySize(const fs::RomFileSystemInformation &header) { return header.directory_bucket_size + header.directory_entry_size + header.file_bucket_size + header.file_entry_size; } class RomFsFile : public ams::fs::fsa::IFile, public ams::fs::impl::Newable { private: RomFsFileSystem *m_parent; s64 m_start; s64 m_end; private: s64 GetSize() const { return m_end - m_start; } public: RomFsFile(RomFsFileSystem *p, s64 s, s64 e) : m_parent(p), m_start(s), m_end(e) { /* ... */ } virtual ~RomFsFile() { /* ... */ } public: virtual Result DoRead(size_t *out, s64 offset, void *buffer, size_t size, const fs::ReadOption &option) override { R_TRY(buffers::DoContinuouslyUntilBufferIsAllocated([&]() -> Result { size_t read_size = 0; R_TRY(this->DryRead(std::addressof(read_size), offset, size, option, fs::OpenMode_Read)); R_TRY(m_parent->GetBaseStorage()->Read(offset + m_start, buffer, read_size)); *out = read_size; R_SUCCEED(); }, AMS_CURRENT_FUNCTION_NAME)); R_SUCCEED(); } virtual Result DoGetSize(s64 *out) override { *out = this->GetSize(); R_SUCCEED(); } virtual Result DoFlush() override { R_SUCCEED(); } virtual Result DoWrite(s64 offset, const void *buffer, size_t size, const fs::WriteOption &option) override { AMS_UNUSED(buffer); bool needs_append; R_TRY(this->DryWrite(std::addressof(needs_append), offset, size, option, fs::OpenMode_Read)); AMS_ASSERT(needs_append == false); R_THROW(fs::ResultUnsupportedWriteForRomFsFile()); } virtual Result DoSetSize(s64 size) override { R_TRY(this->DrySetSize(size, fs::OpenMode_Read)); R_THROW(fs::ResultUnsupportedWriteForRomFsFile()); } virtual Result DoOperateRange(void *dst, size_t dst_size, fs::OperationId op_id, s64 offset, s64 size, const void *src, size_t src_size) override { switch (op_id) { case fs::OperationId::Invalidate: { R_RETURN(buffers::DoContinuouslyUntilBufferIsAllocated([&]() -> Result { R_RETURN(m_parent->GetBaseStorage()->OperateRange(fs::OperationId::Invalidate, 0, std::numeric_limits<s64>::max())); }, AMS_CURRENT_FUNCTION_NAME)); } case fs::OperationId::QueryRange: { R_UNLESS(offset >= 0, fs::ResultInvalidOffset()); R_UNLESS(this->GetSize() >= offset, fs::ResultOutOfRange()); auto operate_size = size; if (offset + operate_size > this->GetSize() || offset + operate_size < offset) { operate_size = this->GetSize() - offset; } R_RETURN(buffers::DoContinuouslyUntilBufferIsAllocated([&]() -> Result { R_RETURN(m_parent->GetBaseStorage()->OperateRange(dst, dst_size, op_id, m_start + offset, operate_size, src, src_size)); }, AMS_CURRENT_FUNCTION_NAME)); } default: R_THROW(fs::ResultUnsupportedOperateRangeForRomFsFile()); } } public: virtual sf::cmif::DomainObjectId GetDomainObjectId() const override { AMS_ABORT(); } }; class RomFsDirectory : public ams::fs::fsa::IDirectory, public ams::fs::impl::Newable { private: using FindPosition = RomFsFileSystem::RomFileTable::FindPosition; private: RomFsFileSystem *m_parent; FindPosition m_current_find; FindPosition m_first_find; fs::OpenDirectoryMode m_mode; public: RomFsDirectory(RomFsFileSystem *p, const FindPosition &f, fs::OpenDirectoryMode m) : m_parent(p), m_current_find(f), m_first_find(f), m_mode(m) { /* ... */ } virtual ~RomFsDirectory() override { /* ... */ } public: virtual Result DoRead(s64 *out_count, fs::DirectoryEntry *out_entries, s64 max_entries) override { R_TRY(buffers::DoContinuouslyUntilBufferIsAllocated([&]() -> Result { R_RETURN(this->ReadInternal(out_count, std::addressof(m_current_find), out_entries, max_entries)); }, AMS_CURRENT_FUNCTION_NAME)); R_SUCCEED(); } virtual Result DoGetEntryCount(s64 *out) override { FindPosition find = m_first_find; R_TRY(buffers::DoContinuouslyUntilBufferIsAllocated([&]() -> Result { R_TRY(this->ReadInternal(out, std::addressof(find), nullptr, 0)); R_SUCCEED(); }, AMS_CURRENT_FUNCTION_NAME)); R_SUCCEED(); } private: Result ReadInternal(s64 *out_count, FindPosition *find, fs::DirectoryEntry *out_entries, s64 max_entries) { constexpr size_t NameBufferSize = fs::EntryNameLengthMax + 1; fs::RomPathChar name[NameBufferSize]; s32 i = 0; if (m_mode & fs::OpenDirectoryMode_Directory) { while (i < max_entries || out_entries == nullptr) { R_TRY_CATCH(m_parent->GetRomFileTable()->FindNextDirectory(name, find, NameBufferSize)) { R_CATCH(fs::ResultDbmFindFinished) { break; } } R_END_TRY_CATCH; if (out_entries) { R_UNLESS(strnlen(name, NameBufferSize) < NameBufferSize, fs::ResultTooLongPath()); strncpy(out_entries[i].name, name, fs::EntryNameLengthMax); out_entries[i].name[fs::EntryNameLengthMax] = '\x00'; out_entries[i].type = fs::DirectoryEntryType_Directory; out_entries[i].file_size = 0; } i++; } } if (m_mode & fs::OpenDirectoryMode_File) { while (i < max_entries || out_entries == nullptr) { auto file_pos = find->next_file; R_TRY_CATCH(m_parent->GetRomFileTable()->FindNextFile(name, find, NameBufferSize)) { R_CATCH(fs::ResultDbmFindFinished) { break; } } R_END_TRY_CATCH; if (out_entries) { R_UNLESS(strnlen(name, NameBufferSize) < NameBufferSize, fs::ResultTooLongPath()); strncpy(out_entries[i].name, name, fs::EntryNameLengthMax); out_entries[i].name[fs::EntryNameLengthMax] = '\x00'; out_entries[i].type = fs::DirectoryEntryType_File; RomFsFileSystem::RomFileTable::FileInfo file_info; R_TRY(m_parent->GetRomFileTable()->OpenFile(std::addressof(file_info), m_parent->GetRomFileTable()->PositionToFileId(file_pos))); out_entries[i].file_size = file_info.size.Get(); } i++; } } *out_count = i; R_SUCCEED(); } public: virtual sf::cmif::DomainObjectId GetDomainObjectId() const override { AMS_ABORT(); } }; } RomFsFileSystem::RomFsFileSystem() : m_base_storage() { /* ... */ } RomFsFileSystem::~RomFsFileSystem() { /* ... */ } fs::IStorage *RomFsFileSystem::GetBaseStorage() { return m_base_storage; } RomFsFileSystem::RomFileTable *RomFsFileSystem::GetRomFileTable() { return std::addressof(m_rom_file_table); } Result RomFsFileSystem::GetRequiredWorkingMemorySize(size_t *out, fs::IStorage *storage) { fs::RomFileSystemInformation header; R_TRY(buffers::DoContinuouslyUntilBufferIsAllocated([&]() -> Result { R_TRY(storage->Read(0, std::addressof(header), sizeof(header))); R_SUCCEED(); }, AMS_CURRENT_FUNCTION_NAME)); *out = CalculateRequiredWorkingMemorySize(header); R_SUCCEED(); } Result RomFsFileSystem::Initialize(fs::IStorage *base, void *work, size_t work_size, bool use_cache) { AMS_ABORT_UNLESS(!use_cache || work != nullptr); AMS_ABORT_UNLESS(base != nullptr); /* Register blocking context for the scope. */ buffers::ScopedBufferManagerContextRegistration _sr; buffers::EnableBlockingBufferManagerAllocation(); /* Read the header. */ fs::RomFileSystemInformation header; R_TRY(base->Read(0, std::addressof(header), sizeof(header))); /* Set up our storages. */ if (use_cache) { const size_t needed_size = CalculateRequiredWorkingMemorySize(header); R_UNLESS(work_size >= needed_size, fs::ResultAllocationMemoryFailedInRomFsFileSystemA()); u8 *buf = static_cast<u8 *>(work); auto dir_bucket_buf = buf; buf += header.directory_bucket_size; auto dir_entry_buf = buf; buf += header.directory_entry_size; auto file_bucket_buf = buf; buf += header.file_bucket_size; auto file_entry_buf = buf; buf += header.file_entry_size; R_TRY(base->Read(header.directory_bucket_offset, dir_bucket_buf, static_cast<size_t>(header.directory_bucket_size))); R_TRY(base->Read(header.directory_entry_offset, dir_entry_buf, static_cast<size_t>(header.directory_entry_size))); R_TRY(base->Read(header.file_bucket_offset, file_bucket_buf, static_cast<size_t>(header.file_bucket_size))); R_TRY(base->Read(header.file_entry_offset, file_entry_buf, static_cast<size_t>(header.file_entry_size))); m_dir_bucket_storage.reset(new fs::MemoryStorage(dir_bucket_buf, header.directory_bucket_size)); m_dir_entry_storage.reset(new fs::MemoryStorage(dir_entry_buf, header.directory_entry_size)); m_file_bucket_storage.reset(new fs::MemoryStorage(file_bucket_buf, header.file_bucket_size)); m_file_entry_storage.reset(new fs::MemoryStorage(file_entry_buf, header.file_entry_size)); } else { m_dir_bucket_storage.reset(new fs::SubStorage(base, header.directory_bucket_offset, header.directory_bucket_size)); m_dir_entry_storage.reset(new fs::SubStorage(base, header.directory_entry_offset, header.directory_entry_size)); m_file_bucket_storage.reset(new fs::SubStorage(base, header.file_bucket_offset, header.file_bucket_size)); m_file_entry_storage.reset(new fs::SubStorage(base, header.file_entry_offset, header.file_entry_size)); } /* Ensure we allocated storages successfully. */ R_UNLESS(m_dir_bucket_storage != nullptr, fs::ResultAllocationMemoryFailedInRomFsFileSystemB()); R_UNLESS(m_dir_entry_storage != nullptr, fs::ResultAllocationMemoryFailedInRomFsFileSystemB()); R_UNLESS(m_file_bucket_storage != nullptr, fs::ResultAllocationMemoryFailedInRomFsFileSystemB()); R_UNLESS(m_file_entry_storage != nullptr, fs::ResultAllocationMemoryFailedInRomFsFileSystemB()); /* Initialize the rom table. */ R_TRY(m_rom_file_table.Initialize(fs::SubStorage(m_dir_bucket_storage.get(), 0, static_cast<u32>(header.directory_bucket_size)), fs::SubStorage(m_dir_entry_storage.get(), 0, static_cast<u32>(header.directory_entry_size)), fs::SubStorage(m_file_bucket_storage.get(), 0, static_cast<u32>(header.file_bucket_size)), fs::SubStorage(m_file_entry_storage.get(), 0, static_cast<u32>(header.file_entry_size)))); /* Set members. */ m_entry_size = header.body_offset; m_base_storage = base; R_SUCCEED(); } Result RomFsFileSystem::Initialize(std::shared_ptr<fs::IStorage> base, void *work, size_t work_size, bool use_cache) { m_shared_storage = std::move(base); R_RETURN(this->Initialize(m_shared_storage.get(), work, work_size, use_cache)); } Result RomFsFileSystem::GetFileInfo(RomFileTable::FileInfo *out, const char *path) { R_TRY(buffers::DoContinuouslyUntilBufferIsAllocated([&]() -> Result { R_TRY_CATCH(m_rom_file_table.OpenFile(out, path)) { R_CONVERT(fs::ResultDbmNotFound, fs::ResultPathNotFound()); } R_END_TRY_CATCH; R_SUCCEED(); }, AMS_CURRENT_FUNCTION_NAME)); R_SUCCEED(); } Result RomFsFileSystem::GetFileBaseOffset(s64 *out, const fs::Path &path) { R_TRY(this->CheckPathFormat(path)); RomFileTable::FileInfo info; R_TRY(this->GetFileInfo(std::addressof(info), path)); *out = m_entry_size + info.offset.Get(); R_SUCCEED(); } Result RomFsFileSystem::DoCreateFile(const fs::Path &path, s64 size, int flags) { AMS_UNUSED(path, size, flags); R_THROW(fs::ResultUnsupportedWriteForRomFsFileSystem()); } Result RomFsFileSystem::DoDeleteFile(const fs::Path &path) { AMS_UNUSED(path); R_THROW(fs::ResultUnsupportedWriteForRomFsFileSystem()); } Result RomFsFileSystem::DoCreateDirectory(const fs::Path &path) { AMS_UNUSED(path); R_THROW(fs::ResultUnsupportedWriteForRomFsFileSystem()); } Result RomFsFileSystem::DoDeleteDirectory(const fs::Path &path) { AMS_UNUSED(path); R_THROW(fs::ResultUnsupportedWriteForRomFsFileSystem()); } Result RomFsFileSystem::DoDeleteDirectoryRecursively(const fs::Path &path) { AMS_UNUSED(path); R_THROW(fs::ResultUnsupportedWriteForRomFsFileSystem()); } Result RomFsFileSystem::DoRenameFile(const fs::Path &old_path, const fs::Path &new_path) { AMS_UNUSED(old_path, new_path); R_THROW(fs::ResultUnsupportedWriteForRomFsFileSystem()); } Result RomFsFileSystem::DoRenameDirectory(const fs::Path &old_path, const fs::Path &new_path) { AMS_UNUSED(old_path, new_path); R_THROW(fs::ResultUnsupportedWriteForRomFsFileSystem()); } Result RomFsFileSystem::DoGetEntryType(fs::DirectoryEntryType *out, const fs::Path &path) { R_TRY(this->CheckPathFormat(path)); R_TRY(buffers::DoContinuouslyUntilBufferIsAllocated([&]() -> Result { fs::HierarchicalRomFileTable::FindPosition find_pos; R_TRY_CATCH(m_rom_file_table.FindOpen(std::addressof(find_pos), path.GetString())) { R_CONVERT(fs::ResultDbmNotFound, fs::ResultPathNotFound()) R_CATCH(fs::ResultDbmInvalidOperation) { *out = fs::DirectoryEntryType_File; R_SUCCEED(); } } R_END_TRY_CATCH; *out = fs::DirectoryEntryType_Directory; R_SUCCEED(); }, AMS_CURRENT_FUNCTION_NAME)); R_SUCCEED(); } Result RomFsFileSystem::DoOpenFile(std::unique_ptr<fs::fsa::IFile> *out_file, const fs::Path &path, fs::OpenMode mode) { R_UNLESS(mode == fs::OpenMode_Read, fs::ResultInvalidOpenMode()); R_TRY(this->CheckPathFormat(path)); RomFileTable::FileInfo file_info; R_TRY(this->GetFileInfo(std::addressof(file_info), path)); auto file = std::make_unique<RomFsFile>(this, m_entry_size + file_info.offset.Get(), m_entry_size + file_info.offset.Get() + file_info.size.Get()); R_UNLESS(file != nullptr, fs::ResultAllocationMemoryFailedInRomFsFileSystemC()); *out_file = std::move(file); R_SUCCEED(); } Result RomFsFileSystem::DoOpenDirectory(std::unique_ptr<fs::fsa::IDirectory> *out_dir, const fs::Path &path, fs::OpenDirectoryMode mode) { R_TRY(this->CheckPathFormat(path)); RomFileTable::FindPosition find; R_TRY(buffers::DoContinuouslyUntilBufferIsAllocated([&]() -> Result { R_TRY_CATCH(m_rom_file_table.FindOpen(std::addressof(find), path.GetString())) { R_CONVERT(fs::ResultDbmNotFound, fs::ResultPathNotFound()) } R_END_TRY_CATCH; R_SUCCEED(); }, AMS_CURRENT_FUNCTION_NAME)); auto dir = std::make_unique<RomFsDirectory>(this, find, mode); R_UNLESS(dir != nullptr, fs::ResultAllocationMemoryFailedInRomFsFileSystemD()); *out_dir = std::move(dir); R_SUCCEED(); } Result RomFsFileSystem::DoCommit() { R_SUCCEED(); } Result RomFsFileSystem::DoGetFreeSpaceSize(s64 *out, const fs::Path &path) { AMS_UNUSED(path); *out = 0; R_SUCCEED(); } Result RomFsFileSystem::DoCleanDirectoryRecursively(const fs::Path &path) { AMS_UNUSED(path); R_THROW(fs::ResultUnsupportedWriteForRomFsFileSystem()); } Result RomFsFileSystem::DoCommitProvisionally(s64 counter) { AMS_UNUSED(counter); R_THROW(fs::ResultUnsupportedCommitProvisionallyForRomFsFileSystem()); } }
19,137
C++
.cpp
337
41.872404
173
0.57439
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,364
fssystem_aes_ctr_storage_external.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssystem/fssystem_aes_ctr_storage_external.cpp
/* * Copyright (c) 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 { AesCtrStorageExternal::AesCtrStorageExternal(std::shared_ptr<fs::IStorage> bs, const void *enc_key, size_t enc_key_size, const void *iv, size_t iv_size, DecryptAesCtrFunction df, s32 kidx, s32 kgen) : m_base_storage(std::move(bs)), m_decrypt_function(df), m_key_index(kidx), m_key_generation(kgen) { AMS_ASSERT(m_base_storage != nullptr); AMS_ASSERT(enc_key_size == KeySize); AMS_ASSERT(iv != nullptr); AMS_ASSERT(iv_size == IvSize); AMS_UNUSED(iv_size); std::memcpy(m_iv, iv, IvSize); std::memcpy(m_encrypted_key, enc_key, enc_key_size); } Result AesCtrStorageExternal::Read(s64 offset, void *buffer, size_t size) { /* Allow zero size. */ R_SUCCEED_IF(size == 0); /* Validate arguments. */ /* NOTE: For some reason, Nintendo uses InvalidArgument instead of InvalidOffset/InvalidSize here. */ R_UNLESS(buffer != nullptr, fs::ResultNullptrArgument()); R_UNLESS(util::IsAligned(offset, BlockSize), fs::ResultInvalidArgument()); R_UNLESS(util::IsAligned(size, BlockSize), fs::ResultInvalidArgument()); /* Read the data. */ R_TRY(m_base_storage->Read(offset, buffer, size)); /* Temporarily increase our thread priority. */ ScopedThreadPriorityChanger cp(+1, ScopedThreadPriorityChanger::Mode::Relative); /* Allocate a pooled buffer for decryption. */ PooledBuffer pooled_buffer; pooled_buffer.AllocateParticularlyLarge(size, BlockSize); AMS_ASSERT(pooled_buffer.GetSize() >= BlockSize); /* Setup the counter. */ u8 ctr[IvSize]; std::memcpy(ctr, m_iv, IvSize); AddCounter(ctr, IvSize, offset / BlockSize); /* Setup tracking. */ size_t remaining_size = size; s64 cur_offset = 0; while (remaining_size > 0) { /* Get the current size to process. */ size_t cur_size = std::min(pooled_buffer.GetSize(), remaining_size); char *dst = static_cast<char *>(buffer) + cur_offset; /* Decrypt into the temporary buffer */ m_decrypt_function(pooled_buffer.GetBuffer(), cur_size, m_key_index, m_key_generation, m_encrypted_key, KeySize, ctr, IvSize, dst, cur_size); /* Copy to the destination. */ std::memcpy(dst, pooled_buffer.GetBuffer(), cur_size); /* Update tracking. */ cur_offset += cur_size; remaining_size -= cur_size; if (remaining_size > 0) { AddCounter(ctr, IvSize, cur_size / BlockSize); } } R_SUCCEED(); } Result AesCtrStorageExternal::OperateRange(void *dst, size_t dst_size, fs::OperationId op_id, s64 offset, s64 size, const void *src, size_t src_size) { switch (op_id) { case fs::OperationId::QueryRange: { /* Validate that we have an output range info. */ R_UNLESS(dst != nullptr, fs::ResultNullptrArgument()); R_UNLESS(dst_size == sizeof(fs::QueryRangeInfo), fs::ResultInvalidSize()); /* Operate on our base storage. */ R_TRY(m_base_storage->OperateRange(dst, dst_size, op_id, offset, size, src, src_size)); /* Add in new flags. */ fs::QueryRangeInfo new_info; new_info.Clear(); new_info.aes_ctr_key_type = static_cast<s32>(m_key_index >= 0 ? fs::AesCtrKeyTypeFlag::InternalKeyForHardwareAes : fs::AesCtrKeyTypeFlag::ExternalKeyForHardwareAes); /* Merge the new info in. */ reinterpret_cast<fs::QueryRangeInfo *>(dst)->Merge(new_info); R_SUCCEED(); } default: { /* Operate on our base storage. */ R_RETURN(m_base_storage->OperateRange(dst, dst_size, op_id, offset, size, src, src_size)); } } } Result AesCtrStorageExternal::GetSize(s64 *out) { R_RETURN(m_base_storage->GetSize(out)); } Result AesCtrStorageExternal::Flush() { R_SUCCEED(); } Result AesCtrStorageExternal::Write(s64 offset, const void *buffer, size_t size) { AMS_UNUSED(offset, buffer, size); R_THROW(fs::ResultUnsupportedWriteForAesCtrStorageExternal()); } Result AesCtrStorageExternal::SetSize(s64 size) { AMS_UNUSED(size); R_THROW(fs::ResultUnsupportedSetSizeForAesCtrStorageExternal()); } }
5,324
C++
.cpp
105
40.72381
303
0.612245
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,365
fssystem_aes_ctr_storage.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssystem/fssystem_aes_ctr_storage.cpp
/* * Copyright (c) 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 { template<fs::PointerToStorage BasePointer> void AesCtrStorage<BasePointer>::MakeIv(void *dst, size_t dst_size, u64 upper, s64 offset) { AMS_ASSERT(dst != nullptr); AMS_ASSERT(dst_size == IvSize); AMS_ASSERT(offset >= 0); AMS_UNUSED(dst_size); const uintptr_t out_addr = reinterpret_cast<uintptr_t>(dst); util::StoreBigEndian(reinterpret_cast<u64 *>(out_addr + 0), upper); util::StoreBigEndian(reinterpret_cast<s64 *>(out_addr + sizeof(u64)), static_cast<s64>(offset / BlockSize)); } template<fs::PointerToStorage BasePointer> AesCtrStorage<BasePointer>::AesCtrStorage(BasePointer base, const void *key, size_t key_size, const void *iv, size_t iv_size) : m_base_storage(std::move(base)) { AMS_ASSERT(m_base_storage != nullptr); AMS_ASSERT(key != nullptr); AMS_ASSERT(iv != nullptr); AMS_ASSERT(key_size == KeySize); AMS_ASSERT(iv_size == IvSize); AMS_UNUSED(key_size, iv_size); std::memcpy(m_key, key, KeySize); std::memcpy(m_iv, iv, IvSize); } template<fs::PointerToStorage BasePointer> Result AesCtrStorage<BasePointer>::Read(s64 offset, void *buffer, size_t size) { /* Allow zero-size reads. */ R_SUCCEED_IF(size == 0); /* Ensure buffer is valid. */ R_UNLESS(buffer != nullptr, fs::ResultNullptrArgument()); /* We can only read at block aligned offsets. */ R_UNLESS(util::IsAligned(offset, BlockSize), fs::ResultInvalidArgument()); R_UNLESS(util::IsAligned(size, BlockSize), fs::ResultInvalidArgument()); /* Read the data. */ R_TRY(m_base_storage->Read(offset, buffer, size)); /* Prepare to decrypt the data, with temporarily increased priority. */ ScopedThreadPriorityChanger cp(+1, ScopedThreadPriorityChanger::Mode::Relative); /* Setup the counter. */ char ctr[IvSize]; std::memcpy(ctr, m_iv, IvSize); AddCounter(ctr, IvSize, offset / BlockSize); /* Decrypt, ensure we decrypt correctly. */ auto dec_size = crypto::DecryptAes128Ctr(buffer, size, m_key, KeySize, ctr, IvSize, buffer, size); R_UNLESS(size == dec_size, fs::ResultUnexpectedInAesCtrStorageA()); R_SUCCEED(); } template<fs::PointerToStorage BasePointer> Result AesCtrStorage<BasePointer>::Write(s64 offset, const void *buffer, size_t size) { /* Allow zero-size writes. */ R_SUCCEED_IF(size == 0); /* Ensure buffer is valid. */ R_UNLESS(buffer != nullptr, fs::ResultNullptrArgument()); /* We can only write at block aligned offsets. */ R_UNLESS(util::IsAligned(offset, BlockSize), fs::ResultInvalidArgument()); R_UNLESS(util::IsAligned(size, BlockSize), fs::ResultInvalidArgument()); /* Get a pooled buffer. */ PooledBuffer pooled_buffer; const bool use_work_buffer = !IsDeviceAddress(buffer); if (use_work_buffer) { pooled_buffer.Allocate(size, BlockSize); } /* Setup the counter. */ char ctr[IvSize]; std::memcpy(ctr, m_iv, IvSize); AddCounter(ctr, IvSize, offset / BlockSize); /* Loop until all data is written. */ size_t remaining = size; s64 cur_offset = 0; while (remaining > 0) { /* Determine data we're writing and where. */ const size_t write_size = use_work_buffer ? std::min(pooled_buffer.GetSize(), remaining) : remaining; void *write_buf = use_work_buffer ? pooled_buffer.GetBuffer() : const_cast<void *>(buffer); /* Encrypt the data, with temporarily increased priority. */ { ScopedThreadPriorityChanger cp(+1, ScopedThreadPriorityChanger::Mode::Relative); auto enc_size = crypto::EncryptAes128Ctr(write_buf, write_size, m_key, KeySize, ctr, IvSize, reinterpret_cast<const char *>(buffer) + cur_offset, write_size); R_UNLESS(enc_size == write_size, fs::ResultUnexpectedInAesCtrStorageA()); } /* Write the encrypted data. */ R_TRY(m_base_storage->Write(offset + cur_offset, write_buf, write_size)); /* Advance. */ cur_offset += write_size; remaining -= write_size; if (remaining > 0) { AddCounter(ctr, IvSize, write_size / BlockSize); } } R_SUCCEED(); } template<fs::PointerToStorage BasePointer> Result AesCtrStorage<BasePointer>::Flush() { R_RETURN(m_base_storage->Flush()); } template<fs::PointerToStorage BasePointer> Result AesCtrStorage<BasePointer>::SetSize(s64 size) { AMS_UNUSED(size); R_THROW(fs::ResultUnsupportedSetSizeForAesCtrStorage()); } template<fs::PointerToStorage BasePointer> Result AesCtrStorage<BasePointer>::GetSize(s64 *out) { R_RETURN(m_base_storage->GetSize(out)); } template<fs::PointerToStorage BasePointer> Result AesCtrStorage<BasePointer>::OperateRange(void *dst, size_t dst_size, fs::OperationId op_id, s64 offset, s64 size, const void *src, size_t src_size) { /* If operation isn't invalidate, special case. */ if (op_id != fs::OperationId::Invalidate) { /* Handle the zero-size case. */ if (size == 0) { if (op_id == fs::OperationId::QueryRange) { R_UNLESS(dst != nullptr, fs::ResultNullptrArgument()); R_UNLESS(dst_size == sizeof(fs::QueryRangeInfo), fs::ResultInvalidSize()); reinterpret_cast<fs::QueryRangeInfo *>(dst)->Clear(); } R_SUCCEED(); } /* Ensure alignment. */ R_UNLESS(util::IsAligned(offset, BlockSize), fs::ResultInvalidArgument()); R_UNLESS(util::IsAligned(size, BlockSize), fs::ResultInvalidArgument()); } switch (op_id) { case fs::OperationId::QueryRange: { R_UNLESS(dst != nullptr, fs::ResultNullptrArgument()); R_UNLESS(dst_size == sizeof(fs::QueryRangeInfo), fs::ResultInvalidSize()); R_TRY(m_base_storage->OperateRange(dst, dst_size, op_id, offset, size, src, src_size)); fs::QueryRangeInfo info; info.Clear(); info.aes_ctr_key_type = static_cast<s32>(fs::AesCtrKeyTypeFlag::InternalKeyForSoftwareAes); reinterpret_cast<fs::QueryRangeInfo *>(dst)->Merge(info); } break; default: { R_TRY(m_base_storage->OperateRange(dst, dst_size, op_id, offset, size, src, src_size)); } break; } R_SUCCEED(); } template class AesCtrStorage<fs::IStorage *>; template class AesCtrStorage<std::shared_ptr<fs::IStorage>>; }
7,769
C++
.cpp
156
39.974359
174
0.611962
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,366
fssystem_pooled_buffer.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssystem/fssystem_pooled_buffer.cpp
/* * Copyright (c) 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 { namespace { class AdditionalDeviceAddressEntry { private: os::SdkMutex m_mutex; bool m_is_registered; uintptr_t m_address; size_t m_size; public: constexpr AdditionalDeviceAddressEntry() : m_mutex(), m_is_registered(), m_address(), m_size() { /* ... */ } void Register(uintptr_t addr, size_t sz) { std::scoped_lock lk(m_mutex); AMS_ASSERT(!m_is_registered); if (!m_is_registered) { m_is_registered = true; m_address = addr; m_size = sz; } } void Unregister(uintptr_t addr) { std::scoped_lock lk(m_mutex); if (m_is_registered && m_address == addr) { m_is_registered = false; m_address = 0; m_size = 0; } } bool Includes(const void *ptr) { std::scoped_lock lk(m_mutex); if (m_is_registered) { const uintptr_t addr = reinterpret_cast<uintptr_t>(ptr); return m_address <= addr && addr < m_address + m_size; } else { return false; } } }; constexpr auto RetryWait = TimeSpan::FromMilliSeconds(10); constexpr size_t HeapBlockSize = BufferPoolAlignment; static_assert(HeapBlockSize == 4_KB); /* A heap block is 4KB. An order is a power of two. */ /* This gives blocks of the order 32KB, 512KB, 4MB. */ constexpr s32 HeapOrderTrim = 3; constexpr s32 HeapOrderMax = 7; constexpr s32 HeapOrderMaxForLarge = HeapOrderMax + 3; constexpr size_t HeapAllocatableSizeTrim = HeapBlockSize * (static_cast<size_t>(1) << HeapOrderTrim); constexpr size_t HeapAllocatableSizeMax = HeapBlockSize * (static_cast<size_t>(1) << HeapOrderMax); constexpr size_t HeapAllocatableSizeMaxForLarge = HeapBlockSize * (static_cast<size_t>(1) << HeapOrderMaxForLarge); constinit os::SdkMutex g_heap_mutex; constinit FileSystemBuddyHeap g_heap; constinit std::atomic<size_t> g_retry_count; constinit std::atomic<size_t> g_reduce_allocation_count; constinit void *g_heap_buffer; constinit size_t g_heap_size; constinit size_t g_heap_free_size_peak; constinit AdditionalDeviceAddressEntry g_additional_device_address_entry; } size_t PooledBuffer::GetAllocatableSizeMaxCore(bool large) { return large ? HeapAllocatableSizeMaxForLarge : HeapAllocatableSizeMax; } void PooledBuffer::AllocateCore(size_t ideal_size, size_t required_size, bool large) { /* Ensure preconditions. */ AMS_ASSERT(g_heap_buffer != nullptr); AMS_ASSERT(m_buffer == nullptr); AMS_ASSERT(g_heap.GetBlockSize() == HeapBlockSize); /* Check that we can allocate this size. */ AMS_ASSERT(required_size <= GetAllocatableSizeMaxCore(large)); const size_t target_size = std::min(std::max(ideal_size, required_size), GetAllocatableSizeMaxCore(large)); /* Loop until we allocate. */ while (true) { /* Lock the heap and try to allocate. */ { std::scoped_lock lk(g_heap_mutex); /* Determine how much we can allocate, and don't allocate more than half the heap. */ size_t allocatable_size = g_heap.GetAllocatableSizeMax(); if (allocatable_size > HeapBlockSize) { allocatable_size >>= 1; } /* Check if this allocation is acceptable. */ if (allocatable_size >= required_size) { /* Get the order. */ const auto order = g_heap.GetOrderFromBytes(std::min(target_size, allocatable_size)); /* Allocate and get the size. */ m_buffer = reinterpret_cast<char *>(g_heap.AllocateByOrder(order)); m_size = g_heap.GetBytesFromOrder(order); } } /* Check if we allocated. */ if (m_buffer != nullptr) { /* If we need to trim the end, do so. */ if (this->GetSize() >= target_size + HeapAllocatableSizeTrim) { this->Shrink(util::AlignUp(target_size, HeapAllocatableSizeTrim)); } AMS_ASSERT(this->GetSize() >= required_size); /* If we reduced, note so. */ if (this->GetSize() < std::min(target_size, HeapAllocatableSizeMax)) { g_reduce_allocation_count++; } break; } else { /* Sleep. */ os::SleepThread(RetryWait); g_retry_count++; } } /* Update metrics. */ { std::scoped_lock lk(g_heap_mutex); const size_t free_size = g_heap.GetTotalFreeSize(); if (free_size < g_heap_free_size_peak) { g_heap_free_size_peak = free_size; } } } void PooledBuffer::Shrink(size_t ideal_size) { AMS_ASSERT(ideal_size <= GetAllocatableSizeMaxCore(true)); /* Check if we actually need to shrink. */ if (m_size > ideal_size) { /* If we do, we need to have a buffer allocated from the heap. */ AMS_ASSERT(m_buffer != nullptr); AMS_ASSERT(g_heap.GetBlockSize() == HeapBlockSize); const size_t new_size = util::AlignUp(ideal_size, HeapBlockSize); /* Repeatedly free the tail of our buffer until we're done. */ { std::scoped_lock lk(g_heap_mutex); while (new_size < m_size) { /* Determine the size and order to free. */ const size_t tail_align = util::LeastSignificantOneBit(m_size); const size_t free_size = std::min(util::FloorPowerOfTwo(m_size - new_size), tail_align); const s32 free_order = g_heap.GetOrderFromBytes(free_size); /* Ensure we determined size correctly. */ AMS_ASSERT(util::IsAligned(free_size, HeapBlockSize)); AMS_ASSERT(free_size == g_heap.GetBytesFromOrder(free_order)); /* Actually free the memory. */ g_heap.Free(m_buffer + m_size - free_size, free_order); m_size -= free_size; } } /* Shrinking to zero means that we have no buffer. */ if (m_size == 0) { m_buffer = nullptr; } } } Result InitializeBufferPool(char *buffer, size_t size) { AMS_ASSERT(g_heap_buffer == nullptr); AMS_ASSERT(buffer != nullptr); AMS_ASSERT(util::IsAligned(reinterpret_cast<uintptr_t>(buffer), BufferPoolAlignment)); /* Initialize the heap. */ R_TRY(g_heap.Initialize(reinterpret_cast<uintptr_t>(buffer), size, HeapBlockSize, HeapOrderMaxForLarge + 1)); /* Initialize metrics. */ g_heap_buffer = buffer; g_heap_size = size; g_heap_free_size_peak = size; R_SUCCEED(); } Result InitializeBufferPool(char *buffer, size_t size, char *work, size_t work_size) { AMS_ASSERT(g_heap_buffer == nullptr); AMS_ASSERT(buffer != nullptr); AMS_ASSERT(util::IsAligned(reinterpret_cast<uintptr_t>(buffer), BufferPoolAlignment)); AMS_ASSERT(work_size >= BufferPoolWorkSize); /* Initialize the heap. */ R_TRY(g_heap.Initialize(reinterpret_cast<uintptr_t>(buffer), size, HeapBlockSize, HeapOrderMaxForLarge + 1, work, work_size)); /* Initialize metrics. */ g_heap_buffer = buffer; g_heap_size = size; g_heap_free_size_peak = size; R_SUCCEED(); } bool IsPooledBuffer(const void *buffer) { AMS_ASSERT(buffer != nullptr); return g_heap_buffer <= buffer && buffer < reinterpret_cast<char *>(g_heap_buffer) + g_heap_size; } size_t GetPooledBufferRetriedCount() { return g_retry_count; } size_t GetPooledBufferReduceAllocationCount() { return g_reduce_allocation_count; } size_t GetPooledBufferFreeSizePeak() { return g_heap_free_size_peak; } void ClearPooledBufferPeak() { std::scoped_lock lk(g_heap_mutex); g_heap_free_size_peak = g_heap.GetTotalFreeSize(); g_retry_count = 0; g_reduce_allocation_count = 0; } void RegisterAdditionalDeviceAddress(uintptr_t address, size_t size) { g_additional_device_address_entry.Register(address, size); } void UnregisterAdditionalDeviceAddress(uintptr_t address) { g_additional_device_address_entry.Unregister(address); } bool IsAdditionalDeviceAddress(const void *ptr) { return g_additional_device_address_entry.Includes(ptr); } }
10,110
C++
.cpp
214
35.079439
134
0.566406
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,367
fssystem_aes_xts_storage_external.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssystem/fssystem_aes_xts_storage_external.cpp
/* * Copyright (c) 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 { template<fs::PointerToStorage BasePointer> AesXtsStorageExternal<BasePointer>::AesXtsStorageExternal(BasePointer bs, const void *key1, const void *key2, size_t key_size, const void *iv, size_t iv_size, size_t block_size, CryptAesXtsFunction ef, CryptAesXtsFunction df) : m_base_storage(std::move(bs)), m_block_size(block_size), m_encrypt_function(ef), m_decrypt_function(df) { AMS_ASSERT(key_size == KeySize); AMS_ASSERT(iv_size == IvSize); AMS_UNUSED(key_size, iv_size); if (key1 != nullptr) { std::memcpy(m_key[0], key1, KeySize); } if (key2 != nullptr) { std::memcpy(m_key[1], key2, KeySize); } std::memcpy(m_iv, iv, IvSize); } template<fs::PointerToStorage BasePointer> Result AesXtsStorageExternal<BasePointer>::Read(s64 offset, void *buffer, size_t size) { /* Allow zero size. */ R_SUCCEED_IF(size == 0); /* Ensure buffer is valid. */ R_UNLESS(buffer != nullptr, fs::ResultNullptrArgument()); /* Ensure we can decrypt. */ R_UNLESS(m_decrypt_function != nullptr, fs::ResultNullptrArgument()); /* We can only read at block aligned offsets. */ R_UNLESS(util::IsAligned(offset, AesBlockSize), fs::ResultInvalidArgument()); R_UNLESS(util::IsAligned(size, AesBlockSize), fs::ResultInvalidArgument()); /* Read the data. */ R_TRY(m_base_storage->Read(offset, buffer, size)); /* Temporarily increase our thread priority. */ ScopedThreadPriorityChanger cp(+1, ScopedThreadPriorityChanger::Mode::Relative); /* Setup the counter. */ char ctr[IvSize]; std::memcpy(ctr, m_iv, IvSize); AddCounter(ctr, IvSize, offset / m_block_size); /* Handle any unaligned data before the start. */ size_t processed_size = 0; if ((offset % m_block_size) != 0) { /* Determine the size of the pre-data read. */ const size_t skip_size = static_cast<size_t>(offset - util::AlignDown(offset, m_block_size)); const size_t data_size = std::min(size, m_block_size - skip_size); /* Decrypt into a pooled buffer. */ { PooledBuffer tmp_buf(m_block_size, m_block_size); AMS_ASSERT(tmp_buf.GetSize() >= m_block_size); std::memset(tmp_buf.GetBuffer(), 0, skip_size); std::memcpy(tmp_buf.GetBuffer() + skip_size, buffer, data_size); /* Decrypt. */ R_TRY(m_decrypt_function(tmp_buf.GetBuffer(), m_block_size, m_key[0], m_key[1], KeySize, ctr, IvSize, tmp_buf.GetBuffer(), m_block_size)); std::memcpy(buffer, tmp_buf.GetBuffer() + skip_size, data_size); } AddCounter(ctr, IvSize, 1); processed_size += data_size; AMS_ASSERT(processed_size == std::min(size, m_block_size - skip_size)); } /* Decrypt aligned chunks. */ char *cur = static_cast<char *>(buffer) + processed_size; size_t remaining = size - processed_size; while (remaining > 0) { const size_t cur_size = std::min(m_block_size, remaining); R_TRY(m_decrypt_function(cur, cur_size, m_key[0], m_key[1], KeySize, ctr, IvSize, cur, cur_size)); remaining -= cur_size; cur += cur_size; AddCounter(ctr, IvSize, 1); } R_SUCCEED(); } template<fs::PointerToStorage BasePointer> Result AesXtsStorageExternal<BasePointer>::Write(s64 offset, const void *buffer, size_t size) { /* Allow zero-size writes. */ R_SUCCEED_IF(size == 0); /* Ensure buffer is valid. */ R_UNLESS(buffer != nullptr, fs::ResultNullptrArgument()); /* Ensure we can encrypt. */ R_UNLESS(m_encrypt_function != nullptr, fs::ResultNullptrArgument()); /* We can only write at block aligned offsets. */ R_UNLESS(util::IsAligned(offset, AesBlockSize), fs::ResultInvalidArgument()); R_UNLESS(util::IsAligned(size, AesBlockSize), fs::ResultInvalidArgument()); /* Get a pooled buffer. */ PooledBuffer pooled_buffer; const bool use_work_buffer = !IsDeviceAddress(buffer); if (use_work_buffer) { pooled_buffer.Allocate(size, m_block_size); } /* Setup the counter. */ char ctr[IvSize]; std::memcpy(ctr, m_iv, IvSize); AddCounter(ctr, IvSize, offset / m_block_size); /* Handle any unaligned data before the start. */ size_t processed_size = 0; if ((offset % m_block_size) != 0) { /* Determine the size of the pre-data read. */ const size_t skip_size = static_cast<size_t>(offset - util::AlignDown(offset, m_block_size)); const size_t data_size = std::min(size, m_block_size - skip_size); /* Encrypt into a pooled buffer. */ { /* NOTE: Nintendo allocates a second pooled buffer here despite having one already allocated above. */ PooledBuffer tmp_buf(m_block_size, m_block_size); AMS_ASSERT(tmp_buf.GetSize() >= m_block_size); std::memset(tmp_buf.GetBuffer(), 0, skip_size); std::memcpy(tmp_buf.GetBuffer() + skip_size, buffer, data_size); R_TRY(m_encrypt_function(tmp_buf.GetBuffer(), m_block_size, m_key[0], m_key[1], KeySize, ctr, IvSize, tmp_buf.GetBuffer(), m_block_size)); R_TRY(m_base_storage->Write(offset, tmp_buf.GetBuffer() + skip_size, data_size)); } AddCounter(ctr, IvSize, 1); processed_size += data_size; AMS_ASSERT(processed_size == std::min(size, m_block_size - skip_size)); } /* Encrypt aligned chunks. */ size_t remaining = size - processed_size; s64 cur_offset = offset + processed_size; while (remaining > 0) { /* Determine data we're writing and where. */ const size_t write_size = use_work_buffer ? std::min(pooled_buffer.GetSize(), remaining) : remaining; /* Encrypt the data, with temporarily increased priority. */ { ScopedThreadPriorityChanger cp(+1, ScopedThreadPriorityChanger::Mode::Relative); size_t remaining_write = write_size; size_t encrypt_offset = 0; while (remaining_write > 0) { const size_t cur_size = std::min(remaining_write, m_block_size); const void *src = static_cast<const char *>(buffer) + processed_size + encrypt_offset; void *dst = use_work_buffer ? pooled_buffer.GetBuffer() + encrypt_offset : const_cast<void *>(src); R_TRY(m_encrypt_function(dst, cur_size, m_key[0], m_key[1], KeySize, ctr, IvSize, src, cur_size)); AddCounter(ctr, IvSize, 1); encrypt_offset += cur_size; remaining_write -= cur_size; } } /* Write the encrypted data. */ const void *write_buf = use_work_buffer ? pooled_buffer.GetBuffer() : static_cast<const char *>(buffer) + processed_size; R_TRY(m_base_storage->Write(cur_offset, write_buf, write_size)); /* Advance. */ cur_offset += write_size; processed_size += write_size; remaining -= write_size; } R_SUCCEED(); } template<fs::PointerToStorage BasePointer> Result AesXtsStorageExternal<BasePointer>::OperateRange(void *dst, size_t dst_size, fs::OperationId op_id, s64 offset, s64 size, const void *src, size_t src_size) { /* Unless invalidating cache, check the arguments. */ if (op_id != fs::OperationId::Invalidate) { /* Handle the zero size case. */ R_SUCCEED_IF(size == 0); /* Ensure alignment. */ R_UNLESS(util::IsAligned(offset, AesBlockSize), fs::ResultInvalidArgument()); R_UNLESS(util::IsAligned(size, AesBlockSize), fs::ResultInvalidArgument()); } R_RETURN(m_base_storage->OperateRange(dst, dst_size, op_id, offset, size, src, src_size)); } template<fs::PointerToStorage BasePointer> Result AesXtsStorageExternal<BasePointer>::GetSize(s64 *out) { R_RETURN(m_base_storage->GetSize(out)); } template<fs::PointerToStorage BasePointer> Result AesXtsStorageExternal<BasePointer>::Flush() { R_RETURN(m_base_storage->Flush()); } template<fs::PointerToStorage BasePointer> Result AesXtsStorageExternal<BasePointer>::SetSize(s64 size) { R_UNLESS(util::IsAligned(size, AesBlockSize), fs::ResultUnexpectedInAesXtsStorageA()); R_RETURN(m_base_storage->SetSize(size)); } template class AesXtsStorageExternal<fs::IStorage *>; template class AesXtsStorageExternal<std::shared_ptr<fs::IStorage>>; }
9,717
C++
.cpp
181
43.370166
337
0.611345
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,368
fssystem_hierarchical_sha256_storage.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssystem/fssystem_hierarchical_sha256_storage.cpp
/* * Copyright (c) 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 "fssystem_hierarchical_sha256_storage.hpp" namespace ams::fssystem { namespace { s32 Log2(s32 value) { AMS_ASSERT(value > 0); AMS_ASSERT(util::IsPowerOfTwo(value)); s32 log = 0; while ((value >>= 1) > 0) { ++log; } return log; } } template<typename BaseStorageType> Result HierarchicalSha256Storage<BaseStorageType>::Initialize(BaseStorageType *base_storages, s32 layer_count, size_t htbs, void *hash_buf, size_t hash_buf_size, fssystem::IHash256GeneratorFactory *hgf) { /* Validate preconditions. */ AMS_ASSERT(layer_count == LayerCount); AMS_ASSERT(util::IsPowerOfTwo(htbs)); AMS_ASSERT(hash_buf != nullptr); AMS_ASSERT(hgf != nullptr); AMS_UNUSED(layer_count); /* Set size tracking members. */ m_hash_target_block_size = htbs; m_log_size_ratio = Log2(m_hash_target_block_size / HashSize); m_hash_generator_factory = hgf; /* Get the base storage size. */ R_TRY(base_storages[2]->GetSize(std::addressof(m_base_storage_size))); { auto size_guard = SCOPE_GUARD { m_base_storage_size = 0; }; R_UNLESS(m_base_storage_size <= static_cast<s64>(HashSize) << m_log_size_ratio << m_log_size_ratio, fs::ResultHierarchicalSha256BaseStorageTooLarge()); size_guard.Cancel(); } /* Set hash buffer tracking members. */ m_base_storage = base_storages[2]; m_hash_buffer = static_cast<char *>(hash_buf); m_hash_buffer_size = hash_buf_size; /* Read the master hash. */ u8 master_hash[HashSize]; R_TRY(base_storages[0]->Read(0, master_hash, HashSize)); /* Read and validate the data being hashed. */ s64 hash_storage_size; R_TRY(base_storages[1]->GetSize(std::addressof(hash_storage_size))); AMS_ASSERT(util::IsAligned(hash_storage_size, HashSize)); AMS_ASSERT(hash_storage_size <= m_hash_target_block_size); AMS_ASSERT(hash_storage_size <= static_cast<s64>(m_hash_buffer_size)); R_TRY(base_storages[1]->Read(0, m_hash_buffer, static_cast<size_t>(hash_storage_size))); /* Calculate and verify the master hash. */ u8 calc_hash[HashSize]; m_hash_generator_factory->GenerateHash(calc_hash, sizeof(calc_hash), m_hash_buffer, static_cast<size_t>(hash_storage_size)); R_UNLESS(crypto::IsSameBytes(master_hash, calc_hash, HashSize), fs::ResultHierarchicalSha256HashVerificationFailed()); R_SUCCEED(); } template<typename BaseStorageType> Result HierarchicalSha256Storage<BaseStorageType>::Read(s64 offset, void *buffer, size_t size) { /* Succeed if zero-size. */ R_SUCCEED_IF(size == 0); /* Validate that we have a buffer to read into. */ R_UNLESS(buffer != nullptr, fs::ResultNullptrArgument()); /* Validate preconditions. */ R_UNLESS(util::IsAligned(offset, m_hash_target_block_size), fs::ResultInvalidArgument()); R_UNLESS(util::IsAligned(size, m_hash_target_block_size), fs::ResultInvalidArgument()); /* Read the data. */ const size_t reduced_size = static_cast<size_t>(std::min<s64>(m_base_storage_size, util::AlignUp(offset + size, m_hash_target_block_size)) - offset); R_TRY(m_base_storage->Read(offset, buffer, reduced_size)); /* Temporarily increase our thread priority. */ ScopedThreadPriorityChanger cp(+1, ScopedThreadPriorityChanger::Mode::Relative); /* Setup tracking variables. */ auto cur_offset = offset; auto remaining_size = reduced_size; while (remaining_size > 0) { /* Generate the hash of the region we're validating. */ u8 hash[HashSize]; const auto cur_size = static_cast<size_t>(std::min<s64>(m_hash_target_block_size, remaining_size)); m_hash_generator_factory->GenerateHash(hash, sizeof(hash), static_cast<u8 *>(buffer) + (cur_offset - offset), cur_size); AMS_ASSERT(static_cast<size_t>(cur_offset >> m_log_size_ratio) < m_hash_buffer_size); /* Check the hash. */ { std::scoped_lock lk(m_mutex); auto clear_guard = SCOPE_GUARD { std::memset(buffer, 0, size); }; R_UNLESS(crypto::IsSameBytes(hash, std::addressof(m_hash_buffer[cur_offset >> m_log_size_ratio]), HashSize), fs::ResultHierarchicalSha256HashVerificationFailed()); clear_guard.Cancel(); } /* Advance. */ cur_offset += cur_size; remaining_size -= cur_size; } R_SUCCEED(); } template<typename BaseStorageType> Result HierarchicalSha256Storage<BaseStorageType>::Write(s64 offset, const void *buffer, size_t size) { /* Succeed if zero-size. */ R_SUCCEED_IF(size == 0); /* Validate that we have a buffer to read into. */ R_UNLESS(buffer != nullptr, fs::ResultNullptrArgument()); /* Validate preconditions. */ R_UNLESS(util::IsAligned(offset, m_hash_target_block_size), fs::ResultInvalidArgument()); R_UNLESS(util::IsAligned(size, m_hash_target_block_size), fs::ResultInvalidArgument()); /* Setup tracking variables. */ const size_t reduced_size = static_cast<size_t>(std::min<s64>(m_base_storage_size, util::AlignUp(offset + size, m_hash_target_block_size)) - offset); auto cur_offset = offset; auto remaining_size = reduced_size; while (remaining_size > 0) { /* Generate the hash of the region we're validating. */ u8 hash[HashSize]; const auto cur_size = static_cast<size_t>(std::min<s64>(m_hash_target_block_size, remaining_size)); { /* Temporarily increase our thread priority. */ ScopedThreadPriorityChanger cp(+1, ScopedThreadPriorityChanger::Mode::Relative); m_hash_generator_factory->GenerateHash(hash, sizeof(hash), static_cast<const u8 *>(buffer) + (cur_offset - offset), cur_size); } /* Write the data. */ R_TRY(m_base_storage->Write(cur_offset, static_cast<const u8 *>(buffer) + (cur_offset - offset), cur_size)); /* Write the hash. */ { std::scoped_lock lk(m_mutex); std::memcpy(std::addressof(m_hash_buffer[cur_offset >> m_log_size_ratio]), hash, HashSize); } /* Advance. */ cur_offset += cur_size; remaining_size -= cur_size; } R_SUCCEED(); } template<typename BaseStorageType> Result HierarchicalSha256Storage<BaseStorageType>::OperateRange(void *dst, size_t dst_size, fs::OperationId op_id, s64 offset, s64 size, const void *src, size_t src_size) { if (op_id == fs::OperationId::Invalidate) { R_RETURN(m_base_storage->OperateRange(fs::OperationId::Invalidate, offset, size)); } else { /* Succeed if zero-size. */ R_SUCCEED_IF(size == 0); /* Validate preconditions. */ R_UNLESS(util::IsAligned(offset, m_hash_target_block_size), fs::ResultInvalidArgument()); R_UNLESS(util::IsAligned(size, m_hash_target_block_size), fs::ResultInvalidArgument()); /* Determine size to use. */ const auto reduced_size = std::min<s64>(m_base_storage_size, util::AlignUp(offset + size, m_hash_target_block_size)) - offset; /* Operate on the base storage. */ R_RETURN(m_base_storage->OperateRange(dst, dst_size, op_id, offset, reduced_size, src, src_size)); } } template class HierarchicalSha256Storage<fs::SubStorage>; }
8,521
C++
.cpp
157
44.675159
208
0.626982
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,369
fssystem_compression_configuration.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssystem/fssystem_compression_configuration.cpp
/* * Copyright (c) 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 "fssystem_key_slot_cache.hpp" namespace ams::fssystem { namespace { Result DecompressLz4(void *dst, size_t dst_size, const void *src, size_t src_size) { R_UNLESS(util::DecompressLZ4(dst, dst_size, src, src_size) == static_cast<int>(dst_size), fs::ResultUnexpectedInCompressedStorageC()); R_SUCCEED(); } constexpr DecompressorFunction GetNcaDecompressorFunction(CompressionType type) { switch (type) { case CompressionType_Lz4: return DecompressLz4; default: return nullptr; } } constexpr NcaCompressionConfiguration g_nca_compression_configuration { .get_decompressor = GetNcaDecompressorFunction, }; } const ::ams::fssystem::NcaCompressionConfiguration *GetNcaCompressionConfiguration() { return std::addressof(g_nca_compression_configuration); } }
1,634
C++
.cpp
39
35.102564
146
0.687461
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,370
fssystem_hierarchical_integrity_verification_storage.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssystem/fssystem_hierarchical_integrity_verification_storage.cpp
/* * Copyright (c) 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 { namespace { constexpr inline u32 IntegrityVerificationStorageMagic = util::FourCC<'I','V','F','C'>::Code; constexpr inline u32 IntegrityVerificationStorageVersion = 0x00020000; constexpr inline u32 IntegrityVerificationStorageVersionMask = 0xFFFF0000; constexpr inline auto AccessCountMax = 5; constexpr inline auto AccessTimeout = TimeSpan::FromMilliSeconds(10); os::Semaphore g_read_semaphore(AccessCountMax, AccessCountMax); os::Semaphore g_write_semaphore(AccessCountMax, AccessCountMax); constexpr inline const char MasterKey[] = "HierarchicalIntegrityVerificationStorage::Master"; constexpr inline const char L1Key[] = "HierarchicalIntegrityVerificationStorage::L1"; constexpr inline const char L2Key[] = "HierarchicalIntegrityVerificationStorage::L2"; constexpr inline const char L3Key[] = "HierarchicalIntegrityVerificationStorage::L3"; constexpr inline const char L4Key[] = "HierarchicalIntegrityVerificationStorage::L4"; constexpr inline const char L5Key[] = "HierarchicalIntegrityVerificationStorage::L5"; constexpr inline const struct { const char *key; size_t size; } KeyArray[] = { { MasterKey, sizeof(MasterKey) }, { L1Key, sizeof(L1Key) }, { L2Key, sizeof(L2Key) }, { L3Key, sizeof(L3Key) }, { L4Key, sizeof(L4Key) }, { L5Key, sizeof(L5Key) }, }; } /* Instantiate the global random generation function. */ constinit HierarchicalIntegrityVerificationStorage::GenerateRandomFunction HierarchicalIntegrityVerificationStorage::s_generate_random = nullptr; Result HierarchicalIntegrityVerificationStorageControlArea::QuerySize(HierarchicalIntegrityVerificationSizeSet *out, const InputParam &input_param, s32 layer_count, s64 data_size) { /* Validate preconditions. */ AMS_ASSERT(out != nullptr); AMS_ASSERT((static_cast<s32>(IntegrityMinLayerCount) <= layer_count) && (layer_count <= static_cast<s32>(IntegrityMaxLayerCount))); for (s32 level = 0; level < (layer_count - 1); ++level) { AMS_ASSERT(input_param.level_block_size[level] > 0); AMS_ASSERT(IsPowerOfTwo(static_cast<s32>(input_param.level_block_size[level]))); } /* Set the control size. */ out->control_size = sizeof(HierarchicalIntegrityVerificationMetaInformation); /* Determine the level sizes. */ s64 level_size[IntegrityMaxLayerCount]; s32 level = layer_count - 1; level_size[level] = util::AlignUp(data_size, input_param.level_block_size[level - 1]); --level; for (/* ... */; level > 0; --level) { level_size[level] = util::AlignUp(level_size[level + 1] / input_param.level_block_size[level] * HashSize, input_param.level_block_size[level - 1]); } /* Determine the master size. */ level_size[0] = level_size[1] / input_param.level_block_size[0] * HashSize; /* Set the master size. */ out->master_hash_size = level_size[0]; /* Set the level sizes. */ for (level = 1; level < layer_count - 1; ++level) { out->layered_hash_sizes[level - 1] = level_size[level]; } R_SUCCEED(); } Result HierarchicalIntegrityVerificationStorageControlArea::Expand(fs::SubStorage meta_storage, const HierarchicalIntegrityVerificationMetaInformation &meta) { /* Check the meta size. */ { s64 meta_size = 0; R_TRY(meta_storage.GetSize(std::addressof(meta_size))); R_UNLESS(meta_size >= static_cast<s64>(sizeof(meta)), fs::ResultInvalidSize()); } /* Validate both the previous and new metas. */ { /* Read the previous meta. */ HierarchicalIntegrityVerificationMetaInformation prev_meta = {}; R_TRY(meta_storage.Read(0, std::addressof(prev_meta), sizeof(prev_meta))); /* Validate both magics. */ R_UNLESS(prev_meta.magic == IntegrityVerificationStorageMagic, fs::ResultIncorrectIntegrityVerificationMagic()); R_UNLESS(prev_meta.magic == meta.magic, fs::ResultIncorrectIntegrityVerificationMagic()); /* Validate both versions. */ R_UNLESS(prev_meta.version == IntegrityVerificationStorageVersion, fs::ResultUnsupportedVersion()); R_UNLESS(prev_meta.version == meta.version, fs::ResultUnsupportedVersion()); } /* Write the new meta. */ R_TRY(meta_storage.Write(0, std::addressof(meta), sizeof(meta))); R_TRY(meta_storage.Flush()); R_SUCCEED(); } Result HierarchicalIntegrityVerificationStorageControlArea::Initialize(fs::SubStorage meta_storage) { /* Check the meta size. */ { s64 meta_size = 0; R_TRY(meta_storage.GetSize(std::addressof(meta_size))); R_UNLESS(meta_size >= static_cast<s64>(sizeof(m_meta)), fs::ResultInvalidSize()); } /* Set the storage and read the meta. */ m_storage = meta_storage; R_TRY(m_storage.Read(0, std::addressof(m_meta), sizeof(m_meta))); /* Validate the meta magic. */ R_UNLESS(m_meta.magic == IntegrityVerificationStorageMagic, fs::ResultIncorrectIntegrityVerificationMagic()); /* Validate the meta version. */ R_UNLESS((m_meta.version & IntegrityVerificationStorageVersionMask) == (IntegrityVerificationStorageVersion & IntegrityVerificationStorageVersionMask), fs::ResultUnsupportedVersion()); R_SUCCEED(); } void HierarchicalIntegrityVerificationStorageControlArea::Finalize() { m_storage = fs::SubStorage(); } Result HierarchicalIntegrityVerificationStorage::Initialize(const HierarchicalIntegrityVerificationInformation &info, HierarchicalStorageInformation storage, FileSystemBufferManagerSet *bufs, IHash256GeneratorFactory *hgf, bool hash_salt_enabled, os::SdkRecursiveMutex *mtx, os::Semaphore *read_sema, os::Semaphore *write_sema, int max_data_cache_entries, int max_hash_cache_entries, s8 buffer_level, bool is_writable, bool allow_cleared_blocks) { /* Validate preconditions. */ AMS_ASSERT(bufs != nullptr); AMS_ASSERT(IntegrityMinLayerCount <= info.max_layers && info.max_layers <= IntegrityMaxLayerCount); /* Set member variables. */ m_max_layers = info.max_layers; m_buffers = bufs; m_mutex = mtx; m_read_semaphore = read_sema; m_write_semaphore = write_sema; /* If hash salt is enabled, generate it. */ util::optional<fs::HashSalt> hash_salt = util::nullopt; if (hash_salt_enabled) { hash_salt.emplace(); crypto::GenerateHmacSha256(hash_salt->value, sizeof(hash_salt->value), info.seed.value, sizeof(info.seed), KeyArray[0].key, KeyArray[0].size); } /* Initialize the top level verification storage. */ m_verify_storages[0].Initialize(storage[HierarchicalStorageInformation::MasterStorage], storage[HierarchicalStorageInformation::Layer1Storage], static_cast<s64>(1) << info.info[0].block_order, HashSize, m_buffers->buffers[m_max_layers - 2], hgf, hash_salt, false, is_writable, allow_cleared_blocks); /* Ensure we don't leak state if further initialization goes wrong. */ ON_RESULT_FAILURE { m_verify_storages[0].Finalize(); m_data_size = -1; m_buffers = nullptr; m_mutex = nullptr; }; /* Initialize the top level buffer storage. */ R_TRY(m_buffer_storages[0].Initialize(m_buffers->buffers[0], m_mutex, std::addressof(m_verify_storages[0]), info.info[0].size, static_cast<s64>(1) << info.info[0].block_order, max_hash_cache_entries, false, 0x10, false, is_writable)); ON_RESULT_FAILURE_2 { m_buffer_storages[0].Finalize(); }; /* Prepare to initialize the level storages. */ s32 level = 0; /* Ensure we don't leak state if further initialization goes wrong. */ ON_RESULT_FAILURE_2 { m_verify_storages[level + 1].Finalize(); for (/* ... */; level > 0; --level) { m_buffer_storages[level].Finalize(); m_verify_storages[level].Finalize(); } }; /* Initialize the level storages. */ for (/* ... */; level < m_max_layers - 3; ++level) { /* If hash salt is enabled, generate it. */ util::optional<fs::HashSalt> hash_salt = util::nullopt; if (hash_salt_enabled) { hash_salt.emplace(); crypto::GenerateHmacSha256(hash_salt->value, sizeof(hash_salt->value), info.seed.value, sizeof(info.seed), KeyArray[level + 1].key, KeyArray[level + 1].size); } /* Initialize the verification storage. */ fs::SubStorage buffer_storage(std::addressof(m_buffer_storages[level]), 0, info.info[level].size); m_verify_storages[level + 1].Initialize(buffer_storage, storage[level + 2], static_cast<s64>(1) << info.info[level + 1].block_order, static_cast<s64>(1) << info.info[level].block_order, m_buffers->buffers[m_max_layers - 2], hgf, hash_salt, false, is_writable, allow_cleared_blocks); /* Initialize the buffer storage. */ R_TRY(m_buffer_storages[level + 1].Initialize(m_buffers->buffers[level + 1], m_mutex, std::addressof(m_verify_storages[level + 1]), info.info[level + 1].size, static_cast<s64>(1) << info.info[level + 1].block_order, max_hash_cache_entries, false, 0x11 + static_cast<s8>(level), false, is_writable)); } /* Initialize the final level storage. */ { /* If hash salt is enabled, generate it. */ util::optional<fs::HashSalt> hash_salt = util::nullopt; if (hash_salt_enabled) { hash_salt.emplace(); crypto::GenerateHmacSha256(hash_salt->value, sizeof(hash_salt->value), info.seed.value, sizeof(info.seed), KeyArray[level + 1].key, KeyArray[level + 1].size); } /* Initialize the verification storage. */ fs::SubStorage buffer_storage(std::addressof(m_buffer_storages[level]), 0, info.info[level].size); m_verify_storages[level + 1].Initialize(buffer_storage, storage[level + 2], static_cast<s64>(1) << info.info[level + 1].block_order, static_cast<s64>(1) << info.info[level].block_order, m_buffers->buffers[m_max_layers - 2], hgf, hash_salt, true, is_writable, allow_cleared_blocks); /* Initialize the buffer storage. */ R_TRY(m_buffer_storages[level + 1].Initialize(m_buffers->buffers[level + 1], m_mutex, std::addressof(m_verify_storages[level + 1]), info.info[level + 1].size, static_cast<s64>(1) << info.info[level + 1].block_order, max_data_cache_entries, true, buffer_level, true, is_writable)); } /* Set the data size. */ m_data_size = info.info[level + 1].size; /* We succeeded. */ R_SUCCEED(); } void HierarchicalIntegrityVerificationStorage::Finalize() { if (m_data_size >= 0) { m_data_size = 0; m_buffers = nullptr; m_mutex = nullptr; for (s32 level = m_max_layers - 2; level >= 0; --level) { m_buffer_storages[level].Finalize(); m_verify_storages[level].Finalize(); } m_data_size = -1; } } Result HierarchicalIntegrityVerificationStorage::Read(s64 offset, void *buffer, size_t size) { /* Validate preconditions. */ AMS_ASSERT(m_data_size >= 0); /* Succeed if zero-size. */ R_SUCCEED_IF(size == 0); /* Validate arguments. */ R_UNLESS(buffer != nullptr, fs::ResultNullptrArgument()); /* If we have a read semaphore, acquire it. */ if (m_read_semaphore != nullptr) { m_read_semaphore->Acquire(); } ON_SCOPE_EXIT { if (m_read_semaphore != nullptr) { m_read_semaphore->Release(); } }; /* Acquire access to the global read semaphore. */ if (!g_read_semaphore.TimedAcquire(AccessTimeout)) { for (auto level = m_max_layers - 2; level >= 0; --level) { R_TRY(m_buffer_storages[level].Flush()); } g_read_semaphore.Acquire(); } /* Ensure that we release the semaphore when done. */ ON_SCOPE_EXIT { g_read_semaphore.Release(); }; /* Read the data. */ R_RETURN(m_buffer_storages[m_max_layers - 2].Read(offset, buffer, size)); } Result HierarchicalIntegrityVerificationStorage::Write(s64 offset, const void *buffer, size_t size) { /* Validate preconditions. */ AMS_ASSERT(m_data_size >= 0); /* Succeed if zero-size. */ R_SUCCEED_IF(size == 0); /* Validate arguments. */ R_UNLESS(buffer != nullptr, fs::ResultNullptrArgument()); /* If we have a write semaphore, acquire it. */ if (m_write_semaphore != nullptr) { m_write_semaphore->Acquire(); } ON_SCOPE_EXIT { if (m_write_semaphore != nullptr) { m_write_semaphore->Release(); } }; /* Acquire access to the write semaphore. */ if (!g_write_semaphore.TimedAcquire(AccessTimeout)) { for (auto level = m_max_layers - 2; level >= 0; --level) { R_TRY(m_buffer_storages[level].Flush()); } g_write_semaphore.Acquire(); } /* Ensure that we release the semaphore when done. */ ON_SCOPE_EXIT { g_write_semaphore.Release(); }; /* Write the data. */ R_RETURN(m_buffer_storages[m_max_layers - 2].Write(offset, buffer, size)); } Result HierarchicalIntegrityVerificationStorage::GetSize(s64 *out) { AMS_ASSERT(out != nullptr); AMS_ASSERT(m_data_size >= 0); *out = m_data_size; R_SUCCEED(); } Result HierarchicalIntegrityVerificationStorage::Flush() { R_SUCCEED(); } Result HierarchicalIntegrityVerificationStorage::OperateRange(void *dst, size_t dst_size, fs::OperationId op_id, s64 offset, s64 size, const void *src, size_t src_size) { switch (op_id) { case fs::OperationId::FillZero: case fs::OperationId::DestroySignature: { R_TRY(m_buffer_storages[m_max_layers - 2].OperateRange(dst, dst_size, op_id, offset, size, src, src_size)); R_SUCCEED(); } case fs::OperationId::Invalidate: case fs::OperationId::QueryRange: { R_TRY(m_buffer_storages[m_max_layers - 2].OperateRange(dst, dst_size, op_id, offset, size, src, src_size)); R_SUCCEED(); } default: R_THROW(fs::ResultUnsupportedOperateRangeForHierarchicalIntegrityVerificationStorage()); } } Result HierarchicalIntegrityVerificationStorage::Commit() { for (s32 level = m_max_layers - 2; level >= 0; --level) { R_TRY(m_buffer_storages[level].Commit()); } R_SUCCEED(); } Result HierarchicalIntegrityVerificationStorage::OnRollback() { for (s32 level = m_max_layers - 2; level >= 0; --level) { R_TRY(m_buffer_storages[level].OnRollback()); } R_SUCCEED(); } }
16,306
C++
.cpp
283
47.625442
451
0.627257
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,371
fssystem_allocator_utility.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssystem/fssystem_allocator_utility.cpp
/* * Copyright (c) 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 { namespace { constexpr bool UseDefaultAllocators = false; constinit bool g_used_default_allocator = false; void *DefaultAllocate(size_t size) { g_used_default_allocator = true; return ams::Malloc(size); } void DefaultDeallocate(void *ptr, size_t size) { AMS_UNUSED(size); ams::Free(ptr); } constinit os::SdkMutex g_allocate_mutex; constinit os::SdkMutex g_allocate_mutex_for_system; constinit AllocateFunction g_allocate_func = UseDefaultAllocators ? DefaultAllocate : nullptr; constinit DeallocateFunction g_deallocate_func = UseDefaultAllocators ? DefaultDeallocate : nullptr; constinit AllocateFunction g_allocate_func_for_system = nullptr; constinit DeallocateFunction g_deallocate_func_for_system = nullptr; void *AllocateUnsafe(size_t size) { /* Check pre-conditions. */ AMS_ASSERT(g_allocate_mutex.IsLockedByCurrentThread()); AMS_ASSERT(g_allocate_func != nullptr); /* Allocate memory. */ return g_allocate_func(size); } void DeallocateUnsafe(void *ptr, size_t size) { /* Check pre-conditions. */ AMS_ASSERT(g_allocate_mutex.IsLockedByCurrentThread()); AMS_ASSERT(g_deallocate_func != nullptr); /* Deallocate the pointer. */ g_deallocate_func(ptr, size); } } namespace impl { /* Normal allocator set. */ template<> void *AllocatorFunctionSet<false>::Allocate(size_t size) { return ::ams::fssystem::Allocate(size); } template<> void *AllocatorFunctionSet<false>::AllocateUnsafe(size_t size) { return ::ams::fssystem::AllocateUnsafe(size); } template<> void AllocatorFunctionSet<false>::Deallocate(void *ptr, size_t size) { return ::ams::fssystem::Deallocate(ptr, size); } template<> void AllocatorFunctionSet<false>::DeallocateUnsafe(void *ptr, size_t size) { return ::ams::fssystem::DeallocateUnsafe(ptr, size); } template<> void AllocatorFunctionSet<false>::LockAllocatorMutex() { ::ams::fssystem::g_allocate_mutex.Lock(); } template<> void AllocatorFunctionSet<false>::UnlockAllocatorMutex() { ::ams::fssystem::g_allocate_mutex.Unlock(); } /* System allocator set. */ template<> void *AllocatorFunctionSet<true>::AllocateUnsafe(size_t size) { /* Check pre-conditions. */ AMS_ASSERT(::ams::fssystem::g_allocate_mutex_for_system.IsLockedByCurrentThread()); AMS_ASSERT(::ams::fssystem::g_allocate_func_for_system != nullptr); /* Allocate memory. */ return g_allocate_func_for_system(size); } template<> void AllocatorFunctionSet<true>::DeallocateUnsafe(void *ptr, size_t size) { /* Check pre-conditions. */ AMS_ASSERT(::ams::fssystem::g_allocate_mutex_for_system.IsLockedByCurrentThread()); AMS_ASSERT(::ams::fssystem::g_deallocate_func_for_system != nullptr); /* Deallocate the pointer. */ ::ams::fssystem::g_deallocate_func_for_system(ptr, size); } template<> void *AllocatorFunctionSet<true>::Allocate(size_t size) { std::scoped_lock lk(::ams::fssystem::g_allocate_mutex_for_system); return ::ams::fssystem::impl::AllocatorFunctionSet<true>::AllocateUnsafe(size); } template<> void AllocatorFunctionSet<true>::Deallocate(void *ptr, size_t size) { std::scoped_lock lk(::ams::fssystem::g_allocate_mutex_for_system); return ::ams::fssystem::impl::AllocatorFunctionSet<true>::DeallocateUnsafe(ptr, size); } template<> void AllocatorFunctionSet<true>::LockAllocatorMutex() { ::ams::fssystem::g_allocate_mutex_for_system.Lock(); } template<> void AllocatorFunctionSet<true>::UnlockAllocatorMutex() { ::ams::fssystem::g_allocate_mutex_for_system.Unlock(); } } void *Allocate(size_t size) { std::scoped_lock lk(g_allocate_mutex); return AllocateUnsafe(size); } void Deallocate(void *ptr, size_t size) { std::scoped_lock lk(g_allocate_mutex); return DeallocateUnsafe(ptr, size); } void InitializeAllocator(AllocateFunction allocate_func, DeallocateFunction deallocate_func) { /* Check pre-conditions. */ AMS_ASSERT(allocate_func != nullptr); AMS_ASSERT(deallocate_func != nullptr); /* Check that we can initialize. */ if constexpr (UseDefaultAllocators) { AMS_ASSERT(g_used_default_allocator == false); } else { AMS_ASSERT(g_allocate_func == nullptr); AMS_ASSERT(g_deallocate_func == nullptr); } /* Set the allocator functions. */ g_allocate_func = allocate_func; g_deallocate_func = deallocate_func; } void InitializeAllocatorForSystem(AllocateFunction allocate_func, DeallocateFunction deallocate_func) { /* Check pre-conditions. */ AMS_ASSERT(allocate_func != nullptr); AMS_ASSERT(deallocate_func != nullptr); /* Check that we can initialize. */ AMS_ASSERT(g_allocate_func_for_system == nullptr); AMS_ASSERT(g_deallocate_func_for_system == nullptr); /* Set the system allocator functions. */ g_allocate_func_for_system = allocate_func; g_deallocate_func_for_system = deallocate_func; } }
6,207
C++
.cpp
118
43.754237
150
0.65703
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,372
fssystem_local_file_system.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssystem/fssystem_local_file_system.cpp
/* * Copyright (c) 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> #if defined(ATMOSPHERE_OS_WINDOWS) #include <stratosphere/windows.hpp> #include <winerror.h> #include <winioctl.h> #elif defined(ATMOSPHERE_OS_LINUX) || defined(ATMOSPHERE_OS_MACOS) #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/statvfs.h> #include <unistd.h> #include <dirent.h> #endif #if defined(ATMOSPHERE_OS_LINUX) #include <sys/syscall.h> #elif defined(ATMOSPHERE_OS_MACOS) extern "C" ssize_t __getdirentries64(int fd, char *buffer, size_t buffer_size, uintptr_t *basep); #endif #if !defined(ATMOSPHERE_OS_HORIZON) namespace ams::fssystem { namespace { constexpr s64 NanoSecondsPerWindowsTick = 100; constexpr s64 WindowsTicksPerSecond = TimeSpan::FromSeconds(1).GetNanoSeconds() / TimeSpan::FromNanoSeconds(NanoSecondsPerWindowsTick).GetNanoSeconds(); constexpr s64 OffsetToConvertToPosixTime = 11644473600; [[maybe_unused]] constexpr ALWAYS_INLINE s64 ConvertWindowsTimeToPosixTime(s64 windows_ticks) { return (windows_ticks / WindowsTicksPerSecond) - OffsetToConvertToPosixTime; } [[maybe_unused]] constexpr ALWAYS_INLINE s64 ConvertPosixTimeToWindowsTime(s64 posix_sec, s64 posix_ns = 0) { return ((posix_sec + OffsetToConvertToPosixTime) * WindowsTicksPerSecond) + util::DivideUp<s64>(posix_ns, NanoSecondsPerWindowsTick); } #if defined(ATMOSPHERE_OS_WINDOWS) constexpr int MaxFilePathLength = MAX_PATH - 1; constexpr int MaxDirectoryPathLength = MaxFilePathLength - (8 + 1 + 3); static_assert(MaxFilePathLength == 259); static_assert(MaxDirectoryPathLength == 247); bool AreLongPathsEnabledImpl() { /* Get handle to ntdll. */ const HMODULE module = ::GetModuleHandleW(L"ntdll"); if (module == nullptr) { return true; } /* Get function pointer to long paths enabled. */ const auto enabled_funcptr = ::GetProcAddress(module, "RtlAreLongPathsEnabled"); if (enabled_funcptr == nullptr) { return true; } /* Get whether long paths are enabled. */ using FunctionType = BOOLEAN (NTAPI *)(); return reinterpret_cast<FunctionType>(reinterpret_cast<uintptr_t>(enabled_funcptr))(); } Result ConvertLastErrorToResult() { switch (::GetLastError()) { case ERROR_FILE_NOT_FOUND: case ERROR_PATH_NOT_FOUND: case ERROR_NO_MORE_FILES: case ERROR_BAD_NETPATH: case ERROR_BAD_NET_NAME: case ERROR_DIRECTORY: case ERROR_BAD_DEVICE: case ERROR_CONNECTION_UNAVAIL: case ERROR_NO_NET_OR_BAD_PATH: case ERROR_NOT_CONNECTED: R_THROW(fs::ResultPathNotFound()); case ERROR_ACCESS_DENIED: case ERROR_SHARING_VIOLATION: R_THROW(fs::ResultTargetLocked()); case ERROR_HANDLE_EOF: R_THROW(fs::ResultOutOfRange()); case ERROR_FILE_EXISTS: case ERROR_ALREADY_EXISTS: R_THROW(fs::ResultPathAlreadyExists()); case ERROR_DISK_FULL: case ERROR_SPACES_NOT_ENOUGH_DRIVES: R_THROW(fs::ResultNotEnoughFreeSpace()); case ERROR_DIR_NOT_EMPTY: R_THROW(fs::ResultDirectoryNotEmpty()); case ERROR_BAD_PATHNAME: R_THROW(fs::ResultInvalidPathFormat()); case ERROR_FILENAME_EXCED_RANGE: R_THROW(fs::ResultTooLongPath()); default: //printf("Returning ConvertLastErrorToResult() -> ResultUnexpectedInLocalFileSystemE, last_error=0x%08x\n", static_cast<u32>(::GetLastError())); R_THROW(fs::ResultUnexpectedInLocalFileSystemE()); } } Result WaitDeletionCompletion(const wchar_t *native_path) { /* Wait for the path to be deleted. */ constexpr int MaxTryCount = 25; for (int i = 0; i < MaxTryCount; ++i) { /* Get the file attributes. */ const auto attr = ::GetFileAttributesW(native_path); /* If they're not invalid, we're done. */ R_SUCCEED_IF(attr != INVALID_FILE_ATTRIBUTES); /* Get last error. */ const auto err = ::GetLastError(); /* If error was file not found, the delete is complete. */ R_SUCCEED_IF(err == ERROR_FILE_NOT_FOUND); /* If the error was access denied, we want to try again. */ R_UNLESS(err == ERROR_ACCESS_DENIED, ConvertLastErrorToResult()); /* Sleep before checking again. */ ::Sleep(2); } /* We received access denied 25 times in a row. */ R_THROW(fs::ResultTargetLocked()); } Result GetEntryTypeImpl(fs::DirectoryEntryType *out, const wchar_t *native_path) { const auto res = ::GetFileAttributesW(native_path); if (res == INVALID_FILE_ATTRIBUTES) { switch (::GetLastError()) { case ERROR_FILE_NOT_FOUND: case ERROR_PATH_NOT_FOUND: case ERROR_ACCESS_DENIED: case ERROR_BAD_NETPATH: case ERROR_BAD_NET_NAME: case ERROR_BAD_DEVICE: case ERROR_CONNECTION_UNAVAIL: case ERROR_NO_NET_OR_BAD_PATH: case ERROR_NOT_CONNECTED: R_THROW(fs::ResultPathNotFound()); default: //printf("Returning GetEntryTypeImpl() -> ResultUnexpectedInLocalFileSystemF, last_error=0x%08x\n", static_cast<u32>(::GetLastError())); R_THROW(fs::ResultUnexpectedInLocalFileSystemF()); } } *out = (res & FILE_ATTRIBUTE_DIRECTORY) ? fs::DirectoryEntryType_Directory : fs::DirectoryEntryType_File; R_SUCCEED(); } Result SetFileSizeImpl(HANDLE handle, s64 size) { /* Seek to the desired size. */ LARGE_INTEGER seek; seek.QuadPart = size; R_UNLESS(::SetFilePointerEx(handle, seek, nullptr, FILE_BEGIN) != 0, ConvertLastErrorToResult()); /* Try to set the file size. */ if (::SetEndOfFile(handle) == 0) { /* Check if the error resulted from too large size. */ R_UNLESS(::GetLastError() == ERROR_INVALID_PARAMETER, ConvertLastErrorToResult()); R_UNLESS(size <= INT64_C(0x00000FFFFFFF0000), ConvertLastErrorToResult()); /* The file size is too large. */ R_THROW(fs::ResultTooLargeSize()); } R_SUCCEED(); } class LocalFile : public ::ams::fs::fsa::IFile, public ::ams::fs::impl::Newable { private: const HANDLE m_handle; const fs::OpenMode m_open_mode; public: LocalFile(HANDLE h, fs::OpenMode m) : m_handle(h), m_open_mode(m) { /* ... */ } virtual ~LocalFile() { ::CloseHandle(m_handle); } public: virtual Result DoRead(size_t *out, s64 offset, void *buffer, size_t size, const fs::ReadOption &option) override { /* Check that read is possible. */ size_t dry_read_size; R_TRY(this->DryRead(std::addressof(dry_read_size), offset, size, option, m_open_mode)); /* If we have nothing to read, we don't need to do anything. */ if (dry_read_size == 0) { *out = 0; R_SUCCEED(); } /* Prepare to do asynchronous IO. */ OVERLAPPED overlapped = {}; overlapped.Offset = static_cast<DWORD>(offset); overlapped.OffsetHigh = static_cast<DWORD>(offset >> BITSIZEOF(DWORD)); overlapped.hEvent = ::CreateEvent(nullptr, true, false, nullptr); R_UNLESS(overlapped.hEvent != nullptr, fs::ResultUnexpectedInLocalFileSystemA()); ON_SCOPE_EXIT { ::CloseHandle(overlapped.hEvent); }; /* Read from the file. */ DWORD size_read; if (!::ReadFile(m_handle, buffer, static_cast<DWORD>(size), std::addressof(size_read), std::addressof(overlapped))) { /* If we fail for reason other than io pending, return the error result. */ const auto err = ::GetLastError(); R_UNLESS(err == ERROR_IO_PENDING, ConvertLastErrorToResult()); /* Get the wait result. */ if (!::GetOverlappedResult(m_handle, std::addressof(overlapped), std::addressof(size_read), true)) { /* We failed...check if it's because we're at the end of the file. */ R_UNLESS(::GetLastError() == ERROR_HANDLE_EOF, ConvertLastErrorToResult()); /* Get the file size. */ LARGE_INTEGER file_size; R_UNLESS(::GetFileSizeEx(m_handle, std::addressof(file_size)), ConvertLastErrorToResult()); /* Check the filesize matches offset. */ R_UNLESS(file_size.QuadPart == offset, ConvertLastErrorToResult()); } } /* Set the output read size. */ *out = size_read; R_SUCCEED(); } virtual Result DoGetSize(s64 *out) override { /* Get the file size. */ LARGE_INTEGER size; R_UNLESS(::GetFileSizeEx(m_handle, std::addressof(size)), fs::ResultUnexpectedInLocalFileSystemD()); /* Set the output. */ *out = size.QuadPart; R_SUCCEED(); } virtual Result DoFlush() override { /* If we're not writable, we have nothing to flush. */ R_SUCCEED_IF((m_open_mode & fs::OpenMode_Write) == 0); /* Flush our buffer. */ R_UNLESS(::FlushFileBuffers(m_handle), fs::ResultUnexpectedInLocalFileSystemC()); R_SUCCEED(); } virtual Result DoWrite(s64 offset, const void *buffer, size_t size, const fs::WriteOption &option) override { /* Verify that we can write. */ bool needs_append; R_TRY(this->DryWrite(std::addressof(needs_append), offset, size, option, m_open_mode)); /* If we need to, perform the write. */ if (size != 0) { /* Prepare to do asynchronous IO. */ OVERLAPPED overlapped = {}; overlapped.Offset = static_cast<DWORD>(offset); overlapped.OffsetHigh = static_cast<DWORD>(offset >> BITSIZEOF(DWORD)); overlapped.hEvent = ::CreateEvent(nullptr, true, false, nullptr); R_UNLESS(overlapped.hEvent != nullptr, fs::ResultUnexpectedInLocalFileSystemA()); ON_SCOPE_EXIT { ::CloseHandle(overlapped.hEvent); }; /* Write to the file. */ DWORD size_written; if (!::WriteFile(m_handle, buffer, static_cast<DWORD>(size), std::addressof(size_written), std::addressof(overlapped))) { /* If we fail for reason other than io pending, return the error result. */ const auto err = ::GetLastError(); R_UNLESS(err == ERROR_IO_PENDING, ConvertLastErrorToResult()); /* Get the wait result. */ R_UNLESS(::GetOverlappedResult(m_handle, std::addressof(overlapped), std::addressof(size_written), true), ConvertLastErrorToResult()); } /* Check that a correct amount of data was written. */ R_UNLESS(size_written >= size, fs::ResultNotEnoughFreeSpace()); /* Sanity check that we wrote the right amount. */ AMS_ASSERT(size_written == size); } /* If we need to, flush. */ if (option.HasFlushFlag()) { R_TRY(this->Flush()); } R_SUCCEED(); } virtual Result DoSetSize(s64 size) override { /* Verify we can set the size. */ R_TRY(this->DrySetSize(size, m_open_mode)); /* Try to set the file size. */ R_RETURN(SetFileSizeImpl(m_handle, size)); } virtual Result DoOperateRange(void *dst, size_t dst_size, fs::OperationId op_id, s64 offset, s64 size, const void *src, size_t src_size) override { AMS_UNUSED(offset, size, src, src_size); switch (op_id) { case fs::OperationId::Invalidate: R_SUCCEED(); case fs::OperationId::QueryRange: R_UNLESS(dst != nullptr, fs::ResultNullptrArgument()); R_UNLESS(dst_size == sizeof(fs::QueryRangeInfo), fs::ResultInvalidSize()); static_cast<fs::QueryRangeInfo *>(dst)->Clear(); R_SUCCEED(); default: R_THROW(fs::ResultUnsupportedOperateRangeForTmFileSystemFile()); } } public: virtual sf::cmif::DomainObjectId GetDomainObjectId() const override { AMS_ABORT("GetDomainObjectId() should never be called on a LocalFile"); } }; bool IsDirectory(const WIN32_FIND_DATAW &fd) { return fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY; } class LocalDirectory : public ::ams::fs::fsa::IDirectory, public ::ams::fs::impl::Newable { private: std::unique_ptr<wchar_t[], ::ams::fs::impl::Deleter> m_path; HANDLE m_dir_handle; HANDLE m_search_handle; fs::OpenDirectoryMode m_open_mode; public: LocalDirectory(HANDLE d, fs::OpenDirectoryMode m, std::unique_ptr<wchar_t[], ::ams::fs::impl::Deleter> &&p) : m_path(std::move(p)), m_dir_handle(d), m_search_handle(INVALID_HANDLE_VALUE) { m_open_mode = static_cast<fs::OpenDirectoryMode>(util::ToUnderlying(m) & ~util::ToUnderlying(fs::OpenDirectoryMode_NotRequireFileSize)); } virtual ~LocalDirectory() { if (m_search_handle != INVALID_HANDLE_VALUE) { ::FindClose(m_search_handle); } ::CloseHandle(m_dir_handle); } public: virtual Result DoRead(s64 *out_count, fs::DirectoryEntry *out_entries, s64 max_entries) override { auto read_count = 0; while (read_count < max_entries) { /* Read the next file. */ WIN32_FIND_DATAW fd; std::memset(fd.cFileName, 0, sizeof(fd.cFileName)); if (m_search_handle == INVALID_HANDLE_VALUE) { /* Create our search handle. */ if (m_search_handle = ::FindFirstFileW(m_path.get(), std::addressof(fd)); m_search_handle == INVALID_HANDLE_VALUE) { /* Check that we failed because there are no files. */ R_UNLESS(::GetLastError() == ERROR_FILE_NOT_FOUND, ConvertLastErrorToResult()); break; } } else if (!::FindNextFileW(m_search_handle, std::addressof(fd))) { /* Check that we failed because we ran out of files. */ R_UNLESS(::GetLastError() == ERROR_NO_MORE_FILES, ConvertLastErrorToResult()); break; } /* If we shouldn't create an entry, continue. */ if (!this->IsReadTarget(fd)) { continue; } /* Create the entry. */ auto &entry = out_entries[read_count++]; std::memset(entry.name, 0, sizeof(entry.name)); const auto wide_res = ::WideCharToMultiByte(CP_UTF8, 0, fd.cFileName, -1, entry.name, sizeof(entry.name), nullptr, nullptr); R_UNLESS(wide_res != 0, fs::ResultInvalidPath()); entry.type = IsDirectory(fd) ? fs::DirectoryEntryType_Directory : fs::DirectoryEntryType_File; entry.file_size = static_cast<s64>(fd.nFileSizeLow) | static_cast<s64>(static_cast<u64>(fd.nFileSizeHigh) << BITSIZEOF(fd.nFileSizeLow)); } /* Set the output read count. */ *out_count = read_count; R_SUCCEED(); } virtual Result DoGetEntryCount(s64 *out) override { /* Open a new search handle. */ WIN32_FIND_DATAW fd; auto handle = ::FindFirstFileW(m_path.get(), std::addressof(fd)); R_UNLESS(handle != INVALID_HANDLE_VALUE, ConvertLastErrorToResult()); ON_SCOPE_EXIT { ::FindClose(handle); }; /* Iterate to get the total entry count. */ auto entry_count = 0; while (::FindNextFileW(handle, std::addressof(fd))) { if (this->IsReadTarget(fd)) { ++entry_count; } } /* Check that we stopped iterating because we ran out of files. */ R_UNLESS(::GetLastError() == ERROR_NO_MORE_FILES, ConvertLastErrorToResult()); /* Set the output. */ *out = entry_count; R_SUCCEED(); } private: bool IsReadTarget(const WIN32_FIND_DATAW &fd) const { /* If the file is "..", don't return it. */ if (::wcsncmp(fd.cFileName, L"..", 3) == 0 || ::wcsncmp(fd.cFileName, L".", 2) == 0) { return false; } /* Return whether our open mode supports the target. */ if (IsDirectory(fd)) { return m_open_mode != fs::OpenDirectoryMode_File; } else { return m_open_mode != fs::OpenDirectoryMode_Directory; } } public: virtual sf::cmif::DomainObjectId GetDomainObjectId() const override { AMS_ABORT("GetDomainObjectId() should never be called on a LocalDirectory"); } }; #else constexpr int MaxFilePathLength = PATH_MAX - 1; constexpr int MaxDirectoryPathLength = PATH_MAX - 1; #if defined (ATMOSPHERE_OS_LINUX) struct linux_dirent64 { ino64_t d_ino; off64_t d_off; unsigned short d_reclen; unsigned char d_type; char d_name[]; }; using NativeDirectoryEntryType = struct linux_dirent64; #else using NativeDirectoryEntryType = struct dirent; #endif bool AreLongPathsEnabledImpl() { /* TODO: How does this work on linux/macos? */ return true; } enum ErrnoSource { ErrnoSource_OpenFile, // 0 ErrnoSource_CreateFile, // 1 ErrnoSource_Unlink, // 2 ErrnoSource_Pread, // 3 ErrnoSource_Pwrite, // 4 ErrnoSource_Ftruncate, // 5 // ErrnoSource_OpenDirectory, // 6 ErrnoSource_Mkdir, // 7 ErrnoSource_Rmdir, // 8 ErrnoSource_GetDents, // 9 // ErrnoSource_RenameDirectory, // 10 ErrnoSource_RenameFile, // 11 // ErrnoSource_Stat, // 12 ErrnoSource_Statvfs, // 13 }; Result ConvertErrnoToResult(ErrnoSource source) { switch (errno) { case ENOENT: R_THROW(fs::ResultPathNotFound()); case EEXIST: switch (source) { case ErrnoSource_Rmdir: R_THROW(fs::ResultDirectoryNotEmpty()); default: R_THROW(fs::ResultPathAlreadyExists()); } case ENOTDIR: switch (source) { case ErrnoSource_Rmdir: R_THROW(fs::ResultPathNotFound()); default: R_THROW(fs::ResultPathNotFound()); } case EISDIR: switch (source) { case ErrnoSource_CreateFile: R_THROW(fs::ResultPathAlreadyExists()); case ErrnoSource_OpenFile: case ErrnoSource_Unlink: R_THROW(fs::ResultPathNotFound()); default: R_THROW(fs::ResultUnexpectedInLocalFileSystemE()); } case ENOTEMPTY: R_THROW(fs::ResultDirectoryNotEmpty()); case EACCES: case EINTR: R_THROW(fs::ResultTargetLocked()); default: //printf("Returning default errno -> result, errno=%d, source=%d\n", errno, static_cast<int>(source)); R_THROW(fs::ResultUnexpectedInLocalFileSystemE()); } } Result WaitDeletionCompletion(const char *native_path) { /* TODO: Does linux need to wait for delete to complete? */ AMS_UNUSED(native_path); R_SUCCEED(); } Result GetEntryTypeImpl(fs::DirectoryEntryType *out, const char *native_path) { struct stat st; R_UNLESS(::stat(native_path, std::addressof(st)) == 0, ConvertErrnoToResult(ErrnoSource_Stat)); *out = (S_ISDIR(st.st_mode)) ? fs::DirectoryEntryType_Directory : fs::DirectoryEntryType_File; R_SUCCEED(); } auto RetryForEIntr(auto f) { decltype(f()) res; do { res = f(); } while (res < 0 && errno == EINTR); return res; }; void CloseFileDescriptor(int handle) { const int res = RetryForEIntr([&] () ALWAYS_INLINE_LAMBDA { return ::close(handle); }); AMS_ASSERT(res == 0); AMS_UNUSED(res); } Result SetFileSizeImpl(int handle, s64 size) { const auto res = RetryForEIntr([&] () ALWAYS_INLINE_LAMBDA { return ::ftruncate(handle, size); }); R_UNLESS(res == 0, ConvertErrnoToResult(ErrnoSource_Ftruncate)); R_SUCCEED(); } class LocalFile : public ::ams::fs::fsa::IFile, public ::ams::fs::impl::Newable { private: const int m_handle; const fs::OpenMode m_open_mode; public: LocalFile(int h, fs::OpenMode m) : m_handle(h), m_open_mode(m) { /* ... */ } virtual ~LocalFile() { CloseFileDescriptor(m_handle); } public: virtual Result DoRead(size_t *out, s64 offset, void *buffer, size_t size, const fs::ReadOption &option) override { /* Check that read is possible. */ size_t dry_read_size; R_TRY(this->DryRead(std::addressof(dry_read_size), offset, size, option, m_open_mode)); /* If we have nothing to read, we don't need to do anything. */ if (dry_read_size == 0) { *out = 0; R_SUCCEED(); } /* Read. */ const auto read_size = RetryForEIntr([&] () ALWAYS_INLINE_LAMBDA -> ssize_t { return ::pread(m_handle, buffer, size, offset); }); R_UNLESS(read_size >= 0, ConvertErrnoToResult(ErrnoSource_Pread)); /* Set output. */ *out = static_cast<size_t>(read_size); R_SUCCEED(); } virtual Result DoGetSize(s64 *out) override { /* Get the file size. */ const auto size = RetryForEIntr([&] () ALWAYS_INLINE_LAMBDA -> s64 { return ::lseek(m_handle, 0, SEEK_END); }); R_UNLESS(size >= 0, fs::ResultUnexpectedInLocalFileSystemD()); /* Set the output. */ *out = size; R_SUCCEED(); } virtual Result DoFlush() override { /* If we're not writable, we have nothing to flush. */ R_SUCCEED_IF((m_open_mode & fs::OpenMode_Write) == 0); /* Flush our buffer. */ const auto res = RetryForEIntr([&] () ALWAYS_INLINE_LAMBDA { return ::fsync(m_handle); }); R_UNLESS(res == 0, fs::ResultUnexpectedInLocalFileSystemC()); R_SUCCEED(); } virtual Result DoWrite(s64 offset, const void *buffer, size_t size, const fs::WriteOption &option) override { /* Verify that we can write. */ bool needs_append; R_TRY(this->DryWrite(std::addressof(needs_append), offset, size, option, m_open_mode)); /* If we need to, perform the write. */ if (size != 0) { /* Read. */ const auto size_written = RetryForEIntr([&] () ALWAYS_INLINE_LAMBDA -> ssize_t { return ::pwrite(m_handle, buffer, size, offset); }); R_UNLESS(size_written >= 0, ConvertErrnoToResult(ErrnoSource_Pwrite)); /* Check that a correct amount of data was written. */ R_UNLESS(static_cast<size_t>(size_written) >= size, fs::ResultNotEnoughFreeSpace()); /* Sanity check that we wrote the right amount. */ AMS_ASSERT(static_cast<size_t>(size_written) == size); } /* If we need to, flush. */ if (option.HasFlushFlag()) { R_TRY(this->Flush()); } R_SUCCEED(); } virtual Result DoSetSize(s64 size) override { /* Verify we can set the size. */ R_TRY(this->DrySetSize(size, m_open_mode)); /* Try to set the file size. */ R_RETURN(SetFileSizeImpl(m_handle, size)); } virtual Result DoOperateRange(void *dst, size_t dst_size, fs::OperationId op_id, s64 offset, s64 size, const void *src, size_t src_size) override { AMS_UNUSED(offset, size, src, src_size); switch (op_id) { case fs::OperationId::Invalidate: R_SUCCEED(); case fs::OperationId::QueryRange: R_UNLESS(dst != nullptr, fs::ResultNullptrArgument()); R_UNLESS(dst_size == sizeof(fs::QueryRangeInfo), fs::ResultInvalidSize()); static_cast<fs::QueryRangeInfo *>(dst)->Clear(); R_SUCCEED(); default: R_THROW(fs::ResultUnsupportedOperateRangeForTmFileSystemFile()); } } public: virtual sf::cmif::DomainObjectId GetDomainObjectId() const override { AMS_ABORT("GetDomainObjectId() should never be called on a LocalFile"); } }; class LocalDirectory : public ::ams::fs::fsa::IDirectory, public ::ams::fs::impl::Newable { private: std::unique_ptr<char[], ::ams::fs::impl::Deleter> m_path; int m_dir_handle; fs::OpenDirectoryMode m_open_mode; bool m_not_require_file_size; std::unique_ptr<fs::DirectoryEntry[], ::ams::fs::impl::Deleter> m_temp_entries; int m_temp_entries_count; int m_temp_entries_ofs; #if defined(ATMOSPHERE_OS_MACOS) uintptr_t m_basep = 0; #endif public: LocalDirectory(int d, fs::OpenDirectoryMode m, std::unique_ptr<char[], ::ams::fs::impl::Deleter> &&p) : m_path(std::move(p)), m_dir_handle(d), m_temp_entries(nullptr), m_temp_entries_count(0), m_temp_entries_ofs(0) { m_open_mode = static_cast<fs::OpenDirectoryMode>(util::ToUnderlying(m) & ~util::ToUnderlying(fs::OpenDirectoryMode_NotRequireFileSize)); m_not_require_file_size = m & fs::OpenDirectoryMode_NotRequireFileSize; } virtual ~LocalDirectory() { CloseFileDescriptor(m_dir_handle); } public: virtual Result DoRead(s64 *out_count, fs::DirectoryEntry *out_entries, s64 max_entries) override { auto read_count = 0; /* Copy out any pending entries from a previous call. */ while (m_temp_entries_ofs < m_temp_entries_count && read_count < max_entries) { out_entries[read_count++] = m_temp_entries[m_temp_entries_ofs++]; } /* If we're done with our temporary entries, release them. */ if (m_temp_entries_ofs == m_temp_entries_count) { m_temp_entries.reset(); m_temp_entries_ofs = 0; m_temp_entries_count = 0; } if (read_count < max_entries) { /* Declare buffer to hold temporary path. */ char path_buf[PATH_MAX]; auto base_path_len = std::strlen(m_path.get()); std::memcpy(path_buf, m_path.get(), base_path_len); if (path_buf[base_path_len - 1] != '/') { path_buf[base_path_len++] = '/'; } #if defined(ATMOSPHERE_OS_LINUX) char buf[1_KB]; #else char buf[2_KB]; #endif NativeDirectoryEntryType *ent = nullptr; while (read_count < max_entries) { /* Read next entries. */ #if defined (ATMOSPHERE_OS_LINUX) const auto nread = ::syscall(SYS_getdents64, m_dir_handle, buf, sizeof(buf)); #elif defined(ATMOSPHERE_OS_MACOS) const auto nread = ::__getdirentries64(m_dir_handle, buf, sizeof(buf), std::addressof(m_basep)); #else #error "Unknown OS to read from directory FD" #endif R_UNLESS(nread >= 0, ConvertErrnoToResult(ErrnoSource_GetDents)); /* If we read nothing, we've hit the end of the directory. */ if (nread == 0) { break; } /* Determine the number of entries we read. */ auto cur_read_entries = 0; for (auto pos = 0; pos < nread; pos += ent->d_reclen) { /* Get the native entry. */ ent = reinterpret_cast<NativeDirectoryEntryType *>(buf + pos); /* If the entry isn't a read target, ignore it. */ if (IsReadTarget(ent)) { ++cur_read_entries; } } /* If we'll end up reading more than we can fit, allocate a temporary buffer. */ if (read_count + cur_read_entries > max_entries) { /* Allocate temporary entries. */ m_temp_entries_count = (read_count + cur_read_entries) - max_entries; m_temp_entries_ofs = 0; /* TODO: Non-fatal? */ m_temp_entries = fs::impl::MakeUnique<fs::DirectoryEntry[]>(m_temp_entries_count); AMS_ABORT_UNLESS(m_temp_entries != nullptr); } /* Iterate received entries. */ for (auto pos = 0; pos < nread; pos += ent->d_reclen) { /* Get the native entry. */ ent = reinterpret_cast<NativeDirectoryEntryType *>(buf + pos); /* If the entry isn't a read target, ignore it. */ if (!IsReadTarget(ent)) { continue; } /* Decide on the output entry. */ fs::DirectoryEntry *out_entry; if (read_count < max_entries) { out_entry = std::addressof(out_entries[read_count++]); } else { out_entry = std::addressof(m_temp_entries[m_temp_entries_ofs++]); } /* Setup the output entry. */ { std::memset(out_entry->name, 0, sizeof(out_entry->name)); const auto name_len = std::strlen(ent->d_name); AMS_ABORT_UNLESS(name_len <= fs::EntryNameLengthMax); std::memcpy(out_entry->name, ent->d_name, name_len + 1); out_entry->type = (ent->d_type == DT_DIR) ? fs::DirectoryEntryType_Directory : fs::DirectoryEntryType_File; /* If we have to, get the filesize. This is (unfortunately) expensive on linux. */ if (out_entry->type == fs::DirectoryEntryType_File && !m_not_require_file_size) { /* Set up the temporary file path. */ AMS_ABORT_UNLESS(base_path_len + name_len + 1 <= PATH_MAX); std::memcpy(path_buf + base_path_len, ent->d_name, name_len + 1); /* Get the file stats. */ struct stat st; R_UNLESS(::stat(path_buf, std::addressof(st)) == 0, ConvertErrnoToResult(ErrnoSource_Stat)); out_entry->file_size = static_cast<s64>(st.st_size); } } } /* Ensure our temporary entries are correct. */ if (m_temp_entries != nullptr) { AMS_ASSERT(read_count == max_entries); AMS_ASSERT(m_temp_entries_ofs == m_temp_entries_count); m_temp_entries_ofs = 0; } } } /* Set the output read count. */ *out_count = read_count; R_SUCCEED(); } virtual Result DoGetEntryCount(s64 *out) override { /* Open the directory anew. */ const auto handle = RetryForEIntr([&] () ALWAYS_INLINE_LAMBDA { return ::open(m_path.get(), O_RDONLY | O_DIRECTORY); }); R_UNLESS(handle >= 0, ConvertErrnoToResult(ErrnoSource_OpenDirectory)); ON_SCOPE_EXIT { CloseFileDescriptor(handle); }; /* Iterate to get the total entry count. */ auto entry_count = 0; { #if defined(ATMOSPHERE_OS_LINUX) char buf[1_KB]; #else char buf[2_KB]; uintptr_t basep = 0; #endif NativeDirectoryEntryType *ent = nullptr; while (true) { /* Read next entries. */ #if defined (ATMOSPHERE_OS_LINUX) const auto nread = ::syscall(SYS_getdents64, handle, buf, sizeof(buf)); #elif defined(ATMOSPHERE_OS_MACOS) const auto nread = ::__getdirentries64(handle, buf, sizeof(buf), std::addressof(basep)); #else #error "Unknown OS to read from directory FD" #endif R_UNLESS(nread >= 0, ConvertErrnoToResult(ErrnoSource_GetDents)); /* If we read nothing, we've hit the end of the directory. */ if (nread == 0) { break; } /* Iterate received entries. */ for (auto pos = 0; pos < nread; pos += ent->d_reclen) { /* Get the entry. */ ent = reinterpret_cast<NativeDirectoryEntryType *>(buf + pos); /* If the entry is a read target, increment our count. */ if (IsReadTarget(ent)) { ++entry_count; } } } } *out = entry_count; R_SUCCEED(); } private: bool IsReadTarget(const NativeDirectoryEntryType *ent) const { /* If the file is "..", don't return it. */ if (std::strcmp(ent->d_name, ".") == 0 || std::strcmp(ent->d_name, "..") == 0) { return false; } /* Return whether our open mode supports the target. */ if (ent->d_type == DT_DIR) { return m_open_mode != fs::OpenDirectoryMode_File; } else { return m_open_mode != fs::OpenDirectoryMode_Directory; } } public: virtual sf::cmif::DomainObjectId GetDomainObjectId() const override { AMS_ABORT("GetDomainObjectId() should never be called on a LocalDirectory"); } }; #endif bool AreLongPathsEnabled() { AMS_FUNCTION_LOCAL_STATIC(bool, s_enabled, AreLongPathsEnabledImpl()); return s_enabled; } } Result LocalFileSystem::Initialize(const fs::Path &root_path, fssystem::PathCaseSensitiveMode case_sensitive_mode) { /* Initialize our root path. */ R_TRY(m_root_path.Initialize(root_path)); /* If we're not empty, we'll need to convert to a native path. */ if (m_root_path.IsEmpty()) { /* Reset our native path, since we're acting without a root. */ m_native_path_buffer.reset(nullptr); m_native_path_length = 0; } else { /* Convert to native path. */ NativePathBuffer native_path = nullptr; int native_len = 0; #if defined(ATMOSPHERE_OS_WINDOWS) { /* Get path length. */ native_len = ::MultiByteToWideChar(CP_UTF8, 0, m_root_path.GetString(), -1, nullptr, 0); /* Allocate our native path buffer. */ native_path = fs::impl::MakeUnique<NativeCharacterType[]>(native_len + 1); R_UNLESS(native_path != nullptr, fs::ResultAllocationMemoryFailedMakeUnique()); /* Convert path. */ const auto res = ::MultiByteToWideChar(CP_UTF8, 0, m_root_path.GetString(), -1, native_path.get(), native_len); R_UNLESS(res != 0, fs::ResultTooLongPath()); R_UNLESS(res <= static_cast<int>(fs::EntryNameLengthMax + 1), fs::ResultTooLongPath()); /* Fix up directory separators. */ for (NativeCharacterType *p = native_path.get(); *p != 0; ++p) { if (*p == '/') { *p = '\\'; } } } #else { /* Get path size. */ native_len = std::strlen(m_root_path.GetString()); /* Tentatively assume other operating systems do the sane thing and use utf-8 strings. */ native_path = fs::impl::MakeUnique<NativeCharacterType[]>(native_len + 1); R_UNLESS(native_path != nullptr, fs::ResultAllocationMemoryFailedMakeUnique()); /* Copy in path. */ std::memcpy(native_path.get(), m_root_path.GetString(), native_len + 1); } #endif /* Temporarily set case sensitive mode to insensitive, and verify we can get the root directory. */ m_case_sensitive_mode = fssystem::PathCaseSensitiveMode_CaseInsensitive; { constexpr fs::Path RequiredRootPath = fs::MakeConstantPath("/"); fs::DirectoryEntryType type; R_TRY(this->GetEntryType(std::addressof(type), RequiredRootPath)); R_UNLESS(type == fs::DirectoryEntryType_Directory, fs::ResultPathNotFound()); } /* Set our native path members. */ m_native_path_buffer = std::move(native_path); m_native_path_length = native_len; } /* Set our case sensitive mode. */ m_case_sensitive_mode = case_sensitive_mode; R_SUCCEED(); } Result LocalFileSystem::GetCaseSensitivePath(int *out_size, char *dst, size_t dst_size, const char *path, const char *work_path) { AMS_UNUSED(out_size, dst, dst_size, path, work_path); AMS_ABORT("TODO"); } Result LocalFileSystem::CheckPathCaseSensitively(const NativeCharacterType *path, const NativeCharacterType *root_path, NativeCharacterType *cs_buf, size_t cs_size, bool check_case_sensitivity) { AMS_UNUSED(path, root_path, cs_buf, cs_size, check_case_sensitivity); AMS_ABORT("TODO"); } Result LocalFileSystem::ResolveFullPath(NativePathBuffer *out, const fs::Path &path, int max_len, int min_len, bool check_case_sensitivity) { /* Create the full path. */ fs::Path full_path; R_TRY(full_path.Combine(m_root_path, path)); /* Check that the path is valid. */ fs::PathFlags flags; flags.AllowWindowsPath(); flags.AllowRelativePath(); flags.AllowEmptyPath(); R_TRY(fs::PathFormatter::CheckPathFormat(full_path.GetString(), flags)); /* Check the path's character count. */ #if defined(ATMOSPHERE_OS_WINDOWS) AreLongPathsEnabled(); // TODO: R_TRY(fs::CheckCharacterCountForWindows(full_path.GetString(), MaxBasePathLength, AreLongPathsEnabled() ? 0 : max_len)); AMS_UNUSED(max_len); #else AreLongPathsEnabled(); /* TODO: Check character count for linux/macos? */ AMS_UNUSED(max_len); #endif /* Convert to native path. */ NativePathBuffer native_path = nullptr; #if defined(ATMOSPHERE_OS_WINDOWS) { /* Get path length. */ const int native_len = ::MultiByteToWideChar(CP_UTF8, 0, full_path.GetString(), -1, nullptr, 0); /* Allocate our native path buffer. */ native_path = fs::impl::MakeUnique<NativeCharacterType[]>(native_len + min_len + 1); R_UNLESS(native_path != nullptr, fs::ResultAllocationMemoryFailedMakeUnique()); /* Convert path. */ const auto res = ::MultiByteToWideChar(CP_UTF8, 0, full_path.GetString(), -1, native_path.get(), native_len); R_UNLESS(res != 0, fs::ResultTooLongPath()); R_UNLESS(res <= native_len, fs::ResultTooLongPath()); /* Fix up directory separators. */ s32 len = 0; for (NativeCharacterType *p = native_path.get(); *p != 0; ++p) { if (*p == '/') { *p = '\\'; } ++len; } /* Fix up trailing : */ if (native_path[len - 1] == ':') { native_path[len] = '\\'; native_path[len + 1] = 0; } /* If case sensitivity is required, allocate case sensitive buffer. */ if (m_case_sensitive_mode == PathCaseSensitiveMode_CaseSensitive && native_path[0] != 0) { /* Allocate case sensitive buffer. */ auto case_sensitive_buffer_size = sizeof(NativeCharacterType) * (m_native_path_length + native_len + 1 + fs::EntryNameLengthMax); NativePathBuffer case_sensitive_path_buffer = fs::impl::MakeUnique<NativeCharacterType[]>(case_sensitive_buffer_size / sizeof(NativeCharacterType)); R_UNLESS(case_sensitive_path_buffer != nullptr, fs::ResultAllocationMemoryFailedMakeUnique()); /* Get root path. */ const NativeCharacterType *root_path = m_native_path_buffer.get() != nullptr ? m_native_path_buffer.get() : L""; /* Perform case sensitive path checking. */ R_TRY(this->CheckPathCaseSensitively(native_path.get(), root_path, case_sensitive_path_buffer.get(), case_sensitive_buffer_size, check_case_sensitivity)); } /* Set default path, if empty. */ if (native_path[0] == 0) { native_path[0] = '.'; native_path[1] = '\\'; native_path[2] = 0; } } #else { /* Get path size. */ const int native_len = std::strlen(full_path.GetString()); /* Tentatively assume other operating systems do the sane thing and use utf-8 strings. */ native_path = fs::impl::MakeUnique<NativeCharacterType[]>(native_len + min_len + 1); R_UNLESS(native_path != nullptr, fs::ResultAllocationMemoryFailedMakeUnique()); /* Copy in path. */ std::memcpy(native_path.get(), full_path.GetString(), native_len + 1); /* TODO: Is case sensitivity adjustment needed here? */ AMS_UNUSED(check_case_sensitivity); } #endif /* Set the output path. */ *out = std::move(native_path); R_SUCCEED(); } Result LocalFileSystem::DoGetDiskFreeSpace(s64 *out_free, s64 *out_total, s64 *out_total_free, const fs::Path &path) { /* Resolve the path. */ NativePathBuffer native_path; R_TRY(this->ResolveFullPath(std::addressof(native_path), path, MaxFilePathLength, 0, false)); /* Get the disk free space. */ #if defined(ATMOSPHERE_OS_WINDOWS) { ULARGE_INTEGER free, total, total_free; R_UNLESS(::GetDiskFreeSpaceExW(native_path.get(), std::addressof(free), std::addressof(total), std::addressof(total_free)), ConvertLastErrorToResult()); *out_free = static_cast<s64>(free.QuadPart); *out_total = static_cast<s64>(total.QuadPart); *out_total_free = static_cast<s64>(total_free.QuadPart); } #else { struct statvfs st; const auto res = RetryForEIntr([&] () ALWAYS_INLINE_LAMBDA { return ::statvfs(native_path.get(), std::addressof(st)); }); R_UNLESS(res >= 0, ConvertErrnoToResult(ErrnoSource_Statvfs)); *out_free = static_cast<s64>(st.f_bavail) * static_cast<s64>(st.f_frsize); *out_total = static_cast<s64>(st.f_blocks) * static_cast<s64>(st.f_frsize); *out_total_free = static_cast<s64>(st.f_bfree) * static_cast<s64>(st.f_frsize); } #endif R_SUCCEED(); } Result LocalFileSystem::DeleteDirectoryRecursivelyInternal(const NativeCharacterType *path, bool delete_top) { #if defined(ATMOSPHERE_OS_WINDOWS) { /* Get the path length. */ const auto path_len = ::wcslen(path); /* Allocate a new path buffer. */ NativePathBuffer cur_path_buf = fs::impl::MakeUnique<NativeCharacterType[]>(path_len + MAX_PATH); R_UNLESS(cur_path_buf.get() != nullptr, fs::ResultAllocationMemoryFailedMakeUnique()); /* Copy the path into the temporary buffer. */ ::wcscpy(cur_path_buf.get(), path); ::wcscat(cur_path_buf.get(), L"\\*"); /* Iterate the directory, deleting all contents. */ { /* Begin finding. */ WIN32_FIND_DATAW fd; const auto handle = ::FindFirstFileW(cur_path_buf.get(), std::addressof(fd)); R_UNLESS(handle != INVALID_HANDLE_VALUE, ConvertLastErrorToResult()); ON_SCOPE_EXIT { ::FindClose(handle); }; /* Clear the path from <path>\\* to path\\ */ wchar_t * const dst = cur_path_buf.get() + path_len + 1; *dst = 0; /* Loop files. */ while (::FindNextFileW(handle, std::addressof(fd))) { /* Skip . and .. */ if (::wcsncmp(fd.cFileName, L"..", 3) == 0 || ::wcsncmp(fd.cFileName, L".", 2) == 0) { continue; } /* Copy the current filename to our working path. */ ::wcscpy(dst, fd.cFileName); if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { /* If a directory, delete it recursively. */ R_TRY(this->DeleteDirectoryRecursivelyInternal(cur_path_buf.get(), true)); } else { /* If a file, just delete it. */ auto delete_file = [&]() -> Result { R_UNLESS(::DeleteFileW(cur_path_buf.get()), ConvertLastErrorToResult()); R_SUCCEED(); }; R_TRY(fssystem::RetryToAvoidTargetLocked(delete_file)); R_TRY(WaitDeletionCompletion(cur_path_buf.get())); } } /* Check that we stopped iterating because we ran out of files. */ R_UNLESS(::GetLastError() == ERROR_NO_MORE_FILES, ConvertLastErrorToResult()); } /* If we should, delete the top level directory. */ if (delete_top) { auto delete_impl = [&] () -> Result { R_UNLESS(::RemoveDirectoryW(path), ConvertLastErrorToResult()); R_SUCCEED(); }; /* Perform the delete. */ R_TRY(fssystem::RetryToAvoidTargetLocked(delete_impl)); /* Wait for the deletion to complete. */ R_TRY(WaitDeletionCompletion(path)); } } #else { /* Get the path length. */ const auto path_len = std::strlen(path); /* Allocate a temporary buffer. */ NativePathBuffer cur_path_buf = fs::impl::MakeUnique<NativeCharacterType[]>(path_len + PATH_MAX); R_UNLESS(cur_path_buf.get() != nullptr, fs::ResultAllocationMemoryFailedMakeUnique()); /* Copy the path into the temporary buffer. */ std::memcpy(cur_path_buf.get(), path, path_len); auto ofs = path_len; if (cur_path_buf.get()[ofs - 1] != '/') { cur_path_buf.get()[ofs++] = '/'; } /* Iterate the directory, deleting all contents. */ { /* Open the directory. */ const auto handle = RetryForEIntr([&] () ALWAYS_INLINE_LAMBDA { return ::open(path, O_RDONLY | O_DIRECTORY); }); R_UNLESS(handle >= 0, ConvertErrnoToResult(ErrnoSource_OpenDirectory)); ON_SCOPE_EXIT { CloseFileDescriptor(handle); }; #if defined(ATMOSPHERE_OS_LINUX) char buf[1_KB]; #else char buf[2_KB]; uintptr_t basep = 0; #endif NativeDirectoryEntryType *ent = nullptr; static_assert(sizeof(*ent) <= sizeof(buf)); while (true) { /* Read next entries. */ #if defined (ATMOSPHERE_OS_LINUX) const auto nread = ::syscall(SYS_getdents64, handle, buf, sizeof(buf)); #elif defined(ATMOSPHERE_OS_MACOS) const auto nread = ::__getdirentries64(handle, buf, sizeof(buf), std::addressof(basep)); #else #error "Unknown OS to read from directory FD" #endif R_UNLESS(nread >= 0, ConvertErrnoToResult(ErrnoSource_GetDents)); /* If we read nothing, we've hit the end of the directory. */ if (nread == 0) { break; } /* Iterate received entries. */ for (auto pos = 0; pos < nread; pos += ent->d_reclen) { /* Get the entry. */ ent = reinterpret_cast<NativeDirectoryEntryType *>(buf + pos); /* Skip . and .. */ if (std::strcmp(ent->d_name, ".") == 0 || std::strcmp(ent->d_name, "..") == 0) { continue; } /* Get the entry name length. */ const int e_len = std::strlen(ent->d_name); std::memcpy(cur_path_buf.get() + ofs, ent->d_name, e_len + 1); /* Get the dir type. */ const auto d_type = ent->d_type; if (d_type == DT_DIR) { /* If a directory, recursively delete it. */ R_TRY(this->DeleteDirectoryRecursivelyInternal(cur_path_buf.get(), true)); } else { /* If a file, just delete it. */ auto delete_file = [&]() -> Result { const auto res = ::unlink(cur_path_buf.get()); R_UNLESS(res >= 0, ConvertErrnoToResult(ErrnoSource_Unlink)); R_SUCCEED(); }; R_TRY(fssystem::RetryToAvoidTargetLocked(delete_file)); R_TRY(WaitDeletionCompletion(cur_path_buf.get())); } } } } /* If we should, delete the top level directory. */ if (delete_top) { auto delete_impl = [&] () -> Result { R_UNLESS(::rmdir(path) == 0, ConvertErrnoToResult(ErrnoSource_Rmdir)); R_SUCCEED(); }; /* Perform the delete. */ R_TRY(fssystem::RetryToAvoidTargetLocked(delete_impl)); /* Wait for the deletion to complete. */ R_TRY(WaitDeletionCompletion(path)); } } #endif R_SUCCEED(); } Result LocalFileSystem::DoCreateFile(const fs::Path &path, s64 size, int flags) { AMS_UNUSED(flags); /* Resolve the path. */ NativePathBuffer native_path; R_TRY(this->ResolveFullPath(std::addressof(native_path), path, MaxFilePathLength, 0, false)); /* Create the file. */ #if defined(ATMOSPHERE_OS_WINDOWS) { /* Get handle to created file. */ const auto handle = ::CreateFileW(native_path.get(), GENERIC_WRITE, 0, nullptr, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr); if (handle == INVALID_HANDLE_VALUE) { /* If we failed because of target locked, it may be the case that the path already exists as a directory. */ R_TRY_CATCH(ConvertLastErrorToResult()) { R_CATCH(fs::ResultTargetLocked) { /* Get the file attributes. */ const auto attr = ::GetFileAttributesW(native_path.get()); /* Check they're valid. */ R_UNLESS(attr != INVALID_FILE_ATTRIBUTES, R_CURRENT_RESULT); /* Check that they specify a directory. */ R_UNLESS((attr & FILE_ATTRIBUTE_DIRECTORY) != 0, R_CURRENT_RESULT); /* The path is an existing directory. */ R_THROW(fs::ResultPathAlreadyExists()); } } R_END_TRY_CATCH; } ON_RESULT_FAILURE { ::DeleteFileW(native_path.get()); }; ON_SCOPE_EXIT { ::CloseHandle(handle); }; /* Set the file as sparse. */ { DWORD dummy; ::DeviceIoControl(handle, FSCTL_SET_SPARSE, nullptr, 0, nullptr, 0, std::addressof(dummy), nullptr); } /* Set the file size. */ if (size > 0) { R_TRY(SetFileSizeImpl(handle, size)); } } #else { /* Create the file. */ const auto handle = RetryForEIntr([&] () ALWAYS_INLINE_LAMBDA -> int { return ::open(native_path.get(), O_WRONLY | O_CREAT | O_EXCL, 0666); }); R_UNLESS(handle >= 0, ConvertErrnoToResult(ErrnoSource_CreateFile)); ON_RESULT_FAILURE { ::unlink(native_path.get()); }; ON_SCOPE_EXIT { CloseFileDescriptor(handle); }; /* Set the file as sparse. */ /* TODO: How do you do this on macos/linux? */ /* Set the file size. */ if (size > 0) { R_TRY(SetFileSizeImpl(handle, size)); } } #endif R_SUCCEED(); } Result LocalFileSystem::DoDeleteFile(const fs::Path &path) { /* Resolve the path. */ NativePathBuffer native_path; R_TRY(this->ResolveFullPath(std::addressof(native_path), path, MaxFilePathLength, 0, true)); /* Delete the file, retrying on target locked. */ auto delete_impl = [&] () -> Result { #if defined(ATMOSPHERE_OS_WINDOWS) { /* Try to delete the file directly. */ R_SUCCEED_IF(::DeleteFileW(native_path.get())); /* Convert the last error to a result. */ const auto last_error_result = ConvertLastErrorToResult(); /* Check if access denied; it may indicate we tried to open a directory. */ R_UNLESS(::GetLastError() == ERROR_ACCESS_DENIED, last_error_result); /* Check if we tried to open a directory. */ fs::DirectoryEntryType type{}; R_TRY(GetEntryTypeImpl(std::addressof(type), native_path.get())); /* If the type is anything other than directory, perform generic result conversion. */ R_UNLESS(type == fs::DirectoryEntryType_Directory, last_error_result); /* Return path not found, for trying to open a file as a directory. */ R_THROW(fs::ResultPathNotFound()); } #else { /* If on macOS, we need to check if the path is a directory before trying to unlink it. */ /* This is because unlink succeeds on directories when executing as superuser. */ #if defined(ATMOSPHERE_OS_MACOS) { /* Check if we tried to open a directory. */ fs::DirectoryEntryType type; R_TRY(GetEntryTypeImpl(std::addressof(type), native_path.get())); R_UNLESS(type == fs::DirectoryEntryType_File, fs::ResultPathNotFound()); } #endif /* Delete the file. */ const auto res = ::unlink(native_path.get()); R_UNLESS(res >= 0, ConvertErrnoToResult(ErrnoSource_Unlink)); } #endif R_SUCCEED(); }; /* Perform the delete. */ R_TRY(fssystem::RetryToAvoidTargetLocked(delete_impl)); /* Wait for the deletion to complete. */ R_RETURN(WaitDeletionCompletion(native_path.get())); } Result LocalFileSystem::DoCreateDirectory(const fs::Path &path) { /* Check for path validity. */ R_UNLESS(path != "/", fs::ResultPathNotFound()); R_UNLESS(path != ".", fs::ResultPathNotFound()); /* Resolve the path. */ NativePathBuffer native_path; R_TRY(this->ResolveFullPath(std::addressof(native_path), path, MaxDirectoryPathLength, 0, false)); /* Create the directory. */ #if defined(ATMOSPHERE_OS_WINDOWS) R_UNLESS(::CreateDirectoryW(native_path.get(), nullptr), ConvertLastErrorToResult()); #else R_UNLESS(::mkdir(native_path.get(), 0777) == 0, ConvertErrnoToResult(ErrnoSource_Mkdir)); #endif R_SUCCEED(); } Result LocalFileSystem::DoDeleteDirectory(const fs::Path &path) { /* Guard against deletion of raw drive. */ #if defined(ATMOSPHERE_OS_WINDOWS) R_UNLESS(!fs::IsWindowsDriveRootPath(path), fs::ResultDirectoryNotDeletable()); #else /* TODO: Linux/macOS? */ #endif /* Resolve the path. */ NativePathBuffer native_path; R_TRY(this->ResolveFullPath(std::addressof(native_path), path, MaxFilePathLength, 0, true)); /* Delete the directory, retrying on target locked. */ auto delete_impl = [&] () -> Result { #if defined(ATMOSPHERE_OS_WINDOWS) R_UNLESS(::RemoveDirectoryW(native_path.get()), ConvertLastErrorToResult()); #else R_UNLESS(::rmdir(native_path.get()) == 0, ConvertErrnoToResult(ErrnoSource_Rmdir)); #endif R_SUCCEED(); }; /* Perform the delete. */ R_TRY(fssystem::RetryToAvoidTargetLocked(delete_impl)); /* Wait for the deletion to complete. */ R_RETURN(WaitDeletionCompletion(native_path.get())); } Result LocalFileSystem::DoDeleteDirectoryRecursively(const fs::Path &path) { /* Guard against deletion of raw drive. */ #if defined(ATMOSPHERE_OS_WINDOWS) R_UNLESS(!fs::IsWindowsDriveRootPath(path), fs::ResultDirectoryNotDeletable()); #else /* TODO: Linux/macOS? */ #endif /* Resolve the path. */ NativePathBuffer native_path; R_TRY(this->ResolveFullPath(std::addressof(native_path), path, MaxFilePathLength, 0, true)); /* Delete the directory. */ R_RETURN(this->DeleteDirectoryRecursivelyInternal(native_path.get(), true)); } Result LocalFileSystem::DoRenameFile(const fs::Path &old_path, const fs::Path &new_path) { /* Resolve the old path. */ NativePathBuffer native_old_path; R_TRY(this->ResolveFullPath(std::addressof(native_old_path), old_path, MaxFilePathLength, 0, true)); /* Resolve the new path. */ NativePathBuffer native_new_path; R_TRY(this->ResolveFullPath(std::addressof(native_new_path), new_path, MaxFilePathLength, 0, false)); /* Check that the old path is a file. */ fs::DirectoryEntryType type{}; R_TRY(GetEntryTypeImpl(std::addressof(type), native_old_path.get())); R_UNLESS(type == fs::DirectoryEntryType_File, fs::ResultPathNotFound()); /* Perform the rename. */ auto rename_impl = [&]() -> Result { #if defined(ATMOSPHERE_OS_WINDOWS) if (!::MoveFileW(native_old_path.get(), native_new_path.get())) { R_TRY_CATCH(ConvertLastErrorToResult()) { R_CATCH(fs::ResultTargetLocked) { /* If we're performing a self rename, succeed. */ R_SUCCEED_IF(::wcscmp(native_old_path.get(), native_new_path.get()) == 0); /* Otherwise, check if the new path already exists. */ const auto attr = ::GetFileAttributesW(native_new_path.get()); R_UNLESS(attr == INVALID_FILE_ATTRIBUTES, fs::ResultPathAlreadyExists()); /* Return the original result. */ R_THROW(R_CURRENT_RESULT); } } R_END_TRY_CATCH; } #else { /* ::rename() will destroy an existing file at new path...so check for that case ahead of time. */ { struct stat st; R_UNLESS(::stat(native_new_path.get(), std::addressof(st)) < 0, fs::ResultPathAlreadyExists()); } /* Rename the file. */ R_UNLESS(::rename(native_old_path.get(), native_new_path.get()) == 0, ConvertErrnoToResult(ErrnoSource_RenameFile)); } #endif R_SUCCEED(); }; R_RETURN(fssystem::RetryToAvoidTargetLocked(rename_impl)); } Result LocalFileSystem::DoRenameDirectory(const fs::Path &old_path, const fs::Path &new_path) { /* Resolve the old path. */ NativePathBuffer native_old_path; R_TRY(this->ResolveFullPath(std::addressof(native_old_path), old_path, MaxDirectoryPathLength, 0, true)); /* Resolve the new path. */ NativePathBuffer native_new_path; R_TRY(this->ResolveFullPath(std::addressof(native_new_path), new_path, MaxDirectoryPathLength, 0, false)); /* Check that the old path is a file. */ fs::DirectoryEntryType type{}; R_TRY(GetEntryTypeImpl(std::addressof(type), native_old_path.get())); R_UNLESS(type == fs::DirectoryEntryType_Directory, fs::ResultPathNotFound()); /* Perform the rename. */ auto rename_impl = [&]() -> Result { #if defined(ATMOSPHERE_OS_WINDOWS) if (!::MoveFileW(native_old_path.get(), native_new_path.get())) { R_TRY_CATCH(ConvertLastErrorToResult()) { R_CATCH(fs::ResultTargetLocked) { /* If we're performing a self rename, succeed. */ R_SUCCEED_IF(::wcscmp(native_old_path.get(), native_new_path.get()) == 0); /* Otherwise, check if the new path already exists. */ const auto attr = ::GetFileAttributesW(native_new_path.get()); R_UNLESS(attr == INVALID_FILE_ATTRIBUTES, fs::ResultPathAlreadyExists()); /* Return the original result. */ R_THROW(R_CURRENT_RESULT); } } R_END_TRY_CATCH; } #else { /* ::rename() will overwrite an existing empty directory at the target, so check for that ahead of time. */ { struct stat st; R_UNLESS(::stat(native_new_path.get(), std::addressof(st)) < 0, fs::ResultPathAlreadyExists()); } /* Rename the directory. */ R_UNLESS(::rename(native_old_path.get(), native_new_path.get()) == 0, ConvertErrnoToResult(ErrnoSource_RenameDirectory)); } #endif R_SUCCEED(); }; R_RETURN(fssystem::RetryToAvoidTargetLocked(rename_impl)); } Result LocalFileSystem::DoGetEntryType(fs::DirectoryEntryType *out, const fs::Path &path) { /* Resolve the path. */ NativePathBuffer native_path; R_TRY(this->ResolveFullPath(std::addressof(native_path), path, MaxFilePathLength, 0, true)); /* Get the entry type. */ R_RETURN(GetEntryTypeImpl(out, native_path.get())); } Result LocalFileSystem::DoOpenFile(std::unique_ptr<fs::fsa::IFile> *out_file, const fs::Path &path, fs::OpenMode mode) { /* Resolve the path. */ NativePathBuffer native_path; R_TRY(this->ResolveFullPath(std::addressof(native_path), path, MaxFilePathLength, 0, true)); /* Open the file, retrying on target locked. */ auto open_impl = [&] () -> Result { #if defined(ATMOSPHERE_OS_WINDOWS) /* Open a windows file handle. */ const DWORD desired_access = ((mode & fs::OpenMode_Read) ? GENERIC_READ : 0) | ((mode & fs::OpenMode_Write) ? GENERIC_WRITE : 0); const auto file_handle = ::CreateFileW(native_path.get(), desired_access, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, nullptr); if (file_handle == INVALID_HANDLE_VALUE) { /* Convert the last error to a result. */ const auto last_error_result = ConvertLastErrorToResult(); /* Check if access denied; it may indicate we tried to open a directory. */ R_UNLESS(::GetLastError() == ERROR_ACCESS_DENIED, last_error_result); /* Check if we tried to open a directory. */ fs::DirectoryEntryType type{}; R_TRY(GetEntryTypeImpl(std::addressof(type), native_path.get())); /* If the type isn't file, return path not found. */ R_UNLESS(type == fs::DirectoryEntryType_File, fs::ResultPathNotFound()); /* Return the error we encountered earlier. */ R_THROW(last_error_result); } ON_RESULT_FAILURE { ::CloseHandle(file_handle); }; #else const bool is_read = (mode & fs::OpenMode_Read); const bool is_write = (mode & fs::OpenMode_Write); int file_handle = RetryForEIntr([&] () ALWAYS_INLINE_LAMBDA { return ::open(native_path.get(), (is_read && is_write) ? (O_RDWR) : (is_write ? (O_WRONLY) : (is_read ? (O_RDONLY) : (0)))); }); R_UNLESS(file_handle >= 0, ConvertErrnoToResult(ErrnoSource_OpenFile)); ON_RESULT_FAILURE { CloseFileDescriptor(file_handle); }; #endif /* Create a new local file. */ auto file = std::make_unique<LocalFile>(file_handle, mode); R_UNLESS(file != nullptr, fs::ResultAllocationMemoryFailedInLocalFileSystemA()); /* Set the output file. */ *out_file = std::move(file); R_SUCCEED(); }; R_RETURN(fssystem::RetryToAvoidTargetLocked(open_impl)); } Result LocalFileSystem::DoOpenDirectory(std::unique_ptr<fs::fsa::IDirectory> *out_dir, const fs::Path &path, fs::OpenDirectoryMode mode) { /* Resolve the path. */ NativePathBuffer native_path; R_TRY(this->ResolveFullPath(std::addressof(native_path), path, MaxFilePathLength, 3, true)); /* Open the directory, retrying on target locked. */ auto open_impl = [&] () -> Result { #if defined(ATMOSPHERE_OS_WINDOWS) /* Open a handle file handle. */ const auto dir_handle = ::CreateFileW(native_path.get(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, nullptr); R_UNLESS(dir_handle != INVALID_HANDLE_VALUE, ConvertLastErrorToResult()); ON_RESULT_FAILURE { ::CloseHandle(dir_handle); }; /* Check that we tried to open a directory. */ fs::DirectoryEntryType type{}; R_TRY(GetEntryTypeImpl(std::addressof(type), native_path.get())); /* If the type isn't directory, return path not found. */ R_UNLESS(type == fs::DirectoryEntryType_Directory, fs::ResultPathNotFound()); /* Fix up the path for us to perform a windows search. */ const auto native_len = ::wcslen(native_path.get()); const bool has_sep = native_len > 0 && native_path[native_len - 1] == '\\'; if (has_sep) { native_path[native_len + 0] = '*'; native_path[native_len + 1] = 0; } else { native_path[native_len + 0] = '\\'; native_path[native_len + 1] = '*'; native_path[native_len + 2] = 0; } #else /* Open the directory. */ const auto dir_handle = RetryForEIntr([&] () ALWAYS_INLINE_LAMBDA { return ::open(native_path.get(), O_RDONLY | O_DIRECTORY); }); R_UNLESS(dir_handle >= 0, ConvertErrnoToResult(ErrnoSource_OpenDirectory)); ON_RESULT_FAILURE { CloseFileDescriptor(dir_handle); }; #endif /* Create a new local directory. */ auto dir = std::make_unique<LocalDirectory>(dir_handle, mode, std::move(native_path)); R_UNLESS(dir != nullptr, fs::ResultAllocationMemoryFailedInLocalFileSystemB()); /* Set the output directory. */ *out_dir = std::move(dir); R_SUCCEED(); }; R_RETURN(fssystem::RetryToAvoidTargetLocked(open_impl)); } Result LocalFileSystem::DoCommit() { R_SUCCEED(); } Result LocalFileSystem::DoGetFreeSpaceSize(s64 *out, const fs::Path &path) { s64 dummy; R_RETURN(this->DoGetDiskFreeSpace(out, std::addressof(dummy), std::addressof(dummy), path)); } Result LocalFileSystem::DoGetTotalSpaceSize(s64 *out, const fs::Path &path) { s64 dummy; R_RETURN(this->DoGetDiskFreeSpace(std::addressof(dummy), out, std::addressof(dummy), path)); } Result LocalFileSystem::DoCleanDirectoryRecursively(const fs::Path &path) { /* Resolve the path. */ NativePathBuffer native_path; R_TRY(this->ResolveFullPath(std::addressof(native_path), path, MaxFilePathLength, 0, true)); /* Delete the directory. */ R_RETURN(this->DeleteDirectoryRecursivelyInternal(native_path.get(), false)); } Result LocalFileSystem::DoGetFileTimeStampRaw(fs::FileTimeStampRaw *out, const fs::Path &path) { /* Resolve the path. */ NativePathBuffer native_path; R_TRY(this->ResolveFullPath(std::addressof(native_path), path, MaxFilePathLength, 0, true)); /* Get the file timestamp. */ #if defined(ATMOSPHERE_OS_WINDOWS) { /* Get the file attributes. */ WIN32_FILE_ATTRIBUTE_DATA attr; R_UNLESS(::GetFileAttributesExW(native_path.get(), GetFileExInfoStandard, std::addressof(attr)), ConvertLastErrorToResult()); /* Check that the file isn't a directory. */ R_UNLESS((attr.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0, fs::ResultPathNotFound()); /* Decode the FILETIME values. */ const s64 create = static_cast<s64>(static_cast<u64>(attr.ftCreationTime.dwLowDateTime ) | (static_cast<u64>(attr.ftCreationTime.dwHighDateTime ) << BITSIZEOF(attr.ftCreationTime.dwLowDateTime ))); const s64 access = static_cast<s64>(static_cast<u64>(attr.ftLastAccessTime.dwLowDateTime) | (static_cast<u64>(attr.ftLastAccessTime.dwHighDateTime) << BITSIZEOF(attr.ftLastAccessTime.dwLowDateTime))); const s64 modify = static_cast<s64>(static_cast<u64>(attr.ftLastWriteTime.dwLowDateTime ) | (static_cast<u64>(attr.ftLastWriteTime.dwHighDateTime ) << BITSIZEOF(attr.ftLastWriteTime.dwLowDateTime ))); /* Set the output timestamps. */ if (m_use_posix_time) { out->create = ConvertWindowsTimeToPosixTime(create); out->access = ConvertWindowsTimeToPosixTime(access); out->modify = ConvertWindowsTimeToPosixTime(modify); } else { out->create = create; out->access = access; out->modify = modify; } /* We're not using local timestamps. */ out->is_local_time = false; } #else { /* Get the file stats. */ struct stat st; R_UNLESS(::stat(native_path.get(), std::addressof(st)) == 0, ConvertErrnoToResult(ErrnoSource_Stat)); /* Check that the path isn't a directory. */ R_UNLESS(!(S_ISDIR(st.st_mode)), fs::ResultPathNotFound()); /* Set the output timestamps. */ #if defined(ATMOSPHERE_OS_LINUX) if (m_use_posix_time) { out->create = st.st_ctim.tv_sec; out->access = st.st_atim.tv_sec; out->modify = st.st_mtim.tv_sec; } else { out->create = ConvertPosixTimeToWindowsTime(st.st_ctim.tv_sec, st.st_ctim.tv_nsec); out->access = ConvertPosixTimeToWindowsTime(st.st_atim.tv_sec, st.st_atim.tv_nsec); out->modify = ConvertPosixTimeToWindowsTime(st.st_mtim.tv_sec, st.st_mtim.tv_nsec); } #else if (m_use_posix_time) { out->create = st.st_ctimespec.tv_sec; out->access = st.st_atimespec.tv_sec; out->modify = st.st_mtimespec.tv_sec; } else { out->create = ConvertPosixTimeToWindowsTime(st.st_ctimespec.tv_sec, st.st_ctimespec.tv_nsec); out->access = ConvertPosixTimeToWindowsTime(st.st_atimespec.tv_sec, st.st_atimespec.tv_nsec); out->modify = ConvertPosixTimeToWindowsTime(st.st_mtimespec.tv_sec, st.st_mtimespec.tv_nsec); } #endif /* We're not using local timestamps. */ out->is_local_time = false; } #endif R_SUCCEED(); } Result LocalFileSystem::DoQueryEntry(char *dst, size_t dst_size, const char *src, size_t src_size, fs::fsa::QueryId query, const fs::Path &path) { AMS_UNUSED(dst, dst_size, src, src_size, query, path); R_THROW(fs::ResultUnsupportedOperation()); } Result LocalFileSystem::DoCommitProvisionally(s64 counter) { AMS_UNUSED(counter); R_SUCCEED(); } Result LocalFileSystem::DoRollback() { R_SUCCEED(); } } #endif
81,703
C++
.cpp
1,491
37.749162
232
0.515864
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,373
fssystem_integrity_romfs_storage.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssystem/fssystem_integrity_romfs_storage.cpp
/* * Copyright (c) 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 { Result IntegrityRomFsStorage::Initialize(HierarchicalIntegrityVerificationInformation level_hash_info, Hash master_hash, HierarchicalIntegrityVerificationStorage::HierarchicalStorageInformation storage_info, fs::IBufferManager *bm, int max_data_cache_entries, int max_hash_cache_entries, s8 buffer_level, IHash256GeneratorFactory *hgf) { /* Validate preconditions. */ AMS_ASSERT(bm != nullptr); /* Set master hash. */ m_master_hash = master_hash; m_master_hash_storage = std::make_unique<fs::MemoryStorage>(std::addressof(m_master_hash), sizeof(Hash)); R_UNLESS(m_master_hash_storage != nullptr, fs::ResultAllocationMemoryFailedInIntegrityRomFsStorageA()); /* Set the master hash storage. */ storage_info[0] = fs::SubStorage(m_master_hash_storage.get(), 0, sizeof(Hash)); /* Set buffers. */ for (size_t i = 0; i < util::size(m_buffers.buffers); ++i) { m_buffers.buffers[i] = bm; } /* Initialize our integrity storage. */ R_RETURN(m_integrity_storage.Initialize(level_hash_info, storage_info, std::addressof(m_buffers), hgf, false, std::addressof(m_mutex), max_data_cache_entries, max_hash_cache_entries, buffer_level, false, false)); } void IntegrityRomFsStorage::Finalize() { m_integrity_storage.Finalize(); } }
2,050
C++
.cpp
37
50.027027
341
0.714214
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,374
fssystem_partition_file_system_meta.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssystem/fssystem_partition_file_system_meta.cpp
/* * Copyright (c) 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 { template <typename Format> struct PartitionFileSystemMetaCore<Format>::PartitionFileSystemHeader { char signature[sizeof(Format::VersionSignature)]; s32 entry_count; u32 name_table_size; u32 reserved; }; static_assert(util::is_pod<PartitionFileSystemMeta::PartitionFileSystemHeader>::value); static_assert(sizeof(PartitionFileSystemMeta::PartitionFileSystemHeader) == 0x10); template <typename Format> PartitionFileSystemMetaCore<Format>::~PartitionFileSystemMetaCore() { this->DeallocateBuffer(); } template <typename Format> Result PartitionFileSystemMetaCore<Format>::Initialize(fs::IStorage *storage, MemoryResource *allocator) { /* Validate preconditions. */ AMS_ASSERT(allocator != nullptr); /* Determine the meta data size. */ R_TRY(this->QueryMetaDataSize(std::addressof(m_meta_data_size), storage)); /* Deallocate any old meta buffer and allocate a new one. */ this->DeallocateBuffer(); m_allocator = allocator; m_buffer = static_cast<char *>(m_allocator->Allocate(m_meta_data_size)); R_UNLESS(m_buffer != nullptr, fs::ResultAllocationMemoryFailedInPartitionFileSystemMetaA()); /* Perform regular initialization. */ R_RETURN(this->Initialize(storage, m_buffer, m_meta_data_size)); } template <typename Format> Result PartitionFileSystemMetaCore<Format>::Initialize(fs::IStorage *storage, void *meta, size_t meta_size) { /* Validate size for header. */ R_UNLESS(meta_size >= sizeof(PartitionFileSystemHeader), fs::ResultInvalidSize()); /* Read the header. */ R_TRY(storage->Read(0, meta, sizeof(PartitionFileSystemHeader))); /* Set and validate the header. */ m_header = reinterpret_cast<PartitionFileSystemHeader *>(meta); R_UNLESS(crypto::IsSameBytes(m_header->signature, Format::VersionSignature, sizeof(Format::VersionSignature)), typename Format::ResultSignatureVerificationFailed()); /* Setup entries and name table. */ const size_t entries_size = m_header->entry_count * sizeof(typename Format::PartitionEntry); m_entries = reinterpret_cast<PartitionEntry *>(static_cast<u8 *>(meta) + sizeof(PartitionFileSystemHeader)); m_name_table = static_cast<char *>(meta) + sizeof(PartitionFileSystemHeader) + entries_size; /* Validate size for header + entries + name table. */ R_UNLESS(meta_size >= sizeof(PartitionFileSystemHeader) + entries_size + m_header->name_table_size, fs::ResultInvalidSize()); /* Read entries and name table. */ R_TRY(storage->Read(sizeof(PartitionFileSystemHeader), m_entries, entries_size + m_header->name_table_size)); /* Mark as initialized. */ m_initialized = true; R_SUCCEED(); } template <typename Format> void PartitionFileSystemMetaCore<Format>::DeallocateBuffer() { if (m_buffer != nullptr) { AMS_ABORT_UNLESS(m_allocator != nullptr); m_allocator->Deallocate(m_buffer, m_meta_data_size); m_buffer = nullptr; } } template <typename Format> const typename Format::PartitionEntry *PartitionFileSystemMetaCore<Format>::GetEntry(s32 index) const { if (m_initialized && 0 <= index && index < static_cast<s32>(m_header->entry_count)) { return std::addressof(m_entries[index]); } return nullptr; } template <typename Format> s32 PartitionFileSystemMetaCore<Format>::GetEntryCount() const { if (m_initialized) { return m_header->entry_count; } return 0; } template <typename Format> s32 PartitionFileSystemMetaCore<Format>::GetEntryIndex(const char *name) const { /* Fail if not initialized. */ if (!m_initialized) { return 0; } for (s32 i = 0; i < static_cast<s32>(m_header->entry_count); i++) { const auto &entry = m_entries[i]; /* Name offset is invalid. */ if (entry.name_offset >= m_header->name_table_size) { return 0; } /* Compare to input name. */ const s32 max_name_len = m_header->name_table_size - entry.name_offset; if (std::strncmp(std::addressof(m_name_table[entry.name_offset]), name, max_name_len) == 0) { return i; } } /* Not found. */ return -1; } template <typename Format> const char *PartitionFileSystemMetaCore<Format>::GetEntryName(s32 index) const { if (m_initialized && index < static_cast<s32>(m_header->entry_count)) { return std::addressof(m_name_table[this->GetEntry(index)->name_offset]); } return nullptr; } template <typename Format> size_t PartitionFileSystemMetaCore<Format>::GetHeaderSize() const { return sizeof(PartitionFileSystemHeader); } template <typename Format> size_t PartitionFileSystemMetaCore<Format>::GetMetaDataSize() const { return m_meta_data_size; } template <typename Format> Result PartitionFileSystemMetaCore<Format>::QueryMetaDataSize(size_t *out_size, fs::IStorage *storage) { /* Read and validate the header. */ PartitionFileSystemHeader header; R_TRY(storage->Read(0, std::addressof(header), sizeof(PartitionFileSystemHeader))); R_UNLESS(crypto::IsSameBytes(std::addressof(header), Format::VersionSignature, sizeof(Format::VersionSignature)), typename Format::ResultSignatureVerificationFailed()); /* Output size. */ *out_size = sizeof(PartitionFileSystemHeader) + header.entry_count * sizeof(typename Format::PartitionEntry) + header.name_table_size; R_SUCCEED(); } template class PartitionFileSystemMetaCore<impl::PartitionFileSystemFormat>; template class PartitionFileSystemMetaCore<impl::Sha256PartitionFileSystemFormat>; Result Sha256PartitionFileSystemMeta::Initialize(fs::IStorage *base_storage, MemoryResource *allocator, const void *hash, size_t hash_size, util::optional<u8> suffix) { /* Ensure preconditions. */ R_UNLESS(hash_size == crypto::Sha256Generator::HashSize, fs::ResultPreconditionViolation()); /* Get metadata size. */ R_TRY(QueryMetaDataSize(std::addressof(m_meta_data_size), base_storage)); /* Ensure we have no buffer. */ this->DeallocateBuffer(); /* Set allocator and allocate buffer. */ m_allocator = allocator; m_buffer = static_cast<char *>(m_allocator->Allocate(m_meta_data_size)); R_UNLESS(m_buffer != nullptr, fs::ResultAllocationMemoryFailedInPartitionFileSystemMetaB()); /* Read metadata. */ R_TRY(base_storage->Read(0, m_buffer, m_meta_data_size)); /* Calculate hash. */ char calc_hash[crypto::Sha256Generator::HashSize]; { crypto::Sha256Generator generator; generator.Initialize(); generator.Update(m_buffer, m_meta_data_size); if (suffix) { u8 suffix_val = *suffix; generator.Update(std::addressof(suffix_val), 1); } generator.GetHash(calc_hash, sizeof(calc_hash)); } /* Ensure hash is valid. */ R_UNLESS(crypto::IsSameBytes(hash, calc_hash, sizeof(calc_hash)), fs::ResultSha256PartitionHashVerificationFailed()); /* Give access to Format */ using Format = impl::Sha256PartitionFileSystemFormat; /* Set header. */ m_header = reinterpret_cast<PartitionFileSystemHeader *>(m_buffer); R_UNLESS(crypto::IsSameBytes(m_header->signature, Format::VersionSignature, sizeof(Format::VersionSignature)), typename Format::ResultSignatureVerificationFailed()); /* Validate size for entries and name table. */ const size_t entries_size = m_header->entry_count * sizeof(typename Format::PartitionEntry); R_UNLESS(m_meta_data_size >= sizeof(PartitionFileSystemHeader) + entries_size + m_header->name_table_size, fs::ResultInvalidSha256PartitionMetaDataSize()); /* Set entries and name table. */ m_entries = reinterpret_cast<PartitionEntry *>(m_buffer + sizeof(PartitionFileSystemHeader)); m_name_table = m_buffer + sizeof(PartitionFileSystemHeader) + entries_size; /* We initialized. */ m_initialized = true; R_SUCCEED(); } }
9,199
C++
.cpp
178
43.47191
176
0.671381
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,375
fssystem_file_system_proxy_api.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssystem/fssystem_file_system_proxy_api.cpp
/* * Copyright (c) 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 "../fssrv/impl/fssrv_program_registry_manager.hpp" namespace ams::fssystem { /* TODO: All of this should really be inside fs process, but ams.mitm wants it to. */ /* How should we handle this? */ namespace { constexpr inline auto FileSystemProxyServerThreadCount = fssrv::FileSystemProxyServerActiveSessionCount; /* TODO: Heap sizes need to match FS, when this is FS in master rather than ams.mitm. */ /* Official FS has a 4.5 MB exp heap, a 6 MB buffer pool, an 8 MB device buffer manager heap, and a 14 MB buffer manager heap. */ /* We don't need so much memory for ams.mitm (as we're servicing a much more limited context). */ /* We'll give ourselves a 1.5 MB exp heap, a 1 MB buffer pool, a 1 MB device buffer manager heap, and a 1 MB buffer manager heap. */ /* These numbers are 1 MB less than signed-system-partition safe FS in all pools. */ constexpr size_t ExpHeapSize = 1_MB + 512_KB; constexpr size_t BufferPoolSize = 1_MB; constexpr size_t DeviceBufferSize = 1_MB; constexpr size_t BufferManagerHeapSize = 1_MB; constexpr size_t MaxCacheCount = 1024; constexpr size_t BlockSize = 16_KB; alignas(os::MemoryPageSize) constinit u8 g_exp_heap_buffer[ExpHeapSize]; constinit lmem::HeapHandle g_exp_heap_handle = nullptr; constinit fssrv::PeakCheckableMemoryResourceFromExpHeap g_exp_allocator(ExpHeapSize); void InitializeExpHeap() { if (g_exp_heap_handle == nullptr) { g_exp_heap_handle = lmem::CreateExpHeap(g_exp_heap_buffer, ExpHeapSize, lmem::CreateOption_ThreadSafe); AMS_ABORT_UNLESS(g_exp_heap_handle != nullptr); g_exp_allocator.SetHeapHandle(g_exp_heap_handle); } } void *AllocateForFileSystemProxy(size_t size) { AMS_ABORT_UNLESS(g_exp_heap_handle != nullptr); auto scoped_lock = g_exp_allocator.GetScopedLock(); void *p = lmem::AllocateFromExpHeap(g_exp_heap_handle, size); g_exp_allocator.OnAllocate(p, size); return p; } void DeallocateForFileSystemProxy(void *p, size_t size) { AMS_ABORT_UNLESS(g_exp_heap_handle != nullptr); auto scoped_lock = g_exp_allocator.GetScopedLock(); g_exp_allocator.OnDeallocate(p, size); lmem::FreeToExpHeap(g_exp_heap_handle, p); } alignas(os::MemoryPageSize) constinit u8 g_device_buffer[DeviceBufferSize] = {}; alignas(os::MemoryPageSize) constinit u8 g_buffer_pool[BufferPoolSize] = {}; constinit util::TypedStorage<mem::StandardAllocator> g_buffer_allocator = {}; constinit util::TypedStorage<fssrv::MemoryResourceFromStandardAllocator> g_allocator = {}; /* TODO: Nintendo uses os::SetMemoryHeapSize (svc::SetHeapSize) and os::AllocateMemoryBlock for the BufferManager heap. */ /* It's unclear how we should handle this in ams.mitm (especially hoping to reuse some logic for fs reimpl). */ /* Should we be doing the same(?) */ constinit util::TypedStorage<fssystem::FileSystemBufferManager> g_buffer_manager = {}; alignas(os::MemoryPageSize) constinit u8 g_buffer_manager_heap[BufferManagerHeapSize] = {}; /* FileSystem creators. */ constinit util::TypedStorage<fssrv::fscreator::RomFileSystemCreator> g_rom_fs_creator = {}; constinit util::TypedStorage<fssrv::fscreator::PartitionFileSystemCreator> g_partition_fs_creator = {}; constinit util::TypedStorage<fssrv::fscreator::StorageOnNcaCreator> g_storage_on_nca_creator = {}; constinit fssrv::fscreator::FileSystemCreatorInterfaces g_fs_creator_interfaces = {}; } void InitializeForFileSystemProxy() { /* TODO FS-REIMPL: Setup MainThreadStackUsageReporter. */ /* Register service context for main thread. */ fssystem::ServiceContext context; fssystem::RegisterServiceContext(std::addressof(context)); /* Initialize spl library. */ spl::InitializeForFs(); /* TODO FS-REIMPL: spl::SetIsAvailableAccessKeyHandler(fssrv::IsAvailableAccessKey) */ /* Determine whether we're prod or dev. */ bool is_prod = !spl::IsDevelopment(); bool is_development_function_enabled = spl::IsDevelopmentFunctionEnabled(); /* Set debug flags. */ fssrv::SetDebugFlagEnabled(is_development_function_enabled); /* Setup our crypto configuration. */ SetUpKekAccessKeys(is_prod); /* Setup our heap. */ InitializeExpHeap(); /* Initialize buffer allocator. */ util::ConstructAt(g_buffer_allocator, g_buffer_pool, BufferPoolSize); util::ConstructAt(g_allocator, GetPointer(g_buffer_allocator)); /* Set allocators. */ /* TODO FS-REIMPL: sf::SetGlobalDefaultMemoryResource() */ fs::SetAllocator(AllocateForFileSystemProxy, DeallocateForFileSystemProxy); fssystem::InitializeAllocator(AllocateForFileSystemProxy, DeallocateForFileSystemProxy); fssystem::InitializeAllocatorForSystem(AllocateForFileSystemProxy, DeallocateForFileSystemProxy); /* Initialize the buffer manager. */ /* TODO FS-REIMPL: os::AllocateMemoryBlock(...); */ util::ConstructAt(g_buffer_manager); GetReference(g_buffer_manager).Initialize(MaxCacheCount, reinterpret_cast<uintptr_t>(g_buffer_manager_heap), BufferManagerHeapSize, BlockSize); /* TODO FS-REIMPL: os::AllocateMemoryBlock(...); */ /* TODO FS-REIMPL: fssrv::storage::CreateDeviceAddressSpace(...); */ fssystem::InitializeBufferPool(reinterpret_cast<char *>(g_device_buffer), DeviceBufferSize); /* TODO FS-REIMPL: Create Pooled Threads/Stack Usage Reporter, fssystem::RegisterThreadPool. */ /* TODO FS-REIMPL: fssrv::GetFileSystemProxyServices(), some service creation. */ /* Initialize fs creators. */ /* TODO FS-REIMPL: Revise for accuracy. */ util::ConstructAt(g_rom_fs_creator, GetPointer(g_allocator)); util::ConstructAt(g_partition_fs_creator); util::ConstructAt(g_storage_on_nca_creator, GetPointer(g_allocator), *GetNcaCryptoConfiguration(is_prod), *GetNcaCompressionConfiguration(), GetPointer(g_buffer_manager), fs::impl::GetNcaHashGeneratorFactorySelector()); /* TODO FS-REIMPL: Initialize other creators. */ g_fs_creator_interfaces = { .rom_fs_creator = GetPointer(g_rom_fs_creator), .partition_fs_creator = GetPointer(g_partition_fs_creator), .storage_on_nca_creator = GetPointer(g_storage_on_nca_creator), }; /* TODO FS-REIMPL: Revise above for latest firmware, all the new Services creation. */ fssrv::ProgramRegistryServiceImpl program_registry_service(fssrv::ProgramRegistryServiceImpl::Configuration{}); fssrv::ProgramRegistryImpl::Initialize(std::addressof(program_registry_service)); /* TODO FS-REIMPL: Memory Report Creators, fssrv::SetMemoryReportCreator */ /* TODO FS-REIMPL: Sd Card detection, speed emulation. */ /* Initialize fssrv. TODO FS-REIMPL: More arguments, more actions taken. */ const fssrv::FileSystemProxyConfiguration config = { .m_fs_creator_interfaces = std::addressof(g_fs_creator_interfaces), .m_base_storage_service_impl = nullptr /* TODO */, .m_base_file_system_service_impl = nullptr /* TODO */, .m_nca_file_system_service_impl = nullptr /* TODO */, .m_save_data_file_system_service_impl = nullptr /* TODO */, .m_access_failure_management_service_impl = nullptr /* TODO */, .m_time_service_impl = nullptr /* TODO */, .m_status_report_service_impl = nullptr /* TODO */, .m_program_registry_service_impl = std::addressof(program_registry_service), .m_access_log_service_impl = nullptr /* TODO */, .m_debug_configuration_service_impl = nullptr /* TODO */, }; fssrv::InitializeForFileSystemProxy(config); /* TODO FS-REIMPL: GetFileSystemProxyServiceObject(), set current process, initialize global service object. */ /* Disable auto-abort in fs library code. */ fs::SetEnabledAutoAbort(false); /* Initialize fsp server. */ fssrv::InitializeFileSystemProxyServer(FileSystemProxyServerThreadCount); /* TODO FS-REIMPL: Cleanup calls. */ /* TODO FS-REIMPL: Spawn worker threads. */ /* TODO FS-REIMPL: Set mmc devices ready. */ /* TODO FS-REIMPL: fssrv::LoopPmEventServer(...); */ /* TODO FS-REIMPL: Wait/destroy threads. */ /* TODO FS-REIMPL: spl::Finalize(); */ } void InitializeForAtmosphereMitm() { /* Initialize spl library. */ spl::InitializeForFs(); /* TODO FS-REIMPL: spl::SetIsAvailableAccessKeyHandler(fssrv::IsAvailableAccessKey) */ /* Determine whether we're prod or dev. */ bool is_prod = !spl::IsDevelopment(); bool is_development_function_enabled = spl::IsDevelopmentFunctionEnabled(); /* Set debug flags. */ fssrv::SetDebugFlagEnabled(is_development_function_enabled); /* Setup our crypto configuration. */ SetUpKekAccessKeys(is_prod); /* Setup our heap. */ InitializeExpHeap(); /* Initialize buffer allocator. */ util::ConstructAt(g_buffer_allocator, g_buffer_pool, BufferPoolSize); util::ConstructAt(g_allocator, GetPointer(g_buffer_allocator)); /* Set allocators. */ /* TODO FS-REIMPL: sf::SetGlobalDefaultMemoryResource() */ fs::SetAllocator(AllocateForFileSystemProxy, DeallocateForFileSystemProxy); fssystem::InitializeAllocator(AllocateForFileSystemProxy, DeallocateForFileSystemProxy); fssystem::InitializeAllocatorForSystem(AllocateForFileSystemProxy, DeallocateForFileSystemProxy); /* Initialize the buffer manager. */ /* TODO FS-REIMPL: os::AllocateMemoryBlock(...); */ util::ConstructAt(g_buffer_manager); GetReference(g_buffer_manager).Initialize(MaxCacheCount, reinterpret_cast<uintptr_t>(g_buffer_manager_heap), BufferManagerHeapSize, BlockSize); /* TODO FS-REIMPL: os::AllocateMemoryBlock(...); */ /* TODO FS-REIMPL: fssrv::storage::CreateDeviceAddressSpace(...); */ fssystem::InitializeBufferPool(reinterpret_cast<char *>(g_device_buffer), DeviceBufferSize); /* TODO FS-REIMPL: Create Pooled Threads/Stack Usage Reporter, fssystem::RegisterThreadPool. */ /* TODO FS-REIMPL: fssrv::GetFileSystemProxyServices(), some service creation. */ /* Initialize fs creators. */ /* TODO FS-REIMPL: Revise for accuracy. */ util::ConstructAt(g_rom_fs_creator, GetPointer(g_allocator)); util::ConstructAt(g_partition_fs_creator); util::ConstructAt(g_storage_on_nca_creator, GetPointer(g_allocator), *GetNcaCryptoConfiguration(is_prod), *GetNcaCompressionConfiguration(), GetPointer(g_buffer_manager), fs::impl::GetNcaHashGeneratorFactorySelector()); /* TODO FS-REIMPL: Initialize other creators. */ g_fs_creator_interfaces = { .rom_fs_creator = GetPointer(g_rom_fs_creator), .partition_fs_creator = GetPointer(g_partition_fs_creator), .storage_on_nca_creator = GetPointer(g_storage_on_nca_creator), }; /* Initialize fssrv. TODO FS-REIMPL: More arguments, more actions taken. */ const fssrv::FileSystemProxyConfiguration config = { .m_fs_creator_interfaces = std::addressof(g_fs_creator_interfaces), .m_base_storage_service_impl = nullptr /* TODO */, .m_base_file_system_service_impl = nullptr /* TODO */, .m_nca_file_system_service_impl = nullptr /* TODO */, .m_save_data_file_system_service_impl = nullptr /* TODO */, .m_access_failure_management_service_impl = nullptr /* TODO */, .m_time_service_impl = nullptr /* TODO */, .m_status_report_service_impl = nullptr /* TODO */, .m_program_registry_service_impl = nullptr /* TODO */, .m_access_log_service_impl = nullptr /* TODO */, .m_debug_configuration_service_impl = nullptr /* TODO */, }; fssrv::InitializeForFileSystemProxy(config); /* Disable auto-abort in fs library code. */ fs::SetEnabledAutoAbort(false); /* Quick sanity check, before we leave. */ #if defined(ATMOSPHERE_OS_HORIZON) AMS_ABORT_UNLESS(os::GetCurrentProgramId() == ncm::AtmosphereProgramId::Mitm); #endif } const ::ams::fssrv::fscreator::FileSystemCreatorInterfaces *GetFileSystemCreatorInterfaces() { return std::addressof(g_fs_creator_interfaces); } }
13,695
C++
.cpp
215
54.353488
227
0.670271
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,376
fssystem_partition_file_system.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssystem/fssystem_partition_file_system.cpp
/* * Copyright (c) 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 { namespace { constexpr const char RootPath[] = "/"; class PartitionFileSystemDefaultAllocator : public MemoryResource { private: virtual void *AllocateImpl(size_t size, size_t alignment) override { AMS_UNUSED(alignment); return ::ams::fs::impl::Allocate(size); } virtual void DeallocateImpl(void *buffer, size_t size, size_t alignment) override { AMS_UNUSED(alignment); ::ams::fs::impl::Deallocate(buffer, size); } virtual bool IsEqualImpl(const MemoryResource &rhs) const override { return this == std::addressof(rhs); } }; PartitionFileSystemDefaultAllocator g_partition_filesystem_default_allocator; } template <typename MetaType> class PartitionFileSystemCore<MetaType>::PartitionFile : public fs::fsa::IFile, public fs::impl::Newable { private: const typename MetaType::PartitionEntry *m_partition_entry; const PartitionFileSystemCore<MetaType> *m_parent; const fs::OpenMode m_mode; public: PartitionFile(PartitionFileSystemCore<MetaType> *parent, const typename MetaType::PartitionEntry *partition_entry, fs::OpenMode mode) : m_partition_entry(partition_entry), m_parent(parent), m_mode(mode) { /* ... */ } private: virtual Result DoRead(size_t *out, s64 offset, void *buffer, size_t size, const fs::ReadOption &option) override final; virtual Result DoGetSize(s64 *out) override final { *out = m_partition_entry->size; R_SUCCEED(); } virtual Result DoFlush() override final { /* Nothing to do if writing disallowed. */ R_SUCCEED_IF((m_mode & fs::OpenMode_Write) == 0); /* Flush base storage. */ R_RETURN(m_parent->m_base_storage->Flush()); } virtual Result DoWrite(s64 offset, const void *buffer, size_t size, const fs::WriteOption &option) override final { /* Ensure appending is not required. */ bool needs_append; R_TRY(this->DryWrite(std::addressof(needs_append), offset, size, option, m_mode)); R_UNLESS(!needs_append, fs::ResultUnsupportedWriteForPartitionFile()); /* Appending is prohibited. */ AMS_ASSERT((m_mode & fs::OpenMode_AllowAppend) == 0); /* Validate offset and size. */ R_UNLESS(offset <= static_cast<s64>(m_partition_entry->size), fs::ResultOutOfRange()); R_UNLESS(static_cast<s64>(offset + size) <= static_cast<s64>(m_partition_entry->size), fs::ResultInvalidSize()); /* Write to the base storage. */ R_RETURN(m_parent->m_base_storage->Write(m_parent->m_meta_data_size + m_partition_entry->offset + offset, buffer, size)); } virtual Result DoSetSize(s64 size) override final { R_TRY(this->DrySetSize(size, m_mode)); R_RETURN(fs::ResultUnsupportedWriteForPartitionFile()); } virtual Result DoOperateRange(void *dst, size_t dst_size, fs::OperationId op_id, s64 offset, s64 size, const void *src, size_t src_size) override final { /* Validate preconditions for operation. */ s64 operate_offset; s64 operate_size; switch (op_id) { case fs::OperationId::Invalidate: R_UNLESS((m_mode & fs::OpenMode_Read) != 0, fs::ResultReadNotPermitted()); R_UNLESS((m_mode & fs::OpenMode_Write) == 0, fs::ResultUnsupportedOperateRangeForPartitionFile()); /* Set offset/size. */ operate_offset = 0; operate_size = std::numeric_limits<s64>::max(); break; case fs::OperationId::QueryRange: /* Validate offset and size. */ R_UNLESS(offset >= 0, fs::ResultOutOfRange()); R_UNLESS(offset <= static_cast<s64>(m_partition_entry->size), fs::ResultOutOfRange()); R_UNLESS(static_cast<s64>(offset + size) <= static_cast<s64>(m_partition_entry->size), fs::ResultInvalidSize()); R_UNLESS(static_cast<s64>(offset + size) >= offset, fs::ResultInvalidSize()); /* Set offset/size. */ operate_offset = m_parent->m_meta_data_size + m_partition_entry->offset + offset; operate_size = size; break; default: R_THROW(fs::ResultUnsupportedOperateRangeForPartitionFile()); } R_RETURN(m_parent->m_base_storage->OperateRange(dst, dst_size, op_id, operate_offset, operate_size, src, src_size)); } public: virtual sf::cmif::DomainObjectId GetDomainObjectId() const override { /* TODO: How should this be handled? */ return sf::cmif::InvalidDomainObjectId; } }; template<> Result PartitionFileSystemCore<PartitionFileSystemMeta>::PartitionFile::DoRead(size_t *out, s64 offset, void *dst, size_t dst_size, const fs::ReadOption &option) { /* Perform a dry read. */ size_t read_size = 0; R_TRY(this->DryRead(std::addressof(read_size), offset, dst_size, option, m_mode)); /* Read from the base storage. */ R_TRY(m_parent->m_base_storage->Read(m_parent->m_meta_data_size + m_partition_entry->offset + offset, dst, read_size)); /* Set output size. */ *out = read_size; R_SUCCEED(); } template<> Result PartitionFileSystemCore<Sha256PartitionFileSystemMeta>::PartitionFile::DoRead(size_t *out, s64 offset, void *dst, size_t dst_size, const fs::ReadOption &option) { /* Perform a dry read. */ size_t read_size = 0; R_TRY(this->DryRead(std::addressof(read_size), offset, dst_size, option, m_mode)); const s64 entry_start = m_parent->m_meta_data_size + m_partition_entry->offset; const s64 read_end = static_cast<s64>(offset + read_size); const s64 hash_start = static_cast<s64>(m_partition_entry->hash_target_offset); const s64 hash_end = hash_start + m_partition_entry->hash_target_size; if (read_end <= hash_start || hash_end <= offset) { /* We aren't reading hashed data, so we can just read from the base storage. */ R_TRY(m_parent->m_base_storage->Read(entry_start + offset, dst, read_size)); } else { /* Only hash target offset == 0 is supported. */ R_UNLESS(hash_start == 0, fs::ResultInvalidSha256PartitionHashTarget()); /* Ensure that the hash region is valid. */ R_UNLESS(m_partition_entry->hash_target_offset + m_partition_entry->hash_target_size <= m_partition_entry->size, fs::ResultInvalidSha256PartitionHashTarget()); /* Validate our read offset. */ const s64 read_offset = entry_start + offset; R_UNLESS(read_offset >= offset, fs::ResultOutOfRange()); /* Prepare a buffer for our calculated hash. */ char hash[crypto::Sha256Generator::HashSize]; crypto::Sha256Generator generator; /* Ensure we can perform our read. */ const bool hash_in_read = offset <= hash_start && hash_end <= read_end; const bool read_in_hash = hash_start <= offset && read_end <= hash_end; R_UNLESS(hash_in_read || read_in_hash, fs::ResultInvalidSha256PartitionHashTarget()); /* Initialize the generator. */ generator.Initialize(); if (hash_in_read) { /* Easy case: hash region is contained within the bounds. */ R_TRY(m_parent->m_base_storage->Read(entry_start + offset, dst, read_size)); generator.Update(static_cast<u8 *>(dst) + hash_start - offset, m_partition_entry->hash_target_size); } else /* if (read_in_hash) */ { /* We're reading a portion of what's hashed. */ s64 remaining_hash_size = m_partition_entry->hash_target_size; s64 hash_offset = entry_start + hash_start; s64 remaining_size = read_size; s64 copy_offset = 0; while (remaining_hash_size > 0) { /* Read some portion of data into the buffer. */ constexpr size_t HashBufferSize = 0x200; char hash_buffer[HashBufferSize]; size_t cur_size = static_cast<size_t>(std::min(static_cast<s64>(HashBufferSize), remaining_hash_size)); R_TRY(m_parent->m_base_storage->Read(hash_offset, hash_buffer, cur_size)); /* Update the hash. */ generator.Update(hash_buffer, cur_size); /* If we need to copy, do so. */ if (read_offset <= (hash_offset + static_cast<s64>(cur_size)) && remaining_size > 0) { const s64 hash_buffer_offset = std::max<s64>(read_offset - hash_offset, 0); const size_t copy_size = static_cast<size_t>(std::min<s64>(cur_size - hash_buffer_offset, remaining_size)); std::memcpy(static_cast<u8 *>(dst) + copy_offset, hash_buffer + hash_buffer_offset, copy_size); remaining_size -= copy_size; copy_offset += copy_size; } /* Update offsets. */ remaining_hash_size -= cur_size; hash_offset += cur_size; } } /* Get the hash. */ generator.GetHash(hash, sizeof(hash)); /* Validate the hash. */ auto hash_guard = SCOPE_GUARD { std::memset(dst, 0, read_size); }; R_UNLESS(crypto::IsSameBytes(m_partition_entry->hash, hash, sizeof(hash)), fs::ResultSha256PartitionHashVerificationFailed()); /* We successfully completed our read. */ hash_guard.Cancel(); } /* Set output size. */ *out = read_size; R_SUCCEED(); } template <typename MetaType> class PartitionFileSystemCore<MetaType>::PartitionDirectory : public fs::fsa::IDirectory, public fs::impl::Newable { private: u32 m_cur_index; const PartitionFileSystemCore<MetaType> *m_parent; const fs::OpenDirectoryMode m_mode; public: PartitionDirectory(PartitionFileSystemCore<MetaType> *parent, fs::OpenDirectoryMode mode) : m_cur_index(0), m_parent(parent), m_mode(mode) { /* ... */ } public: virtual Result DoRead(s64 *out_count, fs::DirectoryEntry *out_entries, s64 max_entries) override final { /* There are no subdirectories. */ if ((m_mode & fs::OpenDirectoryMode_File) == 0) { *out_count = 0; R_SUCCEED(); } /* Calculate number of entries. */ const s64 entry_count = std::min(max_entries, static_cast<s64>(m_parent->m_meta_data->GetEntryCount() - m_cur_index)); /* Populate output directory entries. */ for (auto i = 0; i < entry_count; i++, m_cur_index++) { fs::DirectoryEntry &dir_entry = out_entries[i]; /* Setup the output directory entry. */ dir_entry.type = fs::DirectoryEntryType_File; dir_entry.file_size = m_parent->m_meta_data->GetEntry(m_cur_index)->size; std::strncpy(dir_entry.name, m_parent->m_meta_data->GetEntryName(m_cur_index), sizeof(dir_entry.name) - 1); dir_entry.name[sizeof(dir_entry.name) - 1] = fs::StringTraits::NullTerminator; } *out_count = entry_count; R_SUCCEED(); } virtual Result DoGetEntryCount(s64 *out) override final { /* Output the parent meta data entry count for files, otherwise 0. */ if (m_mode & fs::OpenDirectoryMode_File) { *out = m_parent->m_meta_data->GetEntryCount(); } else { *out = 0; } R_SUCCEED(); } virtual sf::cmif::DomainObjectId GetDomainObjectId() const override { /* TODO: How should this be handled? */ return sf::cmif::InvalidDomainObjectId; } }; template <typename MetaType> PartitionFileSystemCore<MetaType>::PartitionFileSystemCore() : m_initialized(false) { /* ... */ } template <typename MetaType> PartitionFileSystemCore<MetaType>::~PartitionFileSystemCore() { /* ... */ } template <typename MetaType> Result PartitionFileSystemCore<MetaType>::Initialize(fs::IStorage *base_storage, MemoryResource *allocator) { /* Validate preconditions. */ R_UNLESS(!m_initialized, fs::ResultPreconditionViolation()); /* Allocate meta data. */ m_unique_meta_data = std::make_unique<MetaType>(); R_UNLESS(m_unique_meta_data != nullptr, fs::ResultAllocationMemoryFailedInPartitionFileSystemA()); /* Initialize meta data. */ R_TRY(m_unique_meta_data->Initialize(base_storage, allocator)); /* Initialize members. */ m_meta_data = m_unique_meta_data.get(); m_base_storage = base_storage; m_meta_data_size = m_meta_data->GetMetaDataSize(); m_initialized = true; R_SUCCEED(); } template <typename MetaType> Result PartitionFileSystemCore<MetaType>::Initialize(std::unique_ptr<MetaType> &&meta_data, std::shared_ptr<fs::IStorage> base_storage) { m_unique_meta_data = std::move(meta_data); R_RETURN(this->Initialize(m_unique_meta_data.get(), base_storage)); } template <typename MetaType> Result PartitionFileSystemCore<MetaType>::Initialize(MetaType *meta_data, std::shared_ptr<fs::IStorage> base_storage) { /* Validate preconditions. */ R_UNLESS(!m_initialized, fs::ResultPreconditionViolation()); /* Initialize members. */ m_shared_storage = std::move(base_storage); m_base_storage = m_shared_storage.get(); m_meta_data = meta_data; m_meta_data_size = m_meta_data->GetMetaDataSize(); m_initialized = true; R_SUCCEED(); } template <typename MetaType> Result PartitionFileSystemCore<MetaType>::Initialize(fs::IStorage *base_storage) { R_RETURN(this->Initialize(base_storage, std::addressof(g_partition_filesystem_default_allocator))); } template <typename MetaType> Result PartitionFileSystemCore<MetaType>::Initialize(std::shared_ptr<fs::IStorage> base_storage) { m_shared_storage = std::move(base_storage); R_RETURN(this->Initialize(m_shared_storage.get())); } template <typename MetaType> Result PartitionFileSystemCore<MetaType>::Initialize(std::shared_ptr<fs::IStorage> base_storage, MemoryResource *allocator) { m_shared_storage = std::move(base_storage); R_RETURN(this->Initialize(m_shared_storage.get(), allocator)); } template <typename MetaType> Result PartitionFileSystemCore<MetaType>::GetFileBaseOffset(s64 *out_offset, const char *path) { /* Validate preconditions. */ R_UNLESS(m_initialized, fs::ResultPreconditionViolation()); /* Obtain and validate the entry index. */ const s32 entry_index = m_meta_data->GetEntryIndex(path + 1); R_UNLESS(entry_index >= 0, fs::ResultPathNotFound()); /* Output offset. */ *out_offset = m_meta_data_size + m_meta_data->GetEntry(entry_index)->offset; R_SUCCEED(); } template <typename MetaType> Result PartitionFileSystemCore<MetaType>::DoGetEntryType(fs::DirectoryEntryType *out, const fs::Path &path) { /* Validate preconditions. */ R_UNLESS(m_initialized, fs::ResultPreconditionViolation()); const char * const p = path.GetString(); R_UNLESS(p[0] == RootPath[0], fs::ResultInvalidPathFormat()); /* Check if the path is for a directory. */ if (util::Strncmp(p, RootPath, sizeof(RootPath)) == 0) { *out = fs::DirectoryEntryType_Directory; R_SUCCEED(); } /* Ensure that path is for a file. */ R_UNLESS(m_meta_data->GetEntryIndex(p + 1) >= 0, fs::ResultPathNotFound()); *out = fs::DirectoryEntryType_File; R_SUCCEED(); } template <typename MetaType> Result PartitionFileSystemCore<MetaType>::DoOpenFile(std::unique_ptr<fs::fsa::IFile> *out_file, const fs::Path &path, fs::OpenMode mode) { /* Validate preconditions. */ R_UNLESS(m_initialized, fs::ResultPreconditionViolation()); /* Obtain and validate the entry index. */ const s32 entry_index = m_meta_data->GetEntryIndex(path.GetString() + 1); R_UNLESS(entry_index >= 0, fs::ResultPathNotFound()); /* Create and output the file directory. */ std::unique_ptr file = std::make_unique<PartitionFile>(this, m_meta_data->GetEntry(entry_index), mode); R_UNLESS(file != nullptr, fs::ResultAllocationMemoryFailedInPartitionFileSystemB()); *out_file = std::move(file); R_SUCCEED(); } template <typename MetaType> Result PartitionFileSystemCore<MetaType>::DoOpenDirectory(std::unique_ptr<fs::fsa::IDirectory> *out_dir, const fs::Path &path, fs::OpenDirectoryMode mode) { /* Validate preconditions. */ R_UNLESS(m_initialized, fs::ResultPreconditionViolation()); R_UNLESS(path == RootPath, fs::ResultPathNotFound()); /* Create and output the partition directory. */ std::unique_ptr directory = std::make_unique<PartitionDirectory>(this, mode); R_UNLESS(directory != nullptr, fs::ResultAllocationMemoryFailedInPartitionFileSystemC()); *out_dir = std::move(directory); R_SUCCEED(); } template <typename MetaType> Result PartitionFileSystemCore<MetaType>::DoCommit() { R_SUCCEED(); } template <typename MetaType> Result PartitionFileSystemCore<MetaType>::DoCleanDirectoryRecursively(const fs::Path &path) { AMS_UNUSED(path); R_THROW(fs::ResultUnsupportedWriteForPartitionFileSystem()); } template <typename MetaType> Result PartitionFileSystemCore<MetaType>::DoCreateDirectory(const fs::Path &path) { AMS_UNUSED(path); R_THROW(fs::ResultUnsupportedWriteForPartitionFileSystem()); } template <typename MetaType> Result PartitionFileSystemCore<MetaType>::DoCreateFile(const fs::Path &path, s64 size, int option) { AMS_UNUSED(path, size, option); R_THROW(fs::ResultUnsupportedWriteForPartitionFileSystem()); } template <typename MetaType> Result PartitionFileSystemCore<MetaType>::DoDeleteDirectory(const fs::Path &path) { AMS_UNUSED(path); R_THROW(fs::ResultUnsupportedWriteForPartitionFileSystem()); } template <typename MetaType> Result PartitionFileSystemCore<MetaType>::DoDeleteDirectoryRecursively(const fs::Path &path) { AMS_UNUSED(path); R_THROW(fs::ResultUnsupportedWriteForPartitionFileSystem()); } template <typename MetaType> Result PartitionFileSystemCore<MetaType>::DoDeleteFile(const fs::Path &path) { AMS_UNUSED(path); R_THROW(fs::ResultUnsupportedWriteForPartitionFileSystem()); } template <typename MetaType> Result PartitionFileSystemCore<MetaType>::DoRenameDirectory(const fs::Path &old_path, const fs::Path &new_path) { AMS_UNUSED(old_path, new_path); R_THROW(fs::ResultUnsupportedWriteForPartitionFileSystem()); } template <typename MetaType> Result PartitionFileSystemCore<MetaType>::DoRenameFile(const fs::Path &old_path, const fs::Path &new_path) { AMS_UNUSED(old_path, new_path); R_THROW(fs::ResultUnsupportedWriteForPartitionFileSystem()); } template <typename MetaType> Result PartitionFileSystemCore<MetaType>::DoCommitProvisionally(s64 counter) { AMS_UNUSED(counter); R_THROW(fs::ResultUnsupportedCommitProvisionallyForPartitionFileSystem()); } template class PartitionFileSystemCore<PartitionFileSystemMeta>; template class PartitionFileSystemCore<Sha256PartitionFileSystemMeta>; }
21,786
C++
.cpp
389
44.313625
228
0.607545
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,377
fssystem_buffer_manager_utils.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssystem/buffers/fssystem_buffer_manager_utils.cpp
/* * Copyright (c) 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::buffers { namespace { /* TODO: os::SdkThreadLocalStorage g_buffer_manager_context_tls_slot; */ class ThreadLocalStorageWrapper { private: os::TlsSlot m_tls_slot; public: ThreadLocalStorageWrapper() { R_ABORT_UNLESS(os::AllocateTlsSlot(std::addressof(m_tls_slot), nullptr)); } ~ThreadLocalStorageWrapper() { os::FreeTlsSlot(m_tls_slot); } void SetValue(uintptr_t value) { os::SetTlsValue(m_tls_slot, value); } uintptr_t GetValue() const { return os::GetTlsValue(m_tls_slot); } os::TlsSlot GetTlsSlot() const { return m_tls_slot; } } g_buffer_manager_context_tls_slot; } void RegisterBufferManagerContext(const BufferManagerContext *context) { g_buffer_manager_context_tls_slot.SetValue(reinterpret_cast<uintptr_t>(context)); } BufferManagerContext *GetBufferManagerContext() { return reinterpret_cast<BufferManagerContext *>(g_buffer_manager_context_tls_slot.GetValue()); } void EnableBlockingBufferManagerAllocation() { if (auto context = GetBufferManagerContext(); context != nullptr) { context->SetNeedBlocking(true); } } }
1,944
C++
.cpp
42
39.47619
121
0.687632
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,378
fssystem_file_system_buffer_manager.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssystem/buffers/fssystem_file_system_buffer_manager.cpp
/* * Copyright (c) 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 { Result FileSystemBufferManager::CacheHandleTable::Initialize(s32 max_cache_count) { /* Validate pre-conditions. */ AMS_ASSERT(m_entries == nullptr); AMS_ASSERT(m_internal_entry_buffer == nullptr); /* If we don't have an external buffer, try to allocate an internal one. */ if (m_external_entry_buffer == nullptr) { m_entry_buffer_size = sizeof(Entry) * max_cache_count; m_internal_entry_buffer = fs::impl::MakeUnique<char[]>(m_entry_buffer_size); } /* We need to have at least one entry buffer. */ R_UNLESS(m_internal_entry_buffer != nullptr || m_external_entry_buffer != nullptr, fs::ResultAllocationMemoryFailedInFileSystemBufferManagerA()); /* Set entries. */ m_entries = reinterpret_cast<Entry *>(m_external_entry_buffer != nullptr ? m_external_entry_buffer : m_internal_entry_buffer.get()); m_entry_count = 0; m_entry_count_max = max_cache_count; AMS_ASSERT(m_entries != nullptr); m_cache_count_min = max_cache_count / 16; m_cache_size_min = m_cache_count_min * 0x100; R_SUCCEED(); } void FileSystemBufferManager::CacheHandleTable::Finalize() { if (m_entries != nullptr) { AMS_ASSERT(m_entry_count == 0); if (m_external_attr_info_buffer == nullptr) { auto it = m_attr_list.begin(); while (it != m_attr_list.end()) { const auto attr_info = std::addressof(*it); it = m_attr_list.erase(it); delete attr_info; } } m_internal_entry_buffer.reset(); m_external_entry_buffer = nullptr; m_entry_buffer_size = 0; m_entries = nullptr; m_total_cache_size = 0; } } bool FileSystemBufferManager::CacheHandleTable::Register(CacheHandle *out, uintptr_t address, size_t size, const BufferAttribute &attr) { /* Validate pre-conditions. */ AMS_ASSERT(m_entries != nullptr); AMS_ASSERT(out != nullptr); /* Get the entry. */ auto entry = this->AcquireEntry(address, size, attr); /* If we don't have an entry, we can't register. */ if (entry == nullptr) { return false; } /* Get the attr info. If we have one, increment. */ if (const auto attr_info = this->FindAttrInfo(attr); attr_info != nullptr) { attr_info->IncrementCacheCount(); attr_info->AddCacheSize(size); } else { /* Make a new attr info and add it to the list. */ AttrInfo *new_info = nullptr; if (m_external_attr_info_buffer == nullptr) { new_info = new AttrInfo(attr.GetLevel(), 1, size); } else if (0 <= attr.GetLevel() && attr.GetLevel() < m_external_attr_info_count) { void *buffer = m_external_attr_info_buffer + attr.GetLevel() * sizeof(AttrInfo); new_info = std::construct_at(reinterpret_cast<AttrInfo *>(buffer), attr.GetLevel(), 1, size); } /* If we failed to make a new attr info, we can't register. */ if (new_info == nullptr) { this->ReleaseEntry(entry); return false; } m_attr_list.push_back(*new_info); } m_total_cache_size += size; *out = entry->GetHandle(); return true; } bool FileSystemBufferManager::CacheHandleTable::Unregister(uintptr_t *out_address, size_t *out_size, CacheHandle handle) { /* Validate pre-conditions. */ AMS_ASSERT(m_entries != nullptr); AMS_ASSERT(out_address != nullptr); AMS_ASSERT(out_size != nullptr); /* Find the lower bound for the entry. */ const auto entry = std::lower_bound(m_entries, m_entries + m_entry_count, handle, [](const Entry &entry, CacheHandle handle) { return entry.GetHandle() < handle; }); /* If the entry is a match, unregister it. */ if (entry != m_entries + m_entry_count && entry->GetHandle() == handle) { this->UnregisterCore(out_address, out_size, entry); return true; } else { return false; } } bool FileSystemBufferManager::CacheHandleTable::UnregisterOldest(uintptr_t *out_address, size_t *out_size, const BufferAttribute &attr, size_t required_size) { AMS_UNUSED(attr, required_size); /* Validate pre-conditions. */ AMS_ASSERT(m_entries != nullptr); AMS_ASSERT(out_address != nullptr); AMS_ASSERT(out_size != nullptr); /* If we have no entries, we can't unregister any. */ if (m_entry_count == 0) { return false; } const auto CanUnregister = [this](const Entry &entry) { const auto attr_info = this->FindAttrInfo(entry.GetBufferAttribute()); AMS_ASSERT(attr_info != nullptr); const auto ccm = this->GetCacheCountMin(entry.GetBufferAttribute()); const auto csm = this->GetCacheSizeMin(entry.GetBufferAttribute()); return ccm < attr_info->GetCacheCount() && csm + entry.GetSize() <= attr_info->GetCacheSize(); }; /* Find an entry, falling back to the first entry. */ auto entry = std::find_if(m_entries, m_entries + m_entry_count, CanUnregister); if (entry == m_entries + m_entry_count) { entry = m_entries; } AMS_ASSERT(entry != m_entries + m_entry_count); this->UnregisterCore(out_address, out_size, entry); return true; } void FileSystemBufferManager::CacheHandleTable::UnregisterCore(uintptr_t *out_address, size_t *out_size, Entry *entry) { /* Validate pre-conditions. */ AMS_ASSERT(m_entries != nullptr); AMS_ASSERT(out_address != nullptr); AMS_ASSERT(out_size != nullptr); AMS_ASSERT(entry != nullptr); /* Get the attribute info. */ const auto attr_info = this->FindAttrInfo(entry->GetBufferAttribute()); AMS_ASSERT(attr_info != nullptr); AMS_ASSERT(attr_info->GetCacheCount() > 0); AMS_ASSERT(attr_info->GetCacheSize() >= entry->GetSize()); /* Release from the attr info. */ attr_info->DecrementCacheCount(); attr_info->SubtractCacheSize(entry->GetSize()); /* Release from cached size. */ AMS_ASSERT(m_total_cache_size >= entry->GetSize()); m_total_cache_size -= entry->GetSize(); /* Release the entry. */ *out_address = entry->GetAddress(); *out_size = entry->GetSize(); this->ReleaseEntry(entry); } FileSystemBufferManager::CacheHandle FileSystemBufferManager::CacheHandleTable::PublishCacheHandle() { AMS_ASSERT(m_entries != nullptr); return (++m_current_handle); } size_t FileSystemBufferManager::CacheHandleTable::GetTotalCacheSize() const { return m_total_cache_size; } FileSystemBufferManager::CacheHandleTable::Entry *FileSystemBufferManager::CacheHandleTable::AcquireEntry(uintptr_t address, size_t size, const BufferAttribute &attr) { /* Validate pre-conditions. */ AMS_ASSERT(m_entries != nullptr); Entry *entry = nullptr; if (m_entry_count < m_entry_count_max) { entry = m_entries + m_entry_count; entry->Initialize(this->PublishCacheHandle(), address, size, attr); ++m_entry_count; AMS_ASSERT(m_entry_count == 1 || (entry-1)->GetHandle() < entry->GetHandle()); } return entry; } void FileSystemBufferManager::CacheHandleTable::ReleaseEntry(Entry *entry) { /* Validate pre-conditions. */ AMS_ASSERT(m_entries != nullptr); AMS_ASSERT(entry != nullptr); /* Ensure the entry is valid. */ { const auto entry_buffer = m_external_entry_buffer != nullptr ? m_external_entry_buffer : m_internal_entry_buffer.get(); AMS_ASSERT(static_cast<void *>(entry_buffer) <= static_cast<void *>(entry)); AMS_ASSERT(static_cast<void *>(entry) < static_cast<void *>(entry_buffer + m_entry_buffer_size)); AMS_UNUSED(entry_buffer); } /* Copy the entries back by one. */ std::memmove(entry, entry + 1, sizeof(Entry) * (m_entry_count - ((entry + 1) - m_entries))); /* Decrement our entry count. */ --m_entry_count; } FileSystemBufferManager::CacheHandleTable::AttrInfo *FileSystemBufferManager::CacheHandleTable::FindAttrInfo(const BufferAttribute &attr) { const auto it = std::find_if(m_attr_list.begin(), m_attr_list.end(), [&attr](const AttrInfo &info) { return attr.GetLevel() == info.GetLevel(); }); return it != m_attr_list.end() ? std::addressof(*it) : nullptr; } const fs::IBufferManager::MemoryRange FileSystemBufferManager::AllocateBufferImpl(size_t size, const BufferAttribute &attr) { /* Get/sanity check the required order. */ fs::IBufferManager::MemoryRange range = {}; const auto order = m_buddy_heap.GetOrderFromBytes(size); AMS_ASSERT(order >= 0); while (true) { /* Try to allocate a buffer at the desired order. */ if (auto address = m_buddy_heap.AllocateByOrder(order); address != 0) { /* Check that we allocated enough. */ const auto allocated_size = m_buddy_heap.GetBytesFromOrder(order); AMS_ASSERT(size <= allocated_size); /* Set up the range extents. */ range.first = reinterpret_cast<uintptr_t>(address); range.second = allocated_size; /* Update our peak tracking variables. */ const size_t free_size = m_buddy_heap.GetTotalFreeSize(); m_peak_free_size = std::min(m_peak_free_size, free_size); const size_t total_allocatable_size = free_size + m_cache_handle_table.GetTotalCacheSize(); m_peak_total_allocatable_size = std::min(m_peak_total_allocatable_size, total_allocatable_size); break; } /* We failed, to we'll need to deallocate something and retry. */ ++m_retried_count; /* Deallocate a buffer. */ uintptr_t deallocate_address = 0; size_t deallocate_size = 0; if (m_cache_handle_table.UnregisterOldest(std::addressof(deallocate_address), std::addressof(deallocate_size), attr, size)) { this->DeallocateBufferImpl(deallocate_address, deallocate_size); } else { break; } } /* Return the range we allocated. */ return range; } void FileSystemBufferManager::DeallocateBufferImpl(uintptr_t address, size_t size) { AMS_ASSERT(util::IsPowerOfTwo(size)); m_buddy_heap.Free(reinterpret_cast<void *>(address), m_buddy_heap.GetOrderFromBytes(size)); } FileSystemBufferManager::CacheHandle FileSystemBufferManager::RegisterCacheImpl(uintptr_t address, size_t size, const BufferAttribute &attr) { CacheHandle handle = 0; while (true) { /* Try to register the handle. */ if (m_cache_handle_table.Register(std::addressof(handle), address, size, attr)) { break; } /* Deallocate a buffer. */ uintptr_t deallocate_address = 0; size_t deallocate_size = 0; ++m_retried_count; if (m_cache_handle_table.UnregisterOldest(std::addressof(deallocate_address), std::addressof(deallocate_size), attr)) { this->DeallocateBufferImpl(deallocate_address, deallocate_size); } else { this->DeallocateBufferImpl(address, size); handle = m_cache_handle_table.PublishCacheHandle(); break; } } return handle; } const fs::IBufferManager::MemoryRange FileSystemBufferManager::AcquireCacheImpl(CacheHandle handle) { fs::IBufferManager::MemoryRange range = {}; if (m_cache_handle_table.Unregister(std::addressof(range.first), std::addressof(range.second), handle)) { const size_t total_allocatable_size = m_buddy_heap.GetTotalFreeSize() + m_cache_handle_table.GetTotalCacheSize(); m_peak_total_allocatable_size = std::min(m_peak_total_allocatable_size, total_allocatable_size); } else { range.first = 0; range.second = 0; } return range; } size_t FileSystemBufferManager::GetFreeSizeImpl() const { return m_buddy_heap.GetTotalFreeSize(); } size_t FileSystemBufferManager::GetTotalAllocatableSizeImpl() const { return this->GetFreeSizeImpl() + m_cache_handle_table.GetTotalCacheSize(); } size_t FileSystemBufferManager::GetFreeSizePeakImpl() const { return m_peak_free_size; } size_t FileSystemBufferManager::GetTotalAllocatableSizePeakImpl() const { return m_peak_total_allocatable_size; } size_t FileSystemBufferManager::GetRetriedCountImpl() const { return m_retried_count; } void FileSystemBufferManager::ClearPeakImpl() { m_peak_free_size = this->GetFreeSizeImpl(); m_peak_total_allocatable_size = this->GetTotalAllocatableSizeImpl(); m_retried_count = 0; } const fs::IBufferManager::MemoryRange FileSystemBufferManager::DoAllocateBuffer(size_t size, const BufferAttribute &attr) { std::scoped_lock lk(m_mutex); return this->AllocateBufferImpl(size, attr); } void FileSystemBufferManager::DoDeallocateBuffer(uintptr_t address, size_t size) { std::scoped_lock lk(m_mutex); return this->DeallocateBufferImpl(address, size); } FileSystemBufferManager::CacheHandle FileSystemBufferManager::DoRegisterCache(uintptr_t address, size_t size, const BufferAttribute &attr) { std::scoped_lock lk(m_mutex); return this->RegisterCacheImpl(address, size, attr); } const fs::IBufferManager::MemoryRange FileSystemBufferManager::DoAcquireCache(CacheHandle handle) { std::scoped_lock lk(m_mutex); return this->AcquireCacheImpl(handle); } size_t FileSystemBufferManager::DoGetTotalSize() const { return m_total_size; } size_t FileSystemBufferManager::DoGetFreeSize() const { std::scoped_lock lk(m_mutex); return this->GetFreeSizeImpl(); } size_t FileSystemBufferManager::DoGetTotalAllocatableSize() const { std::scoped_lock lk(m_mutex); return this->GetTotalAllocatableSizeImpl(); } size_t FileSystemBufferManager::DoGetFreeSizePeak() const { std::scoped_lock lk(m_mutex); return this->GetFreeSizePeakImpl(); } size_t FileSystemBufferManager::DoGetTotalAllocatableSizePeak() const { std::scoped_lock lk(m_mutex); return this->GetTotalAllocatableSizePeakImpl(); } size_t FileSystemBufferManager::DoGetRetriedCount() const { std::scoped_lock lk(m_mutex); return this->GetRetriedCountImpl(); } void FileSystemBufferManager::DoClearPeak() { std::scoped_lock lk(m_mutex); return this->ClearPeakImpl(); } }
16,210
C++
.cpp
330
39.445455
172
0.623456
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,379
fssystem_file_system_buddy_heap.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssystem/buffers/fssystem_file_system_buddy_heap.cpp
/* * Copyright (c) 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 { FileSystemBuddyHeap::PageEntry *FileSystemBuddyHeap::PageList::PopFront() { AMS_ASSERT(m_entry_count > 0); /* Get the first entry. */ auto page_entry = m_first_page_entry; /* Advance our list. */ m_first_page_entry = page_entry->next; page_entry->next = nullptr; /* Decrement our count. */ --m_entry_count; AMS_ASSERT(m_entry_count >= 0); /* If this was our last page, clear our last entry. */ if (m_entry_count == 0) { m_last_page_entry = nullptr; } return page_entry; } void FileSystemBuddyHeap::PageList::PushBack(PageEntry *page_entry) { AMS_ASSERT(page_entry != nullptr); /* If we're empty, we want to set the first page entry. */ if (this->IsEmpty()) { m_first_page_entry = page_entry; } else { /* We're not empty, so push the page to the back. */ AMS_ASSERT(m_last_page_entry != page_entry); m_last_page_entry->next = page_entry; } /* Set our last page entry to be this one, and link it to the list. */ m_last_page_entry = page_entry; m_last_page_entry->next = nullptr; /* Increment our entry count. */ ++m_entry_count; AMS_ASSERT(m_entry_count > 0); } bool FileSystemBuddyHeap::PageList::Remove(PageEntry *page_entry) { AMS_ASSERT(page_entry != nullptr); /* If we're empty, we can't remove the page list. */ if (this->IsEmpty()) { return false; } /* We're going to loop over all pages to find this one, then unlink it. */ PageEntry *prev_entry = nullptr; PageEntry *cur_entry = m_first_page_entry; while (true) { /* Check if we found the page. */ if (cur_entry == page_entry) { if (cur_entry == m_first_page_entry) { /* If it's the first page, we just set our first. */ m_first_page_entry = cur_entry->next; } else if (cur_entry == m_last_page_entry) { /* If it's the last page, we set our last. */ m_last_page_entry = prev_entry; m_last_page_entry->next = nullptr; } else { /* If it's in the middle, we just unlink. */ prev_entry->next = cur_entry->next; } /* Unlink this entry's next. */ cur_entry->next = nullptr; /* Update our entry count. */ --m_entry_count; AMS_ASSERT(m_entry_count >= 0); return true; } /* If we have no next page, we can't remove. */ if (cur_entry->next == nullptr) { return false; } /* Advance to the next item in the list. */ prev_entry = cur_entry; cur_entry = cur_entry->next; } } Result FileSystemBuddyHeap::Initialize(uintptr_t address, size_t size, size_t block_size, s32 order_max) { /* Ensure our preconditions. */ AMS_ASSERT(m_free_lists == nullptr); AMS_ASSERT(address != 0); AMS_ASSERT(util::IsAligned(address, BufferAlignment)); AMS_ASSERT(block_size >= BlockSizeMin); AMS_ASSERT(util::IsPowerOfTwo(block_size)); AMS_ASSERT(size >= block_size); AMS_ASSERT(order_max > 0); AMS_ASSERT(order_max < OrderUpperLimit); /* Set up our basic member variables */ m_block_size = block_size; m_order_max = order_max; m_heap_start = address; m_heap_size = (size / m_block_size) * m_block_size; m_total_free_size = 0; /* Determine page sizes. */ const auto max_page_size = m_block_size << m_order_max; const auto max_page_count = util::AlignUp(m_heap_size, max_page_size) / max_page_size; AMS_ASSERT(max_page_count > 0); /* Setup the free lists. */ if (m_external_free_lists != nullptr) { AMS_ASSERT(m_internal_free_lists == nullptr); m_free_lists = m_external_free_lists; } else { m_internal_free_lists.reset(new PageList[m_order_max + 1]); m_free_lists = m_internal_free_lists.get(); R_UNLESS(m_free_lists != nullptr, fs::ResultAllocationMemoryFailedInFileSystemBuddyHeapA()); } /* All but the last page region should go to the max order. */ for (size_t i = 0; i < max_page_count - 1; i++) { auto page_entry = this->GetPageEntryFromAddress(m_heap_start + i * max_page_size); m_free_lists[m_order_max].PushBack(page_entry); } m_total_free_size += m_free_lists[m_order_max].GetSize() * this->GetBytesFromOrder(m_order_max); /* Allocate remaining space to smaller orders as possible. */ { auto remaining = m_heap_size - (max_page_count - 1) * max_page_size; auto cur_address = m_heap_start + (max_page_count - 1) * max_page_size; AMS_ASSERT(util::IsAligned(remaining, m_block_size)); do { /* Determine what order we can use. */ auto order = GetOrderFromBytes(remaining + 1); if (order < 0) { AMS_ASSERT(GetOrderFromBytes(remaining) == m_order_max); order = m_order_max + 1; } AMS_ASSERT(0 < order); AMS_ASSERT(order <= m_order_max + 1); /* Add to the correct free list. */ m_free_lists[order - 1].PushBack(GetPageEntryFromAddress(cur_address)); m_total_free_size += GetBytesFromOrder(order - 1); /* Move on to the next order. */ const auto page_size = GetBytesFromOrder(order - 1); cur_address += page_size; remaining -= page_size; } while (m_block_size <= remaining); } R_SUCCEED(); } void FileSystemBuddyHeap::Finalize() { AMS_ASSERT(m_free_lists != nullptr); m_free_lists = nullptr; m_external_free_lists = nullptr; m_internal_free_lists.reset(); } void *FileSystemBuddyHeap::AllocateByOrder(s32 order) { AMS_ASSERT(m_free_lists != nullptr); AMS_ASSERT(order >= 0); AMS_ASSERT(order <= this->GetOrderMax()); /* Get the page entry. */ if (const auto page_entry = this->GetFreePageEntry(order); page_entry != nullptr) { /* Ensure we're allocating an unlinked page. */ AMS_ASSERT(page_entry->next == nullptr); /* Return the address for this entry. */ return reinterpret_cast<void *>(this->GetAddressFromPageEntry(*page_entry)); } else { return nullptr; } } void FileSystemBuddyHeap::Free(void *ptr, s32 order) { AMS_ASSERT(m_free_lists != nullptr); AMS_ASSERT(order >= 0); AMS_ASSERT(order <= this->GetOrderMax()); /* Allow free(nullptr) */ if (ptr == nullptr) { return; } /* Ensure the pointer is block aligned. */ AMS_ASSERT(util::IsAligned(reinterpret_cast<uintptr_t>(ptr) - m_heap_start, this->GetBlockSize())); /* Get the page entry. */ auto page_entry = this->GetPageEntryFromAddress(reinterpret_cast<uintptr_t>(ptr)); AMS_ASSERT(this->IsAlignedToOrder(page_entry, order)); /* Reinsert into the free lists. */ this->JoinBuddies(page_entry, order); } size_t FileSystemBuddyHeap::GetTotalFreeSize() const { AMS_ASSERT(m_free_lists != nullptr); return m_total_free_size; } size_t FileSystemBuddyHeap::GetAllocatableSizeMax() const { AMS_ASSERT(m_free_lists != nullptr); /* The maximum allocatable size is a chunk from the biggest non-empty order. */ for (s32 order = this->GetOrderMax(); order >= 0; --order) { if (!m_free_lists[order].IsEmpty()) { return this->GetBytesFromOrder(order); } } /* If all orders are empty, then we can't allocate anything. */ return 0; } void FileSystemBuddyHeap::Dump() const { AMS_ASSERT(m_free_lists != nullptr); /* TODO: Support logging metrics. */ } void FileSystemBuddyHeap::DivideBuddies(PageEntry *page_entry, s32 required_order, s32 chosen_order) { AMS_ASSERT(page_entry != nullptr); AMS_ASSERT(required_order >= 0); AMS_ASSERT(chosen_order >= required_order); AMS_ASSERT(chosen_order <= this->GetOrderMax()); /* Start at the end of the entry. */ auto address = this->GetAddressFromPageEntry(*page_entry) + this->GetBytesFromOrder(chosen_order); for (auto order = chosen_order; order > required_order; --order) { /* For each order, subtract that order's size from the address to get the start of a new block. */ address -= this->GetBytesFromOrder(order - 1); auto divided_entry = this->GetPageEntryFromAddress(address); /* Push back to the list. */ m_free_lists[order - 1].PushBack(divided_entry); m_total_free_size += this->GetBytesFromOrder(order - 1); } } void FileSystemBuddyHeap::JoinBuddies(PageEntry *page_entry, s32 order) { AMS_ASSERT(page_entry != nullptr); AMS_ASSERT(order >= 0); AMS_ASSERT(order <= this->GetOrderMax()); auto cur_entry = page_entry; auto cur_order = order; while (cur_order < this->GetOrderMax()) { /* Get the buddy page. */ const auto buddy_entry = this->GetBuddy(cur_entry, cur_order); /* Check whether the buddy is in the relevant free list. */ if (buddy_entry != nullptr && m_free_lists[cur_order].Remove(buddy_entry)) { m_total_free_size -= GetBytesFromOrder(cur_order); /* Ensure we coalesce with the correct buddy when page is aligned */ if (!this->IsAlignedToOrder(cur_entry, cur_order + 1)) { cur_entry = buddy_entry; } ++cur_order; } else { /* Buddy isn't in the free list, so we can't coalesce. */ break; } } /* Insert the coalesced entry into the free list. */ m_free_lists[cur_order].PushBack(cur_entry); m_total_free_size += this->GetBytesFromOrder(cur_order); } FileSystemBuddyHeap::PageEntry *FileSystemBuddyHeap::GetBuddy(PageEntry *page_entry, s32 order) { AMS_ASSERT(page_entry != nullptr); AMS_ASSERT(order >= 0); AMS_ASSERT(order <= this->GetOrderMax()); const auto address = this->GetAddressFromPageEntry(*page_entry); const auto offset = this->GetBlockCountFromOrder(order) * this->GetBlockSize(); if (this->IsAlignedToOrder(page_entry, order + 1)) { /* If the page entry is aligned to the next order, return the buddy block to the right of the current entry. */ return (address + offset < m_heap_start + m_heap_size) ? GetPageEntryFromAddress(address + offset) : nullptr; } else { /* If the page entry isn't aligned, return the buddy block to the left of the current entry. */ return (m_heap_start <= address - offset) ? GetPageEntryFromAddress(address - offset) : nullptr; } } FileSystemBuddyHeap::PageEntry *FileSystemBuddyHeap::GetFreePageEntry(s32 order) { AMS_ASSERT(order >= 0); AMS_ASSERT(order <= this->GetOrderMax()); /* Try orders from low to high until we find a free page entry. */ for (auto cur_order = order; cur_order <= this->GetOrderMax(); cur_order++) { if (auto &free_list = m_free_lists[cur_order]; !free_list.IsEmpty()) { /* The current list isn't empty, so grab an entry from it. */ PageEntry *page_entry = free_list.PopFront(); AMS_ASSERT(page_entry != nullptr); /* Update size bookkeeping. */ m_total_free_size -= GetBytesFromOrder(cur_order); /* If we allocated more memory than needed, free the unneeded portion. */ this->DivideBuddies(page_entry, order, cur_order); AMS_ASSERT(page_entry->next == nullptr); /* Return the newly-divided entry. */ return page_entry; } } /* We failed to find a free page. */ return nullptr; } s32 FileSystemBuddyHeap::GetOrderFromBlockCount(s32 block_count) const { AMS_ASSERT(block_count >= 0); /* Return the first order with a big enough block count. */ for (s32 order = 0; order <= this->GetOrderMax(); ++order) { if (block_count <= this->GetBlockCountFromOrder(order)) { return order; } } return -1; } }
13,816
C++
.cpp
292
36.59589
123
0.57937
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,380
sf_interface_id_for_debug_enforcement.os.horizon.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/sf/sf_interface_id_for_debug_enforcement.os.horizon.cpp
/* * Copyright (c) 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 "../capsrv/server/decodersrv/decodersrv_decoder_control_service.hpp" #include "../lm/sf/lm_i_log_getter.hpp" #include "../lm/sf/lm_i_log_service.hpp" #include "../sf/hipc/sf_i_hipc_manager.hpp" #include "../sprofile/srv/sprofile_srv_i_service_getter.hpp" namespace { constexpr u32 GenerateInterfaceIdFromName(const char *s) { /* Get the interface length. */ const auto len = ams::util::Strlen(s); /* Calculate the sha256. */ u8 hash[ams::crypto::Sha256Generator::HashSize] = {}; ams::crypto::GenerateSha256(hash, sizeof(hash), s, len); /* Read it out as little endian. */ u32 id = 0; for (size_t i = 0; i < sizeof(id); ++i) { id |= static_cast<u32>(hash[i]) << (BITSIZEOF(u8) * i); } return id; } static_assert(GenerateInterfaceIdFromName("nn::sf::hipc::detail::IHipcManager") == 0xEC6BE3FF); constexpr void ConvertAtmosphereNameToNintendoName(char *dst, const char *src) { /* Determine src len. */ const auto len = ams::util::Strlen(src); const auto *s = src; /* Atmosphere names begin with ams::, Nintendo names begin with nn::. */ AMS_ASSUME(src[0] == 'a'); AMS_ASSUME(src[1] == 'm'); AMS_ASSERT(src[2] == 's'); dst[0] = 'n'; dst[1] = 'n'; src += 3; dst += 2; /* Copy over. */ while ((src - s) < len) { /* Atmosphere uses ::impl:: instead of ::detail::, ::IDeprecated* for deprecated services. */ if (src[0] == ':' && src[1] == ':' && src[2] == 'i' && src[3] == 'm' && src[4] == 'p' && src[5] == 'l' && src[6] == ':' && src[7] == ':') { dst[0] = ':'; dst[1] = ':'; dst[2] = 'd'; dst[3] = 'e'; dst[4] = 't'; dst[5] = 'a'; dst[6] = 'i'; dst[7] = 'l'; src += 6; /* ::impl */ dst += 8; /* ::detail */ } else if (src[0] == ':' && src[1] == ':' && src[2] == 'I' && src[3] == 'D' && src[4] == 'e' && src[5] == 'p' && src[6] == 'r' && src[7] == 'e' && src[8] == 'c' && src[9] == 'a' && src[10] == 't' && src[11] == 'e' && src[12] == 'd') { dst[0] = ':'; dst[1] = ':'; dst[2] = 'I'; src += 13; /* ::IDeprecated */ dst += 3; /* ::I */ } else { *(dst++) = *(src++); } } *dst = 0; } constexpr u32 GenerateInterfaceIdFromAtmosphereName(const char *ams) { char nn[0x100] = {}; ConvertAtmosphereNameToNintendoName(nn, ams); return GenerateInterfaceIdFromName(nn); } static_assert(GenerateInterfaceIdFromAtmosphereName("ams::sf::hipc::impl::IHipcManager") == GenerateInterfaceIdFromName("nn::sf::hipc::detail::IHipcManager")); } #define AMS_IMPL_CHECK_INTERFACE_ID(AMS_INTF) \ static_assert(AMS_INTF::InterfaceIdForDebug == GenerateInterfaceIdFromAtmosphereName( #AMS_INTF ), #AMS_INTF) AMS_IMPL_CHECK_INTERFACE_ID(ams::capsrv::sf::IDecoderControlService); AMS_IMPL_CHECK_INTERFACE_ID(ams::erpt::sf::IAttachment); AMS_IMPL_CHECK_INTERFACE_ID(ams::erpt::sf::IContext); AMS_IMPL_CHECK_INTERFACE_ID(ams::erpt::sf::IManager); AMS_IMPL_CHECK_INTERFACE_ID(ams::erpt::sf::IReport); AMS_IMPL_CHECK_INTERFACE_ID(ams::erpt::sf::ISession); static_assert(::ams::fatal::impl::IPrivateService::InterfaceIdForDebug == GenerateInterfaceIdFromName("nn::fatalsrv::IPrivateService")); // TODO: FIX-TO-MATCH static_assert(::ams::fatal::impl::IService::InterfaceIdForDebug == GenerateInterfaceIdFromName("nn::fatalsrv::IService")); // TODO: FIX-TO-MATCH AMS_IMPL_CHECK_INTERFACE_ID(ams::fssrv::sf::IDirectory); AMS_IMPL_CHECK_INTERFACE_ID(ams::fssrv::sf::IFile); AMS_IMPL_CHECK_INTERFACE_ID(ams::fssrv::sf::IFileSystem); AMS_IMPL_CHECK_INTERFACE_ID(ams::fssrv::sf::IStorage); AMS_IMPL_CHECK_INTERFACE_ID(ams::fssrv::sf::IDeviceOperator); AMS_IMPL_CHECK_INTERFACE_ID(ams::fssrv::sf::IEventNotifier); AMS_IMPL_CHECK_INTERFACE_ID(ams::fssrv::sf::IFileSystemProxy); AMS_IMPL_CHECK_INTERFACE_ID(ams::fssrv::sf::IFileSystemProxyForLoader); AMS_IMPL_CHECK_INTERFACE_ID(ams::fssrv::sf::IProgramRegistry); static_assert(::ams::gpio::sf::IManager::InterfaceIdForDebug == GenerateInterfaceIdFromName("nn::gpio::IManager")); // TODO: FIX-TO-MATCH static_assert(::ams::gpio::sf::IPadSession::InterfaceIdForDebug == GenerateInterfaceIdFromName("nn::gpio::IPadSession")); // TODO: FIX-TO-MATCH AMS_IMPL_CHECK_INTERFACE_ID(ams::htc::tenv::IService); AMS_IMPL_CHECK_INTERFACE_ID(ams::htc::tenv::IServiceManager); static_assert(::ams::i2c::sf::IManager::InterfaceIdForDebug == GenerateInterfaceIdFromName("nn::i2c::IManager")); // TODO: FIX-TO-MATCH static_assert(::ams::i2c::sf::ISession::InterfaceIdForDebug == GenerateInterfaceIdFromName("nn::i2c::ISession")); // TODO: FIX-TO-MATCH AMS_IMPL_CHECK_INTERFACE_ID(ams::ldr::impl::IDebugMonitorInterface); AMS_IMPL_CHECK_INTERFACE_ID(ams::ldr::impl::IProcessManagerInterface); AMS_IMPL_CHECK_INTERFACE_ID(ams::ldr::impl::IShellInterface); AMS_IMPL_CHECK_INTERFACE_ID(ams::lr::IAddOnContentLocationResolver); AMS_IMPL_CHECK_INTERFACE_ID(ams::lr::ILocationResolver); AMS_IMPL_CHECK_INTERFACE_ID(ams::lr::ILocationResolverManager); AMS_IMPL_CHECK_INTERFACE_ID(ams::lr::IRegisteredLocationResolver); AMS_IMPL_CHECK_INTERFACE_ID(ams::lm::ILogGetter); AMS_IMPL_CHECK_INTERFACE_ID(ams::lm::ILogger); AMS_IMPL_CHECK_INTERFACE_ID(ams::lm::ILogService); AMS_IMPL_CHECK_INTERFACE_ID(ams::ncm::IContentManager); AMS_IMPL_CHECK_INTERFACE_ID(ams::ncm::IContentMetaDatabase); AMS_IMPL_CHECK_INTERFACE_ID(ams::ncm::IContentStorage); AMS_IMPL_CHECK_INTERFACE_ID(ams::ns::impl::IAsyncResult); //AMS_IMPL_CHECK_INTERFACE_ID(ams::pgl::sf::IEventObserver); //AMS_IMPL_CHECK_INTERFACE_ID(ams::pgl::sf::IShellInterface); AMS_IMPL_CHECK_INTERFACE_ID(ams::pm::impl::IBootModeInterface); AMS_IMPL_CHECK_INTERFACE_ID(ams::pm::impl::IDebugMonitorInterface); AMS_IMPL_CHECK_INTERFACE_ID(ams::pm::impl::IDeprecatedDebugMonitorInterface); AMS_IMPL_CHECK_INTERFACE_ID(ams::pm::impl::IInformationInterface); AMS_IMPL_CHECK_INTERFACE_ID(ams::pm::impl::IShellInterface); AMS_IMPL_CHECK_INTERFACE_ID(ams::pm::impl::IDeprecatedShellInterface); AMS_IMPL_CHECK_INTERFACE_ID(ams::psc::sf::IPmModule); AMS_IMPL_CHECK_INTERFACE_ID(ams::psc::sf::IPmService); static_assert(::ams::pwm::sf::IChannelSession::InterfaceIdForDebug == GenerateInterfaceIdFromName("nn::pwm::IChannelSession")); // TODO: FIX-TO-MATCH static_assert(::ams::pwm::sf::IManager::InterfaceIdForDebug == GenerateInterfaceIdFromName("nn::pwm::IManager")); // TODO: FIX-TO-MATCH AMS_IMPL_CHECK_INTERFACE_ID(ams::ro::impl::IDebugMonitorInterface); AMS_IMPL_CHECK_INTERFACE_ID(ams::ro::impl::IRoInterface); //AMS_IMPL_CHECK_INTERFACE_ID(ams::sf::hipc::impl::IMitmQueryService); AMS_IMPL_CHECK_INTERFACE_ID(ams::sf::hipc::impl::IHipcManager); AMS_IMPL_CHECK_INTERFACE_ID(ams::spl::impl::ICryptoInterface); AMS_IMPL_CHECK_INTERFACE_ID(ams::spl::impl::IDeprecatedGeneralInterface); AMS_IMPL_CHECK_INTERFACE_ID(ams::spl::impl::IDeviceUniqueDataInterface); AMS_IMPL_CHECK_INTERFACE_ID(ams::spl::impl::IEsInterface); AMS_IMPL_CHECK_INTERFACE_ID(ams::spl::impl::IFsInterface); AMS_IMPL_CHECK_INTERFACE_ID(ams::spl::impl::IGeneralInterface); AMS_IMPL_CHECK_INTERFACE_ID(ams::spl::impl::IManuInterface); AMS_IMPL_CHECK_INTERFACE_ID(ams::spl::impl::IRandomInterface); AMS_IMPL_CHECK_INTERFACE_ID(ams::spl::impl::ISslInterface); AMS_IMPL_CHECK_INTERFACE_ID(ams::sprofile::srv::IProfileControllerForDebug); AMS_IMPL_CHECK_INTERFACE_ID(ams::sprofile::srv::IProfileImporter); AMS_IMPL_CHECK_INTERFACE_ID(ams::sprofile::srv::IProfileReader); AMS_IMPL_CHECK_INTERFACE_ID(ams::sprofile::srv::IProfileUpdateObserver); AMS_IMPL_CHECK_INTERFACE_ID(ams::sprofile::srv::ISprofileServiceForBgAgent); AMS_IMPL_CHECK_INTERFACE_ID(ams::sprofile::srv::ISprofileServiceForSystemProcess); AMS_IMPL_CHECK_INTERFACE_ID(ams::sprofile::srv::IServiceGetter); AMS_IMPL_CHECK_INTERFACE_ID(ams::tma::IDirectoryAccessor); AMS_IMPL_CHECK_INTERFACE_ID(ams::tma::IFileAccessor); AMS_IMPL_CHECK_INTERFACE_ID(ams::tma::IFileManager); AMS_IMPL_CHECK_INTERFACE_ID(ams::tma::IDeprecatedFileManager); AMS_IMPL_CHECK_INTERFACE_ID(ams::tma::IHtcsManager); AMS_IMPL_CHECK_INTERFACE_ID(ams::tma::IHtcManager); AMS_IMPL_CHECK_INTERFACE_ID(ams::tma::ISocket); AMS_IMPL_CHECK_INTERFACE_ID(ams::usb::ds::IDsEndpoint); AMS_IMPL_CHECK_INTERFACE_ID(ams::usb::ds::IDsInterface); AMS_IMPL_CHECK_INTERFACE_ID(ams::usb::ds::IDsService); AMS_IMPL_CHECK_INTERFACE_ID(ams::usb::ds::IDsRootSession);
9,388
C++
.cpp
163
52.656442
246
0.685357
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,381
sf_default_allocation_policy.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/sf/sf_default_allocation_policy.cpp
/* * Copyright (c) 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::sf { namespace { struct DefaultAllocatorImpl { os::SdkMutexType tls_lock; std::atomic_bool tls_allocated; os::TlsSlot current_mr_tls_slot; MemoryResource *default_mr; void EnsureCurrentMemoryResourceTlsSlotInitialized() { if (!tls_allocated.load(std::memory_order_acquire)) { os::LockSdkMutex(std::addressof(tls_lock)); if (!tls_allocated.load(std::memory_order_relaxed)) { R_ABORT_UNLESS(os::SdkAllocateTlsSlot(std::addressof(current_mr_tls_slot), nullptr)); tls_allocated.store(true, std::memory_order_release); } os::UnlockSdkMutex(std::addressof(tls_lock)); } } MemoryResource *GetDefaultMemoryResource() { return default_mr; } MemoryResource *SetDefaultMemoryResource(MemoryResource *mr) { return util::Exchange(std::addressof(default_mr), mr); } MemoryResource *GetCurrentMemoryResource() { EnsureCurrentMemoryResourceTlsSlotInitialized(); return reinterpret_cast<MemoryResource *>(os::GetTlsValue(current_mr_tls_slot)); } MemoryResource *SetCurrentMemoryResource(MemoryResource *mr) { EnsureCurrentMemoryResourceTlsSlotInitialized(); auto ret = reinterpret_cast<MemoryResource *>(os::GetTlsValue(current_mr_tls_slot)); os::SetTlsValue(current_mr_tls_slot, reinterpret_cast<uintptr_t>(mr)); return ret; } MemoryResource *GetCurrentEffectiveMemoryResourceImpl() { if (auto mr = GetCurrentMemoryResource(); mr != nullptr) { return mr; } if (auto mr = GetGlobalDefaultMemoryResource(); mr != nullptr) { return mr; } return nullptr; } }; constinit DefaultAllocatorImpl g_default_allocator_impl = {}; inline void *DefaultAllocate(size_t size, size_t align) { AMS_UNUSED(align); return ::operator new(size, std::nothrow); } inline void DefaultDeallocate(void *ptr, size_t size, size_t align) { AMS_UNUSED(size, align); return ::operator delete(ptr, std::nothrow); } class NewDeleteMemoryResource final : public MemoryResource { private: virtual void *AllocateImpl(size_t size, size_t alignment) override { return DefaultAllocate(size, alignment); } virtual void DeallocateImpl(void *buffer, size_t size, size_t alignment) override { return DefaultDeallocate(buffer, size, alignment); } virtual bool IsEqualImpl(const MemoryResource &resource) const override { return this == std::addressof(resource); } }; constinit NewDeleteMemoryResource g_new_delete_memory_resource; } namespace impl { void *DefaultAllocateImpl(size_t size, size_t align, size_t offset) { auto mr = g_default_allocator_impl.GetCurrentEffectiveMemoryResourceImpl(); auto h = mr != nullptr ? mr->allocate(size, align) : DefaultAllocate(size, align); if (h == nullptr) { return nullptr; } *static_cast<MemoryResource **>(h) = mr; return static_cast<u8 *>(h) + offset; } void DefaultDeallocateImpl(void *ptr, size_t size, size_t align, size_t offset) { if (ptr == nullptr) { return; } auto h = static_cast<u8 *>(ptr) - offset; if (auto mr = *reinterpret_cast<MemoryResource **>(h); mr != nullptr) { return mr->deallocate(h, size, align); } else { return DefaultDeallocate(h, size, align); } } } MemoryResource *GetGlobalDefaultMemoryResource() { return g_default_allocator_impl.GetDefaultMemoryResource(); } MemoryResource *GetCurrentEffectiveMemoryResource() { if (auto mr = g_default_allocator_impl.GetCurrentEffectiveMemoryResourceImpl(); mr != nullptr) { return mr; } return GetNewDeleteMemoryResource(); } MemoryResource *GetCurrentMemoryResource() { return g_default_allocator_impl.GetCurrentMemoryResource(); } MemoryResource *GetNewDeleteMemoryResource() { return std::addressof(g_new_delete_memory_resource); } MemoryResource *SetGlobalDefaultMemoryResource(MemoryResource *mr) { return g_default_allocator_impl.SetDefaultMemoryResource(mr); } MemoryResource *SetCurrentMemoryResource(MemoryResource *mr) { return g_default_allocator_impl.SetCurrentMemoryResource(mr); } ScopedCurrentMemoryResourceSetter::ScopedCurrentMemoryResourceSetter(MemoryResource *mr) : m_prev(g_default_allocator_impl.GetCurrentMemoryResource()) { os::SetTlsValue(g_default_allocator_impl.current_mr_tls_slot, reinterpret_cast<uintptr_t>(mr)); } ScopedCurrentMemoryResourceSetter::~ScopedCurrentMemoryResourceSetter() { os::SetTlsValue(g_default_allocator_impl.current_mr_tls_slot, reinterpret_cast<uintptr_t>(m_prev)); } }
6,192
C++
.cpp
132
35.659091
156
0.622657
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,382
sf_hipc_api.os.generic.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/sf/hipc/sf_hipc_api.os.generic.cpp
/* * Copyright (c) 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::sf::hipc { void AttachMultiWaitHolderForAccept(os::MultiWaitHolderType *, os::NativeHandle) { AMS_ABORT("TODO: Generic ams::sf::hipc::AttachMultiWaitHolderForAccept"); } void AttachMultiWaitHolderForReply(os::MultiWaitHolderType *, os::NativeHandle) { AMS_ABORT("TODO: Generic ams::sf::hipc::AttachMultiWaitHolderForAccept"); } Result Receive(ReceiveResult *, os::NativeHandle, const cmif::PointerAndSize &) { AMS_ABORT("TODO: Generic ams::sf::hipc::Receive(ReceiveResult *, os::NativeHandle, const cmif::PointerAndSize &)"); } Result Receive(bool *, os::NativeHandle, const cmif::PointerAndSize &) { AMS_ABORT("TODO: Generic ams::sf::hipc::Receive(bool *, os::NativeHandle, const cmif::PointerAndSize &)"); } Result Reply(os::NativeHandle, const cmif::PointerAndSize &) { AMS_ABORT("TODO: Generic ams::sf::hipc::Reply"); } Result CreateSession(os::NativeHandle *, os::NativeHandle *) { AMS_ABORT("TODO: Generic ams::sf::hipc::CreateSession"); } }
1,730
C++
.cpp
36
43.777778
123
0.717082
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,383
sf_hipc_server_manager.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/sf/hipc/sf_hipc_server_manager.cpp
/* * Copyright (c) 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 "sf_hipc_mitm_query_api.hpp" namespace ams::sf::hipc { #if AMS_SF_MITM_SUPPORTED Result ServerManagerBase::InstallMitmServerImpl(os::NativeHandle *out_port_handle, sm::ServiceName service_name, ServerManagerBase::MitmQueryFunction query_func) { /* Install the Mitm. */ os::NativeHandle query_handle; R_TRY(sm::mitm::InstallMitm(out_port_handle, std::addressof(query_handle), service_name)); /* Register the query handle. */ impl::RegisterMitmQueryHandle(query_handle, query_func); /* Clear future declarations if any, now that our query handler is present. */ R_ABORT_UNLESS(sm::mitm::ClearFutureMitm(service_name)); R_SUCCEED(); } #endif void ServerManagerBase::RegisterServerSessionToWait(ServerSession *session) { session->m_has_received = false; /* Set user data tag. */ os::SetMultiWaitHolderUserData(session, static_cast<uintptr_t>(UserDataTag::Session)); this->LinkToDeferredList(session); } void ServerManagerBase::LinkToDeferredList(os::MultiWaitHolderType *holder) { std::scoped_lock lk(m_deferred_list_mutex); os::LinkMultiWaitHolder(std::addressof(m_deferred_list), holder); m_notify_event.Signal(); } void ServerManagerBase::LinkDeferred() { std::scoped_lock lk(m_deferred_list_mutex); os::MoveAllMultiWaitHolder(std::addressof(m_multi_wait), std::addressof(m_deferred_list)); } os::MultiWaitHolderType *ServerManagerBase::WaitSignaled() { std::scoped_lock lk(m_selection_mutex); while (true) { this->LinkDeferred(); auto selected = os::WaitAny(std::addressof(m_multi_wait)); if (selected == std::addressof(m_request_stop_event_holder)) { return nullptr; } else if (selected == std::addressof(m_notify_event_holder)) { m_notify_event.Clear(); } else { os::UnlinkMultiWaitHolder(selected); return selected; } } } void ServerManagerBase::ResumeProcessing() { m_request_stop_event.Clear(); } void ServerManagerBase::RequestStopProcessing() { m_request_stop_event.Signal(); } void ServerManagerBase::AddUserMultiWaitHolder(os::MultiWaitHolderType *holder) { const auto user_data_tag = static_cast<UserDataTag>(os::GetMultiWaitHolderUserData(holder)); AMS_ABORT_UNLESS(user_data_tag != UserDataTag::Server); AMS_ABORT_UNLESS(user_data_tag != UserDataTag::Session); #if AMS_SF_MITM_SUPPORTED AMS_ABORT_UNLESS(user_data_tag != UserDataTag::MitmServer); #endif this->LinkToDeferredList(holder); } Result ServerManagerBase::ProcessForServer(os::MultiWaitHolderType *holder) { AMS_ABORT_UNLESS(static_cast<UserDataTag>(os::GetMultiWaitHolderUserData(holder)) == UserDataTag::Server); Server *server = static_cast<Server *>(holder); ON_SCOPE_EXIT { this->LinkToDeferredList(server); }; /* Create new session. */ if (server->m_static_object) { R_RETURN(this->AcceptSession(server->m_port_handle, server->m_static_object.Clone())); } else { R_RETURN(this->OnNeedsToAccept(server->m_index, server)); } } #if AMS_SF_MITM_SUPPORTED Result ServerManagerBase::ProcessForMitmServer(os::MultiWaitHolderType *holder) { AMS_ABORT_UNLESS(static_cast<UserDataTag>(os::GetMultiWaitHolderUserData(holder)) == UserDataTag::MitmServer); Server *server = static_cast<Server *>(holder); ON_SCOPE_EXIT { this->LinkToDeferredList(server); }; /* Create resources for new session. */ R_RETURN(this->OnNeedsToAccept(server->m_index, server)); } #endif Result ServerManagerBase::ProcessForSession(os::MultiWaitHolderType *holder) { AMS_ABORT_UNLESS(static_cast<UserDataTag>(os::GetMultiWaitHolderUserData(holder)) == UserDataTag::Session); ServerSession *session = static_cast<ServerSession *>(holder); cmif::PointerAndSize tls_message(hipc::GetMessageBufferOnTls(), hipc::TlsMessageBufferSize); if (this->CanDeferInvokeRequest()) { const cmif::PointerAndSize &saved_message = session->m_saved_message; AMS_ABORT_UNLESS(tls_message.GetSize() == saved_message.GetSize()); if (!session->m_has_received) { R_TRY(this->ReceiveRequest(session, tls_message)); session->m_has_received = true; std::memcpy(saved_message.GetPointer(), tls_message.GetPointer(), tls_message.GetSize()); } else { /* We were deferred and are re-receiving, so just memcpy. */ std::memcpy(tls_message.GetPointer(), saved_message.GetPointer(), tls_message.GetSize()); } /* Treat a meta "Context Invalidated" message as a success. */ R_TRY_CATCH(this->ProcessRequest(session, tls_message)) { R_CONVERT(sf::impl::ResultRequestInvalidated, ResultSuccess()); } R_END_TRY_CATCH; } else { if (!session->m_has_received) { R_TRY(this->ReceiveRequest(session, tls_message)); session->m_has_received = true; #if AMS_SF_MITM_SUPPORTED if (this->CanManageMitmServers()) { const cmif::PointerAndSize &saved_message = session->m_saved_message; AMS_ABORT_UNLESS(tls_message.GetSize() == saved_message.GetSize()); std::memcpy(saved_message.GetPointer(), tls_message.GetPointer(), tls_message.GetSize()); } #endif } R_TRY_CATCH(this->ProcessRequest(session, tls_message)) { R_CATCH(sf::ResultRequestDeferred) { AMS_ABORT("Request Deferred on server which does not support deferral"); } R_CATCH(sf::impl::ResultRequestInvalidated) { AMS_ABORT("Request Invalidated on server which does not support deferral"); } } R_END_TRY_CATCH; } R_SUCCEED(); } Result ServerManagerBase::Process(os::MultiWaitHolderType *holder) { switch (static_cast<UserDataTag>(os::GetMultiWaitHolderUserData(holder))) { case UserDataTag::Server: R_RETURN(this->ProcessForServer(holder)); case UserDataTag::Session: R_RETURN(this->ProcessForSession(holder)); #if AMS_SF_MITM_SUPPORTED case UserDataTag::MitmServer: AMS_ABORT_UNLESS(this->CanManageMitmServers()); R_RETURN(this->ProcessForMitmServer(holder)); #endif AMS_UNREACHABLE_DEFAULT_CASE(); } } bool ServerManagerBase::WaitAndProcessImpl() { if (auto *signaled_holder = this->WaitSignaled(); signaled_holder != nullptr) { R_ABORT_UNLESS(this->Process(signaled_holder)); return true; } else { return false; } } void ServerManagerBase::WaitAndProcess() { this->WaitAndProcessImpl(); } void ServerManagerBase::LoopProcess() { while (this->WaitAndProcessImpl()) { /* ... */ } } }
8,002
C++
.cpp
164
39.231707
167
0.642491
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,384
sf_hipc_api.os.horizon.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/sf/hipc/sf_hipc_api.os.horizon.cpp
/* * Copyright (c) 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::sf::hipc { namespace { ALWAYS_INLINE Result ReceiveImpl(os::NativeHandle session_handle, void *message_buf, size_t message_buf_size) { s32 unused_index; if (message_buf == hipc::GetMessageBufferOnTls()) { /* Consider: AMS_ABORT_UNLESS(message_buf_size == TlsMessageBufferSize); */ R_RETURN(svc::ReplyAndReceive(&unused_index, &session_handle, 1, svc::InvalidHandle, std::numeric_limits<u64>::max())); } else { R_RETURN(svc::ReplyAndReceiveWithUserBuffer(&unused_index, reinterpret_cast<uintptr_t>(message_buf), message_buf_size, &session_handle, 1, svc::InvalidHandle, std::numeric_limits<u64>::max())); } } ALWAYS_INLINE Result ReplyImpl(os::NativeHandle session_handle, void *message_buf, size_t message_buf_size) { s32 unused_index; if (message_buf == hipc::GetMessageBufferOnTls()) { /* Consider: AMS_ABORT_UNLESS(message_buf_size == TlsMessageBufferSize); */ R_RETURN(svc::ReplyAndReceive(&unused_index, &session_handle, 0, session_handle, 0)); } else { R_RETURN(svc::ReplyAndReceiveWithUserBuffer(&unused_index, reinterpret_cast<uintptr_t>(message_buf), message_buf_size, &session_handle, 0, session_handle, 0)); } } } void AttachMultiWaitHolderForAccept(os::MultiWaitHolderType *holder, os::NativeHandle port) { return os::InitializeMultiWaitHolder(holder, port); } void AttachMultiWaitHolderForReply(os::MultiWaitHolderType *holder, os::NativeHandle request) { return os::InitializeMultiWaitHolder(holder, request); } Result Receive(ReceiveResult *out_recv_result, os::NativeHandle session_handle, const cmif::PointerAndSize &message_buffer) { R_TRY_CATCH(ReceiveImpl(session_handle, message_buffer.GetPointer(), message_buffer.GetSize())) { R_CATCH(svc::ResultSessionClosed) { *out_recv_result = ReceiveResult::Closed; R_SUCCEED(); } R_CATCH(svc::ResultReceiveListBroken) { *out_recv_result = ReceiveResult::NeedsRetry; R_SUCCEED(); } } R_END_TRY_CATCH; *out_recv_result = ReceiveResult::Success; R_SUCCEED(); } Result Receive(bool *out_closed, os::NativeHandle session_handle, const cmif::PointerAndSize &message_buffer) { R_TRY_CATCH(ReceiveImpl(session_handle, message_buffer.GetPointer(), message_buffer.GetSize())) { R_CATCH(svc::ResultSessionClosed) { *out_closed = true; R_SUCCEED(); } } R_END_TRY_CATCH; *out_closed = false; R_SUCCEED(); } Result Reply(os::NativeHandle session_handle, const cmif::PointerAndSize &message_buffer) { R_TRY_CATCH(ReplyImpl(session_handle, message_buffer.GetPointer(), message_buffer.GetSize())) { R_CONVERT(svc::ResultTimedOut, ResultSuccess()) R_CONVERT(svc::ResultSessionClosed, ResultSuccess()) } R_END_TRY_CATCH; /* ReplyImpl should *always* return an error. */ AMS_ABORT_UNLESS(false); } Result CreateSession(os::NativeHandle *out_server_handle, os::NativeHandle *out_client_handle) { R_TRY_CATCH(svc::CreateSession(out_server_handle, out_client_handle, 0, 0)) { R_CONVERT(svc::ResultOutOfResource, sf::hipc::ResultOutOfSessions()); } R_END_TRY_CATCH; R_SUCCEED(); } }
4,237
C++
.cpp
82
42.792683
209
0.655805
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,385
sf_hipc_server_domain_session_manager.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/sf/hipc/sf_hipc_server_domain_session_manager.cpp
/* * Copyright (c) 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 "sf_i_hipc_manager.hpp" namespace ams::sf::hipc { namespace impl { class HipcManagerImpl { private: ServerDomainSessionManager *m_manager; ServerSession *m_session; #if AMS_SF_MITM_SUPPORTED const bool m_is_mitm_session; #endif private: Result CloneCurrentObjectImpl(sf::OutMoveHandle &out_client_handle, ServerSessionManager *tagged_manager) { /* Clone the object. */ cmif::ServiceObjectHolder &&clone = m_session->m_srv_obj_holder.Clone(); R_UNLESS(clone, sf::hipc::ResultDomainObjectNotFound()); /* Create new session handles. */ os::NativeHandle server_handle, client_handle; R_ABORT_UNLESS(hipc::CreateSession(std::addressof(server_handle), std::addressof(client_handle))); /* Register with manager. */ #if AMS_SF_MITM_SUPPORTED if (!m_is_mitm_session) { #endif R_ABORT_UNLESS(tagged_manager->RegisterSession(server_handle, std::move(clone))); #if AMS_SF_MITM_SUPPORTED } else { /* Check that we can create a mitm session. */ AMS_ABORT_UNLESS(ServerManagerBase::CanAnyManageMitmServers()); /* Clone the forward service. */ std::shared_ptr<::Service> new_forward_service = ServerSession::CreateForwardService(); R_ABORT_UNLESS(serviceClone(util::GetReference(m_session->m_forward_service).get(), new_forward_service.get())); R_ABORT_UNLESS(tagged_manager->RegisterMitmSession(server_handle, std::move(clone), std::move(new_forward_service))); } #endif /* Set output client handle. */ out_client_handle.SetValue(client_handle, false); R_SUCCEED(); } public: #if AMS_SF_MITM_SUPPORTED explicit HipcManagerImpl(ServerDomainSessionManager *m, ServerSession *s) : m_manager(m), m_session(s), m_is_mitm_session(s->IsMitmSession()) { /* ... */ } #else explicit HipcManagerImpl(ServerDomainSessionManager *m, ServerSession *s) : m_manager(m), m_session(s) { /* ... */ } #endif Result ConvertCurrentObjectToDomain(sf::Out<cmif::DomainObjectId> out) { /* Allocate a domain. */ auto domain = m_manager->AllocateDomainServiceObject(); R_UNLESS(domain, sf::hipc::ResultOutOfDomains()); /* Set up the new domain object. */ cmif::DomainObjectId object_id = cmif::InvalidDomainObjectId; #if AMS_SF_MITM_SUPPORTED if (m_is_mitm_session) { /* Check that we can create a mitm session. */ AMS_ABORT_UNLESS(ServerManagerBase::CanAnyManageMitmServers()); /* Make a new shared pointer to manage the allocated domain. */ SharedPointer<cmif::MitmDomainServiceObject> cmif_domain(static_cast<cmif::MitmDomainServiceObject *>(domain), false); /* Convert the remote session to domain. */ AMS_ABORT_UNLESS(util::GetReference(m_session->m_forward_service)->own_handle); R_TRY(serviceConvertToDomain(util::GetReference(m_session->m_forward_service).get())); /* The object ID reservation cannot fail here, as that would cause desynchronization from target domain. */ object_id = cmif::DomainObjectId{util::GetReference(m_session->m_forward_service)->object_id}; domain->ReserveSpecificIds(std::addressof(object_id), 1); /* Register the object. */ domain->RegisterObject(object_id, std::move(m_session->m_srv_obj_holder)); /* Set the new object holder. */ m_session->m_srv_obj_holder = cmif::ServiceObjectHolder(std::move(cmif_domain)); } else { #else { #endif /* Make a new shared pointer to manage the allocated domain. */ SharedPointer<cmif::DomainServiceObject> cmif_domain(domain, false); /* Reserve a new object in the domain. */ R_TRY(domain->ReserveIds(std::addressof(object_id), 1)); /* Register the object. */ domain->RegisterObject(object_id, std::move(m_session->m_srv_obj_holder)); /* Set the new object holder. */ m_session->m_srv_obj_holder = cmif::ServiceObjectHolder(std::move(cmif_domain)); } /* Return the allocated id. */ AMS_ABORT_UNLESS(object_id != cmif::InvalidDomainObjectId); *out = object_id; R_SUCCEED(); } Result CopyFromCurrentDomain(sf::OutMoveHandle out, cmif::DomainObjectId object_id) { /* Get domain. */ auto domain = m_session->m_srv_obj_holder.GetServiceObject<cmif::DomainServiceObject>(); R_UNLESS(domain != nullptr, sf::hipc::ResultTargetNotDomain()); /* Get domain object. */ auto &&object = domain->GetObject(object_id); #if AMS_SF_MITM_SUPPORTED if (!object) { R_UNLESS(m_is_mitm_session, sf::hipc::ResultDomainObjectNotFound()); /* Check that we can create a mitm session. */ AMS_ABORT_UNLESS(ServerManagerBase::CanAnyManageMitmServers()); os::NativeHandle handle; R_TRY(cmifCopyFromCurrentDomain(util::GetReference(m_session->m_forward_service)->session, object_id.value, std::addressof(handle))); out.SetValue(handle, false); R_SUCCEED(); } #else R_UNLESS(!!(object), sf::hipc::ResultDomainObjectNotFound()); #endif #if AMS_SF_MITM_SUPPORTED if (!m_is_mitm_session || (ServerManagerBase::CanAnyManageMitmServers() && object_id.value != serviceGetObjectId(util::GetReference(m_session->m_forward_service).get()))) { #else { #endif /* Create new session handles. */ os::NativeHandle server_handle, client_handle; R_ABORT_UNLESS(hipc::CreateSession(std::addressof(server_handle), std::addressof(client_handle))); /* Register. */ R_ABORT_UNLESS(m_manager->RegisterSession(server_handle, std::move(object))); /* Set output client handle. */ out.SetValue(client_handle, false); #if AMS_SF_MITM_SUPPORTED } else { /* Check that we can create a mitm session. */ AMS_ABORT_UNLESS(ServerManagerBase::CanAnyManageMitmServers()); /* Copy from the target domain. */ os::NativeHandle new_forward_target; R_TRY(cmifCopyFromCurrentDomain(util::GetReference(m_session->m_forward_service)->session, object_id.value, std::addressof(new_forward_target))); /* Create new session handles. */ os::NativeHandle server_handle, client_handle; R_ABORT_UNLESS(hipc::CreateSession(std::addressof(server_handle), std::addressof(client_handle))); /* Register. */ std::shared_ptr<::Service> new_forward_service = ServerSession::CreateForwardService(); serviceCreate(new_forward_service.get(), new_forward_target); R_ABORT_UNLESS(m_manager->RegisterMitmSession(server_handle, std::move(object), std::move(new_forward_service))); /* Set output client handle. */ out.SetValue(client_handle, false); #endif } R_SUCCEED(); } Result CloneCurrentObject(sf::OutMoveHandle out) { R_RETURN(this->CloneCurrentObjectImpl(out, m_manager)); } void QueryPointerBufferSize(sf::Out<u16> out) { out.SetValue(m_session->m_pointer_buffer.GetSize()); } Result CloneCurrentObjectEx(sf::OutMoveHandle out, u32 tag) { R_RETURN(this->CloneCurrentObjectImpl(out, m_manager->GetSessionManagerByTag(tag))); } }; static_assert(IsIHipcManager<HipcManagerImpl>); } Result ServerDomainSessionManager::DispatchManagerRequest(ServerSession *session, const cmif::PointerAndSize &in_message, const cmif::PointerAndSize &out_message) { /* Make a stack object, and pass a shared pointer to it to DispatchRequest. */ /* Note: This is safe, as no additional references to the hipc manager can ever be stored. */ /* The shared pointer to stack object is definitely gross, though. */ UnmanagedServiceObject<impl::IHipcManager, impl::HipcManagerImpl> hipc_manager(this, session); R_RETURN(this->DispatchRequest(cmif::ServiceObjectHolder(hipc_manager.GetShared()), session, in_message, out_message)); } }
10,731
C++
.cpp
170
44.317647
192
0.552547
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,386
sf_hipc_server_session_manager.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/sf/hipc/sf_hipc_server_session_manager.cpp
/* * Copyright (c) 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::sf::hipc { namespace { #if AMS_SF_MITM_SUPPORTED constexpr inline void PreProcessCommandBufferForMitm(const cmif::ServiceDispatchContext &ctx, const cmif::PointerAndSize &pointer_buffer, uintptr_t cmd_buffer) { /* TODO: Less gross method of editing command buffer? */ if (ctx.request.meta.send_pid) { constexpr u64 MitmProcessIdTag = 0xFFFE000000000000ul; constexpr u64 OldProcessIdMask = 0x0000FFFFFFFFFFFFul; u64 *process_id = reinterpret_cast<u64 *>(cmd_buffer + sizeof(HipcHeader) + sizeof(HipcSpecialHeader)); *process_id = (MitmProcessIdTag) | (*process_id & OldProcessIdMask); } if (ctx.request.meta.num_recv_statics) { /* TODO: Can we do this without gross bit-hackery? */ reinterpret_cast<HipcHeader *>(cmd_buffer)->recv_static_mode = 2; const uintptr_t old_recv_list_entry = reinterpret_cast<uintptr_t>(ctx.request.data.recv_list); const size_t old_recv_list_offset = old_recv_list_entry - util::AlignDown(old_recv_list_entry, TlsMessageBufferSize); *reinterpret_cast<HipcRecvListEntry *>(cmd_buffer + old_recv_list_offset) = hipcMakeRecvStatic(pointer_buffer.GetPointer(), pointer_buffer.GetSize()); } } #endif } #if AMS_SF_MITM_SUPPORTED Result ServerSession::ForwardRequest(const cmif::ServiceDispatchContext &ctx) const { AMS_ABORT_UNLESS(ServerManagerBase::CanAnyManageMitmServers()); AMS_ABORT_UNLESS(this->IsMitmSession()); /* TODO: Support non-TLS messages? */ AMS_ABORT_UNLESS(m_saved_message.GetPointer() != nullptr); AMS_ABORT_UNLESS(m_saved_message.GetSize() == TlsMessageBufferSize); /* Get TLS message buffer. */ u32 * const message_buffer = static_cast<u32 *>(hipc::GetMessageBufferOnTls()); /* Copy saved TLS in. */ std::memcpy(message_buffer, m_saved_message.GetPointer(), m_saved_message.GetSize()); /* Prepare buffer. */ PreProcessCommandBufferForMitm(ctx, m_pointer_buffer, reinterpret_cast<uintptr_t>(message_buffer)); /* Dispatch forwards. */ R_TRY(svc::SendSyncRequest(util::GetReference(m_forward_service)->session)); /* Parse, to ensure we catch any copy handles and close them. */ { const auto response = hipcParseResponse(message_buffer); if (response.num_copy_handles) { ctx.handles_to_close->num_handles = response.num_copy_handles; for (size_t i = 0; i < response.num_copy_handles; i++) { ctx.handles_to_close->handles[i] = response.copy_handles[i]; } } } R_SUCCEED(); } #endif void ServerSessionManager::DestroySession(ServerSession *session) { /* Destroy object. */ std::destroy_at(session); /* Free object memory. */ this->FreeSession(session); } void ServerSessionManager::CloseSessionImpl(ServerSession *session) { const auto session_handle = session->m_session_handle; os::FinalizeMultiWaitHolder(session); this->DestroySession(session); os::CloseNativeHandle(session_handle); } Result ServerSessionManager::RegisterSessionImpl(ServerSession *session_memory, os::NativeHandle session_handle, cmif::ServiceObjectHolder &&obj) { /* Create session object. */ std::construct_at(session_memory, session_handle, std::forward<cmif::ServiceObjectHolder>(obj)); /* Assign session resources. */ session_memory->m_pointer_buffer = this->GetSessionPointerBuffer(session_memory); session_memory->m_saved_message = this->GetSessionSavedMessageBuffer(session_memory); /* Register to wait list. */ this->RegisterServerSessionToWait(session_memory); R_SUCCEED(); } Result ServerSessionManager::AcceptSessionImpl(ServerSession *session_memory, os::NativeHandle port_handle, cmif::ServiceObjectHolder &&obj) { /* Create session handle. */ os::NativeHandle session_handle; #if defined(ATMOSPHERE_OS_HORIZON) R_TRY(svc::AcceptSession(std::addressof(session_handle), port_handle)); #else AMS_UNUSED(port_handle); AMS_ABORT("TODO"); #endif auto session_guard = SCOPE_GUARD { os::CloseNativeHandle(session_handle); }; /* Register session. */ R_TRY(this->RegisterSessionImpl(session_memory, session_handle, std::forward<cmif::ServiceObjectHolder>(obj))); session_guard.Cancel(); R_SUCCEED(); } #if AMS_SF_MITM_SUPPORTED Result ServerSessionManager::RegisterMitmSessionImpl(ServerSession *session_memory, os::NativeHandle mitm_session_handle, cmif::ServiceObjectHolder &&obj, std::shared_ptr<::Service> &&fsrv) { AMS_ABORT_UNLESS(ServerManagerBase::CanAnyManageMitmServers()); /* Create session object. */ std::construct_at(session_memory, mitm_session_handle, std::forward<cmif::ServiceObjectHolder>(obj), std::forward<std::shared_ptr<::Service>>(fsrv)); /* Assign session resources. */ session_memory->m_pointer_buffer = this->GetSessionPointerBuffer(session_memory); session_memory->m_saved_message = this->GetSessionSavedMessageBuffer(session_memory); /* Validate session pointer buffer. */ AMS_ABORT_UNLESS(session_memory->m_pointer_buffer.GetSize() >= util::GetReference(session_memory->m_forward_service)->pointer_buffer_size); session_memory->m_pointer_buffer = cmif::PointerAndSize(session_memory->m_pointer_buffer.GetAddress(), util::GetReference(session_memory->m_forward_service)->pointer_buffer_size); /* Register to wait list. */ this->RegisterServerSessionToWait(session_memory); R_SUCCEED(); } Result ServerSessionManager::AcceptMitmSessionImpl(ServerSession *session_memory, os::NativeHandle mitm_port_handle, cmif::ServiceObjectHolder &&obj, std::shared_ptr<::Service> &&fsrv) { AMS_ABORT_UNLESS(ServerManagerBase::CanAnyManageMitmServers()); /* Create session handle. */ os::NativeHandle mitm_session_handle; R_TRY(svc::AcceptSession(std::addressof(mitm_session_handle), mitm_port_handle)); auto session_guard = SCOPE_GUARD { os::CloseNativeHandle(mitm_session_handle); }; /* Register session. */ R_TRY(this->RegisterMitmSessionImpl(session_memory, mitm_session_handle, std::forward<cmif::ServiceObjectHolder>(obj), std::forward<std::shared_ptr<::Service>>(fsrv))); session_guard.Cancel(); R_SUCCEED(); } #endif Result ServerSessionManager::RegisterSession(os::NativeHandle session_handle, cmif::ServiceObjectHolder &&obj) { /* We don't actually care about what happens to the session. It'll get linked. */ ServerSession *session_ptr = nullptr; R_RETURN(this->RegisterSession(std::addressof(session_ptr), session_handle, std::forward<cmif::ServiceObjectHolder>(obj))); } Result ServerSessionManager::AcceptSession(os::NativeHandle port_handle, cmif::ServiceObjectHolder &&obj) { /* We don't actually care about what happens to the session. It'll get linked. */ ServerSession *session_ptr = nullptr; R_RETURN(this->AcceptSession(std::addressof(session_ptr), port_handle, std::forward<cmif::ServiceObjectHolder>(obj))); } #if AMS_SF_MITM_SUPPORTED Result ServerSessionManager::RegisterMitmSession(os::NativeHandle mitm_session_handle, cmif::ServiceObjectHolder &&obj, std::shared_ptr<::Service> &&fsrv) { /* We don't actually care about what happens to the session. It'll get linked. */ ServerSession *session_ptr = nullptr; R_RETURN(this->RegisterMitmSession(std::addressof(session_ptr), mitm_session_handle, std::forward<cmif::ServiceObjectHolder>(obj), std::forward<std::shared_ptr<::Service>>(fsrv))); } Result ServerSessionManager::AcceptMitmSession(os::NativeHandle mitm_port_handle, cmif::ServiceObjectHolder &&obj, std::shared_ptr<::Service> &&fsrv) { /* We don't actually care about what happens to the session. It'll get linked. */ ServerSession *session_ptr = nullptr; R_RETURN(this->AcceptMitmSession(std::addressof(session_ptr), mitm_port_handle, std::forward<cmif::ServiceObjectHolder>(obj), std::forward<std::shared_ptr<::Service>>(fsrv))); } #endif Result ServerSessionManager::ReceiveRequestImpl(ServerSession *session, const cmif::PointerAndSize &message) { const cmif::PointerAndSize &pointer_buffer = session->m_pointer_buffer; /* If the receive list is odd, we may need to receive repeatedly. */ while (true) { if (pointer_buffer.GetPointer()) { hipcMakeRequestInline(message.GetPointer(), .type = CmifCommandType_Invalid, .num_recv_statics = HIPC_AUTO_RECV_STATIC, ).recv_list[0] = hipcMakeRecvStatic(pointer_buffer.GetPointer(), pointer_buffer.GetSize()); } else { hipcMakeRequestInline(message.GetPointer(), .type = CmifCommandType_Invalid, ); } hipc::ReceiveResult recv_result; R_TRY(hipc::Receive(std::addressof(recv_result), session->m_session_handle, message)); switch (recv_result) { case hipc::ReceiveResult::Success: session->m_is_closed = false; R_SUCCEED(); case hipc::ReceiveResult::Closed: session->m_is_closed = true; R_SUCCEED(); case hipc::ReceiveResult::NeedsRetry: continue; AMS_UNREACHABLE_DEFAULT_CASE(); } } } namespace { ALWAYS_INLINE u32 GetCmifCommandType(const cmif::PointerAndSize &message) { HipcHeader hdr = {}; __builtin_memcpy(std::addressof(hdr), message.GetPointer(), sizeof(hdr)); return hdr.type; } } Result ServerSessionManager::ProcessRequest(ServerSession *session, const cmif::PointerAndSize &message) { if (session->m_is_closed) { this->CloseSessionImpl(session); R_SUCCEED(); } switch (GetCmifCommandType(message)) { case CmifCommandType_Close: { this->CloseSessionImpl(session); R_SUCCEED(); } default: { R_TRY_CATCH(this->ProcessRequestImpl(session, message, message)) { R_CATCH_RETHROW(sf::impl::ResultRequestContextChanged) /* A meta message changing the request context has been sent. */ R_CATCH_ALL() { /* All other results indicate something went very wrong. */ this->CloseSessionImpl(session); R_SUCCEED(); } } R_END_TRY_CATCH; /* We succeeded, so we can process future messages on this session. */ this->RegisterServerSessionToWait(session); R_SUCCEED(); } } } Result ServerSessionManager::ProcessRequestImpl(ServerSession *session, const cmif::PointerAndSize &in_message, const cmif::PointerAndSize &out_message) { /* TODO: Inline context support, retrieve from raw data + 0xC. */ const auto cmif_command_type = GetCmifCommandType(in_message); const auto GetInlineContext = [&]() -> cmif::InlineContext { cmif::InlineContext ret = {}; switch (cmif_command_type) { case CmifCommandType_RequestWithContext: case CmifCommandType_ControlWithContext: if (in_message.GetSize() >= 0x10) { static_assert(sizeof(cmif::InlineContext) == 4); std::memcpy(std::addressof(ret), static_cast<u8 *>(in_message.GetPointer()) + 0xC, sizeof(ret)); } break; default: break; } return ret; }; cmif::ScopedInlineContextChanger sicc(GetInlineContext()); switch (cmif_command_type) { case CmifCommandType_Request: case CmifCommandType_RequestWithContext: R_RETURN(this->DispatchRequest(session->m_srv_obj_holder.Clone(), session, in_message, out_message)); case CmifCommandType_Control: case CmifCommandType_ControlWithContext: R_RETURN(this->DispatchManagerRequest(session, in_message, out_message)); default: R_THROW(sf::hipc::ResultUnknownCommandType()); } } Result ServerSessionManager::DispatchManagerRequest(ServerSession *session, const cmif::PointerAndSize &in_message, const cmif::PointerAndSize &out_message) { /* This will get overridden by ... WithDomain class. */ AMS_UNUSED(session, in_message, out_message); R_THROW(sf::ResultNotSupported()); } Result ServerSessionManager::DispatchRequest(cmif::ServiceObjectHolder &&obj_holder, ServerSession *session, const cmif::PointerAndSize &in_message, const cmif::PointerAndSize &out_message) { /* Create request context. */ cmif::HandlesToClose handles_to_close = {}; cmif::ServiceDispatchContext dispatch_ctx = { .srv_obj = obj_holder.GetServiceObjectUnsafe(), .manager = this, .session = session, .processor = nullptr, /* Filled in by template implementations. */ .handles_to_close = std::addressof(handles_to_close), .pointer_buffer = session->m_pointer_buffer, .in_message_buffer = in_message, .out_message_buffer = out_message, .request = hipcParseRequest(in_message.GetPointer()), }; /* Validate message sizes. */ const uintptr_t in_message_buffer_end = in_message.GetAddress() + in_message.GetSize(); const uintptr_t in_raw_addr = reinterpret_cast<uintptr_t>(dispatch_ctx.request.data.data_words); const size_t in_raw_size = dispatch_ctx.request.meta.num_data_words * sizeof(u32); /* Note: Nintendo does not validate this size before subtracting 0x10 from it. This is not exploitable. */ R_UNLESS(in_raw_size >= 0x10, sf::hipc::ResultInvalidRequestSize()); R_UNLESS(in_raw_addr + in_raw_size <= in_message_buffer_end, sf::hipc::ResultInvalidRequestSize()); const size_t recv_list_size = dispatch_ctx.request.meta.num_recv_statics == HIPC_AUTO_RECV_STATIC ? 1 : dispatch_ctx.request.meta.num_recv_statics; const uintptr_t recv_list_end = reinterpret_cast<uintptr_t>(dispatch_ctx.request.data.recv_list + recv_list_size); R_UNLESS(recv_list_end <= in_message_buffer_end, sf::hipc::ResultInvalidRequestSize()); /* CMIF has 0x10 of padding in raw data, and requires 0x10 alignment. */ const cmif::PointerAndSize in_raw_data(util::AlignUp(in_raw_addr, 0x10), in_raw_size - 0x10); /* Invoke command handler. */ R_TRY(obj_holder.ProcessMessage(dispatch_ctx, in_raw_data)); /* Reply. */ { ON_SCOPE_EXIT { for (size_t i = 0; i < handles_to_close.num_handles; i++) { os::CloseNativeHandle(handles_to_close.handles[i]); } }; R_TRY(hipc::Reply(session->m_session_handle, out_message)); } R_SUCCEED(); } }
16,431
C++
.cpp
289
46.086505
195
0.645384
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,387
sf_hipc_mitm_query_api.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/sf/hipc/sf_hipc_mitm_query_api.cpp
/* * Copyright (c) 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 "sf_hipc_mitm_query_api.hpp" #if AMS_SF_MITM_SUPPORTED #define AMS_SF_HIPC_IMPL_I_MITM_QUERY_SERVICE_INTERFACE_INFO(C, H) \ AMS_SF_METHOD_INFO(C, H, 65000, void, ShouldMitm, (sf::Out<bool> out, const sm::MitmProcessInfo &client_info), (out, client_info)) AMS_SF_DEFINE_INTERFACE(ams::sf::hipc::impl, IMitmQueryService, AMS_SF_HIPC_IMPL_I_MITM_QUERY_SERVICE_INTERFACE_INFO, 0xEC6BE3FF) namespace ams::sf::hipc::impl { namespace { class MitmQueryService { private: const ServerManagerBase::MitmQueryFunction m_query_function; public: MitmQueryService(ServerManagerBase::MitmQueryFunction qf) : m_query_function(qf) { /* ... */ } void ShouldMitm(sf::Out<bool> out, const sm::MitmProcessInfo &client_info) { *out = m_query_function(client_info); } }; static_assert(IsIMitmQueryService<MitmQueryService>); /* Globals. */ constinit os::SdkMutex g_query_server_lock; constinit bool g_constructed_server = false; constinit bool g_registered_any = false; void QueryServerProcessThreadMain(void *query_server) { reinterpret_cast<ServerManagerBase *>(query_server)->LoopProcess(); } alignas(os::ThreadStackAlignment) constinit u8 g_server_process_thread_stack[16_KB]; constinit os::ThreadType g_query_server_process_thread; constexpr size_t MaxServers = 0; util::TypedStorage<sf::hipc::ServerManager<MaxServers>> g_query_server_storage; } void RegisterMitmQueryHandle(os::NativeHandle query_handle, ServerManagerBase::MitmQueryFunction query_func) { std::scoped_lock lk(g_query_server_lock); if (AMS_UNLIKELY(!g_constructed_server)) { util::ConstructAt(g_query_server_storage); g_constructed_server = true; } /* TODO: Better object factory? */ R_ABORT_UNLESS(GetReference(g_query_server_storage).RegisterSession(query_handle, cmif::ServiceObjectHolder(sf::CreateSharedObjectEmplaced<IMitmQueryService, MitmQueryService>(query_func)))); if (AMS_UNLIKELY(!g_registered_any)) { R_ABORT_UNLESS(os::CreateThread(std::addressof(g_query_server_process_thread), &QueryServerProcessThreadMain, GetPointer(g_query_server_storage), g_server_process_thread_stack, sizeof(g_server_process_thread_stack), AMS_GET_SYSTEM_THREAD_PRIORITY(mitm_sf, QueryServerProcessThread))); os::SetThreadNamePointer(std::addressof(g_query_server_process_thread), AMS_GET_SYSTEM_THREAD_NAME(mitm_sf, QueryServerProcessThread)); os::StartThread(std::addressof(g_query_server_process_thread)); g_registered_any = true; } } } #endif
3,449
C++
.cpp
62
48.112903
296
0.700505
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,388
sf_cmif_service_dispatch.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/sf/cmif/sf_cmif_service_dispatch.cpp
/* * Copyright (c) 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::sf::cmif { namespace { constexpr inline u32 InHeaderMagic = util::FourCC<'S','F','C','I'>::Code; constexpr inline u32 OutHeaderMagic = util::FourCC<'S','F','C','O'>::Code; #if defined(ATMOSPHERE_OS_HORIZON) static_assert(InHeaderMagic == CMIF_IN_HEADER_MAGIC); static_assert(OutHeaderMagic == CMIF_OUT_HEADER_MAGIC); #endif ALWAYS_INLINE decltype(ServiceCommandMeta::handler) FindCommandHandlerByBinarySearch(const ServiceCommandMeta *entries, const size_t entry_count, const u32 cmd_id, const hos::Version hos_version) { /* Binary search for the handler. */ ssize_t lo = 0; ssize_t hi = entry_count - 1; while (lo <= hi) { const size_t mid = (lo + hi) / 2; if (entries[mid].cmd_id < cmd_id) { lo = mid + 1; } else if (entries[mid].cmd_id > cmd_id) { hi = mid - 1; } else { /* Find start. */ size_t start = mid; while (start > 0 && entries[start - 1].cmd_id == cmd_id) { --start; } /* Find end. */ size_t end = mid + 1; while (end < entry_count && entries[end].cmd_id == cmd_id) { ++end; } for (size_t idx = start; idx < end; ++idx) { if (entries[idx].MatchesVersion(hos_version)) { return entries[idx].GetHandler(); } } break; } } return nullptr; } ALWAYS_INLINE decltype(ServiceCommandMeta::handler) FindCommandHandlerByLinearSearch(const ServiceCommandMeta *entries, const size_t entry_count, const u32 cmd_id, const hos::Version hos_version) { for (size_t i = 0; i < entry_count; ++i) { if (entries[i].Matches(cmd_id, hos_version)) { return entries[i].GetHandler(); break; } } return nullptr; } ALWAYS_INLINE decltype(ServiceCommandMeta::handler) FindCommandHandler(const ServiceCommandMeta *entries, const size_t entry_count, const u32 cmd_id, const hos::Version hos_version) { if (entry_count >= 8) { return FindCommandHandlerByBinarySearch(entries, entry_count, cmd_id, hos_version); } else { return FindCommandHandlerByLinearSearch(entries, entry_count, cmd_id, hos_version); } } } Result impl::ServiceDispatchTableBase::ProcessMessageImpl(ServiceDispatchContext &ctx, const cmif::PointerAndSize &in_raw_data, const ServiceCommandMeta *entries, const size_t entry_count, u32 interface_id_for_debug) const { /* Get versioning info. */ const auto hos_version = hos::GetVersion(); const u32 max_cmif_version = hos_version >= hos::Version_5_0_0 ? 1 : 0; /* Parse the CMIF in header. */ const CmifInHeader *in_header = reinterpret_cast<const CmifInHeader *>(in_raw_data.GetPointer()); R_UNLESS(in_raw_data.GetSize() >= sizeof(*in_header), sf::cmif::ResultInvalidHeaderSize()); R_UNLESS(in_header->magic == InHeaderMagic && in_header->version <= max_cmif_version, sf::cmif::ResultInvalidInHeader()); const cmif::PointerAndSize in_message_raw_data = cmif::PointerAndSize(in_raw_data.GetAddress() + sizeof(*in_header), in_raw_data.GetSize() - sizeof(*in_header)); const u32 cmd_id = in_header->command_id; /* Find a handler. */ const auto cmd_handler = FindCommandHandler(entries, entry_count, cmd_id, hos_version); R_UNLESS(cmd_handler != nullptr, sf::cmif::ResultUnknownCommandId()); /* Invoke handler. */ CmifOutHeader *out_header = nullptr; Result command_result = cmd_handler(&out_header, ctx, in_message_raw_data); /* Forward any meta-context change result. */ if (sf::impl::ResultRequestContextChanged::Includes(command_result)) { R_RETURN(command_result); } /* Otherwise, ensure that we're able to write the output header. */ if (out_header == nullptr) { AMS_ABORT_UNLESS(R_FAILED(command_result)); R_RETURN(command_result); } /* Write output header to raw data. */ *out_header = CmifOutHeader{OutHeaderMagic, 0, command_result.GetValue(), interface_id_for_debug}; R_SUCCEED(); } #if AMS_SF_MITM_SUPPORTED Result impl::ServiceDispatchTableBase::ProcessMessageForMitmImpl(ServiceDispatchContext &ctx, const cmif::PointerAndSize &in_raw_data, const ServiceCommandMeta *entries, const size_t entry_count, u32 interface_id_for_debug) const { /* Get versioning info. */ const auto hos_version = hos::GetVersion(); const u32 max_cmif_version = hos_version >= hos::Version_5_0_0 ? 1 : 0; /* Parse the CMIF in header. */ const CmifInHeader *in_header = reinterpret_cast<const CmifInHeader *>(in_raw_data.GetPointer()); R_UNLESS(in_raw_data.GetSize() >= sizeof(*in_header), sf::cmif::ResultInvalidHeaderSize()); R_UNLESS(in_header->magic == InHeaderMagic && in_header->version <= max_cmif_version, sf::cmif::ResultInvalidInHeader()); const cmif::PointerAndSize in_message_raw_data = cmif::PointerAndSize(in_raw_data.GetAddress() + sizeof(*in_header), in_raw_data.GetSize() - sizeof(*in_header)); const u32 cmd_id = in_header->command_id; /* Find a handler. */ const auto cmd_handler = FindCommandHandler(entries, entry_count, cmd_id, hos_version); /* If we didn't find a handler, forward the request. */ if (cmd_handler == nullptr) { R_RETURN(ctx.session->ForwardRequest(ctx)); } /* Invoke handler. */ CmifOutHeader *out_header = nullptr; Result command_result = cmd_handler(&out_header, ctx, in_message_raw_data); /* If we should, forward the request to the forward session. */ if (sm::mitm::ResultShouldForwardToSession::Includes(command_result)) { R_RETURN(ctx.session->ForwardRequest(ctx)); } /* Forward any meta-context change result. */ if (sf::impl::ResultRequestContextChanged::Includes(command_result)) { R_RETURN(command_result); } /* Otherwise, ensure that we're able to write the output header. */ if (out_header == nullptr) { AMS_ABORT_UNLESS(R_FAILED(command_result)); R_RETURN(command_result); } /* Write output header to raw data. */ *out_header = CmifOutHeader{OutHeaderMagic, 0, command_result.GetValue(), interface_id_for_debug}; R_SUCCEED(); } #endif }
7,655
C++
.cpp
140
43.642857
235
0.6093
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,389
sf_cmif_inline_context.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/sf/cmif/sf_cmif_inline_context.cpp
/* * Copyright (c) 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::sf { namespace cmif { namespace { #if !defined(ATMOSPHERE_COMPILER_CLANG) ALWAYS_INLINE util::AtomicRef<uintptr_t> GetAtomicSfInlineContext(os::ThreadType *thread = os::GetCurrentThread()) { uintptr_t * const p = std::addressof(os::GetSdkInternalTlsArray(thread)->sf_inline_context); return util::AtomicRef<uintptr_t>(*p); } #else ALWAYS_INLINE util::Atomic<uintptr_t> &GetAtomicSfInlineContext(os::ThreadType *thread = os::GetCurrentThread()) { uintptr_t * const p = std::addressof(os::GetSdkInternalTlsArray(thread)->sf_inline_context); static_assert(sizeof(std::atomic<uintptr_t>) == sizeof(uintptr_t)); static_assert(sizeof(util::Atomic<uintptr_t>) == sizeof(std::atomic<uintptr_t>)); return *reinterpret_cast<util::Atomic<uintptr_t> *>(p); } #endif ALWAYS_INLINE void OnSetInlineContext(os::ThreadType *thread) { #if defined(ATMOSPHERE_OS_HORIZON) /* Ensure that libnx receives the priority value. */ ::fsSetPriority(static_cast<::FsPriority>(::ams::sf::GetFsInlineContext(thread))); #else AMS_UNUSED(thread); #endif } } InlineContext GetInlineContext() { /* Get the context. */ uintptr_t thread_context = GetAtomicSfInlineContext().Load(); /* Copy it out. */ InlineContext ctx; static_assert(sizeof(ctx) <= sizeof(thread_context)); std::memcpy(std::addressof(ctx), std::addressof(thread_context), sizeof(ctx)); return ctx; } InlineContext SetInlineContext(InlineContext ctx) { /* Get current thread. */ os::ThreadType * const cur_thread = os::GetCurrentThread(); ON_SCOPE_EXIT { OnSetInlineContext(cur_thread); }; /* Create the new context. */ static_assert(sizeof(ctx) <= sizeof(uintptr_t)); uintptr_t new_context_value = 0; std::memcpy(std::addressof(new_context_value), std::addressof(ctx), sizeof(ctx)); /* Get the old context. */ uintptr_t old_context_value = GetAtomicSfInlineContext(cur_thread).Exchange(new_context_value); /* Convert and copy it out. */ InlineContext old_ctx; std::memcpy(std::addressof(old_ctx), std::addressof(old_context_value), sizeof(old_ctx)); return old_ctx; } } namespace { #if !defined(ATMOSPHERE_COMPILER_CLANG) ALWAYS_INLINE util::AtomicRef<u8> GetAtomicFsInlineContext(os::ThreadType *thread) { uintptr_t * const p = std::addressof(os::GetSdkInternalTlsArray(thread)->sf_inline_context); return util::AtomicRef<u8>(*reinterpret_cast<u8 *>(p)); } #else ALWAYS_INLINE util::Atomic<u8> &GetAtomicFsInlineContext(os::ThreadType *thread) { uintptr_t * const p = std::addressof(os::GetSdkInternalTlsArray(thread)->sf_inline_context); static_assert(sizeof(std::atomic<u8>) == sizeof(u8)); static_assert(sizeof(util::Atomic<u8>) == sizeof(std::atomic<u8>)); return *reinterpret_cast<util::Atomic<u8> *>(reinterpret_cast<u8 *>(p)); } #endif } u8 GetFsInlineContext(os::ThreadType *thread) { return GetAtomicFsInlineContext(thread).Load(); } u8 SetFsInlineContext(os::ThreadType *thread, u8 ctx) { ON_SCOPE_EXIT { cmif::OnSetInlineContext(thread); }; return GetAtomicFsInlineContext(thread).Exchange(ctx); } }
4,417
C++
.cpp
89
39.52809
128
0.626626
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,390
sf_cmif_service_object_holder.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/sf/cmif/sf_cmif_service_object_holder.cpp
/* * Copyright (c) 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::sf::cmif { Result ServiceObjectHolder::ProcessMessage(ServiceDispatchContext &ctx, const cmif::PointerAndSize &in_raw_data) const { const auto ProcessHandler = m_dispatch_meta->ProcessHandler; const auto *DispatchTable = m_dispatch_meta->DispatchTable; return (DispatchTable->*ProcessHandler)(ctx, in_raw_data); } }
1,029
C++
.cpp
23
41.608696
124
0.750748
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,391
sf_cmif_domain_manager.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/sf/cmif/sf_cmif_domain_manager.cpp
/* * Copyright (c) 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::sf::cmif { ServerDomainManager::Domain::~Domain() { while (!m_entries.empty()) { Entry *entry = std::addressof(m_entries.front()); { std::scoped_lock lk(m_manager->m_entry_owner_lock); AMS_ABORT_UNLESS(entry->owner == this); entry->owner = nullptr; } entry->object.Reset(); m_entries.pop_front(); m_manager->m_entry_manager.FreeEntry(entry); } } void ServerDomainManager::Domain::DisposeImpl() { ServerDomainManager *manager = m_manager; std::destroy_at(this); manager->FreeDomain(this); } Result ServerDomainManager::Domain::ReserveIds(DomainObjectId *out_ids, size_t count) { for (size_t i = 0; i < count; i++) { Entry *entry = m_manager->m_entry_manager.AllocateEntry(); R_UNLESS(entry != nullptr, sf::cmif::ResultOutOfDomainEntries()); AMS_ABORT_UNLESS(entry->owner == nullptr); out_ids[i] = m_manager->m_entry_manager.GetId(entry); } R_SUCCEED(); } void ServerDomainManager::Domain::ReserveSpecificIds(const DomainObjectId *ids, size_t count) { m_manager->m_entry_manager.AllocateSpecificEntries(ids, count); } void ServerDomainManager::Domain::UnreserveIds(const DomainObjectId *ids, size_t count) { for (size_t i = 0; i < count; i++) { Entry *entry = m_manager->m_entry_manager.GetEntry(ids[i]); AMS_ABORT_UNLESS(entry != nullptr); AMS_ABORT_UNLESS(entry->owner == nullptr); m_manager->m_entry_manager.FreeEntry(entry); } } void ServerDomainManager::Domain::RegisterObject(DomainObjectId id, ServiceObjectHolder &&obj) { Entry *entry = m_manager->m_entry_manager.GetEntry(id); AMS_ABORT_UNLESS(entry != nullptr); { std::scoped_lock lk(m_manager->m_entry_owner_lock); AMS_ABORT_UNLESS(entry->owner == nullptr); entry->owner = this; m_entries.push_back(*entry); } entry->object = std::move(obj); } ServiceObjectHolder ServerDomainManager::Domain::UnregisterObject(DomainObjectId id) { ServiceObjectHolder obj; Entry *entry = m_manager->m_entry_manager.GetEntry(id); if (entry == nullptr) { return ServiceObjectHolder(); } { std::scoped_lock lk(m_manager->m_entry_owner_lock); if (entry->owner != this) { return ServiceObjectHolder(); } entry->owner = nullptr; obj = std::move(entry->object); m_entries.erase(m_entries.iterator_to(*entry)); } m_manager->m_entry_manager.FreeEntry(entry); return obj; } ServiceObjectHolder ServerDomainManager::Domain::GetObject(DomainObjectId id) { Entry *entry = m_manager->m_entry_manager.GetEntry(id); if (entry == nullptr) { return ServiceObjectHolder(); } { std::scoped_lock lk(m_manager->m_entry_owner_lock); if (entry->owner != this) { return ServiceObjectHolder(); } } return entry->object.Clone(); } ServerDomainManager::EntryManager::EntryManager(DomainEntryStorage *entry_storage, size_t entry_count) : m_lock() { m_entries = reinterpret_cast<Entry *>(entry_storage); m_num_entries = entry_count; for (size_t i = 0; i < m_num_entries; i++) { m_free_list.push_back(*std::construct_at(m_entries + i)); } } ServerDomainManager::EntryManager::~EntryManager() { for (size_t i = 0; i < m_num_entries; i++) { std::destroy_at(m_entries + i); } } ServerDomainManager::Entry *ServerDomainManager::EntryManager::AllocateEntry() { std::scoped_lock lk(m_lock); if (m_free_list.empty()) { return nullptr; } Entry *e = std::addressof(m_free_list.front()); m_free_list.pop_front(); return e; } void ServerDomainManager::EntryManager::FreeEntry(Entry *entry) { std::scoped_lock lk(m_lock); AMS_ABORT_UNLESS(entry->owner == nullptr); AMS_ABORT_UNLESS(!entry->object); m_free_list.push_front(*entry); } void ServerDomainManager::EntryManager::AllocateSpecificEntries(const DomainObjectId *ids, size_t count) { std::scoped_lock lk(m_lock); /* Allocate new IDs. */ for (size_t i = 0; i < count; i++) { const auto id = ids[i]; Entry *entry = this->GetEntry(id); if (id != InvalidDomainObjectId) { AMS_ABORT_UNLESS(entry != nullptr); AMS_ABORT_UNLESS(entry->owner == nullptr); m_free_list.erase(m_free_list.iterator_to(*entry)); } } } }
5,623
C++
.cpp
138
31.797101
119
0.603
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,392
sf_cmif_domain_service_object.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/sf/cmif/sf_cmif_domain_service_object.cpp
/* * Copyright (c) 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::sf::cmif { Result DomainServiceObjectDispatchTable::ProcessMessage(ServiceDispatchContext &ctx, const cmif::PointerAndSize &in_raw_data) const { R_RETURN(this->ProcessMessageImpl(ctx, static_cast<DomainServiceObject *>(ctx.srv_obj)->GetServerDomain(), in_raw_data)); } #if AMS_SF_MITM_SUPPORTED Result DomainServiceObjectDispatchTable::ProcessMessageForMitm(ServiceDispatchContext &ctx, const cmif::PointerAndSize &in_raw_data) const { R_RETURN(this->ProcessMessageForMitmImpl(ctx, static_cast<DomainServiceObject *>(ctx.srv_obj)->GetServerDomain(), in_raw_data)); } #endif Result DomainServiceObjectDispatchTable::ProcessMessageImpl(ServiceDispatchContext &ctx, ServerDomainBase *domain, const cmif::PointerAndSize &in_raw_data) const { const CmifDomainInHeader *in_header = reinterpret_cast<const CmifDomainInHeader *>(in_raw_data.GetPointer()); R_UNLESS(in_raw_data.GetSize() >= sizeof(*in_header), sf::cmif::ResultInvalidHeaderSize()); const cmif::PointerAndSize in_domain_raw_data = cmif::PointerAndSize(in_raw_data.GetAddress() + sizeof(*in_header), in_raw_data.GetSize() - sizeof(*in_header)); const DomainObjectId target_object_id = DomainObjectId{in_header->object_id}; switch (in_header->type) { case CmifDomainRequestType_SendMessage: { auto target_object = domain->GetObject(target_object_id); R_UNLESS(static_cast<bool>(target_object), sf::cmif::ResultTargetNotFound()); R_UNLESS(in_header->data_size + in_header->num_in_objects * sizeof(DomainObjectId) <= in_domain_raw_data.GetSize(), sf::cmif::ResultInvalidHeaderSize()); const cmif::PointerAndSize in_message_raw_data = cmif::PointerAndSize(in_domain_raw_data.GetAddress(), in_header->data_size); DomainObjectId in_object_ids[8]; R_UNLESS(in_header->num_in_objects <= util::size(in_object_ids), sf::cmif::ResultInvalidNumInObjects()); std::memcpy(in_object_ids, reinterpret_cast<DomainObjectId *>(in_message_raw_data.GetAddress() + in_message_raw_data.GetSize()), sizeof(DomainObjectId) * in_header->num_in_objects); DomainServiceObjectProcessor domain_processor(domain, in_object_ids, in_header->num_in_objects); if (ctx.processor == nullptr) { ctx.processor = std::addressof(domain_processor); } else { ctx.processor->SetImplementationProcessor(std::addressof(domain_processor)); } ctx.srv_obj = target_object.GetServiceObjectUnsafe(); R_RETURN(target_object.ProcessMessage(ctx, in_message_raw_data)); } case CmifDomainRequestType_Close: /* TODO: N doesn't error check here. Should we? */ domain->UnregisterObject(target_object_id); R_SUCCEED(); default: R_THROW(sf::cmif::ResultInvalidInHeader()); } } #if AMS_SF_MITM_SUPPORTED Result DomainServiceObjectDispatchTable::ProcessMessageForMitmImpl(ServiceDispatchContext &ctx, ServerDomainBase *domain, const cmif::PointerAndSize &in_raw_data) const { const CmifDomainInHeader *in_header = reinterpret_cast<const CmifDomainInHeader *>(in_raw_data.GetPointer()); R_UNLESS(in_raw_data.GetSize() >= sizeof(*in_header), sf::cmif::ResultInvalidHeaderSize()); const cmif::PointerAndSize in_domain_raw_data = cmif::PointerAndSize(in_raw_data.GetAddress() + sizeof(*in_header), in_raw_data.GetSize() - sizeof(*in_header)); const DomainObjectId target_object_id = DomainObjectId{in_header->object_id}; switch (in_header->type) { case CmifDomainRequestType_SendMessage: { auto target_object = domain->GetObject(target_object_id); /* Mitm. If we don't have a target object, we should forward to let the server handle. */ if (!target_object) { R_RETURN(ctx.session->ForwardRequest(ctx)); } R_UNLESS(in_header->data_size + in_header->num_in_objects * sizeof(DomainObjectId) <= in_domain_raw_data.GetSize(), sf::cmif::ResultInvalidHeaderSize()); const cmif::PointerAndSize in_message_raw_data = cmif::PointerAndSize(in_domain_raw_data.GetAddress(), in_header->data_size); DomainObjectId in_object_ids[8]; R_UNLESS(in_header->num_in_objects <= util::size(in_object_ids), sf::cmif::ResultInvalidNumInObjects()); std::memcpy(in_object_ids, reinterpret_cast<DomainObjectId *>(in_message_raw_data.GetAddress() + in_message_raw_data.GetSize()), sizeof(DomainObjectId) * in_header->num_in_objects); DomainServiceObjectProcessor domain_processor(domain, in_object_ids, in_header->num_in_objects); if (ctx.processor == nullptr) { ctx.processor = std::addressof(domain_processor); } else { ctx.processor->SetImplementationProcessor(std::addressof(domain_processor)); } ctx.srv_obj = target_object.GetServiceObjectUnsafe(); R_RETURN(target_object.ProcessMessage(ctx, in_message_raw_data)); } case CmifDomainRequestType_Close: { auto target_object = domain->GetObject(target_object_id); /* If the object is not in the domain, tell the server to close it. */ if (!target_object) { R_RETURN(ctx.session->ForwardRequest(ctx)); } /* If the object is in the domain, close our copy of it. Mitm objects are required to close their associated domain id, so this shouldn't cause desynch. */ domain->UnregisterObject(target_object_id); R_SUCCEED(); } default: R_THROW(sf::cmif::ResultInvalidInHeader()); } } #endif Result DomainServiceObjectProcessor::PrepareForProcess(const ServiceDispatchContext &ctx, const ServerMessageRuntimeMetadata runtime_metadata) const { /* Validate in object count. */ R_UNLESS(m_impl_metadata.GetInObjectCount() == this->GetInObjectCount(), sf::cmif::ResultInvalidNumInObjects()); /* Nintendo reserves domain object IDs here. We do this later, to support mitm semantics. */ /* Pass onwards. */ R_RETURN(m_impl_processor->PrepareForProcess(ctx, runtime_metadata)); } Result DomainServiceObjectProcessor::GetInObjects(ServiceObjectHolder *in_objects) const { for (size_t i = 0; i < this->GetInObjectCount(); i++) { in_objects[i] = m_domain->GetObject(m_in_object_ids[i]); } R_SUCCEED(); } HipcRequest DomainServiceObjectProcessor::PrepareForReply(const cmif::ServiceDispatchContext &ctx, PointerAndSize &out_raw_data, const ServerMessageRuntimeMetadata runtime_metadata) { /* Call into impl processor, get request. */ PointerAndSize raw_data; HipcRequest request = m_impl_processor->PrepareForReply(ctx, raw_data, runtime_metadata); /* Write out header. */ constexpr size_t out_header_size = sizeof(CmifDomainOutHeader); const size_t impl_out_data_total_size = this->GetImplOutDataTotalSize(); AMS_ABORT_UNLESS(out_header_size + impl_out_data_total_size + sizeof(DomainObjectId) * this->GetOutObjectCount() <= raw_data.GetSize()); *reinterpret_cast<CmifDomainOutHeader *>(raw_data.GetPointer()) = CmifDomainOutHeader{ .num_out_objects = static_cast<u32>(this->GetOutObjectCount()), }; /* Set output raw data. */ out_raw_data = cmif::PointerAndSize(raw_data.GetAddress() + out_header_size, raw_data.GetSize() - out_header_size); m_out_object_ids = reinterpret_cast<DomainObjectId *>(out_raw_data.GetAddress() + impl_out_data_total_size); return request; } void DomainServiceObjectProcessor::PrepareForErrorReply(const cmif::ServiceDispatchContext &ctx, PointerAndSize &out_raw_data, const ServerMessageRuntimeMetadata runtime_metadata) { /* Call into impl processor, get request. */ PointerAndSize raw_data; m_impl_processor->PrepareForErrorReply(ctx, raw_data, runtime_metadata); /* Write out header. */ constexpr size_t out_header_size = sizeof(CmifDomainOutHeader); const size_t impl_out_headers_size = this->GetImplOutHeadersSize(); AMS_ABORT_UNLESS(out_header_size + impl_out_headers_size <= raw_data.GetSize()); *reinterpret_cast<CmifDomainOutHeader *>(raw_data.GetPointer()) = CmifDomainOutHeader{ .num_out_objects = 0, }; /* Set output raw data. */ out_raw_data = cmif::PointerAndSize(raw_data.GetAddress() + out_header_size, raw_data.GetSize() - out_header_size); /* Nintendo unreserves domain entries here, but we haven't reserved them yet. */ } void DomainServiceObjectProcessor::SetOutObjects(const cmif::ServiceDispatchContext &ctx, const HipcRequest &response, ServiceObjectHolder *out_objects, DomainObjectId *selected_ids) { AMS_UNUSED(ctx, response); const size_t num_out_objects = this->GetOutObjectCount(); /* Copy input object IDs from command impl (normally these are Invalid, in mitm they should be set). */ DomainObjectId object_ids[8]; bool is_reserved[8]; for (size_t i = 0; i < num_out_objects; i++) { object_ids[i] = selected_ids[i]; is_reserved[i] = false; } /* Reserve object IDs as necessary. */ { DomainObjectId reservations[8]; { size_t num_unreserved_ids = 0; DomainObjectId specific_ids[8]; size_t num_specific_ids = 0; for (size_t i = 0; i < num_out_objects; i++) { /* In the mitm case, we must not reserve IDs in use by other objects, so mitm objects will set this. */ if (object_ids[i] == InvalidDomainObjectId) { num_unreserved_ids++; } else { specific_ids[num_specific_ids++] = object_ids[i]; } } /* TODO: Can we make this error non-fatal? It isn't for N, since they can reserve IDs earlier due to not having to worry about mitm. */ R_ABORT_UNLESS(m_domain->ReserveIds(reservations, num_unreserved_ids)); m_domain->ReserveSpecificIds(specific_ids, num_specific_ids); } size_t reservation_index = 0; for (size_t i = 0; i < num_out_objects; i++) { if (object_ids[i] == InvalidDomainObjectId) { object_ids[i] = reservations[reservation_index++]; is_reserved[i] = true; } } } /* Actually set out objects. */ for (size_t i = 0; i < num_out_objects; i++) { if (!out_objects[i]) { if (is_reserved[i]) { m_domain->UnreserveIds(object_ids + i, 1); } object_ids[i] = InvalidDomainObjectId; continue; } m_domain->RegisterObject(object_ids[i], std::move(out_objects[i])); } /* Set out object IDs in message. */ for (size_t i = 0; i < num_out_objects; i++) { m_out_object_ids[i] = object_ids[i]; } } }
12,294
C++
.cpp
195
51.312821
197
0.639377
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,393
socket_api.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/socket/socket_api.cpp
/* * Copyright (c) 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 "impl/socket_api.hpp" namespace ams::socket { Errno GetLastError() { return impl::GetLastError(); } void SetLastError(Errno err) { return impl::SetLastError(err); } u32 InetHtonl(u32 host) { return impl::InetHtonl(host); } u16 InetHtons(u16 host) { return impl::InetHtons(host); } u32 InetNtohl(u32 net) { return impl::InetNtohl(net); } u16 InetNtohs(u16 net) { return impl::InetNtohs(net); } Result Initialize(const Config &config) { R_RETURN(impl::Initialize(config)); } Result Finalize() { R_RETURN(impl::Finalize()); } Result InitializeAllocatorForInternal(void *buffer, size_t size) { R_RETURN(impl::InitializeAllocatorForInternal(buffer, size)); } ssize_t RecvFrom(s32 desc, void *buffer, size_t buffer_size, MsgFlag flags, SockAddr *out_address, SockLenT *out_addr_len){ return impl::RecvFrom(desc, buffer, buffer_size, flags, out_address, out_addr_len); } ssize_t Recv(s32 desc, void *buffer, size_t buffer_size, MsgFlag flags) { return impl::Recv(desc, buffer, buffer_size, flags); } ssize_t SendTo(s32 desc, const void *buffer, size_t buffer_size, MsgFlag flags, const SockAddr *address, SockLenT len) { return impl::SendTo(desc, buffer, buffer_size, flags, address, len); } ssize_t Send(s32 desc, const void *buffer, size_t buffer_size, MsgFlag flags) { return impl::Send(desc, buffer, buffer_size, flags); } s32 Shutdown(s32 desc, ShutdownMethod how) { return impl::Shutdown(desc, how); } s32 Socket(Family domain, Type type, Protocol protocol) { return impl::Socket(domain, type, protocol); } s32 SocketExempt(Family domain, Type type, Protocol protocol) { return impl::SocketExempt(domain, type, protocol); } s32 Accept(s32 desc, SockAddr *out_address, SockLenT *out_addr_len) { return impl::Accept(desc, out_address, out_addr_len); } s32 Bind(s32 desc, const SockAddr *address, SockLenT len) { return impl::Bind(desc, address, len); } s32 Connect(s32 desc, const SockAddr *address, SockLenT len) { return impl::Connect(desc, address, len); } s32 GetSockName(s32 desc, SockAddr *out_address, SockLenT *out_addr_len) { return impl::GetSockName(desc, out_address, out_addr_len); } s32 SetSockOpt(s32 desc, Level level, Option option_name, const void *option_value, SockLenT option_size) { return impl::SetSockOpt(desc, level, option_name, option_value, option_size); } s32 Listen(s32 desc, s32 backlog) { return impl::Listen(desc, backlog); } s32 Close(s32 desc) { return impl::Close(desc); } }
3,472
C++
.cpp
88
33.829545
127
0.679071
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,394
socket_api.os.windows.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/socket/impl/socket_api.os.windows.cpp
/* * Copyright (c) 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 "socket_api.hpp" #include "socket_allocator.hpp" #include <ws2tcpip.h> #include <stratosphere/socket/impl/socket_platform_types_translation.hpp> namespace ams::socket::impl { extern PosixWinSockConverter g_posix_winsock_converter; namespace { constinit util::Atomic<int> g_init_counter = 0; ALWAYS_INLINE bool IsInitialized() { return g_init_counter > 0; } class FcntlState { private: FcntlFlag m_flags[MaxSocketsPerClient]{}; os::SdkRecursiveMutex m_mutexes[MaxSocketsPerClient]{}; public: constexpr FcntlState() = default; public: void ClearFlag(int fd, FcntlFlag flag) { std::scoped_lock lk(m_mutexes[fd]); m_flags[fd] &= ~flag; } void ClearFlags(int fd) { std::scoped_lock lk(m_mutexes[fd]); m_flags[fd] = FcntlFlag::None; } FcntlFlag GetFlags(int fd) { std::scoped_lock lk(m_mutexes[fd]); return m_flags[fd]; } int GetFlagsInt(int fd) { return static_cast<int>(this->GetFlags(fd)); } os::SdkRecursiveMutex &GetSocketLock(int fd) { return m_mutexes[fd]; } bool IsFlagClear(int fd, FcntlFlag flag) { return !this->IsFlagSet(fd, flag); } bool IsFlagSet(int fd, FcntlFlag flag) { std::scoped_lock lk(m_mutexes[fd]); return (m_flags[fd] & flag) != static_cast<FcntlFlag>(0); } bool IsSocketBlocking(int fd) { return !this->IsSocketNonBlocking(fd); } bool IsSocketNonBlocking(int fd) { return this->IsFlagSet(fd, FcntlFlag::O_NonBlock); } void SetFlag(int fd, FcntlFlag flag) { std::scoped_lock lk(m_mutexes[fd]); m_flags[fd] |= flag; } }; constinit FcntlState g_fcntl_state; void TransmuteWsaError() { switch (::WSAGetLastError()) { case WSAEFAULT: ::WSASetLastError(WSAEINVAL); break; case WSAENOTSOCK: ::WSASetLastError(WSAEBADF); break; case WSAETIMEDOUT: ::WSASetLastError(WSAEWOULDBLOCK); break; } } template<std::integral T> void TransmuteWsaError(T res) { if (static_cast<decltype(SOCKET_ERROR)>(res) == SOCKET_ERROR) { TransmuteWsaError(); } } } #define AMS_SOCKET_IMPL_SCOPED_MAKE_NON_BLOCKING(_cond, _fd) \ /* If the socket is blocking and we need to make it non-blocking, do so. */ \ int nonblock_##__LINE__ = 1; \ bool set_nonblock_##__LINE__ = false; \ if (_cond && g_fcntl_state.IsSocketBlocking(_fd)) { \ if (const auto res = ::ioctlsocket(handle, FIONBIO, reinterpret_cast<u_long *>(std::addressof( nonblock_##__LINE__ ))); res == SOCKET_ERROR) { \ TransmuteWsaError(); \ return res; \ } \ \ set_nonblock_##__LINE__ = true; \ } \ \ ON_SCOPE_EXIT { \ /* Preserve last error. */ \ const auto last_err = socket::impl::GetLastError(); \ ON_SCOPE_EXIT { socket::impl::SetLastError(last_err); }; \ \ /* Restore non-blocking state. */ \ if (set_nonblock_##__LINE__) { \ nonblock_##__LINE__ = 0; \ \ while (true) { \ const auto restore_res = ::ioctlsocket(handle, FIONBIO, reinterpret_cast<u_long *>(std::addressof( nonblock_##__LINE__ ))); \ TransmuteWsaError(restore_res); \ if (!(restore_res == SOCKET_ERROR && socket::impl::GetLastError() == Errno::EInProgress)) { \ break; \ } \ \ os::SleepThread(TimeSpan::FromMilliSeconds(1)); \ } \ } \ } #define AMS_SOCKET_IMPL_DO_WITH_TRANSMUTE(expr) ({ const auto res = (expr); TransmuteWsaError(res); res; }) void *Alloc(size_t size) { return ::std::malloc(size); } void *Calloc(size_t num, size_t size) { const size_t total_size = size * num; void *buf = Alloc(size); if (buf != nullptr) { std::memset(buf, 0, total_size); } return buf; } void Free(void *ptr) { return ::std::free(ptr); } Errno GetLastError() { if (AMS_LIKELY(IsInitialized())) { return MapErrnoValue(::WSAGetLastError()); } else { return Errno::EInval; } } void SetLastError(Errno err) { if (AMS_LIKELY(IsInitialized())) { ::WSASetLastError(MapErrnoValue(err)); } } u32 InetHtonl(u32 host) { return ::htonl(host); } u16 InetHtons(u16 host) { return ::htons(host); } u32 InetNtohl(u32 net) { return ::ntohl(net); } u16 InetNtohs(u16 net) { return ::ntohs(net); } Result Initialize(const Config &config) { AMS_UNUSED(config); /* Increment init counter. */ ++g_init_counter; /* Initialize winsock. */ WSADATA wsa_data; WORD wVersionRequested = MAKEWORD(2, 2); const auto res = ::WSAStartup(wVersionRequested, std::addressof(wsa_data)); AMS_ABORT_UNLESS(res == 0); /* Initialize time services. */ R_ABORT_UNLESS(time::Initialize()); R_SUCCEED(); } Result Finalize() { /* Check pre-conditions. */ --g_init_counter; AMS_ABORT_UNLESS(g_init_counter >= 0); /* Cleanup WSA. */ ::WSACleanup(); /* Finalize time services. */ time::Finalize(); /* Release all posix handles. */ g_posix_winsock_converter.ReleaseAllPosixHandles(); R_SUCCEED(); } ssize_t RecvFromInternal(s32 desc, void *buffer, size_t buffer_size, MsgFlag flags, SockAddr *out_address, SockLenT *out_addr_len) { /* Convert socket. */ SOCKET handle = g_posix_winsock_converter.PosixToWinsockSocket(desc); /* Check input. */ if (handle == static_cast<SOCKET>(socket::InvalidSocket)) { socket::impl::SetLastError(Errno::EBadf); return -1; } /* Convert the sockaddr. */ sockaddr sa = {}; socklen_t addr_len = sizeof(sa); /* Perform the call. */ const auto res = ::recvfrom(handle, static_cast<char *>(buffer), static_cast<int>(buffer_size), MapMsgFlagValue(flags), std::addressof(sa), std::addressof(addr_len)); if (res == SOCKET_ERROR) { if (::WSAGetLastError() == WSAESHUTDOWN) { ::WSASetLastError(WSAENETDOWN); } else { TransmuteWsaError(); } } /* Set output. */ if (out_address != nullptr && out_addr_len != nullptr) { if (addr_len > static_cast<socklen_t>(sizeof(*out_address))) { addr_len = sizeof(*out_address); } if (*out_addr_len != 0) { if (static_cast<socklen_t>(*out_addr_len) > addr_len) { *out_addr_len = addr_len; } SockAddr sa_pl = {}; CopyFromPlatform(reinterpret_cast<SockAddrIn *>(std::addressof(sa_pl)), reinterpret_cast<const sockaddr_in *>(std::addressof(sa))); std::memcpy(out_address, std::addressof(sa_pl), *out_addr_len); } } return res; } ssize_t RecvFrom(s32 desc, void *buffer, size_t buffer_size, MsgFlag flags, SockAddr *out_address, SockLenT *out_addr_len) { /* Check pre-conditions. */ AMS_ABORT_UNLESS(IsInitialized()); /* Convert socket. */ SOCKET handle = g_posix_winsock_converter.PosixToWinsockSocket(desc); /* If the flags have DontWait set, clear WaitAll. */ if ((flags & MsgFlag::Msg_DontWait) == MsgFlag::Msg_DontWait) { flags &= ~MsgFlag::Msg_WaitAll; } /* If the flags haev WaitAll set but the socket is non-blocking, clear WaitAll. */ if ((flags & MsgFlag::Msg_WaitAll) == MsgFlag::Msg_WaitAll && g_fcntl_state.IsSocketNonBlocking(desc)) { flags &= ~MsgFlag::Msg_WaitAll; } /* Check input. */ if (handle == static_cast<SOCKET>(socket::InvalidSocket)) { socket::impl::SetLastError(Errno::EBadf); return -1; } else if (buffer_size == 0) { return 0; } else if (buffer == nullptr) { socket::impl::SetLastError(Errno::EInval); return -1; } else if (buffer_size > std::numeric_limits<u32>::max()) { socket::impl::SetLastError(Errno::EFault); return -1; } /* Handle blocking vs non-blocking. */ if ((flags & MsgFlag::Msg_DontWait) == MsgFlag::Msg_DontWait) { return RecvFromInternal(desc, buffer, buffer_size, flags, out_address, out_addr_len); } else { /* Lock the socket. */ std::scoped_lock lk(g_fcntl_state.GetSocketLock(desc)); /* Clear don't wait from the flags. */ flags &= MsgFlag::Msg_DontWait; /* If the socket is blocking, we need to make it non-blocking. */ AMS_SOCKET_IMPL_SCOPED_MAKE_NON_BLOCKING(true, desc); /* Do the recv from. */ return RecvFromInternal(desc, buffer, buffer_size, flags, out_address, out_addr_len); } } ssize_t Recv(s32 desc, void *buffer, size_t buffer_size, MsgFlag flags) { /* Check pre-conditions. */ AMS_ABORT_UNLESS(IsInitialized()); /* Convert socket. */ SOCKET handle = g_posix_winsock_converter.PosixToWinsockSocket(desc); /* Check input. */ if (handle == static_cast<SOCKET>(socket::InvalidSocket)) { socket::impl::SetLastError(Errno::EBadf); return -1; } else if (buffer_size == 0) { return 0; } else if (buffer == nullptr) { socket::impl::SetLastError(Errno::EInval); return -1; } else if (buffer_size > std::numeric_limits<u32>::max()) { socket::impl::SetLastError(Errno::EFault); return -1; } /* If the socket is blocking, we need to make it non-blocking. */ AMS_SOCKET_IMPL_SCOPED_MAKE_NON_BLOCKING(((flags & MsgFlag::Msg_DontWait) == MsgFlag::Msg_DontWait), desc); /* Perform the call. */ return AMS_SOCKET_IMPL_DO_WITH_TRANSMUTE(::recv(handle, static_cast<char *>(buffer), static_cast<int>(buffer_size), MapMsgFlagValue(flags & ~MsgFlag::Msg_DontWait))); } ssize_t SendTo(s32 desc, const void *buffer, size_t buffer_size, MsgFlag flags, const SockAddr *address, SockLenT len) { /* Check pre-conditions. */ AMS_ABORT_UNLESS(IsInitialized()); /* Convert socket. */ SOCKET handle = g_posix_winsock_converter.PosixToWinsockSocket(desc); /* Check input. */ if (handle == static_cast<SOCKET>(socket::InvalidSocket)) { socket::impl::SetLastError(Errno::EBadf); return -1; } /* Clear don't wait from flags. */ flags &= ~MsgFlag::Msg_DontWait; /* Convert the sockaddr. */ sockaddr sa = {}; socket::impl::CopyToPlatform(reinterpret_cast<sockaddr_in *>(std::addressof(sa)), reinterpret_cast<const SockAddrIn *>(address)); /* Perform the call. */ const auto res = ::sendto(handle, static_cast<const char *>(buffer), static_cast<int>(buffer_size), MapMsgFlagValue(flags), address != nullptr ? std::addressof(sa) : nullptr, static_cast<socklen_t>(len)); if (res == SOCKET_ERROR) { if (::WSAGetLastError() == WSAESHUTDOWN) { ::WSASetLastError(109); } else { TransmuteWsaError(); } } return res; } ssize_t Send(s32 desc, const void *buffer, size_t buffer_size, MsgFlag flags) { /* Check pre-conditions. */ AMS_ABORT_UNLESS(IsInitialized()); /* Convert socket. */ SOCKET handle = g_posix_winsock_converter.PosixToWinsockSocket(desc); /* Check input. */ if (handle == static_cast<SOCKET>(socket::InvalidSocket)) { socket::impl::SetLastError(Errno::EBadf); return -1; } /* Perform the call. */ return AMS_SOCKET_IMPL_DO_WITH_TRANSMUTE(::send(handle, static_cast<const char *>(buffer), static_cast<int>(buffer_size), MapMsgFlagValue(flags))); } s32 Shutdown(s32 desc, ShutdownMethod how) { /* Check pre-conditions. */ AMS_ABORT_UNLESS(IsInitialized()); /* Convert socket. */ SOCKET handle = g_posix_winsock_converter.PosixToWinsockSocket(desc); /* Check input. */ if (handle == static_cast<SOCKET>(socket::InvalidSocket)) { socket::impl::SetLastError(Errno::EBadf); return -1; } /* Perform the call. */ const auto res = ::shutdown(handle, MapShutdownMethodValue(how)); g_posix_winsock_converter.SetShutdown(desc, true); TransmuteWsaError(res); return res; } s32 Socket(Family domain, Type type, Protocol protocol, bool exempt) { /* Check pre-conditions. */ AMS_ABORT_UNLESS(IsInitialized()); const auto res = ::socket(MapFamilyValue(domain), MapTypeValue(type), MapProtocolValue(protocol)); TransmuteWsaError(res); s32 posix_socket = -1; if (res != static_cast<typename std::remove_cv<decltype(res)>::type>(SOCKET_ERROR)) { if (posix_socket = g_posix_winsock_converter.AcquirePosixHandle(res, exempt); posix_socket < 0) { /* Preserve last error. */ const auto last_err = socket::impl::GetLastError(); ON_SCOPE_EXIT { socket::impl::SetLastError(last_err); }; /* Close the socket. */ ::closesocket(res); } } return posix_socket; } s32 Socket(Family domain, Type type, Protocol protocol) { return Socket(domain, type, protocol, false); } s32 SocketExempt(Family domain, Type type, Protocol protocol) { return Socket(domain, type, protocol, true); } s32 Accept(s32 desc, SockAddr *out_address, SockLenT *out_addr_len) { /* Check pre-conditions. */ AMS_ABORT_UNLESS(IsInitialized()); /* Convert socket. */ SOCKET handle = g_posix_winsock_converter.PosixToWinsockSocket(desc); /* Check input. */ if (handle == static_cast<SOCKET>(socket::InvalidSocket)) { socket::impl::SetLastError(Errno::EBadf); return -1; } /* Check shutdown. */ bool is_shutdown = false; if (const auto res = g_posix_winsock_converter.GetShutdown(is_shutdown, desc); res == SOCKET_ERROR || (res == 0 && is_shutdown)) { socket::impl::SetLastError(Errno::EConnAborted); return -1; } /* Accept. */ sockaddr sa = {}; socklen_t sa_len = sizeof(sa); const auto res = ::accept(handle, std::addressof(sa), std::addressof(sa_len)); if (res == static_cast<typename std::remove_cv<decltype(res)>::type>(SOCKET_ERROR)) { if (::WSAGetLastError() == WSAEOPNOTSUPP) { ::WSASetLastError(WSAEINVAL); } else { TransmuteWsaError(); } } /* Set output. */ if (out_address != nullptr && out_addr_len != nullptr) { if (sa_len > static_cast<socklen_t>(sizeof(*out_address))) { sa_len = sizeof(*out_address); } if (*out_addr_len != 0) { if (static_cast<socklen_t>(*out_addr_len) > sa_len) { *out_addr_len = sa_len; } SockAddr sa_pl = {}; CopyFromPlatform(reinterpret_cast<SockAddrIn *>(std::addressof(sa_pl)), reinterpret_cast<const sockaddr_in *>(std::addressof(sa))); std::memcpy(out_address, std::addressof(sa_pl), *out_addr_len); } *out_addr_len = sa_len; } if (res == static_cast<typename std::remove_cv<decltype(res)>::type>(SOCKET_ERROR)) { return res; } s32 fd = -1; bool is_exempt = false; if (g_posix_winsock_converter.GetSocketExempt(is_exempt, desc) == 0) { fd = g_posix_winsock_converter.AcquirePosixHandle(res, is_exempt); } if (fd < 0) { /* Preserve last error. */ const auto last_err = socket::impl::GetLastError(); ON_SCOPE_EXIT { socket::impl::SetLastError(last_err); }; ::closesocket(res); return SOCKET_ERROR; } return fd; } s32 Bind(s32 desc, const SockAddr *address, SockLenT len) { /* Check pre-conditions. */ AMS_ABORT_UNLESS(IsInitialized()); /* Convert socket. */ SOCKET handle = g_posix_winsock_converter.PosixToWinsockSocket(desc); /* Check input. */ if (handle == static_cast<SOCKET>(socket::InvalidSocket)) { socket::impl::SetLastError(Errno::EBadf); return -1; } else if (address == nullptr) { socket::impl::SetLastError(Errno::EInval); return -1; } /* Convert the sockaddr. */ sockaddr sa = {}; socket::impl::CopyToPlatform(reinterpret_cast<sockaddr_in *>(std::addressof(sa)), reinterpret_cast<const SockAddrIn *>(address)); return AMS_SOCKET_IMPL_DO_WITH_TRANSMUTE(::bind(handle, std::addressof(sa), static_cast<socklen_t>(len))); } s32 Connect(s32 desc, const SockAddr *address, SockLenT len) { /* Check pre-conditions. */ AMS_ABORT_UNLESS(IsInitialized()); /* Convert socket. */ SOCKET handle = g_posix_winsock_converter.PosixToWinsockSocket(desc); /* Check input. */ if (handle == static_cast<SOCKET>(socket::InvalidSocket)) { socket::impl::SetLastError(Errno::EBadf); return -1; } /* Convert the sockaddr. */ sockaddr sa = {}; if (address != nullptr) { if (reinterpret_cast<const SockAddrIn *>(address)->sin_port == 0) { socket::impl::SetLastError(Errno::EAddrNotAvail); return -1; } socket::impl::CopyToPlatform(reinterpret_cast<sockaddr_in *>(std::addressof(sa)), reinterpret_cast<const SockAddrIn *>(address)); } const auto res = ::connect(handle, address != nullptr ? std::addressof(sa) : nullptr, len); if (res == SOCKET_ERROR) { const auto wsa_err = ::WSAGetLastError(); if (wsa_err == WSAEWOULDBLOCK) { ::WSASetLastError(WSAEINPROGRESS); } else if (wsa_err != WSAETIMEDOUT) { TransmuteWsaError(); } } return res; } s32 GetSockName(s32 desc, SockAddr *out_address, SockLenT *out_addr_len) { /* Check pre-conditions. */ AMS_ABORT_UNLESS(IsInitialized()); /* Convert socket. */ SOCKET handle = g_posix_winsock_converter.PosixToWinsockSocket(desc); /* Check input. */ if (handle == static_cast<SOCKET>(socket::InvalidSocket)) { socket::impl::SetLastError(Errno::EBadf); return -1; } /* We may end up preserving the last wsa error. */ const auto last_err = ::WSAGetLastError(); /* Do the call. */ sockaddr sa = {}; auto res = ::getsockname(handle, out_address != nullptr ? std::addressof(sa) : nullptr, reinterpret_cast<socklen_t *>(out_addr_len)); if (res == SOCKET_ERROR) { if (::WSAGetLastError() == WSAEINVAL) { ::WSASetLastError(last_err); sa = {}; res = 0; } else { TransmuteWsaError(); } } /* Copy out. */ if (out_address != nullptr) { CopyFromPlatform(reinterpret_cast<SockAddrIn *>(out_address), reinterpret_cast<const sockaddr_in *>(std::addressof(sa))); } return res; } s32 SetSockOpt(s32 desc, Level level, Option option_name, const void *option_value, SockLenT option_size) { /* Check pre-conditions. */ AMS_ABORT_UNLESS(IsInitialized()); /* Convert socket. */ SOCKET handle = g_posix_winsock_converter.PosixToWinsockSocket(desc); /* Check input. */ if (handle == static_cast<SOCKET>(socket::InvalidSocket)) { socket::impl::SetLastError(Errno::EBadf); return -1; } union SocketOptionValue { linger option_linger; DWORD option_timeout_ms; DWORD option_exempt; }; SocketOptionValue sockopt_value = {}; socklen_t option_value_length = option_size; const char *p_option_value = nullptr; switch (option_name) { case Option::So_Linger: case Option::So_Nn_Linger: { if (option_value_length < static_cast<socklen_t>(sizeof(sockopt_value.option_linger))) { socket::impl::SetLastError(Errno::EInval); return -1; } option_value_length = sizeof(sockopt_value.option_linger); CopyToPlatform(std::addressof(sockopt_value.option_linger), reinterpret_cast<const Linger *>(option_value)); p_option_value = reinterpret_cast<const char *>(std::addressof(sockopt_value.option_linger)); } break; case Option::So_SndTimeo: case Option::So_RcvTimeo: { if (option_value_length < static_cast<socklen_t>(sizeof(sockopt_value.option_timeout_ms))) { socket::impl::SetLastError(Errno::EInval); return -1; } option_value_length = sizeof(sockopt_value.option_timeout_ms); sockopt_value.option_timeout_ms = (reinterpret_cast<const TimeVal *>(option_value)->tv_sec * 1000) + (reinterpret_cast<const TimeVal *>(option_value)->tv_usec / 1000); p_option_value = reinterpret_cast<const char *>(std::addressof(sockopt_value.option_timeout_ms)); } break; case Option::So_Nn_Shutdown_Exempt: { if (option_value_length < static_cast<socklen_t>(sizeof(sockopt_value.option_exempt))) { socket::impl::SetLastError(Errno::EInval); return -1; } return g_posix_winsock_converter.SetSocketExempt(desc, *reinterpret_cast<const decltype(sockopt_value.option_exempt) *>(option_value) != 0); } break; default: p_option_value = reinterpret_cast<const char *>(option_value); break; } return AMS_SOCKET_IMPL_DO_WITH_TRANSMUTE(::setsockopt(handle, MapLevelValue(level), MapOptionValue(level, option_name), p_option_value, option_value_length)); } s32 Listen(s32 desc, s32 backlog) { /* Check pre-conditions. */ AMS_ABORT_UNLESS(IsInitialized()); /* Convert socket. */ SOCKET handle = g_posix_winsock_converter.PosixToWinsockSocket(desc); /* Check input. */ if (handle == static_cast<SOCKET>(socket::InvalidSocket)) { socket::impl::SetLastError(Errno::EBadf); return -1; } /* Check shutdown. */ bool is_shutdown = false; if (const auto res = g_posix_winsock_converter.GetShutdown(is_shutdown, desc); res == SOCKET_ERROR || (res == 0 && is_shutdown)) { socket::impl::SetLastError(Errno::EInval); return -1; } return AMS_SOCKET_IMPL_DO_WITH_TRANSMUTE(::listen(handle, backlog)); } s32 Close(s32 desc) { /* Check pre-conditions. */ AMS_ABORT_UNLESS(IsInitialized()); /* Check that we can close. */ static constinit os::SdkMutex s_close_lock; SOCKET handle = static_cast<SOCKET>(socket::InvalidSocket); { std::scoped_lock lk(s_close_lock); handle = g_posix_winsock_converter.PosixToWinsockSocket(desc); if (handle == static_cast<SOCKET>(socket::InvalidSocket)) { return SOCKET_ERROR; } g_posix_winsock_converter.ReleasePosixHandle(desc); } /* Do the close. */ const auto res = ::closesocket(handle); g_fcntl_state.ClearFlags(desc); return res; } }
29,644
C++
.cpp
592
37.503378
212
0.492198
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,395
socket_api.os.horizon.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/socket/impl/socket_api.os.horizon.cpp
/* * Copyright (c) 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 "socket_api.hpp" #include "socket_allocator.hpp" extern "C" { #include <switch/services/bsd.h> } namespace ams::socket::impl { namespace { constinit bool g_initialized = false; constinit os::SdkMutex g_heap_mutex; constinit lmem::HeapHandle g_heap_handle = nullptr; constinit int g_heap_generation = -1; ALWAYS_INLINE bool IsInitialized() { return g_initialized; } } void *Alloc(size_t size) { std::scoped_lock lk(g_heap_mutex); AMS_ASSERT(g_heap_generation > 0); void *ptr = nullptr; if (!g_heap_handle) { socket::impl::SetLastError(Errno::EOpNotSupp); } else if ((ptr = lmem::AllocateFromExpHeap(g_heap_handle, size)) == nullptr) { socket::impl::SetLastError(Errno::ENoMem); } return ptr; } void *Calloc(size_t num, size_t size) { std::scoped_lock lk(g_heap_mutex); AMS_ASSERT(g_heap_generation > 0); void *ptr = nullptr; if (!g_heap_handle) { socket::impl::SetLastError(Errno::EOpNotSupp); } else if ((ptr = lmem::AllocateFromExpHeap(g_heap_handle, size * num)) == nullptr) { socket::impl::SetLastError(Errno::ENoMem); } else { std::memset(ptr, 0, size * num); } return ptr; } void Free(void *ptr) { std::scoped_lock lk(g_heap_mutex); AMS_ASSERT(g_heap_generation > 0); if (!g_heap_handle) { socket::impl::SetLastError(Errno::EOpNotSupp); } else if (ptr != nullptr) { lmem::FreeToExpHeap(g_heap_handle, ptr); } } bool HeapIsAvailable(int generation) { std::scoped_lock lk(g_heap_mutex); return g_heap_handle && g_heap_generation == generation; } int GetHeapGeneration() { std::scoped_lock lk(g_heap_mutex); return g_heap_generation; } Errno GetLastError() { if (AMS_LIKELY(IsInitialized())) { return static_cast<Errno>(errno); } else { return Errno::EInval; } } void SetLastError(Errno err) { if (AMS_LIKELY(IsInitialized())) { errno = static_cast<int>(err); } } u32 InetHtonl(u32 host) { return util::ConvertToBigEndian(host); } u16 InetHtons(u16 host) { return util::ConvertToBigEndian(host); } u32 InetNtohl(u32 net) { return util::ConvertFromBigEndian(net); } u16 InetNtohs(u16 net) { return util::ConvertFromBigEndian(net); } namespace { void InitializeHeapImpl(void *buffer, size_t size) { /* NOTE: Nintendo uses both CreateOption_ThreadSafe *and* a global heap mutex. */ /* This is unnecessary, and using a single SdkMutex is more performant, since we're not recursive. */ std::scoped_lock lk(g_heap_mutex); g_heap_handle = lmem::CreateExpHeap(buffer, size, lmem::CreateOption_None); } Result InitializeCommon(const Config &config) { /* Check pre-conditions. */ AMS_ABORT_UNLESS(!IsInitialized()); AMS_ABORT_UNLESS(config.GetMemoryPool() != nullptr); AMS_ABORT_UNLESS(1 <= config.GetConcurrencyCountMax() && config.GetConcurrencyCountMax() <= ConcurrencyLimitMax); if (!config.IsSmbpClient()) { AMS_ABORT_UNLESS(config.GetAllocatorPoolSize() < config.GetMemoryPoolSize()); } AMS_ABORT_UNLESS(util::IsAligned(config.GetMemoryPoolSize(), os::MemoryPageSize)); AMS_ABORT_UNLESS(util::IsAligned(config.GetAllocatorPoolSize(), os::MemoryPageSize)); AMS_ABORT_UNLESS(config.GetAllocatorPoolSize() >= 4_KB); if (!config.IsSystemClient()) { R_UNLESS(config.GetMemoryPoolSize() >= socket::MinSocketMemoryPoolSize, socket::ResultInsufficientProvidedMemory()); } const size_t transfer_memory_size = config.GetMemoryPoolSize() - config.GetAllocatorPoolSize(); if (!config.IsSmbpClient()) { R_UNLESS(transfer_memory_size >= socket::MinMemHeapAllocatorSize, socket::ResultInsufficientProvidedMemory()); } else { R_UNLESS(config.GetMemoryPoolSize() >= socket::MinimumSharedMbufPoolReservation, socket::ResultInsufficientProvidedMemory()); } /* Initialize the allocator heap. */ InitializeHeapImpl(static_cast<u8 *>(config.GetMemoryPool()) + transfer_memory_size, config.GetAllocatorPoolSize()); /* Initialize libnx. */ { const ::BsdInitConfig libnx_config = { .version = config.GetVersion(), .tmem_buffer = config.GetMemoryPool(), .tmem_buffer_size = transfer_memory_size, .tcp_tx_buf_size = static_cast<u32>(config.GetTcpInitialSendBufferSize()), .tcp_rx_buf_size = static_cast<u32>(config.GetTcpInitialReceiveBufferSize()), .tcp_tx_buf_max_size = static_cast<u32>(config.GetTcpAutoSendBufferSizeMax()), .tcp_rx_buf_max_size = static_cast<u32>(config.GetTcpAutoReceiveBufferSizeMax()), .udp_tx_buf_size = static_cast<u32>(config.GetUdpSendBufferSize()), .udp_rx_buf_size = static_cast<u32>(config.GetUdpReceiveBufferSize()), .sb_efficiency = static_cast<u32>(config.GetSocketBufferEfficiency()), }; const auto service_type = config.IsSystemClient() ? (1 << 1) : (1 << 0); R_ABORT_UNLESS(sm::Initialize()); R_ABORT_UNLESS(::bsdInitialize(std::addressof(libnx_config), static_cast<u32>(config.GetConcurrencyCountMax()), service_type)); } /* Set the heap generation. */ g_heap_generation = (g_heap_generation + 1) % MinimumHeapAlignment; /* TODO: socket::resolver::EnableResolverCalls()? Not necessary in our case (htc), but consider calling it. */ g_initialized = true; R_SUCCEED(); } ALWAYS_INLINE struct sockaddr *ConvertForLibnx(SockAddr *addr) { static_assert(sizeof(SockAddr) == sizeof(struct sockaddr)); static_assert(alignof(SockAddr) == alignof(struct sockaddr)); return reinterpret_cast<struct sockaddr *>(addr); } ALWAYS_INLINE const struct sockaddr *ConvertForLibnx(const SockAddr *addr) { static_assert(sizeof(SockAddr) == sizeof(struct sockaddr)); static_assert(alignof(SockAddr) == alignof(struct sockaddr)); return reinterpret_cast<const struct sockaddr *>(addr); } static_assert(std::same_as<SockLenT, socklen_t>); Errno TranslateResultToBsdErrorImpl(const Result &result) { if (R_SUCCEEDED(result)) { return Errno::ESuccess; } else if (svc::ResultInvalidCurrentMemory::Includes(result) || svc::ResultOutOfAddressSpace::Includes(result)) { return Errno::EFault; } else if (sf::hipc::ResultCommunicationError::Includes(result)) { return Errno::EL3Hlt; } else if (sf::hipc::ResultOutOfResource::Includes(result)) { return Errno::EAgain; } else { R_ABORT_UNLESS(result); return static_cast<Errno>(-1); } } ALWAYS_INLINE void TranslateResultToBsdError(Errno &bsd_error, int &result) { Errno translate_error = Errno::ESuccess; if ((translate_error = TranslateResultToBsdErrorImpl(static_cast<::ams::Result>(::g_bsdResult))) != Errno::ESuccess) { bsd_error = translate_error; result = -1; } } } Result Initialize(const Config &config) { R_RETURN(InitializeCommon(config)); } Result Finalize() { /* Check pre-conditions. */ AMS_ABORT_UNLESS(IsInitialized()); /* TODO: If we support statistics, kill the statistics thread. */ /* TODO: socket::resolver::DisableResolverCalls()? */ /* Finalize libnx. */ ::bsdExit(); /* Finalize the heap. */ lmem::HeapHandle heap_handle; { std::scoped_lock lk(g_heap_mutex); heap_handle = g_heap_handle; g_heap_handle = nullptr; } lmem::DestroyExpHeap(heap_handle); R_SUCCEED(); } Result InitializeAllocatorForInternal(void *buffer, size_t size) { /* Check pre-conditions. */ AMS_ABORT_UNLESS(util::IsAligned(size, os::MemoryPageSize)); AMS_ABORT_UNLESS(size >= 4_KB); InitializeHeapImpl(buffer, size); R_SUCCEED(); } ssize_t RecvFrom(s32 desc, void *buffer, size_t buffer_size, MsgFlag flags, SockAddr *out_address, SockLenT *out_addr_len) { /* Check pre-conditions. */ AMS_ABORT_UNLESS(IsInitialized()); /* Check input. */ if (buffer_size == 0) { return 0; } else if (buffer == nullptr) { socket::impl::SetLastError(Errno::EInval); return -1; } else if (buffer_size > std::numeric_limits<u32>::max()) { socket::impl::SetLastError(Errno::EFault); return -1; } /* If this is just a normal receive call, perform a normal receive. */ if (out_address == nullptr || out_addr_len == nullptr || *out_addr_len == 0) { return impl::Recv(desc, buffer, buffer_size, flags); } /* Perform the call. */ socklen_t length; Errno error = Errno::ESuccess; int result = ::bsdRecvFrom(desc, buffer, buffer_size, static_cast<int>(flags), ConvertForLibnx(out_address), std::addressof(length)); TranslateResultToBsdError(error, result); if (result >= 0) { *out_addr_len = length; } else { socket::impl::SetLastError(error); } return result; } ssize_t Recv(s32 desc, void *buffer, size_t buffer_size, MsgFlag flags) { /* Check pre-conditions. */ AMS_ABORT_UNLESS(IsInitialized()); /* Check input. */ if (buffer_size == 0) { return 0; } else if (buffer == nullptr) { socket::impl::SetLastError(Errno::EInval); return -1; } else if (buffer_size > std::numeric_limits<u32>::max()) { socket::impl::SetLastError(Errno::EFault); return -1; } /* Perform the call. */ Errno error = Errno::ESuccess; int result = ::bsdRecv(desc, buffer, buffer_size, static_cast<int>(flags)); TranslateResultToBsdError(error, result); if (result < 0) { socket::impl::SetLastError(error); } return result; } ssize_t SendTo(s32 desc, const void *buffer, size_t buffer_size, MsgFlag flags, const SockAddr *address, SockLenT len) { /* Check pre-conditions. */ AMS_ABORT_UNLESS(IsInitialized()); /* If this is a normal send, perform a normal send. */ if (address == nullptr || len == 0) { return impl::Send(desc, buffer, buffer_size, flags); } /* Check input. */ if (buffer_size == 0) { return 0; } else if (buffer == nullptr) { socket::impl::SetLastError(Errno::EInval); return -1; } else if (buffer_size > std::numeric_limits<u32>::max()) { socket::impl::SetLastError(Errno::EFault); return -1; } /* Perform the call. */ Errno error = Errno::ESuccess; int result = ::bsdSendTo(desc, buffer, buffer_size, static_cast<int>(flags), ConvertForLibnx(address), len); TranslateResultToBsdError(error, result); if (result < 0) { socket::impl::SetLastError(error); } return result; } ssize_t Send(s32 desc, const void *buffer, size_t buffer_size, MsgFlag flags) { /* Check pre-conditions. */ AMS_ABORT_UNLESS(IsInitialized()); /* Check input. */ if (buffer_size == 0) { return 0; } else if (buffer == nullptr) { socket::impl::SetLastError(Errno::EInval); return -1; } else if (buffer_size > std::numeric_limits<u32>::max()) { socket::impl::SetLastError(Errno::EFault); return -1; } /* Perform the call. */ Errno error = Errno::ESuccess; int result = ::bsdSend(desc, buffer, buffer_size, static_cast<int>(flags)); TranslateResultToBsdError(error, result); if (result < 0) { socket::impl::SetLastError(error); } return result; } s32 Shutdown(s32 desc, ShutdownMethod how) { /* Check pre-conditions. */ AMS_ABORT_UNLESS(IsInitialized()); /* Perform the call. */ Errno error = Errno::ESuccess; int result = ::bsdShutdown(desc, static_cast<int>(how)); TranslateResultToBsdError(error, result); if (result < 0) { socket::impl::SetLastError(error); } return result; } s32 Socket(Family domain, Type type, Protocol protocol) { /* Check pre-conditions. */ AMS_ABORT_UNLESS(IsInitialized()); /* Perform the call. */ Errno error = Errno::ESuccess; int result = ::bsdSocket(static_cast<int>(domain), static_cast<int>(type), static_cast<int>(protocol)); TranslateResultToBsdError(error, result); if (result < 0) { socket::impl::SetLastError(error); } return result; } s32 SocketExempt(Family domain, Type type, Protocol protocol) { /* Check pre-conditions. */ AMS_ABORT_UNLESS(IsInitialized()); /* Perform the call. */ Errno error = Errno::ESuccess; int result = ::bsdSocketExempt(static_cast<int>(domain), static_cast<int>(type), static_cast<int>(protocol)); TranslateResultToBsdError(error, result); if (result < 0) { socket::impl::SetLastError(error); } return result; } s32 Accept(s32 desc, SockAddr *out_address, SockLenT *out_addr_len) { /* Check pre-conditions. */ AMS_ABORT_UNLESS(IsInitialized()); /* Check input. */ if (out_address == nullptr && out_addr_len != nullptr && *out_addr_len != 0) { socket::impl::SetLastError(Errno::EFault); return -1; } socklen_t addrlen = static_cast<socklen_t>((out_address && out_addr_len) ? *out_addr_len : 0); /* Perform the call. */ Errno error = Errno::ESuccess; int result = ::bsdAccept(desc, ConvertForLibnx(out_address), std::addressof(addrlen)); TranslateResultToBsdError(error, result); if (result >= 0) { if (out_addr_len != nullptr) { *out_addr_len = addrlen; } } else { socket::impl::SetLastError(error); } return result; } s32 Bind(s32 desc, const SockAddr *address, SockLenT len) { /* Check pre-conditions. */ AMS_ABORT_UNLESS(IsInitialized()); /* Check input. */ if (address == nullptr || len == 0) { socket::impl::SetLastError(Errno::EInval); return -1; } /* Perform the call. */ Errno error = Errno::ESuccess; int result = ::bsdBind(desc, ConvertForLibnx(address), len); TranslateResultToBsdError(error, result); if (result < 0) { socket::impl::SetLastError(error); } return result; } s32 Connect(s32 desc, const SockAddr *address, SockLenT len) { /* Check pre-conditions. */ AMS_ABORT_UNLESS(IsInitialized()); /* Check input. */ if (address == nullptr || len == 0) { socket::impl::SetLastError(Errno::EInval); return -1; } /* Perform the call. */ Errno error = Errno::ESuccess; int result = ::bsdConnect(desc, ConvertForLibnx(address), len); TranslateResultToBsdError(error, result); if (result < 0) { socket::impl::SetLastError(error); } return result; } s32 GetSockName(s32 desc, SockAddr *out_address, SockLenT *out_addr_len) { /* Check pre-conditions. */ AMS_ABORT_UNLESS(IsInitialized()); /* Check input. */ if (out_address == nullptr || out_addr_len == nullptr || *out_addr_len == 0) { socket::impl::SetLastError(Errno::EInval); return -1; } /* Perform the call. */ socklen_t length; Errno error = Errno::ESuccess; int result = ::bsdGetSockName(desc, ConvertForLibnx(out_address), std::addressof(length)); TranslateResultToBsdError(error, result); if (result >= 0) { *out_addr_len = length; } else { socket::impl::SetLastError(error); } return result; } s32 SetSockOpt(s32 desc, Level level, Option option_name, const void *option_value, SockLenT option_size) { /* Check pre-conditions. */ AMS_ABORT_UNLESS(IsInitialized()); /* Check input. */ if (option_value == nullptr) { socket::impl::SetLastError(Errno::EInval); return -1; } /* Perform the call. */ Errno error = Errno::ESuccess; int result = ::bsdSetSockOpt(desc, static_cast<int>(level), static_cast<int>(option_name), option_value, option_size); TranslateResultToBsdError(error, result); if (result < 0) { socket::impl::SetLastError(error); } return result; } s32 Listen(s32 desc, s32 backlog) { /* Check pre-conditions. */ AMS_ABORT_UNLESS(IsInitialized()); /* Perform the call. */ Errno error = Errno::ESuccess; int result = ::bsdListen(desc, backlog); TranslateResultToBsdError(error, result); if (result < 0) { socket::impl::SetLastError(error); } return result; } s32 Close(s32 desc) { /* Check pre-conditions. */ AMS_ABORT_UNLESS(IsInitialized()); /* Perform the call. */ Errno error = Errno::ESuccess; int result = ::bsdClose(desc); TranslateResultToBsdError(error, result); if (result < 0) { socket::impl::SetLastError(error); } return result; } }
19,459
C++
.cpp
460
32.417391
143
0.586717
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,396
socket_platform_types_translation.os.windows.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/socket/impl/socket_platform_types_translation.os.windows.cpp
/* * Copyright (c) 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 "socket_api.hpp" #include <ws2tcpip.h> #include <stratosphere/socket/impl/socket_platform_types_translation.hpp> namespace ams::socket::impl { ///* TODO: Custom sys/* headers, probably. */ #define AF_LINK 18 #define MSG_TRUNC 0x10 #define MSG_CTRUNC 0x20 #define MSG_DONTWAIT 0x80 #define SHUT_RD 0 #define SHUT_WR 1 #define SHUT_RDWR 2 #define O_NONBLOCK 4 #define TCP_MAXSEG 4 PosixWinSockConverter g_posix_winsock_converter; s32 PosixWinSockConverter::AcquirePosixHandle(SOCKET winsock, bool exempt) { /* Acquire exclusive access. */ std::scoped_lock lk(m_mutex); /* Get initial index. */ const auto initial_index = GetInitialIndex(winsock); /* Try to find an open index. */ for (auto posix = initial_index; posix < static_cast<int>(MaxSocketsPerClient); ++posix) { if (m_data[posix].winsock == static_cast<SOCKET>(INVALID_SOCKET)) { m_data[posix].winsock = winsock; m_data[posix].exempt = exempt; return posix; } } for (auto posix = 0; posix < initial_index; ++posix) { if (m_data[posix].winsock == static_cast<SOCKET>(INVALID_SOCKET)) { m_data[posix].winsock = winsock; m_data[posix].exempt = exempt; return posix; } } /* We're out of open handles. */ socket::impl::SetLastError(Errno::EMFile); return SOCKET_ERROR; } s32 PosixWinSockConverter::GetShutdown(bool &shutdown, s32 posix) { /* Acquire exclusive access. */ std::scoped_lock lk(m_mutex); /* Check input. */ if (static_cast<u32>(posix) >= MaxSocketsPerClient || m_data[posix].winsock == static_cast<SOCKET>(INVALID_SOCKET)) { socket::impl::SetLastError(Errno::EBadf); return SOCKET_ERROR; } /* Set the output. */ shutdown = m_data[posix].shutdown; return 0; } s32 PosixWinSockConverter::GetSocketExempt(bool &exempt, s32 posix) { /* Acquire exclusive access. */ std::scoped_lock lk(m_mutex); /* Check input. */ if (static_cast<u32>(posix) >= MaxSocketsPerClient || m_data[posix].winsock == static_cast<SOCKET>(INVALID_SOCKET)) { socket::impl::SetLastError(Errno::EBadf); return SOCKET_ERROR; } /* Set the output. */ exempt = m_data[posix].exempt; return 0; } SOCKET PosixWinSockConverter::PosixToWinsockSocket(s32 posix) { /* Acquire exclusive access. */ std::scoped_lock lk(m_mutex); /* Check input. */ if (static_cast<u32>(posix) >= MaxSocketsPerClient || m_data[posix].winsock == static_cast<SOCKET>(INVALID_SOCKET)) { socket::impl::SetLastError(Errno::EBadf); return SOCKET_ERROR; } return m_data[posix].winsock; } void PosixWinSockConverter::ReleaseAllPosixHandles() { /* Acquire exclusive access. */ std::scoped_lock lk(m_mutex); for (size_t i = 0; i < MaxSocketsPerClient; ++i) { m_data[i] = SocketData{}; } } void PosixWinSockConverter::ReleasePosixHandle(s32 posix) { /* Acquire exclusive access. */ std::scoped_lock lk(m_mutex); AMS_ASSERT(static_cast<u32>(posix) < MaxSocketsPerClient); m_data[posix] = SocketData{}; } s32 PosixWinSockConverter::SetShutdown(s32 posix, bool shutdown) { /* Acquire exclusive access. */ std::scoped_lock lk(m_mutex); /* Check input. */ if (static_cast<u32>(posix) >= MaxSocketsPerClient || m_data[posix].winsock == static_cast<SOCKET>(INVALID_SOCKET)) { socket::impl::SetLastError(Errno::EBadf); return SOCKET_ERROR; } /* Set the shutdown. */ m_data[posix].shutdown = shutdown; return 0; } s32 PosixWinSockConverter::SetSocketExempt(s32 posix, bool exempt) { /* Acquire exclusive access. */ std::scoped_lock lk(m_mutex); /* Check input. */ if (static_cast<u32>(posix) >= MaxSocketsPerClient || m_data[posix].winsock == static_cast<SOCKET>(INVALID_SOCKET)) { socket::impl::SetLastError(Errno::EBadf); return SOCKET_ERROR; } /* Set the exempt. */ m_data[posix].exempt = exempt; return 0; } s32 PosixWinSockConverter::WinsockToPosixSocket(SOCKET winsock) { /* Acquire exclusive access. */ std::scoped_lock lk(m_mutex); /* Get initial index. */ const auto initial_index = GetInitialIndex(winsock); /* Try to find an open index. */ for (auto posix = initial_index; posix < static_cast<int>(MaxSocketsPerClient); ++posix) { if (m_data[posix].winsock == winsock) { return posix; } } for (auto posix = 0; posix < initial_index; ++posix) { if (m_data[posix].winsock == winsock) { return posix; } } /* We failed to find the posix handle. */ return -1; } s32 MapProtocolValue(Protocol protocol) { s32 mapped = -1; switch (protocol) { case Protocol::IpProto_Ip: mapped = IPPROTO_IP; break; case Protocol::IpProto_Icmp: mapped = IPPROTO_ICMP; break; case Protocol::IpProto_Tcp: mapped = IPPROTO_TCP; break; case Protocol::IpProto_Udp: mapped = IPPROTO_UDP; break; case Protocol::IpProto_None: mapped = IPPROTO_NONE; break; case Protocol::IpProto_UdpLite: mapped = IPPROTO_UDP; break; case Protocol::IpProto_Raw: mapped = IPPROTO_RAW; break; case Protocol::IpProto_Max: mapped = IPPROTO_MAX; break; default: AMS_SDK_LOG("WARNING: Invalid ams::Socket::Protocol %d\n", static_cast<int>(protocol)); break; } if (mapped == -1) { AMS_SDK_LOG("WARNING: ams::Socket::Protocol %d is not supported by Win32/Win64.\n", static_cast<int>(protocol)); } return mapped; } Protocol MapProtocolValue(s32 protocol) { Protocol mapped = Protocol::IpProto_None; switch (protocol) { case IPPROTO_IP: mapped = Protocol::IpProto_Ip; break; case IPPROTO_ICMP: mapped = Protocol::IpProto_Icmp; break; case IPPROTO_TCP: mapped = Protocol::IpProto_Tcp; break; case IPPROTO_UDP: mapped = Protocol::IpProto_Udp; break; case IPPROTO_NONE: mapped = Protocol::IpProto_None; break; case IPPROTO_RAW: mapped = Protocol::IpProto_Raw; break; case IPPROTO_MAX: mapped = Protocol::IpProto_Max; break; default: AMS_SDK_LOG("WARNING: Invalid socket protocol %d\n", static_cast<int>(protocol)); break; } return mapped; } s32 MapTypeValue(Type type) { s32 mapped = -1; switch (type) { case Type::Sock_Default: mapped = 0; break; case Type::Sock_Stream: mapped = SOCK_STREAM; break; case Type::Sock_Dgram: mapped = SOCK_DGRAM; break; case Type::Sock_Raw: mapped = SOCK_RAW; break; case Type::Sock_SeqPacket: mapped = SOCK_SEQPACKET; break; case Type::Sock_NonBlock: mapped = -1; break; default: AMS_SDK_LOG("WARNING: Invalid ams::Socket::Type %d\n", static_cast<int>(type)); break; } if (mapped == -1) { AMS_SDK_LOG("WARNING: ams::Socket::Type %d is not supported by Win32/Win64.\n", static_cast<int>(type)); } return mapped; } Type MapTypeValue(s32 type) { Type mapped = Type::Sock_Default; switch (type) { case 0: mapped = Type::Sock_Default; break; case SOCK_STREAM: mapped = Type::Sock_Stream; break; case SOCK_DGRAM: mapped = Type::Sock_Dgram; break; case SOCK_RAW: mapped = Type::Sock_Raw; break; case SOCK_SEQPACKET: mapped = Type::Sock_SeqPacket; break; default: AMS_SDK_LOG("WARNING: Invalid socket type %d\n", static_cast<int>(type)); break; } return mapped; } s8 MapFamilyValue(Family family) { s8 mapped = -1; switch (family) { case Family::Af_Unspec: mapped = AF_UNSPEC; break; case Family::Af_Inet: mapped = AF_INET; break; case Family::Af_Route: mapped = -1; break; case Family::Af_Link: mapped = AF_LINK; break; case Family::Af_Inet6: mapped = AF_INET6; break; case Family::Af_Max: mapped = AF_MAX; break; default: AMS_SDK_LOG("WARNING: Invalid ams::Socket::Family %d\n", static_cast<int>(family)); break; } if (mapped == -1) { AMS_SDK_LOG("WARNING: ams::Socket::Family %d is not supported by Win32/Win64.\n", static_cast<int>(family)); } return mapped; } Family MapFamilyValue(s8 family) { Family mapped = Family::Af_Unspec; switch (family) { case AF_UNSPEC:mapped = Family::Af_Unspec; break; case AF_INET: mapped = Family::Af_Inet; break; case AF_LINK: mapped = Family::Af_Link; break; case AF_INET6: mapped = Family::Af_Inet6; break; case AF_MAX: mapped = Family::Af_Max; break; default: AMS_SDK_LOG("WARNING: Invalid socket family %d\n", static_cast<int>(family)); break; } return mapped; } s32 MapMsgFlagValue(MsgFlag flag) { s32 mapped = 0; if ((flag & MsgFlag::Msg_Oob) != MsgFlag::Msg_None) { mapped |= MSG_OOB; } if ((flag & MsgFlag::Msg_Peek) != MsgFlag::Msg_None) { mapped |= MSG_PEEK; } if ((flag & MsgFlag::Msg_DontRoute) != MsgFlag::Msg_None) { mapped |= MSG_DONTROUTE; } if ((flag & MsgFlag::Msg_Trunc) != MsgFlag::Msg_None) { mapped |= MSG_TRUNC; } if ((flag & MsgFlag::Msg_CTrunc) != MsgFlag::Msg_None) { mapped |= MSG_CTRUNC; } if ((flag & MsgFlag::Msg_WaitAll) != MsgFlag::Msg_None) { mapped |= MSG_WAITALL; } if ((flag & MsgFlag::Msg_DontWait) != MsgFlag::Msg_None) { mapped |= MSG_DONTWAIT; } return mapped; } MsgFlag MapMsgFlagValue(s32 flag) { MsgFlag mapped = MsgFlag::Msg_None; if (flag & MSG_OOB) { mapped |= MsgFlag::Msg_Oob; } if (flag & MSG_PEEK) { mapped |= MsgFlag::Msg_Peek; } if (flag & MSG_DONTROUTE) { mapped |= MsgFlag::Msg_DontRoute; } if (flag & MSG_TRUNC) { mapped |= MsgFlag::Msg_Trunc; } if (flag & MSG_CTRUNC) { mapped |= MsgFlag::Msg_CTrunc; } if (flag & MSG_WAITALL) { mapped |= MsgFlag::Msg_WaitAll; } if (flag & MSG_DONTWAIT) { mapped |= MsgFlag::Msg_DontWait; } return mapped; } u32 MapAddrInfoFlagValue(AddrInfoFlag flag) { u32 mapped = 0; if ((flag & AddrInfoFlag::Ai_Passive) != AddrInfoFlag::Ai_None) { mapped |= AI_PASSIVE; } if ((flag & AddrInfoFlag::Ai_CanonName) != AddrInfoFlag::Ai_None) { mapped |= AI_CANONNAME; } if ((flag & AddrInfoFlag::Ai_NumericHost) != AddrInfoFlag::Ai_None) { mapped |= AI_NUMERICHOST; } if ((flag & AddrInfoFlag::Ai_NumericServ) != AddrInfoFlag::Ai_None) { mapped |= AI_NUMERICSERV; } if ((flag & AddrInfoFlag::Ai_AddrConfig) != AddrInfoFlag::Ai_None) { mapped |= AI_ADDRCONFIG; } return mapped; } AddrInfoFlag MapAddrInfoFlagValue(u32 flag) { AddrInfoFlag mapped = AddrInfoFlag::Ai_None; if (flag & AI_PASSIVE) { mapped |= AddrInfoFlag::Ai_Passive; } if (flag & AI_CANONNAME) { mapped |= AddrInfoFlag::Ai_CanonName; } if (flag & AI_NUMERICHOST) { mapped |= AddrInfoFlag::Ai_NumericHost; } if (flag & AI_NUMERICSERV) { mapped |= AddrInfoFlag::Ai_NumericServ; } if (flag & AI_ADDRCONFIG) { mapped |= AddrInfoFlag::Ai_AddrConfig; } return mapped; } u32 MapShutdownMethodValue(ShutdownMethod how) { u32 mapped = -1; switch (how) { case ShutdownMethod::Shut_Rd: mapped = SHUT_RD; break; case ShutdownMethod::Shut_Wr: mapped = SHUT_WR; break; case ShutdownMethod::Shut_RdWr: mapped = SHUT_RDWR; break; default: AMS_SDK_LOG("WARNING: Invalid ams::Socket::ShutdownMethod %d\n", static_cast<int>(how)); break; } return mapped; } ShutdownMethod MapShutdownMethodValue(u32 how) { ShutdownMethod mapped = static_cast<ShutdownMethod>(-1); switch (how) { case SHUT_RD: mapped = ShutdownMethod::Shut_Rd; break; case SHUT_WR: mapped = ShutdownMethod::Shut_Wr; break; case SHUT_RDWR: mapped = ShutdownMethod::Shut_RdWr; break; default: AMS_SDK_LOG("WARNING: Invalid socket shutdown %d\n", static_cast<int>(how)); break; } return mapped; } u32 MapFcntlFlagValue(FcntlFlag flag) { u32 mapped = 0; switch (flag) { case FcntlFlag::O_NonBlock: mapped = O_NONBLOCK; break; default: AMS_SDK_LOG("WARNING: Invalid ams::Socket::FcntlFlag %d\n", static_cast<int>(flag)); break; } return mapped; } FcntlFlag MapFcntlFlagValue(u32 flag) { FcntlFlag mapped = FcntlFlag::None; switch (flag) { case O_NONBLOCK: mapped = FcntlFlag::O_NonBlock; break; default: AMS_SDK_LOG("WARNING: Invalid socket fcntl flag %d\n", static_cast<int>(flag)); break; } return mapped; } s32 MapLevelValue(Level level) { s32 mapped = -1; switch (level) { case Level::Sol_Socket: mapped = SOL_SOCKET; break; case Level::Sol_Ip: mapped = IPPROTO_IP; break; case Level::Sol_Icmp: mapped = IPPROTO_ICMP; break; case Level::Sol_Tcp: mapped = IPPROTO_TCP; break; case Level::Sol_Udp: mapped = IPPROTO_UDP; break; case Level::Sol_UdpLite: mapped = IPPROTO_UDP; break; default: AMS_SDK_LOG("WARNING: Invalid ams::Socket::Level %d\n", static_cast<int>(level)); break; } return mapped; } Level MapLevelValue(s32 level) { Level mapped = static_cast<Level>(0); switch (level) { case SOL_SOCKET: mapped = Level::Sol_Socket; break; case IPPROTO_IP: mapped = Level::Sol_Ip; break; case IPPROTO_ICMP: mapped = Level::Sol_Icmp; break; case IPPROTO_TCP: mapped = Level::Sol_Tcp; break; case IPPROTO_UDP: mapped = Level::Sol_Udp; break; default: AMS_SDK_LOG("WARNING: Invalid socket level %d\n", static_cast<int>(level)); break; } return mapped; } s32 MapOptionValue(Level level, Option option) { s32 mapped = -1; switch (level) { case Level::Sol_Socket: switch (option) { case Option::So_Debug: mapped = SO_DEBUG; break; case Option::So_AcceptConn: mapped = SO_ACCEPTCONN; break; case Option::So_ReuseAddr: mapped = SO_REUSEADDR; break; case Option::So_KeepAlive: mapped = SO_KEEPALIVE; break; case Option::So_DontRoute: mapped = SO_DONTROUTE; break; case Option::So_Broadcast: mapped = SO_BROADCAST; break; case Option::So_UseLoopback: mapped = SO_USELOOPBACK; break; case Option::So_Linger: mapped = SO_LINGER; break; case Option::So_OobInline: mapped = SO_OOBINLINE; break; case Option::So_ReusePort: mapped = -1; break; case Option::So_SndBuf: mapped = SO_SNDBUF; break; case Option::So_RcvBuf: mapped = SO_RCVBUF; break; case Option::So_SndLoWat: mapped = SO_SNDLOWAT; break; case Option::So_RcvLoWat: mapped = SO_RCVLOWAT; break; case Option::So_SndTimeo: mapped = SO_SNDTIMEO; break; case Option::So_RcvTimeo: mapped = SO_RCVTIMEO; break; case Option::So_Error: mapped = SO_ERROR; break; case Option::So_Type: mapped = SO_TYPE; break; case Option::So_Label: mapped = -1; break; case Option::So_PeerLabel: mapped = -1; break; case Option::So_ListenQLimit: mapped = -1; break; case Option::So_ListenQLen: mapped = -1; break; case Option::So_ListenIncQLen: mapped = -1; break; case Option::So_SetFib: mapped = -1; break; case Option::So_User_Cookie: mapped = -1; break; case Option::So_Protocol: mapped = -1; break; case Option::So_Vendor: mapped = -1; break; case Option::So_Nn_Linger: mapped = -1; break; case Option::So_Nn_Shutdown_Exempt: mapped = -1; break; default: AMS_SDK_LOG("WARNING: Invalid ams::Socket::Option %d for Level::Sol_Socket\n", static_cast<int>(option)); break; } break; case Level::Sol_Ip: switch (option) { case Option::Ip_Options: mapped = IP_OPTIONS; break; case Option::Ip_HdrIncl: mapped = IP_HDRINCL; break; case Option::Ip_Tos: mapped = IP_TOS; break; case Option::Ip_Ttl: mapped = IP_TTL; break; case Option::Ip_RecvOpts: mapped = -1; break; case Option::Ip_Multicast_If: mapped = IP_MULTICAST_IF; break; case Option::Ip_Multicast_Ttl: mapped = IP_MULTICAST_TTL; break; case Option::Ip_Multicast_Loop: mapped = IP_MULTICAST_LOOP; break; case Option::Ip_Add_Membership: mapped = IP_ADD_MEMBERSHIP; break; case Option::Ip_Drop_Membership: mapped = IP_DROP_MEMBERSHIP; break; case Option::Ip_Multicast_Vif: mapped = -1; break; case Option::Ip_Rsvp_On: mapped = -1; break; case Option::Ip_Rsvp_Off: mapped = -1; break; case Option::Ip_Rsvp_Vif_On: mapped = -1; break; case Option::Ip_Rsvp_Vif_Off: mapped = -1; break; case Option::Ip_PortRange: mapped = -1; break; case Option::Ip_Faith: mapped = -1; break; case Option::Ip_OnesBcast: mapped = -1; break; case Option::Ip_BindAny: mapped = -1; break; case Option::Ip_RecvTtl: mapped = -1; break; case Option::Ip_MinTtl: mapped = -1; break; case Option::Ip_DontFrag: mapped = -1; break; case Option::Ip_RecvTos: mapped = -1; break; case Option::Ip_Add_Source_Membership: mapped = IP_ADD_SOURCE_MEMBERSHIP; break; case Option::Ip_Drop_Source_Membership: mapped = IP_DROP_SOURCE_MEMBERSHIP; break; case Option::Ip_Block_Source: mapped = IP_BLOCK_SOURCE; break; case Option::Ip_Unblock_Source: mapped = IP_UNBLOCK_SOURCE; break; default: AMS_SDK_LOG("WARNING: Invalid ams::Socket::Option %d for Level::Sol_Ip\n", static_cast<int>(option)); break; } break; case Level::Sol_Tcp: switch (option) { case Option::Tcp_NoDelay: mapped = TCP_NODELAY; break; case Option::Tcp_MaxSeg: mapped = TCP_MAXSEG; break; case Option::Tcp_NoPush: mapped = -1; break; case Option::Tcp_NoOpt: mapped = -1; break; case Option::Tcp_Md5Sig: mapped = -1; break; case Option::Tcp_Info: mapped = -1; break; case Option::Tcp_Congestion: mapped = -1; break; case Option::Tcp_KeepInit: mapped = -1; break; case Option::Tcp_KeepIdle: mapped = -1; break; case Option::Tcp_KeepIntvl: mapped = -1; break; case Option::Tcp_KeepCnt: mapped = -1; break; case Option::Tcp_Vendor: mapped = -1; break; default: AMS_SDK_LOG("WARNING: Invalid ams::Socket::Option %d for Level::Sol_Tcp\n", static_cast<int>(option)); break; } break; default: AMS_SDK_LOG("WARNING: Invalid option level %d\n", static_cast<int>(level)); break; } if (mapped == -1) { AMS_SDK_LOG("WARNING: ams::Socket::Option %d is not supported by Win32/Win64.\n", static_cast<int>(option)); } return mapped; } Option MapOptionValue(s32 level, s32 option) { Option mapped = static_cast<Option>(0); switch (level) { case SOL_SOCKET: switch (option) { case SO_DEBUG: mapped = Option::So_Debug; break; case SO_ACCEPTCONN: mapped = Option::So_AcceptConn; break; case SO_REUSEADDR: mapped = Option::So_ReuseAddr; break; case SO_KEEPALIVE: mapped = Option::So_KeepAlive; break; case SO_DONTROUTE: mapped = Option::So_DontRoute; break; case SO_BROADCAST: mapped = Option::So_Broadcast; break; case SO_USELOOPBACK: mapped = Option::So_UseLoopback; break; case SO_LINGER: mapped = Option::So_Linger; break; case SO_OOBINLINE: mapped = Option::So_OobInline; break; case SO_SNDBUF: mapped = Option::So_SndBuf; break; case SO_RCVBUF: mapped = Option::So_RcvBuf; break; case SO_SNDLOWAT: mapped = Option::So_SndLoWat; break; case SO_RCVLOWAT: mapped = Option::So_RcvLoWat; break; case SO_SNDTIMEO: mapped = Option::So_SndTimeo; break; case SO_RCVTIMEO: mapped = Option::So_RcvTimeo; break; case SO_ERROR: mapped = Option::So_Error; break; case SO_TYPE: mapped = Option::So_Type; break; default: AMS_SDK_LOG("WARNING: Invalid socket option %d for SOL_SOCKET\n", static_cast<int>(option)); break; } break; case IPPROTO_IP: switch (option) { case IP_OPTIONS: mapped = Option::Ip_Options; break; case IP_HDRINCL: mapped = Option::Ip_HdrIncl; break; case IP_TOS: mapped = Option::Ip_Tos; break; case IP_TTL: mapped = Option::Ip_Ttl; break; case IP_MULTICAST_IF: mapped = Option::Ip_Multicast_If; break; case IP_MULTICAST_TTL: mapped = Option::Ip_Multicast_Ttl; break; case IP_MULTICAST_LOOP: mapped = Option::Ip_Multicast_Loop; break; case IP_ADD_MEMBERSHIP: mapped = Option::Ip_Add_Membership; break; case IP_DROP_MEMBERSHIP: mapped = Option::Ip_Drop_Membership; break; case IP_ADD_SOURCE_MEMBERSHIP: mapped = Option::Ip_Add_Source_Membership; break; case IP_DROP_SOURCE_MEMBERSHIP: mapped = Option::Ip_Drop_Source_Membership; break; case IP_BLOCK_SOURCE: mapped = Option::Ip_Block_Source; break; case IP_UNBLOCK_SOURCE: mapped = Option::Ip_Unblock_Source; break; default: AMS_SDK_LOG("WARNING: Invalid socket option %d for SOL_IP\n", static_cast<int>(option)); break; } break; case IPPROTO_TCP: switch (option) { case TCP_NODELAY: mapped = Option::Tcp_NoDelay; break; case TCP_MAXSEG: mapped = Option::Tcp_MaxSeg; break; default: AMS_SDK_LOG("WARNING: Invalid ams::Socket::Option %d for SOL_TCP\n", static_cast<int>(option)); break; } break; default: AMS_SDK_LOG("WARNING: Invalid option level %d\n", static_cast<int>(level)); break; } return mapped; } s32 MapErrnoValue(Errno error) { s32 mapped = -1; switch (error) { case Errno::EIntr: mapped = WSAEINTR; break; case Errno::EBadf: mapped = WSAEBADF; break; case Errno::EWouldBlock: mapped = WSAEWOULDBLOCK; break; case Errno::EAcces: mapped = WSAEACCES; break; case Errno::EFault: mapped = WSAEFAULT; break; case Errno::EInval: mapped = WSAEINVAL; break; case Errno::EMFile: mapped = WSAEMFILE; break; case Errno::EPipe: mapped = 109; break; case Errno::ENameTooLong: mapped = WSAENAMETOOLONG; break; case Errno::ENotEmpty: mapped = WSAENOTEMPTY; break; case Errno::ELoop: mapped = WSAELOOP; break; case Errno::ERemote: mapped = WSAEREMOTE; break; case Errno::EUsers: mapped = WSAEUSERS; break; case Errno::ENotSock: mapped = WSAENOTSOCK; break; case Errno::EDestAddrReq: mapped = WSAEDESTADDRREQ; break; case Errno::EMsgSize: mapped = WSAEMSGSIZE; break; case Errno::EPrototype: mapped = WSAEPROTOTYPE; break; case Errno::ENoProtoOpt: mapped = WSAENOPROTOOPT; break; case Errno::EProtoNoSupport: mapped = WSAEPROTONOSUPPORT; break; case Errno::ESocktNoSupport: mapped = WSAESOCKTNOSUPPORT; break; case Errno::EOpNotSupp: mapped = WSAEOPNOTSUPP; break; case Errno::EPfNoSupport: mapped = WSAEPFNOSUPPORT; break; case Errno::EAfNoSupport: mapped = WSAEAFNOSUPPORT; break; case Errno::EAddrInUse: mapped = WSAEADDRINUSE; break; case Errno::EAddrNotAvail: mapped = WSAEADDRNOTAVAIL; break; case Errno::ENetDown: mapped = WSAENETDOWN; break; case Errno::ENetUnreach: mapped = WSAENETUNREACH; break; case Errno::ENetReset: mapped = WSAENETRESET; break; case Errno::EConnAborted: mapped = WSAECONNABORTED; break; case Errno::EConnReset: mapped = WSAECONNRESET; break; case Errno::ENoBufs: mapped = WSAENOBUFS; break; case Errno::EIsConn: mapped = WSAEISCONN; break; case Errno::ENotConn: mapped = WSAENOTCONN; break; case Errno::EShutDown: mapped = WSAESHUTDOWN; break; case Errno::ETooManyRefs: mapped = WSAETOOMANYREFS; break; case Errno::ETimedOut: mapped = WSAETIMEDOUT; break; case Errno::EConnRefused: mapped = WSAECONNREFUSED; break; case Errno::EHostDown: mapped = WSAEHOSTDOWN; break; case Errno::EHostUnreach: mapped = WSAEHOSTUNREACH; break; case Errno::EAlready: mapped = WSAEALREADY; break; case Errno::EInProgress: mapped = WSAEINPROGRESS; break; case Errno::EStale: mapped = WSAESTALE; break; case Errno::EDQuot: mapped = WSAEDQUOT; break; case Errno::ECanceled: mapped = WSAECANCELLED; break; case Errno::EProcLim: mapped = WSAEPROCLIM; break; default: mapped = static_cast<s32>(error); break; } return mapped; } Errno MapErrnoValue(s32 error) { Errno mapped = Errno::ESuccess; switch (error) { case WSAEBADF: mapped = Errno::EBadf; break; case WSAEACCES: mapped = Errno::EAcces; break; case WSAEFAULT: mapped = Errno::EFault; break; case WSAEINVAL: mapped = Errno::EInval; break; case WSAEMFILE: mapped = Errno::EMFile; break; case WSAEWOULDBLOCK: mapped = Errno::EWouldBlock; break; case WSAEINPROGRESS: mapped = Errno::EInProgress; break; case WSAEALREADY: mapped = Errno::EAlready; break; case WSAENOTSOCK: mapped = Errno::ENotSock; break; case WSAEDESTADDRREQ: mapped = Errno::EDestAddrReq; break; case WSAEMSGSIZE: mapped = Errno::EMsgSize; break; case WSAEPROTOTYPE: mapped = Errno::EPrototype; break; case WSAENOPROTOOPT: mapped = Errno::ENoProtoOpt; break; case WSAEPROTONOSUPPORT: mapped = Errno::EProtoNoSupport; break; case WSAESOCKTNOSUPPORT: mapped = Errno::ESocktNoSupport; break; case WSAEOPNOTSUPP: mapped = Errno::EOpNotSupp; break; case WSAEPFNOSUPPORT: mapped = Errno::EPfNoSupport; break; case WSAEAFNOSUPPORT: mapped = Errno::EAfNoSupport; break; case WSAEADDRINUSE: mapped = Errno::EAddrInUse; break; case WSAEADDRNOTAVAIL: mapped = Errno::EAddrNotAvail; break; case WSAENETDOWN: mapped = Errno::ENetDown; break; case WSAENETUNREACH: mapped = Errno::ENetUnreach; break; case WSAENETRESET: mapped = Errno::ENetReset; break; case WSAECONNABORTED: mapped = Errno::EConnAborted; break; case WSAECONNRESET: mapped = Errno::EConnReset; break; case WSAENOBUFS: mapped = Errno::ENoBufs; break; case WSAEISCONN: mapped = Errno::EIsConn; break; case WSAENOTCONN: mapped = Errno::ENotConn; break; case WSAESHUTDOWN: mapped = Errno::EShutDown; break; case WSAETOOMANYREFS: mapped = Errno::ETooManyRefs; break; case WSAETIMEDOUT: mapped = Errno::ETimedOut; break; case WSAECONNREFUSED: mapped = Errno::EConnRefused; break; case WSAELOOP: mapped = Errno::ELoop; break; case WSAENAMETOOLONG: mapped = Errno::ENameTooLong; break; case WSAEHOSTDOWN: mapped = Errno::EHostDown; break; case WSAEHOSTUNREACH: mapped = Errno::EHostUnreach; break; case WSAENOTEMPTY: mapped = Errno::ENotEmpty; break; case WSAEPROCLIM: mapped = Errno::EProcLim; break; case WSAEUSERS: mapped = Errno::EUsers; break; case WSAEDQUOT: mapped = Errno::EDQuot; break; case WSAESTALE: mapped = Errno::EStale; break; case WSAEREMOTE: mapped = Errno::ERemote; break; case WSAECANCELLED: mapped = Errno::ECanceled; break; case WSAEINTR: mapped = Errno::EIntr; break; case 109: mapped = Errno::EPipe; break; default: mapped = static_cast<Errno>(error); break; } return mapped; } void CopyToPlatform(sockaddr_in *dst, const SockAddrIn *src) { if (src != nullptr) { dst->sin_family = MapFamilyValue(src->sin_family); dst->sin_port = src->sin_port; std::memcpy(std::addressof(dst->sin_addr), std::addressof(src->sin_addr), sizeof(dst->sin_addr)); std::memcpy(dst->sin_zero, src->sin_zero, sizeof(dst->sin_zero)); } } void CopyFromPlatform(SockAddrIn *dst, const sockaddr_in *src) { if (dst != nullptr) { dst->sin_family = MapFamilyValue(static_cast<s8>(src->sin_family)); dst->sin_port = src->sin_port; std::memcpy(std::addressof(dst->sin_addr), std::addressof(src->sin_addr), sizeof(dst->sin_addr)); std::memcpy(dst->sin_zero, src->sin_zero, sizeof(dst->sin_zero)); } } void CopyToPlatform(timeval *dst, const TimeVal *src) { if (src != nullptr) { dst->tv_sec = src->tv_sec; dst->tv_usec = src->tv_usec; } } void CopyFromPlatform(TimeVal *dst, const timeval *src) { if (dst != nullptr) { dst->tv_sec = src->tv_sec; dst->tv_usec = src->tv_usec; } } void CopyToPlatform(linger *dst, const Linger *src) { if (src != nullptr) { dst->l_onoff = static_cast<u_short>(src->l_onoff); dst->l_linger = static_cast<u_short>(src->l_linger); } } void CopyFromPlatform(Linger *dst, const linger *src) { if (dst != nullptr) { dst->l_onoff = src->l_onoff; dst->l_linger = src->l_linger; } } }
37,129
C++
.cpp
666
43.211712
129
0.518664
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,397
nsd_device.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/nsd/impl/device/nsd_device.cpp
/* * Copyright (c) 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::nsd::impl::device { namespace { constexpr const char SettingsName[] = "nsd"; constexpr const char SettingsKey[] = "environment_identifier"; constinit os::SdkMutex g_environment_identifier_lock; constinit EnvironmentIdentifier g_environment_identifier = {}; constinit bool g_determined_environment_identifier = false; } const EnvironmentIdentifier &GetEnvironmentIdentifierFromSettings() { if (AMS_UNLIKELY(!g_determined_environment_identifier)) { std::scoped_lock lk(g_environment_identifier_lock); if (AMS_LIKELY(!g_determined_environment_identifier)) { /* Check size. */ AMS_ABORT_UNLESS(settings::fwdbg::GetSettingsItemValueSize(SettingsName, SettingsKey) != 0); /* Get value. */ const size_t size = settings::fwdbg::GetSettingsItemValue(g_environment_identifier.value, EnvironmentIdentifier::Size, SettingsName, SettingsKey); AMS_ABORT_UNLESS(size < EnvironmentIdentifier::Size); AMS_ABORT_UNLESS(g_environment_identifier == EnvironmentIdentifierOfProductDevice || g_environment_identifier == EnvironmentIdentifierOfNotProductDevice); g_determined_environment_identifier = true; } } return g_environment_identifier; } }
2,042
C++
.cpp
40
43.725
170
0.703164
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,398
hos_version_api_private.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/hos/hos_version_api_private.cpp
/* * Copyright (c) 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::hos { namespace { #if defined(ATMOSPHERE_OS_HORIZON) settings::FirmwareVersion GetSettingsFirmwareVersion() { /* Mount the system version title. */ R_ABORT_UNLESS(ams::fs::MountSystemData("sysver", ncm::SystemDataId::SystemVersion)); ON_SCOPE_EXIT { ams::fs::Unmount("sysver"); }; /* Read the firmware version file. */ ams::fs::FileHandle file; R_ABORT_UNLESS(ams::fs::OpenFile(std::addressof(file), "sysver:/file", fs::OpenMode_Read)); ON_SCOPE_EXIT { ams::fs::CloseFile(file); }; /* Must be possible to read firmware version from file. */ settings::FirmwareVersion firmware_version; R_ABORT_UNLESS(ams::fs::ReadFile(file, 0, std::addressof(firmware_version), sizeof(firmware_version))); return firmware_version; } #endif } void InitializeVersionInternal(bool allow_approximate); void SetNonApproximateVersionInternal() { #if defined(ATMOSPHERE_OS_HORIZON) /* Get the settings . */ const auto firmware_version = GetSettingsFirmwareVersion(); /* Set the exosphere api version. */ R_ABORT_UNLESS(spl::SetConfig(spl::ConfigItem::ExosphereApiVersion, (static_cast<u32>(firmware_version.major) << 24) | (static_cast<u32>(firmware_version.minor) << 16) | (static_cast<u32>(firmware_version.micro) << 8))); /* Update our own version value. */ InitializeVersionInternal(false); #endif } }
2,221
C++
.cpp
46
41.326087
229
0.674064
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,399
hos_version_api_weak_for_unit_test.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/hos/hos_version_api_weak_for_unit_test.cpp
/* * Copyright (c) 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::hos { WEAK_SYMBOL bool IsUnitTestProgramForSetVersion() { #if defined(ATMOSPHERE_OS_HORIZON) return false; #else return true; #endif } }
866
C++
.cpp
25
31.04
76
0.725537
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,400
hos_version_api.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/hos/hos_version_api.cpp
/* * Copyright (c) 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::hos { namespace { constinit os::SdkMutex g_hos_init_lock; constinit hos::Version g_hos_version; constinit bool g_set_hos_version; Result GetExosphereApiInfo(exosphere::ApiInfo *out) { u64 exosphere_cfg; R_TRY_CATCH(spl::impl::GetConfig(std::addressof(exosphere_cfg), spl::ConfigItem::ExosphereApiVersion)) { R_CATCH_RETHROW(spl::ResultSecureMonitorNotInitialized) } R_END_TRY_CATCH_WITH_ABORT_UNLESS; *out = { exosphere_cfg }; R_SUCCEED(); } #if defined(ATMOSPHERE_OS_HORIZON) Result GetApproximateExosphereApiInfo(exosphere::ApiInfo *out) { u64 exosphere_cfg; R_TRY_CATCH(spl::impl::GetConfig(std::addressof(exosphere_cfg), spl::ConfigItem::ExosphereApproximateApiVersion)) { R_CATCH_RETHROW(spl::ResultSecureMonitorBusy) } R_END_TRY_CATCH_WITH_ABORT_UNLESS; *out = { exosphere_cfg }; R_SUCCEED(); } #endif exosphere::ApiInfo GetExosphereApiInfo(bool allow_approximate) { exosphere::ApiInfo info; #if defined(ATMOSPHERE_OS_HORIZON) while (true) { if (R_SUCCEEDED(GetExosphereApiInfo(std::addressof(info)))) { break; } if (allow_approximate && R_SUCCEEDED(GetApproximateExosphereApiInfo(std::addressof(info)))) { break; } svc::SleepThread(TimeSpan::FromMilliSeconds(25).GetNanoSeconds()); } #else AMS_UNUSED(allow_approximate); R_ABORT_UNLESS(GetExosphereApiInfo(std::addressof(info))); #endif return info; } } bool IsUnitTestProgramForSetVersion(); void InitializeVersionInternal(bool allow_approximate) { hos::Version current = hos::Version_Current; /* If we're unit testing, just set the version and move on. */ if (IsUnitTestProgramForSetVersion()) { g_hos_version = hos::Version_Current; g_set_hos_version = true; } else { /* Get the current (and previous approximation of) target firmware. */ hos::Version prev; bool has_prev = false; { /* Acquire exclusive access to set hos version. */ std::scoped_lock lk(g_hos_init_lock); /* Save the previous value of g_hos_version. */ prev = g_hos_version; has_prev = g_set_hos_version; /* Set hos version = exosphere api version target firmware. */ g_hos_version = static_cast<hos::Version>(GetExosphereApiInfo(allow_approximate).GetTargetFirmware()); /* Save the current value of g_hos_version. */ current = g_hos_version; /* Note that we've set a previous hos version. */ g_set_hos_version = true; } /* Ensure that this is a hos version we can sanely *try* to run. */ /* To be friendly, we will only require that we recognize the major and minor versions. */ /* We can consider only recognizing major in the future, but micro seems safe to ignore as */ /* there are no breaking IPC changes in minor updates. */ { constexpr u32 MaxMajor = (static_cast<u32>(hos::Version_Max) >> 24) & 0xFF; constexpr u32 MaxMinor = (static_cast<u32>(hos::Version_Max) >> 16) & 0xFF; const u32 major = (static_cast<u32>(current) >> 24) & 0xFF; const u32 minor = (static_cast<u32>(current) >> 16) & 0xFF; const bool is_safely_tryable_version = (current <= hos::Version_Max) || (major == MaxMajor && minor <= MaxMinor); AMS_ABORT_UNLESS(is_safely_tryable_version); } /* Ensure that this is a hos version compatible with previous approximations. */ if (has_prev) { AMS_ABORT_UNLESS(current >= prev); const u32 current_major = (static_cast<u32>(current) >> 24) & 0xFF; const u32 prev_major = (static_cast<u32>(prev) >> 24) & 0xFF; AMS_ABORT_UNLESS(current_major == prev_major); } } #if defined(ATMOSPHERE_OS_HORIZON) /* Set the version for libnx. */ { const u32 major = (static_cast<u32>(current) >> 24) & 0xFF; const u32 minor = (static_cast<u32>(current) >> 16) & 0xFF; const u32 micro = (static_cast<u32>(current) >> 8) & 0xFF; hosversionSet((BIT(31)) | (MAKEHOSVERSION(major, minor, micro))); } #endif } ::ams::hos::Version GetVersion() { return g_hos_version; } }
5,574
C++
.cpp
116
36.672414
129
0.589536
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,401
hos_stratosphere_api.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/hos/hos_stratosphere_api.cpp
/* * Copyright (c) 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 "../os/impl/os_rng_manager.hpp" namespace ams::os { void Initialize(); } #if defined(ATMOSPHERE_OS_HORIZON) extern "C" { /* Provide libnx address space allocation shim. */ uintptr_t __libnx_virtmem_rng(void) { return static_cast<uintptr_t>(::ams::os::impl::GetRngManager().GenerateRandomU64()); } } #endif namespace ams::hos { namespace { bool CanAllowTemporaryApproximateVersion() { /* Check if we're a program that can use a temporary approximate version. */ const auto program_id = os::GetCurrentProgramId(); return program_id == ncm::SystemProgramId::Pm || /* Needed so that boot has permissions to use fsp-srv. */ program_id == ncm::SystemProgramId::Sm || /* Needed so that boot can acquire fsp-srv. */ program_id == ncm::SystemProgramId::Boot || /* Needed so that boot can set the true target firmware. */ program_id == ncm::SystemProgramId::Spl || /* Needed so that FS can complete initialization. */ program_id == ncm::SystemProgramId::Ncm; /* Needed so that FS can determine where SystemVersion is located. */ } } bool IsUnitTestProgramForSetVersion(); void InitializeVersionInternal(bool allow_approximate); void InitializeForStratosphere() { /* Initialize the global os resource managers. This *must* be done before anything else in stratosphere. */ os::Initialize(); /* Initialize hos::Version API. */ hos::InitializeVersionInternal(CanAllowTemporaryApproximateVersion()); #if defined(ATMOSPHERE_OS_HORIZON) /* Check that we're running under mesosphere. */ AMS_ABORT_UNLESS(IsUnitTestProgramForSetVersion() || svc::IsKernelMesosphere()); #endif } }
2,497
C++
.cpp
53
41.018868
132
0.684926
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,402
fssrv_access_control.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssrv/fssrv_access_control.cpp
/* * Copyright (c) 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 { namespace { constinit bool g_is_debug_flag_enabled = false; } bool IsDebugFlagEnabled() { return g_is_debug_flag_enabled; } void SetDebugFlagEnabled(bool en) { /* Set global debug flag. */ g_is_debug_flag_enabled = en; } namespace impl { namespace { constexpr u8 LatestFsAccessControlInfoVersion = 1; } AccessControl::AccessControl(const void *data, s64 data_size, const void *desc, s64 desc_size) : AccessControl(data, data_size, desc, desc_size, g_is_debug_flag_enabled ? AllFlagBitsMask : DebugFlagDisableMask) { /* ... */ } AccessControl::AccessControl(const void *fac_data, s64 data_size, const void *fac_desc, s64 desc_size, u64 flag_mask) { /* If either our data or descriptor is null, give no permissions. */ if (fac_data == nullptr || fac_desc == nullptr) { m_flag_bits.emplace(util::ToUnderlying(AccessControlBits::Bits::None)); return; } /* Check that data/desc are big enough. */ AMS_ABORT_UNLESS(data_size >= static_cast<s64>(sizeof(AccessControlDataHeader))); AMS_ABORT_UNLESS(desc_size >= static_cast<s64>(sizeof(AccessControlDescriptor))); /* Copy in the data/descriptor. */ AccessControlDataHeader data = {}; AccessControlDescriptor desc = {}; std::memcpy(std::addressof(data), fac_data, sizeof(data)); std::memcpy(std::addressof(desc), fac_desc, sizeof(desc)); /* If we don't know how to parse the descriptors, don't. */ if (data.version != desc.version || data.version < LatestFsAccessControlInfoVersion) { m_flag_bits.emplace(util::ToUnderlying(AccessControlBits::Bits::None)); return; } /* Restrict the descriptor's flag bits. */ desc.flag_bits &= flag_mask; /* Create our flag bits. */ m_flag_bits.emplace(data.flag_bits & desc.flag_bits); /* Further check sizes. */ AMS_ABORT_UNLESS(data_size >= data.content_owner_infos_offset + data.content_owner_infos_size); AMS_ABORT_UNLESS(desc_size >= static_cast<s64>(sizeof(AccessControlDescriptor) + desc.content_owner_id_count * sizeof(u64))); /* Read out the content data owner infos. */ uintptr_t data_start = reinterpret_cast<uintptr_t>(fac_data); uintptr_t desc_start = reinterpret_cast<uintptr_t>(fac_desc); if (data.content_owner_infos_size > 0) { /* Get the count. */ const u32 num_content_owner_infos = util::LoadLittleEndian<u32>(reinterpret_cast<u32 *>(data_start + data.content_owner_infos_offset)); /* Validate the id range. */ uintptr_t id_start = data_start + data.content_owner_infos_offset + sizeof(u32); uintptr_t id_end = id_start + sizeof(u64) * num_content_owner_infos; AMS_ABORT_UNLESS(id_end == data_start + data.content_owner_infos_offset + data.content_owner_infos_size); for (u32 i = 0; i < num_content_owner_infos; ++i) { /* Read the id. */ const u64 id = util::LoadLittleEndian<u64>(reinterpret_cast<u64 *>(id_start + i * sizeof(u64))); /* Check that the descriptor allows it. */ bool allowed = false; if (desc.content_owner_id_count != 0) { for (u8 n = 0; n < desc.content_owner_id_count; ++n) { if (id == util::LoadLittleEndian<u64>(reinterpret_cast<u64 *>(desc_start + sizeof(AccessControlDescriptor) + n * sizeof(u64)))) { allowed = true; break; } } } else if ((desc.content_owner_id_min == 0 && desc.content_owner_id_max == 0) || (desc.content_owner_id_min <= id && id <= desc.content_owner_id_max)) { allowed = true; } /* If the id is allowed, create it. */ if (allowed) { if (auto *info = new ContentOwnerInfo(id); info != nullptr) { m_content_owner_infos.push_front(*info); } } } } /* Read out the save data owner infos. */ AMS_ABORT_UNLESS(data_size >= data.save_data_owner_infos_offset + data.save_data_owner_infos_size); AMS_ABORT_UNLESS(desc_size >= static_cast<s64>(sizeof(AccessControlDescriptor) + desc.content_owner_id_count * sizeof(u64) + desc.save_data_owner_id_count * sizeof(u64))); if (data.save_data_owner_infos_size > 0) { /* Get the count. */ const u32 num_save_data_owner_infos = util::LoadLittleEndian<u32>(reinterpret_cast<u32 *>(data_start + data.save_data_owner_infos_offset)); /* Get accessibility region.*/ uintptr_t accessibility_start = data_start + data.save_data_owner_infos_offset + sizeof(u32); /* Validate the id range. */ uintptr_t id_start = accessibility_start + util::AlignUp(num_save_data_owner_infos * sizeof(Accessibility), alignof(u32)); uintptr_t id_end = id_start + sizeof(u64) * num_save_data_owner_infos; AMS_ABORT_UNLESS(id_end == data_start + data.save_data_owner_infos_offset + data.save_data_owner_infos_size); for (u32 i = 0; i < num_save_data_owner_infos; ++i) { /* Read the accessibility/id. */ static_assert(sizeof(Accessibility) == 1); const Accessibility accessibility = *reinterpret_cast<Accessibility *>(accessibility_start + i * sizeof(Accessibility)); const u64 id = util::LoadLittleEndian<u64>(reinterpret_cast<u64 *>(id_start + i * sizeof(u64))); /* Check that the descriptor allows it. */ bool allowed = false; if (desc.save_data_owner_id_count != 0) { for (u8 n = 0; n < desc.save_data_owner_id_count; ++n) { if (id == util::LoadLittleEndian<u64>(reinterpret_cast<u64 *>(desc_start + sizeof(AccessControlDescriptor) + desc.content_owner_id_count * sizeof(u64) + n * sizeof(u64)))) { allowed = true; break; } } } else if ((desc.save_data_owner_id_min == 0 && desc.save_data_owner_id_max == 0) || (desc.save_data_owner_id_min <= id && id <= desc.save_data_owner_id_max)) { allowed = true; } /* If the id is allowed, create it. */ if (allowed) { if (auto *info = new SaveDataOwnerInfo(id, accessibility); info != nullptr) { m_save_data_owner_infos.push_front(*info); } } } } } AccessControl::~AccessControl() { /* Delete all content owner infos. */ while (!m_content_owner_infos.empty()) { auto *info = std::addressof(*m_content_owner_infos.rbegin()); m_content_owner_infos.erase(m_content_owner_infos.iterator_to(*info)); delete info; } /* Delete all save data owner infos. */ while (!m_save_data_owner_infos.empty()) { auto *info = std::addressof(*m_save_data_owner_infos.rbegin()); m_save_data_owner_infos.erase(m_save_data_owner_infos.iterator_to(*info)); delete info; } } bool AccessControl::HasContentOwnerId(u64 owner_id) const { /* Check if we have a matching id. */ for (const auto &info : m_content_owner_infos) { if (info.GetId() == owner_id) { return true; } } return false; } Accessibility AccessControl::GetAccessibilitySaveDataOwnedBy(u64 owner_id) const { /* Find a matching save data owner. */ for (const auto &info : m_save_data_owner_infos) { if (info.GetId() == owner_id) { return info.GetAccessibility(); } } /* Default to no accessibility. */ return Accessibility::MakeAccessibility(false, false); } void AccessControl::ListContentOwnerId(s32 *out_count, u64 *out_owner_ids, s32 offset, s32 count) const { /* If we have nothing to read, just give the count. */ if (count == 0) { *out_count = m_content_owner_infos.size(); return; } /* Read out the ids. */ s32 read_offset = 0; s32 read_count = 0; if (out_owner_ids != nullptr) { auto *cur_out = out_owner_ids; for (const auto &info : m_content_owner_infos) { /* Skip until we get to the desired offset. */ if (read_offset < offset) { ++read_offset; continue; } /* Set the output value. */ *cur_out = info.GetId(); ++cur_out; ++read_count; /* If we've read as many as we can, finish. */ if (read_count == count) { break; } } } /* Set the out value. */ *out_count = read_count; } void AccessControl::ListSaveDataOwnedId(s32 *out_count, ncm::ApplicationId *out_owner_ids, s32 offset, s32 count) const { /* If we have nothing to read, just give the count. */ if (count == 0) { *out_count = m_save_data_owner_infos.size(); return; } /* Read out the ids. */ s32 read_offset = 0; s32 read_count = 0; if (out_owner_ids != nullptr) { auto *cur_out = out_owner_ids; for (const auto &info : m_save_data_owner_infos) { /* Skip until we get to the desired offset. */ if (read_offset < offset) { ++read_offset; continue; } /* Set the output value. */ cur_out->value = info.GetId(); ++cur_out; ++read_count; /* If we've read as many as we can, finish. */ if (read_count == count) { break; } } } /* Set the out value. */ *out_count = read_count; } Accessibility AccessControl::GetAccessibilityFor(AccessibilityType type) const { switch (type) { using enum AccessibilityType; case MountLogo: return Accessibility::MakeAccessibility(m_flag_bits->CanMountLogoRead(), false); case MountContentMeta: return Accessibility::MakeAccessibility(m_flag_bits->CanMountContentMetaRead(), false); case MountContentControl: return Accessibility::MakeAccessibility(m_flag_bits->CanMountContentControlRead(), false); case MountContentManual: return Accessibility::MakeAccessibility(m_flag_bits->CanMountContentManualRead(), false); case MountContentData: return Accessibility::MakeAccessibility(m_flag_bits->CanMountContentDataRead(), false); case MountApplicationPackage: return Accessibility::MakeAccessibility(m_flag_bits->CanMountApplicationPackageRead(), false); case MountSaveDataStorage: return Accessibility::MakeAccessibility(m_flag_bits->CanMountSaveDataStorageRead(), m_flag_bits->CanMountSaveDataStorageWrite()); case MountContentStorage: return Accessibility::MakeAccessibility(m_flag_bits->CanMountContentStorageRead(), m_flag_bits->CanMountContentStorageWrite()); case MountImageAndVideoStorage: return Accessibility::MakeAccessibility(m_flag_bits->CanMountImageAndVideoStorageRead(), m_flag_bits->CanMountImageAndVideoStorageWrite()); case MountCloudBackupWorkStorage: return Accessibility::MakeAccessibility(m_flag_bits->CanMountCloudBackupWorkStorageRead(), m_flag_bits->CanMountCloudBackupWorkStorageWrite()); case MountCustomStorage: return Accessibility::MakeAccessibility(m_flag_bits->CanMountCustomStorage0Read(), m_flag_bits->CanMountCustomStorage0Write()); case MountBisCalibrationFile: return Accessibility::MakeAccessibility(m_flag_bits->CanMountBisCalibrationFileRead(), m_flag_bits->CanMountBisCalibrationFileWrite()); case MountBisSafeMode: return Accessibility::MakeAccessibility(m_flag_bits->CanMountBisSafeModeRead(), m_flag_bits->CanMountBisSafeModeWrite()); case MountBisUser: return Accessibility::MakeAccessibility(m_flag_bits->CanMountBisUserRead(), m_flag_bits->CanMountBisUserWrite()); case MountBisSystem: return Accessibility::MakeAccessibility(m_flag_bits->CanMountBisSystemRead(), m_flag_bits->CanMountBisSystemWrite()); case MountBisSystemProperEncryption: return Accessibility::MakeAccessibility(m_flag_bits->CanMountBisSystemProperEncryptionRead(), m_flag_bits->CanMountBisSystemProperEncryptionWrite()); case MountBisSystemProperPartition: return Accessibility::MakeAccessibility(m_flag_bits->CanMountBisSystemProperPartitionRead(), m_flag_bits->CanMountBisSystemProperPartitionWrite()); case MountSdCard: return Accessibility::MakeAccessibility(m_flag_bits->CanMountSdCardRead(), m_flag_bits->CanMountSdCardWrite()); case MountGameCard: return Accessibility::MakeAccessibility(m_flag_bits->CanMountGameCardRead(), false); case MountDeviceSaveData: return Accessibility::MakeAccessibility(m_flag_bits->CanMountDeviceSaveDataRead(), m_flag_bits->CanMountDeviceSaveDataWrite()); case MountSystemSaveData: return Accessibility::MakeAccessibility(m_flag_bits->CanMountSystemSaveDataRead(), m_flag_bits->CanMountSystemSaveDataWrite()); case MountOthersSaveData: return Accessibility::MakeAccessibility(m_flag_bits->CanMountOthersSaveDataRead(), m_flag_bits->CanMountOthersSaveDataWrite()); case MountOthersSystemSaveData: return Accessibility::MakeAccessibility(m_flag_bits->CanMountOthersSystemSaveDataRead(), m_flag_bits->CanMountOthersSystemSaveDataWrite()); case OpenBisPartitionBootPartition1Root: return Accessibility::MakeAccessibility(m_flag_bits->CanOpenBisPartitionBootPartition1RootRead(), m_flag_bits->CanOpenBisPartitionBootPartition1RootWrite()); case OpenBisPartitionBootPartition2Root: return Accessibility::MakeAccessibility(m_flag_bits->CanOpenBisPartitionBootPartition2RootRead(), m_flag_bits->CanOpenBisPartitionBootPartition2RootWrite()); case OpenBisPartitionUserDataRoot: return Accessibility::MakeAccessibility(m_flag_bits->CanOpenBisPartitionUserDataRootRead(), m_flag_bits->CanOpenBisPartitionUserDataRootWrite()); case OpenBisPartitionBootConfigAndPackage2Part1: return Accessibility::MakeAccessibility(m_flag_bits->CanOpenBisPartitionBootConfigAndPackage2Part1Read(), m_flag_bits->CanOpenBisPartitionBootConfigAndPackage2Part1Write()); case OpenBisPartitionBootConfigAndPackage2Part2: return Accessibility::MakeAccessibility(m_flag_bits->CanOpenBisPartitionBootConfigAndPackage2Part2Read(), m_flag_bits->CanOpenBisPartitionBootConfigAndPackage2Part2Write()); case OpenBisPartitionBootConfigAndPackage2Part3: return Accessibility::MakeAccessibility(m_flag_bits->CanOpenBisPartitionBootConfigAndPackage2Part3Read(), m_flag_bits->CanOpenBisPartitionBootConfigAndPackage2Part3Write()); case OpenBisPartitionBootConfigAndPackage2Part4: return Accessibility::MakeAccessibility(m_flag_bits->CanOpenBisPartitionBootConfigAndPackage2Part4Read(), m_flag_bits->CanOpenBisPartitionBootConfigAndPackage2Part4Write()); case OpenBisPartitionBootConfigAndPackage2Part5: return Accessibility::MakeAccessibility(m_flag_bits->CanOpenBisPartitionBootConfigAndPackage2Part5Read(), m_flag_bits->CanOpenBisPartitionBootConfigAndPackage2Part5Write()); case OpenBisPartitionBootConfigAndPackage2Part6: return Accessibility::MakeAccessibility(m_flag_bits->CanOpenBisPartitionBootConfigAndPackage2Part6Read(), m_flag_bits->CanOpenBisPartitionBootConfigAndPackage2Part6Write()); case OpenBisPartitionCalibrationBinary: return Accessibility::MakeAccessibility(m_flag_bits->CanOpenBisPartitionCalibrationBinaryRead(), m_flag_bits->CanOpenBisPartitionCalibrationBinaryWrite()); case OpenBisPartitionCalibrationFile: return Accessibility::MakeAccessibility(m_flag_bits->CanOpenBisPartitionCalibrationFileRead(), m_flag_bits->CanOpenBisPartitionCalibrationFileWrite()); case OpenBisPartitionSafeMode: return Accessibility::MakeAccessibility(m_flag_bits->CanOpenBisPartitionSafeModeRead(), m_flag_bits->CanOpenBisPartitionSafeModeWrite()); case OpenBisPartitionUser: return Accessibility::MakeAccessibility(m_flag_bits->CanOpenBisPartitionUserRead(), m_flag_bits->CanOpenBisPartitionUserWrite()); case OpenBisPartitionSystem: return Accessibility::MakeAccessibility(m_flag_bits->CanOpenBisPartitionSystemRead(), m_flag_bits->CanOpenBisPartitionSystemWrite()); case OpenBisPartitionSystemProperEncryption: return Accessibility::MakeAccessibility(m_flag_bits->CanOpenBisPartitionSystemProperEncryptionRead(), m_flag_bits->CanOpenBisPartitionSystemProperEncryptionWrite()); case OpenBisPartitionSystemProperPartition: return Accessibility::MakeAccessibility(m_flag_bits->CanOpenBisPartitionSystemProperPartitionRead(), m_flag_bits->CanOpenBisPartitionSystemProperPartitionWrite()); case OpenSdCardStorage: return Accessibility::MakeAccessibility(m_flag_bits->CanOpenSdCardStorageRead(), m_flag_bits->CanOpenSdCardStorageWrite()); case OpenGameCardStorage: return Accessibility::MakeAccessibility(m_flag_bits->CanOpenGameCardStorageRead(), m_flag_bits->CanOpenGameCardStorageWrite()); case MountSystemDataPrivate: return Accessibility::MakeAccessibility(m_flag_bits->CanMountSystemDataPrivateRead(), false); case MountHost: return Accessibility::MakeAccessibility(m_flag_bits->CanMountHostRead(), m_flag_bits->CanMountHostWrite()); case MountRegisteredUpdatePartition: return Accessibility::MakeAccessibility(m_flag_bits->CanMountRegisteredUpdatePartitionRead() && g_is_debug_flag_enabled, false); case MountSaveDataInternalStorage: return Accessibility::MakeAccessibility(m_flag_bits->CanOpenSaveDataInternalStorageRead(), m_flag_bits->CanOpenSaveDataInternalStorageWrite()); case MountTemporaryDirectory: return Accessibility::MakeAccessibility(m_flag_bits->CanMountTemporaryDirectoryRead(), m_flag_bits->CanMountTemporaryDirectoryWrite()); case MountAllBaseFileSystem: return Accessibility::MakeAccessibility(m_flag_bits->CanMountAllBaseFileSystemRead(), m_flag_bits->CanMountAllBaseFileSystemWrite()); case NotMount: return Accessibility::MakeAccessibility(false, false); AMS_UNREACHABLE_DEFAULT_CASE(); } } bool AccessControl::CanCall(OperationType type) const { switch (type) { using enum OperationType; case InvalidateBisCache: return m_flag_bits->CanInvalidateBisCache(); case EraseMmc: return m_flag_bits->CanEraseMmc(); case GetGameCardDeviceCertificate: return m_flag_bits->CanGetGameCardDeviceCertificate(); case GetGameCardIdSet: return m_flag_bits->CanGetGameCardIdSet(); case FinalizeGameCardDriver: return m_flag_bits->CanFinalizeGameCardDriver(); case GetGameCardAsicInfo: return m_flag_bits->CanGetGameCardAsicInfo(); case CreateSaveData: return m_flag_bits->CanCreateSaveData(); case DeleteSaveData: return m_flag_bits->CanDeleteSaveData(); case CreateSystemSaveData: return m_flag_bits->CanCreateSystemSaveData(); case CreateOthersSystemSaveData: return m_flag_bits->CanCreateOthersSystemSaveData(); case DeleteSystemSaveData: return m_flag_bits->CanDeleteSystemSaveData(); case OpenSaveDataInfoReader: return m_flag_bits->CanOpenSaveDataInfoReader(); case OpenSaveDataInfoReaderForSystem: return m_flag_bits->CanOpenSaveDataInfoReaderForSystem(); case OpenSaveDataInfoReaderForInternal: return m_flag_bits->CanOpenSaveDataInfoReaderForInternal(); case OpenSaveDataMetaFile: return m_flag_bits->CanOpenSaveDataMetaFile(); case SetCurrentPosixTime: return m_flag_bits->CanSetCurrentPosixTime(); case ReadSaveDataFileSystemExtraData: return m_flag_bits->CanReadSaveDataFileSystemExtraData(); case SetGlobalAccessLogMode: return m_flag_bits->CanSetGlobalAccessLogMode(); case SetSpeedEmulationMode: return m_flag_bits->CanSetSpeedEmulationMode(); case FillBis: return m_flag_bits->CanFillBis(); case CorruptSaveData: return m_flag_bits->CanCorruptSaveData(); case CorruptSystemSaveData: return m_flag_bits->CanCorruptSystemSaveData(); case VerifySaveData: return m_flag_bits->CanVerifySaveData(); case DebugSaveData: return m_flag_bits->CanDebugSaveData(); case FormatSdCard: return m_flag_bits->CanFormatSdCard(); case GetRightsId: return m_flag_bits->CanGetRightsId(); case RegisterExternalKey: return m_flag_bits->CanRegisterExternalKey(); case SetEncryptionSeed: return m_flag_bits->CanSetEncryptionSeed(); case WriteSaveDataFileSystemExtraDataTimeStamp: return m_flag_bits->CanWriteSaveDataFileSystemExtraDataTimeStamp(); case WriteSaveDataFileSystemExtraDataFlags: return m_flag_bits->CanWriteSaveDataFileSystemExtraDataFlags(); case WriteSaveDataFileSystemExtraDataCommitId: return m_flag_bits->CanWriteSaveDataFileSystemExtraDataCommitId(); case WriteSaveDataFileSystemExtraDataAll: return m_flag_bits->CanWriteSaveDataFileSystemExtraDataAll(); case ExtendSaveData: return m_flag_bits->CanExtendSaveData(); case ExtendSystemSaveData: return m_flag_bits->CanExtendSystemSaveData(); case ExtendOthersSystemSaveData: return m_flag_bits->CanExtendOthersSystemSaveData(); case RegisterUpdatePartition: return m_flag_bits->CanRegisterUpdatePartition() && g_is_debug_flag_enabled; case OpenSaveDataTransferManager: return m_flag_bits->CanOpenSaveDataTransferManager(); case OpenSaveDataTransferManagerVersion2: return m_flag_bits->CanOpenSaveDataTransferManagerVersion2(); case OpenSaveDataTransferManagerForSaveDataRepair: return m_flag_bits->CanOpenSaveDataTransferManagerForSaveDataRepair(); case OpenSaveDataTransferManagerForSaveDataRepairTool: return m_flag_bits->CanOpenSaveDataTransferManagerForSaveDataRepairTool(); case OpenSaveDataTransferProhibiter: return m_flag_bits->CanOpenSaveDataTransferProhibiter(); case OpenSaveDataMover: return m_flag_bits->CanOpenSaveDataMover(); case OpenBisWiper: return m_flag_bits->CanOpenBisWiper(); case ListAccessibleSaveDataOwnerId: return m_flag_bits->CanListAccessibleSaveDataOwnerId(); case ControlMmcPatrol: return m_flag_bits->CanControlMmcPatrol(); case OverrideSaveDataTransferTokenSignVerificationKey: return m_flag_bits->CanOverrideSaveDataTransferTokenSignVerificationKey(); case OpenSdCardDetectionEventNotifier: return m_flag_bits->CanOpenSdCardDetectionEventNotifier(); case OpenGameCardDetectionEventNotifier: return m_flag_bits->CanOpenGameCardDetectionEventNotifier(); case OpenSystemDataUpdateEventNotifier: return m_flag_bits->CanOpenSystemDataUpdateEventNotifier(); case NotifySystemDataUpdateEvent: return m_flag_bits->CanNotifySystemDataUpdateEvent(); case OpenAccessFailureDetectionEventNotifier: return m_flag_bits->CanOpenAccessFailureDetectionEventNotifier(); case GetAccessFailureDetectionEvent: return m_flag_bits->CanGetAccessFailureDetectionEvent(); case IsAccessFailureDetected: return m_flag_bits->CanIsAccessFailureDetected(); case ResolveAccessFailure: return m_flag_bits->CanResolveAccessFailure(); case AbandonAccessFailure: return m_flag_bits->CanAbandonAccessFailure(); case QuerySaveDataInternalStorageTotalSize: return m_flag_bits->CanQuerySaveDataInternalStorageTotalSize(); case GetSaveDataCommitId: return m_flag_bits->CanGetSaveDataCommitId(); case SetSdCardAccessibility: return m_flag_bits->CanSetSdCardAccessibility(); case SimulateDevice: return m_flag_bits->CanSimulateDevice(); case CreateSaveDataWithHashSalt: return m_flag_bits->CanCreateSaveDataWithHashSalt(); case RegisterProgramIndexMapInfo: return m_flag_bits->CanRegisterProgramIndexMapInfo(); case ChallengeCardExistence: return m_flag_bits->CanChallengeCardExistence(); case CreateOwnSaveData: return m_flag_bits->CanCreateOwnSaveData(); case DeleteOwnSaveData: return m_flag_bits->CanDeleteOwnSaveData(); case ReadOwnSaveDataFileSystemExtraData: return m_flag_bits->CanReadOwnSaveDataFileSystemExtraData(); case ExtendOwnSaveData: return m_flag_bits->CanExtendOwnSaveData(); case OpenOwnSaveDataTransferProhibiter: return m_flag_bits->CanOpenOwnSaveDataTransferProhibiter(); case FindOwnSaveDataWithFilter: return m_flag_bits->CanFindOwnSaveDataWithFilter(); case OpenSaveDataTransferManagerForRepair: return m_flag_bits->CanOpenSaveDataTransferManagerForRepair(); case SetDebugConfiguration: return m_flag_bits->CanSetDebugConfiguration(); case OpenDataStorageByPath: return m_flag_bits->CanOpenDataStorageByPath(); AMS_UNREACHABLE_DEFAULT_CASE(); } } } }
30,527
C++
.cpp
357
69.518207
238
0.6
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,403
fssrv_file_system_proxy_api.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssrv/fssrv_file_system_proxy_api.cpp
/* * Copyright (c) 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/fs/impl/fs_service_name.hpp> #include "fssrv_deferred_process_manager.hpp" namespace ams::fssrv { namespace { struct FileSystemProxyServerOptions { static constexpr size_t PointerBufferSize = 0x800; static constexpr size_t MaxDomains = 0x40; static constexpr size_t MaxDomainObjects = 0x4000; static constexpr bool CanDeferInvokeRequest = true; static constexpr bool CanManageMitmServers = false; }; enum PortIndex { PortIndex_FileSystemProxy, PortIndex_ProgramRegistry, PortIndex_FileSystemProxyForLoader, PortIndex_Count, }; constexpr size_t FileSystemProxyMaxSessions = 59; constexpr size_t ProgramRegistryMaxSessions = 1; constexpr size_t FileSystemProxyForLoaderMaxSessions = 1; constexpr size_t NumSessions = FileSystemProxyMaxSessions + ProgramRegistryMaxSessions + FileSystemProxyForLoaderMaxSessions; constinit os::SemaphoreType g_semaphore_for_file_system_proxy_for_loader = {}; constinit os::SemaphoreType g_semaphore_for_program_registry = {}; class FileSystemProxyServerManager final : public ams::sf::hipc::ServerManager<PortIndex_Count, FileSystemProxyServerOptions, NumSessions> { private: virtual ams::Result OnNeedsToAccept(int port_index, Server *server) override { switch (port_index) { case PortIndex_FileSystemProxy: { R_RETURN(this->AcceptImpl(server, impl::GetFileSystemProxyServiceObject())); } case PortIndex_ProgramRegistry: { if (os::TryAcquireSemaphore(std::addressof(g_semaphore_for_program_registry))) { ON_RESULT_FAILURE { os::ReleaseSemaphore(std::addressof(g_semaphore_for_program_registry)); }; R_RETURN(this->AcceptImpl(server, impl::GetProgramRegistryServiceObject())); } else { R_RETURN(this->AcceptImpl(server, impl::GetInvalidProgramRegistryServiceObject())); } } case PortIndex_FileSystemProxyForLoader: { if (os::TryAcquireSemaphore(std::addressof(g_semaphore_for_file_system_proxy_for_loader))) { ON_RESULT_FAILURE { os::ReleaseSemaphore(std::addressof(g_semaphore_for_file_system_proxy_for_loader)); }; R_RETURN(this->AcceptImpl(server, impl::GetFileSystemProxyForLoaderServiceObject())); } else { R_RETURN(this->AcceptImpl(server, impl::GetInvalidFileSystemProxyForLoaderServiceObject())); } } AMS_UNREACHABLE_DEFAULT_CASE(); } } }; constinit util::TypedStorage<FileSystemProxyServerManager> g_server_manager_storage = {}; constinit FileSystemProxyServerManager *g_server_manager = nullptr; constinit os::BarrierType g_server_loop_barrier = {}; constinit os::EventType g_resume_wait_event = {}; constinit bool g_is_suspended = false; void TemporaryNotifyProcessDeferred(u64) { /* TODO */ } constinit DeferredProcessManager<FileSystemProxyServerManager, TemporaryNotifyProcessDeferred> g_deferred_process_manager; } void InitializeForFileSystemProxy(const FileSystemProxyConfiguration &config) { /* TODO FS-REIMPL */ AMS_UNUSED(config); } void InitializeFileSystemProxyServer(int threads) { /* Initialize synchronization primitives. */ os::InitializeBarrier(std::addressof(g_server_loop_barrier), threads + 1); os::InitializeEvent(std::addressof(g_resume_wait_event), false, os::EventClearMode_ManualClear); g_is_suspended = false; os::InitializeSemaphore(std::addressof(g_semaphore_for_file_system_proxy_for_loader), 1, 1); os::InitializeSemaphore(std::addressof(g_semaphore_for_program_registry), 1, 1); /* Initialize deferred process manager. */ g_deferred_process_manager.Initialize(); /* Create the server and register our services. */ AMS_ASSERT(g_server_manager == nullptr); g_server_manager = util::ConstructAt(g_server_manager_storage); /* TODO: Manager handler. */ R_ABORT_UNLESS(g_server_manager->RegisterServer(PortIndex_FileSystemProxy, fs::impl::FileSystemProxyServiceName, FileSystemProxyMaxSessions)); R_ABORT_UNLESS(g_server_manager->RegisterServer(PortIndex_ProgramRegistry, fs::impl::ProgramRegistryServiceName, ProgramRegistryMaxSessions)); R_ABORT_UNLESS(g_server_manager->RegisterServer(PortIndex_FileSystemProxyForLoader, fs::impl::FileSystemProxyForLoaderServiceName, FileSystemProxyForLoaderMaxSessions)); /* Enable processing on server. */ g_server_manager->ResumeProcessing(); } }
5,943
C++
.cpp
101
46.09901
177
0.64713
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,404
fssrv_filesystem_interface_adapter.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssrv/fssrv_filesystem_interface_adapter.cpp
/* * Copyright (c) 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> #include "impl/fssrv_allocator_for_service_framework.hpp" #include "fssrv_retry_utility.hpp" namespace ams::fssrv::impl { namespace { constexpr const char *RootDirectory = "/"; } FileInterfaceAdapter::FileInterfaceAdapter(std::unique_ptr<fs::fsa::IFile> &&file, FileSystemInterfaceAdapter *parent, bool allow_all) : m_parent_filesystem(parent, true), m_base_file(std::move(file)), m_allow_all_operations(allow_all) { /* ... */ } Result FileInterfaceAdapter::Read(ams::sf::Out<s64> out, s64 offset, const ams::sf::OutNonSecureBuffer &buffer, s64 size, fs::ReadOption option) { /* Check pre-conditions. */ R_UNLESS(0 <= offset, fs::ResultInvalidOffset()); R_UNLESS(0 <= size, fs::ResultInvalidSize()); R_UNLESS(size <= static_cast<s64>(buffer.GetSize()), fs::ResultInvalidSize()); /* Read the data, retrying on corruption. */ size_t read_size = 0; R_TRY(RetryFinitelyForDataCorrupted([&] () ALWAYS_INLINE_LAMBDA { R_RETURN(m_base_file->Read(std::addressof(read_size), offset, buffer.GetPointer(), static_cast<size_t>(size), option)); })); /* Set the output size. */ *out = read_size; R_SUCCEED(); } Result FileInterfaceAdapter::Write(s64 offset, const ams::sf::InNonSecureBuffer &buffer, s64 size, fs::WriteOption option) { /* Check pre-conditions. */ R_UNLESS(0 <= offset, fs::ResultInvalidOffset()); R_UNLESS(0 <= size, fs::ResultInvalidSize()); R_UNLESS(size <= static_cast<s64>(buffer.GetSize()), fs::ResultInvalidSize()); /* Temporarily increase our thread's priority. */ fssystem::ScopedThreadPriorityChangerByAccessPriority cp(fssystem::ScopedThreadPriorityChangerByAccessPriority::AccessMode::Write); R_RETURN(m_base_file->Write(offset, buffer.GetPointer(), size, option)); } Result FileInterfaceAdapter::Flush() { R_RETURN(m_base_file->Flush()); } Result FileInterfaceAdapter::SetSize(s64 size) { R_UNLESS(size >= 0, fs::ResultInvalidSize()); R_RETURN(m_base_file->SetSize(size)); } Result FileInterfaceAdapter::GetSize(ams::sf::Out<s64> out) { /* Get the size, retrying on corruption. */ R_RETURN(RetryFinitelyForDataCorrupted([&] () ALWAYS_INLINE_LAMBDA { R_RETURN(m_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()); /* Clear the range info. */ out->Clear(); if (op_id == static_cast<s32>(fs::OperationId::QueryRange)) { fs::FileQueryRangeInfo info; R_TRY(m_base_file->OperateRange(std::addressof(info), sizeof(info), fs::OperationId::QueryRange, offset, size, nullptr, 0)); out->Merge(info); } else if (op_id == static_cast<s32>(fs::OperationId::Invalidate)) { R_TRY(m_base_file->OperateRange(nullptr, 0, fs::OperationId::Invalidate, offset, size, nullptr, 0)); } R_SUCCEED(); } Result FileInterfaceAdapter::OperateRangeWithBuffer(const ams::sf::OutNonSecureBuffer &out_buf, const ams::sf::InNonSecureBuffer &in_buf, s32 op_id, s64 offset, s64 size) { /* Check that we have permission to perform the operation. */ switch (static_cast<fs::OperationId>(op_id)) { using enum fs::OperationId; case QueryUnpreparedRange: case QueryLazyLoadCompletionRate: case SetLazyLoadPriority: /* Lazy load/unprepared operations are always allowed to be performed with buffer. */ break; default: R_UNLESS(m_allow_all_operations, fs::ResultPermissionDenied()); } /* Perform the operation. */ R_RETURN(m_base_file->OperateRange(out_buf.GetPointer(), out_buf.GetSize(), static_cast<fs::OperationId>(op_id), offset, size, in_buf.GetPointer(), in_buf.GetSize())); } DirectoryInterfaceAdapter::DirectoryInterfaceAdapter(std::unique_ptr<fs::fsa::IDirectory> &&dir, FileSystemInterfaceAdapter *parent, bool allow_all) : m_parent_filesystem(parent, true), m_base_dir(std::move(dir)), m_allow_all_operations(allow_all) { /* ... */ } Result DirectoryInterfaceAdapter::Read(ams::sf::Out<s64> out, const ams::sf::OutBuffer &out_entries) { /* Get the maximum number of entries we can read into the buffer. */ const s64 max_num_entries = out_entries.GetSize() / sizeof(fs::DirectoryEntry); R_UNLESS(max_num_entries >= 0, fs::ResultInvalidSize()); /* Get the size, retrying on corruption. */ s64 num_read = 0; R_TRY(RetryFinitelyForDataCorrupted([&] () ALWAYS_INLINE_LAMBDA { R_RETURN(m_base_dir->Read(std::addressof(num_read), reinterpret_cast<fs::DirectoryEntry *>(out_entries.GetPointer()), max_num_entries)); })); /* Set the output. */ *out = num_read; R_SUCCEED(); } Result DirectoryInterfaceAdapter::GetEntryCount(ams::sf::Out<s64> out) { R_RETURN(m_base_dir->GetEntryCount(out.GetPointer())); } Result FileSystemInterfaceAdapter::SetUpPath(fs::Path *out, const fssrv::sf::Path &sf_path) { /* Initialize the fs path. */ if (m_path_flags.IsWindowsPathAllowed()) { R_TRY(out->InitializeWithReplaceUnc(sf_path.str)); } else { R_TRY(out->Initialize(sf_path.str)); } /* Ensure the path is normalized. */ R_RETURN(out->Normalize(m_path_flags)); } Result FileSystemInterfaceAdapter::CreateFile(const fssrv::sf::Path &path, s64 size, s32 option) { /* Check pre-conditions. */ R_UNLESS(size >= 0, fs::ResultInvalidSize()); /* Normalize the input path. */ fs::Path fs_path; R_TRY(this->SetUpPath(std::addressof(fs_path), path)); R_RETURN(m_base_fs->CreateFile(fs_path, size, option)); } Result FileSystemInterfaceAdapter::DeleteFile(const fssrv::sf::Path &path) { /* Normalize the input path. */ fs::Path fs_path; R_TRY(this->SetUpPath(std::addressof(fs_path), path)); R_RETURN(m_base_fs->DeleteFile(fs_path)); } Result FileSystemInterfaceAdapter::CreateDirectory(const fssrv::sf::Path &path) { /* Normalize the input path. */ fs::Path fs_path; R_TRY(this->SetUpPath(std::addressof(fs_path), path)); /* Sanity check that the directory isn't the root. */ R_UNLESS(fs_path != RootDirectory, fs::ResultPathAlreadyExists()); R_RETURN(m_base_fs->CreateDirectory(fs_path)); } Result FileSystemInterfaceAdapter::DeleteDirectory(const fssrv::sf::Path &path) { /* Normalize the input path. */ fs::Path fs_path; R_TRY(this->SetUpPath(std::addressof(fs_path), path)); /* Sanity check that the directory isn't the root. */ R_UNLESS(fs_path != RootDirectory, fs::ResultDirectoryNotDeletable()); R_RETURN(m_base_fs->DeleteDirectory(fs_path)); } Result FileSystemInterfaceAdapter::DeleteDirectoryRecursively(const fssrv::sf::Path &path) { /* Normalize the input path. */ fs::Path fs_path; R_TRY(this->SetUpPath(std::addressof(fs_path), path)); /* Sanity check that the directory isn't the root. */ R_UNLESS(fs_path != RootDirectory, fs::ResultDirectoryNotDeletable()); R_RETURN(m_base_fs->DeleteDirectoryRecursively(fs_path)); } Result FileSystemInterfaceAdapter::RenameFile(const fssrv::sf::Path &old_path, const fssrv::sf::Path &new_path) { /* Normalize the input paths. */ fs::Path fs_old_path; fs::Path fs_new_path; R_TRY(this->SetUpPath(std::addressof(fs_old_path), old_path)); R_TRY(this->SetUpPath(std::addressof(fs_new_path), new_path)); R_RETURN(m_base_fs->RenameFile(fs_old_path, fs_new_path)); } Result FileSystemInterfaceAdapter::RenameDirectory(const fssrv::sf::Path &old_path, const fssrv::sf::Path &new_path) { /* Normalize the input paths. */ fs::Path fs_old_path; fs::Path fs_new_path; R_TRY(this->SetUpPath(std::addressof(fs_old_path), old_path)); R_TRY(this->SetUpPath(std::addressof(fs_new_path), new_path)); R_UNLESS(!fs::IsSubPath(fs_old_path.GetString(), fs_new_path.GetString()), fs::ResultDirectoryNotRenamable()); R_RETURN(m_base_fs->RenameDirectory(fs_old_path, fs_new_path)); } Result FileSystemInterfaceAdapter::GetEntryType(ams::sf::Out<u32> out, const fssrv::sf::Path &path) { /* Normalize the input path. */ fs::Path fs_path; R_TRY(this->SetUpPath(std::addressof(fs_path), path)); static_assert(sizeof(*out.GetPointer()) == sizeof(fs::DirectoryEntryType)); R_RETURN(m_base_fs->GetEntryType(reinterpret_cast<fs::DirectoryEntryType *>(out.GetPointer()), fs_path)); } Result FileSystemInterfaceAdapter::OpenFile(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFile>> out, const fssrv::sf::Path &path, u32 mode) { /* Normalize the input path. */ fs::Path fs_path; R_TRY(this->SetUpPath(std::addressof(fs_path), path)); /* Open the file, retrying on corruption. */ std::unique_ptr<fs::fsa::IFile> file; R_TRY(RetryFinitelyForDataCorrupted([&] () ALWAYS_INLINE_LAMBDA { R_RETURN(m_base_fs->OpenFile(std::addressof(file), fs_path, static_cast<fs::OpenMode>(mode))); })); /* If we're a mitm interface, we should preserve the resulting target object id. */ if (m_is_mitm_interface) { /* TODO: This is a hack to get the mitm API to work. Better solution? */ const auto target_object_id = file->GetDomainObjectId(); ams::sf::SharedPointer<fssrv::sf::IFile> file_intf = FileSystemObjectFactory::CreateSharedEmplaced<fssrv::sf::IFile, FileInterfaceAdapter>(std::move(file), this, m_allow_all_operations); R_UNLESS(file_intf != nullptr, fs::ResultAllocationMemoryFailedInFileSystemInterfaceAdapterA()); out.SetValue(std::move(file_intf), target_object_id); } else { ams::sf::SharedPointer<fssrv::sf::IFile> file_intf = FileSystemObjectFactory::CreateSharedEmplaced<fssrv::sf::IFile, FileInterfaceAdapter>(std::move(file), this, m_allow_all_operations); R_UNLESS(file_intf != nullptr, fs::ResultAllocationMemoryFailedInFileSystemInterfaceAdapterA()); out.SetValue(std::move(file_intf)); } R_SUCCEED(); } Result FileSystemInterfaceAdapter::OpenDirectory(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IDirectory>> out, const fssrv::sf::Path &path, u32 mode) { /* Normalize the input path. */ fs::Path fs_path; R_TRY(this->SetUpPath(std::addressof(fs_path), path)); /* Open the directory, retrying on corruption. */ std::unique_ptr<fs::fsa::IDirectory> dir; R_TRY(RetryFinitelyForDataCorrupted([&] () ALWAYS_INLINE_LAMBDA { R_RETURN(m_base_fs->OpenDirectory(std::addressof(dir), fs_path, static_cast<fs::OpenDirectoryMode>(mode))); })); /* If we're a mitm interface, we should preserve the resulting target object id. */ if (m_is_mitm_interface) { /* TODO: This is a hack to get the mitm API to work. Better solution? */ const auto target_object_id = dir->GetDomainObjectId(); ams::sf::SharedPointer<fssrv::sf::IDirectory> dir_intf = FileSystemObjectFactory::CreateSharedEmplaced<fssrv::sf::IDirectory, DirectoryInterfaceAdapter>(std::move(dir), this, m_allow_all_operations); R_UNLESS(dir_intf != nullptr, fs::ResultAllocationMemoryFailedInFileSystemInterfaceAdapterA()); out.SetValue(std::move(dir_intf), target_object_id); } else { ams::sf::SharedPointer<fssrv::sf::IDirectory> dir_intf = FileSystemObjectFactory::CreateSharedEmplaced<fssrv::sf::IDirectory, DirectoryInterfaceAdapter>(std::move(dir), this, m_allow_all_operations); R_UNLESS(dir_intf != nullptr, fs::ResultAllocationMemoryFailedInFileSystemInterfaceAdapterA()); out.SetValue(std::move(dir_intf)); } R_SUCCEED(); } Result FileSystemInterfaceAdapter::Commit() { R_RETURN(m_base_fs->Commit()); } Result FileSystemInterfaceAdapter::GetFreeSpaceSize(ams::sf::Out<s64> out, const fssrv::sf::Path &path) { /* Normalize the input path. */ fs::Path fs_path; R_TRY(this->SetUpPath(std::addressof(fs_path), path)); R_RETURN(m_base_fs->GetFreeSpaceSize(out.GetPointer(), fs_path)); } Result FileSystemInterfaceAdapter::GetTotalSpaceSize(ams::sf::Out<s64> out, const fssrv::sf::Path &path) { /* Normalize the input path. */ fs::Path fs_path; R_TRY(this->SetUpPath(std::addressof(fs_path), path)); R_RETURN(m_base_fs->GetTotalSpaceSize(out.GetPointer(), fs_path)); } Result FileSystemInterfaceAdapter::CleanDirectoryRecursively(const fssrv::sf::Path &path) { /* Normalize the input path. */ fs::Path fs_path; R_TRY(this->SetUpPath(std::addressof(fs_path), path)); R_RETURN(m_base_fs->CleanDirectoryRecursively(fs_path)); } Result FileSystemInterfaceAdapter::GetFileTimeStampRaw(ams::sf::Out<fs::FileTimeStampRaw> out, const fssrv::sf::Path &path) { /* Normalize the input path. */ fs::Path fs_path; R_TRY(this->SetUpPath(std::addressof(fs_path), path)); R_RETURN(m_base_fs->GetFileTimeStampRaw(out.GetPointer(), fs_path)); } Result FileSystemInterfaceAdapter::QueryEntry(const ams::sf::OutNonSecureBuffer &out_buf, const ams::sf::InNonSecureBuffer &in_buf, s32 query_id, const fssrv::sf::Path &path) { /* Check that we have permission to perform the operation. */ switch (static_cast<fs::fsa::QueryId>(query_id)) { using enum fs::fsa::QueryId; case SetConcatenationFileAttribute: case IsSignedSystemPartitionOnSdCardValid: case QueryUnpreparedFileInformation: /* Only certain operations are unconditionally allowable. */ break; default: R_UNLESS(m_allow_all_operations, fs::ResultPermissionDenied()); } /* Normalize the input path. */ fs::Path fs_path; R_TRY(this->SetUpPath(std::addressof(fs_path), path)); char *dst = reinterpret_cast<char *>(out_buf.GetPointer()); const char *src = reinterpret_cast<const char *>(in_buf.GetPointer()); R_RETURN(m_base_fs->QueryEntry(dst, out_buf.GetSize(), src, in_buf.GetSize(), static_cast<fs::fsa::QueryId>(query_id), fs_path)); } #if defined(ATMOSPHERE_OS_HORIZON) Result RemoteFileSystem::OpenFile(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFile>> out, const fssrv::sf::Path &path, u32 mode) { FsFile f; R_TRY(fsFsOpenFile(std::addressof(m_base_fs), path.str, mode, std::addressof(f))); auto intf = FileSystemObjectFactory::CreateSharedEmplaced<fssrv::sf::IFile, RemoteFile>(f); R_UNLESS(intf != nullptr, fs::ResultAllocationMemoryFailedInFileSystemInterfaceAdapterA()); out.SetValue(std::move(intf)); R_SUCCEED(); } Result RemoteFileSystem::OpenDirectory(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IDirectory>> out, const fssrv::sf::Path &path, u32 mode) { FsDir d; R_TRY(fsFsOpenDirectory(std::addressof(m_base_fs), path.str, mode, std::addressof(d))); auto intf = FileSystemObjectFactory::CreateSharedEmplaced<fssrv::sf::IDirectory, RemoteDirectory>(d); R_UNLESS(intf != nullptr, fs::ResultAllocationMemoryFailedInFileSystemInterfaceAdapterA()); out.SetValue(std::move(intf)); R_SUCCEED(); } #endif }
16,998
C++
.cpp
297
48.703704
211
0.652627
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,405
fssrv_program_registry_service.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssrv/fssrv_program_registry_service.cpp
/* * Copyright (c) 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 "impl/fssrv_program_info.hpp" #include "impl/fssrv_program_registry_manager.hpp" namespace ams::fssrv { Result ProgramRegistryServiceImpl::RegisterProgramInfo(u64 process_id, u64 program_id, u8 storage_id, const void *data, s64 data_size, const void *desc, s64 desc_size) { R_RETURN(m_registry_manager->RegisterProgram(process_id, program_id, storage_id, data, data_size, desc, desc_size)); } Result ProgramRegistryServiceImpl::UnregisterProgramInfo(u64 process_id) { R_RETURN(m_registry_manager->UnregisterProgram(process_id)); } Result ProgramRegistryServiceImpl::ResetProgramIndexMapInfo(const fs::ProgramIndexMapInfo *infos, int count) { R_RETURN(m_index_map_info_manager->Reset(infos, count)); } Result ProgramRegistryServiceImpl::GetProgramInfo(std::shared_ptr<impl::ProgramInfo> *out, u64 process_id) { R_RETURN(m_registry_manager->GetProgramInfo(out, process_id)); } Result ProgramRegistryServiceImpl::GetProgramInfoByProgramId(std::shared_ptr<impl::ProgramInfo> *out, u64 program_id) { R_RETURN(m_registry_manager->GetProgramInfoByProgramId(out, program_id)); } size_t ProgramRegistryServiceImpl::GetProgramIndexMapInfoCount() { return m_index_map_info_manager->GetProgramCount(); } util::optional<fs::ProgramIndexMapInfo> ProgramRegistryServiceImpl::GetProgramIndexMapInfo(const ncm::ProgramId &program_id) { return m_index_map_info_manager->Get(program_id); } ncm::ProgramId ProgramRegistryServiceImpl::GetProgramIdByIndex(const ncm::ProgramId &program_id, u8 index) { return m_index_map_info_manager->GetProgramId(program_id, index); } }
2,360
C++
.cpp
44
49.181818
173
0.752385
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,406
fssrv_storage_interface_adapter.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssrv/fssrv_storage_interface_adapter.cpp
/* * Copyright (c) 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> #include "fssrv_retry_utility.hpp" namespace ams::fssrv::impl { Result StorageInterfaceAdapter::Read(s64 offset, const ams::sf::OutNonSecureBuffer &buffer, s64 size) { /* Check pre-conditions. */ R_UNLESS(0 <= offset, fs::ResultInvalidOffset()); R_UNLESS(0 <= size, fs::ResultInvalidSize()); R_UNLESS(size <= static_cast<s64>(buffer.GetSize()), fs::ResultInvalidSize()); R_RETURN(RetryFinitelyForDataCorrupted([&] () ALWAYS_INLINE_LAMBDA { R_RETURN(m_base_storage->Read(offset, buffer.GetPointer(), size)); })); } Result StorageInterfaceAdapter::Write(s64 offset, const ams::sf::InNonSecureBuffer &buffer, s64 size) { /* Check pre-conditions. */ R_UNLESS(0 <= offset, fs::ResultInvalidOffset()); R_UNLESS(0 <= size, fs::ResultInvalidSize()); R_UNLESS(size <= static_cast<s64>(buffer.GetSize()), fs::ResultInvalidSize()); /* Temporarily increase our thread's priority. */ fssystem::ScopedThreadPriorityChangerByAccessPriority cp(fssystem::ScopedThreadPriorityChangerByAccessPriority::AccessMode::Write); R_RETURN(m_base_storage->Write(offset, buffer.GetPointer(), size)); } Result StorageInterfaceAdapter::Flush() { R_RETURN(m_base_storage->Flush()); } Result StorageInterfaceAdapter::SetSize(s64 size) { R_UNLESS(size >= 0, fs::ResultInvalidSize()); R_RETURN(m_base_storage->SetSize(size)); } Result StorageInterfaceAdapter::GetSize(ams::sf::Out<s64> out) { R_RETURN(m_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()); /* Clear the range info. */ out->Clear(); if (op_id == static_cast<s32>(fs::OperationId::QueryRange)) { fs::FileQueryRangeInfo info; R_TRY(m_base_storage->OperateRange(std::addressof(info), sizeof(info), fs::OperationId::QueryRange, offset, size, nullptr, 0)); out->Merge(info); } else if (op_id == static_cast<s32>(fs::OperationId::Invalidate)) { R_TRY(m_base_storage->OperateRange(nullptr, 0, fs::OperationId::Invalidate, offset, size, nullptr, 0)); } R_SUCCEED(); } }
3,308
C++
.cpp
62
46.935484
139
0.652537
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,407
fssrv_memory_resource_from_exp_heap.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssrv/fssrv_memory_resource_from_exp_heap.cpp
/* * Copyright (c) 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 { namespace { size_t GetUsedSize(void *p) { const auto block_head = reinterpret_cast<const lmem::impl::ExpHeapMemoryBlockHead *>(reinterpret_cast<uintptr_t>(p) - sizeof(lmem::impl::ExpHeapMemoryBlockHead)); return block_head->block_size + ((block_head->attributes >> 8) & 0x7F) + sizeof(lmem::impl::ExpHeapMemoryBlockHead); } } void PeakCheckableMemoryResourceFromExpHeap::OnAllocate(void *p, size_t size) { AMS_UNUSED(size); if (p != nullptr) { m_current_free_size = GetUsedSize(p); m_peak_free_size = std::min(m_peak_free_size, m_current_free_size); } } void PeakCheckableMemoryResourceFromExpHeap::OnDeallocate(void *p, size_t size) { AMS_UNUSED(size); if (p != nullptr) { m_current_free_size += GetUsedSize(p); } } void *PeakCheckableMemoryResourceFromExpHeap::AllocateImpl(size_t size, size_t align) { std::scoped_lock lk(m_mutex); void *p = lmem::AllocateFromExpHeap(m_heap_handle, size, static_cast<s32>(align)); this->OnAllocate(p, size); return p; } void PeakCheckableMemoryResourceFromExpHeap::DeallocateImpl(void *p, size_t size, size_t align) { AMS_UNUSED(align); std::scoped_lock lk(m_mutex); this->OnDeallocate(p, size); lmem::FreeToExpHeap(m_heap_handle, p); } }
2,104
C++
.cpp
49
36.714286
174
0.676139
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,408
fssrv_file_system_proxy_impl.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssrv/fssrv_file_system_proxy_impl.cpp
/* * Copyright (c) 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> #include "impl/fssrv_allocator_for_service_framework.hpp" #include "impl/fssrv_program_info.hpp" namespace ams::fssrv { FileSystemProxyImpl::FileSystemProxyImpl() { /* TODO: Set core impl. */ m_process_id = os::InvalidProcessId.value; } FileSystemProxyImpl::~FileSystemProxyImpl() { /* ... */ } #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" Result FileSystemProxyImpl::OpenFileSystem(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out, const fssrv::sf::FspPath &path, u32 type) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::FileSystemProxyImpl::SetCurrentProcess(const ams::sf::ClientProcessId &client_pid) { /* Set current process. */ m_process_id = client_pid.GetValue().value; /* TODO: Allocate NcaFileSystemService. */ /* TODO: Allocate SaveDataFileSystemService. */ R_SUCCEED(); } Result FileSystemProxyImpl::OpenDataFileSystemByCurrentProcess(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::OpenFileSystemWithPatch(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out, ncm::ProgramId program_id, u32 type) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::OpenFileSystemWithIdObsolete(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out, const fssrv::sf::FspPath &path, u64 program_id, u32 type) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::OpenFileSystemWithId(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out, const fssrv::sf::FspPath &path, fs::ContentAttributes attr, u64 program_id, u32 type) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::OpenDataFileSystemByProgramId(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out, ncm::ProgramId program_id) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::OpenBisFileSystem(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out, const fssrv::sf::FspPath &path, u32 id) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::OpenBisStorage(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IStorage>> out, u32 id) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::InvalidateBisCache() { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::OpenHostFileSystem(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out, const fssrv::sf::FspPath &path) { /* Invoke the modern API from the legacy API. */ R_RETURN(this->OpenHostFileSystemWithOption(out, path, fs::MountHostOption::None._value)); } Result FileSystemProxyImpl::OpenSdCardFileSystem(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::FormatSdCardFileSystem() { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::DeleteSaveDataFileSystem(u64 save_data_id) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::CreateSaveDataFileSystem(const fs::SaveDataAttribute &attribute, const fs::SaveDataCreationInfo &creation_info, const fs::SaveDataMetaInfo &meta_info) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::CreateSaveDataFileSystemBySystemSaveDataId(const fs::SaveDataAttribute &attribute, const fs::SaveDataCreationInfo &creation_info) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::RegisterSaveDataFileSystemAtomicDeletion(const ams::sf::InBuffer &save_data_ids) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::DeleteSaveDataFileSystemBySaveDataSpaceId(u8 indexer_space_id, u64 save_data_id) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::FormatSdCardDryRun() { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::IsExFatSupported(ams::sf::Out<bool> out) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::DeleteSaveDataFileSystemBySaveDataAttribute(u8 space_id, const fs::SaveDataAttribute &attribute) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::OpenGameCardStorage(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IStorage>> out, u32 handle, u32 partition) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::OpenGameCardFileSystem(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out, u32 handle, u32 partition) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::ExtendSaveDataFileSystem(u8 space_id, u64 save_data_id, s64 available_size, s64 journal_size) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::DeleteCacheStorage(u16 index) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::GetCacheStorageSize(ams::sf::Out<s64> out_size, ams::sf::Out<s64> out_journal_size, u16 index) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::CreateSaveDataFileSystemWithHashSalt(const fs::SaveDataAttribute &attribute, const fs::SaveDataCreationInfo &creation_info, const fs::SaveDataMetaInfo &meta_info, const fs::HashSalt &salt) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::OpenHostFileSystemWithOption(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out, const fssrv::sf::FspPath &path, u32 _option) { /* TODO: GetProgramInfo */ /* TODO: GetAccessibility. */ /* TODO: Check Accessibility CanRead/CanWrite */ /* Convert the path. */ fs::Path normalized_path; #if defined(ATMOSPHERE_OS_WINDOWS) R_TRY(normalized_path.Initialize(path.str)); #else if (path.str[0] == '/' && path.str[1] == '/') { R_TRY(normalized_path.Initialize(path.str)); } else { R_TRY(normalized_path.InitializeWithReplaceUnc(path.str)); } #endif /* Normalize the path. */ fs::PathFlags path_flags; path_flags.AllowWindowsPath(); path_flags.AllowRelativePath(); path_flags.AllowEmptyPath(); R_TRY(normalized_path.Normalize(path_flags)); /* Parse option. */ const fs::MountHostOption option{ _option }; /* TODO: FileSystemProxyCoreImpl::OpenHostFileSystem */ /* TODO: use creator interfaces */ std::shared_ptr<fs::fsa::IFileSystem> fs; { fssrv::fscreator::LocalFileSystemCreator local_fs_creator(true); R_TRY(static_cast<fscreator::ILocalFileSystemCreator &>(local_fs_creator).Create(std::addressof(fs), normalized_path, option.HasPseudoCaseSensitiveFlag())); } /* Determine path flags for the result fs. */ fs::PathFlags host_path_flags; if (path.str[0] == 0) { host_path_flags.AllowWindowsPath(); } /* Create an interface adapter. */ auto sf_fs = impl::FileSystemObjectFactory::CreateSharedEmplaced<fssrv::sf::IFileSystem, impl::FileSystemInterfaceAdapter>(std::move(fs), host_path_flags, false); R_UNLESS(sf_fs != nullptr, fs::ResultAllocationMemoryFailedInFileSystemProxyImplA()); /* Set the output. */ *out = std::move(sf_fs); R_SUCCEED(); } Result FileSystemProxyImpl::OpenSaveDataFileSystem(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out, u8 space_id, const fs::SaveDataAttribute &attribute) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::OpenSaveDataFileSystemBySystemSaveDataId(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out, u8 space_id, const fs::SaveDataAttribute &attribute) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::OpenReadOnlySaveDataFileSystem(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out, u8 space_id, const fs::SaveDataAttribute &attribute) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::ReadSaveDataFileSystemExtraDataBySaveDataSpaceId(const ams::sf::OutBuffer &buffer, u8 space_id, u64 save_data_id) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::ReadSaveDataFileSystemExtraData(const ams::sf::OutBuffer &buffer, u64 save_data_id) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::WriteSaveDataFileSystemExtraData(u64 save_data_id, u8 space_id, const ams::sf::InBuffer &buffer) { AMS_ABORT("TODO"); } /* ... */ Result FileSystemProxyImpl::OpenImageDirectoryFileSystem(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out, u32 id) { AMS_ABORT("TODO"); } /* ... */ Result FileSystemProxyImpl::OpenContentStorageFileSystem(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out, u32 id) { AMS_ABORT("TODO"); } /* ... */ Result FileSystemProxyImpl::OpenDataStorageByCurrentProcess(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IStorage>> out) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::OpenDataStorageByProgramId(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IStorage>> out, ncm::ProgramId program_id) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::OpenDataStorageByDataId(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IStorage>> out, ncm::DataId data_id, u8 storage_id) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::OpenPatchDataStorageByCurrentProcess(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IStorage>> out) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::OpenDataFileSystemWithProgramIndex(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out, u8 index) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::OpenDataStorageWithProgramIndex(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IStorage>> out, u8 index) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::OpenDataStorageByPathObsolete(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IStorage>> out, const fssrv::sf::FspPath &path, u32 type) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::OpenDataStorageByPath(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IStorage>> out, const fssrv::sf::FspPath &path, fs::ContentAttributes attr, u32 type) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::OpenDeviceOperator(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IDeviceOperator>> out) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::OpenSdCardDetectionEventNotifier(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IEventNotifier>> out) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::OpenGameCardDetectionEventNotifier(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IEventNotifier>> out) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::OpenSystemDataUpdateEventNotifier(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IEventNotifier>> out) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::NotifySystemDataUpdateEvent() { AMS_ABORT("TODO"); } /* ... */ Result FileSystemProxyImpl::SetCurrentPosixTime(s64 posix_time) { AMS_ABORT("TODO"); } /* ... */ Result FileSystemProxyImpl::GetRightsId(ams::sf::Out<fs::RightsId> out, ncm::ProgramId program_id, ncm::StorageId storage_id) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::RegisterExternalKey(const fs::RightsId &rights_id, const spl::AccessKey &access_key) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::UnregisterAllExternalKey() { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::GetProgramId(ams::sf::Out<ncm::ProgramId> out_program_id, const fssrv::sf::FspPath &path, fs::ContentAttributes attr) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::GetRightsIdByPath(ams::sf::Out<fs::RightsId> out, const fssrv::sf::FspPath &path) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::GetRightsIdAndKeyGenerationByPathObsolete(ams::sf::Out<fs::RightsId> out, ams::sf::Out<u8> out_key_generation, const fssrv::sf::FspPath &path) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::GetRightsIdAndKeyGenerationByPath(ams::sf::Out<fs::RightsId> out, ams::sf::Out<u8> out_key_generation, const fssrv::sf::FspPath &path, fs::ContentAttributes attr) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::SetCurrentPosixTimeWithTimeDifference(s64 posix_time, s32 time_difference) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::GetFreeSpaceSizeForSaveData(ams::sf::Out<s64> out, u8 space_id) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::VerifySaveDataFileSystemBySaveDataSpaceId() { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::CorruptSaveDataFileSystemBySaveDataSpaceId() { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::QuerySaveDataInternalStorageTotalSize() { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::GetSaveDataCommitId() { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::UnregisterExternalKey(const fs::RightsId &rights_id) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::SetSdCardEncryptionSeed(const fs::EncryptionSeed &seed) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::SetSdCardAccessibility(bool accessible) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::IsSdCardAccessible(ams::sf::Out<bool> out) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::IsSignedSystemPartitionOnSdCardValid(ams::sf::Out<bool> out) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::OpenAccessFailureDetectionEventNotifier() { AMS_ABORT("TODO"); } /* ... */ Result FileSystemProxyImpl::GetAndClearErrorInfo(ams::sf::Out<fs::FileSystemProxyErrorInfo> out) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::RegisterProgramIndexMapInfo(const ams::sf::InBuffer &buffer, s32 count) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::SetBisRootForHost(u32 id, const fssrv::sf::FspPath &path) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::SetSaveDataSize(s64 size, s64 journal_size) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::SetSaveDataRootPath(const fssrv::sf::FspPath &path) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::DisableAutoSaveDataCreation() { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::SetGlobalAccessLogMode(u32 mode) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::GetGlobalAccessLogMode(ams::sf::Out<u32> out) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::OutputAccessLogToSdCard(const ams::sf::InBuffer &buf) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::RegisterUpdatePartition() { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::OpenRegisteredUpdatePartition(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::GetAndClearMemoryReportInfo(ams::sf::Out<fs::MemoryReportInfo> out) { AMS_ABORT("TODO"); } /* ... */ Result FileSystemProxyImpl::GetProgramIndexForAccessLog(ams::sf::Out<u32> out_idx, ams::sf::Out<u32> out_count) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::GetFsStackUsage(ams::sf::Out<u32> out, u32 type) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::UnsetSaveDataRootPath() { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::OutputMultiProgramTagAccessLog() { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::FlushAccessLogOnSdCard() { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::OutputApplicationInfoAccessLog() { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::RegisterDebugConfiguration(u32 key, s64 value) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::UnregisterDebugConfiguration(u32 key) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::OverrideSaveDataTransferTokenSignVerificationKey(const ams::sf::InBuffer &buf) { AMS_ABORT("TODO"); } Result FileSystemProxyImpl::CorruptSaveDataFileSystemByOffset(u8 space_id, u64 save_data_id, s64 offset) { AMS_ABORT("TODO"); } /* ... */ #pragma GCC diagnostic pop Result FileSystemProxyImpl::OpenCodeFileSystemDeprecated(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out_fs, const fssrv::sf::Path &path, ncm::ProgramId program_id) { AMS_ABORT("TODO"); AMS_UNUSED(out_fs, path, program_id); } Result FileSystemProxyImpl::OpenCodeFileSystemDeprecated2(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out_fs, ams::sf::Out<fs::CodeVerificationData> out_verif, const fssrv::sf::Path &path, ncm::ProgramId program_id) { AMS_ABORT("TODO"); AMS_UNUSED(out_fs, out_verif, path, program_id); } Result FileSystemProxyImpl::OpenCodeFileSystemDeprecated3(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out_fs, ams::sf::Out<fs::CodeVerificationData> out_verif, const fssrv::sf::Path &path, fs::ContentAttributes attr, ncm::ProgramId program_id) { AMS_ABORT("TODO"); AMS_UNUSED(out_fs, out_verif, path, attr, program_id); } Result FileSystemProxyImpl::OpenCodeFileSystem(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out_fs, const ams::sf::OutBuffer &out_verif, const fssrv::sf::Path &path, fs::ContentAttributes attr, ncm::ProgramId program_id) { AMS_ABORT("TODO"); AMS_UNUSED(out_fs, out_verif, path, attr, program_id); } Result FileSystemProxyImpl::IsArchivedProgram(ams::sf::Out<bool> out, u64 process_id) { AMS_ABORT("TODO"); AMS_UNUSED(out, process_id); } }
18,663
C++
.cpp
376
42.87766
266
0.692756
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,409
fssrv_memory_resource_from_standard_allocator.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssrv/fssrv_memory_resource_from_standard_allocator.cpp
/* * Copyright (c) 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 { MemoryResourceFromStandardAllocator::MemoryResourceFromStandardAllocator(mem::StandardAllocator *allocator) : m_allocator(allocator), m_mutex() { m_current_free_size = m_allocator->GetTotalFreeSize(); this->ClearPeak(); } void MemoryResourceFromStandardAllocator::ClearPeak() { std::scoped_lock lk(m_mutex); m_peak_free_size = m_current_free_size; m_peak_allocated_size = 0; } void *MemoryResourceFromStandardAllocator::AllocateImpl(size_t size, size_t align) { std::scoped_lock lk(m_mutex); void *p = m_allocator->Allocate(size, align); if (p != nullptr) { m_current_free_size -= m_allocator->GetSizeOf(p); m_peak_free_size = std::min(m_peak_free_size, m_current_free_size); } m_peak_allocated_size = std::max(m_peak_allocated_size, size); return p; } void MemoryResourceFromStandardAllocator::DeallocateImpl(void *p, size_t size, size_t align) { AMS_UNUSED(size, align); std::scoped_lock lk(m_mutex); m_current_free_size += m_allocator->GetSizeOf(p); m_allocator->Free(p); } }
1,858
C++
.cpp
43
37.511628
149
0.688297
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,410
fssrv_program_registry_impl.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssrv/fssrv_program_registry_impl.cpp
/* * Copyright (c) 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 "impl/fssrv_program_info.hpp" namespace ams::fssrv { namespace { constinit ProgramRegistryServiceImpl *g_impl = nullptr; } ProgramRegistryImpl::ProgramRegistryImpl() : m_process_id(os::InvalidProcessId.value) { /* ... */ } ProgramRegistryImpl::~ProgramRegistryImpl() { /* ... */ } void ProgramRegistryImpl::Initialize(ProgramRegistryServiceImpl *service) { /* Check pre-conditions. */ AMS_ASSERT(service != nullptr); AMS_ASSERT(g_impl == nullptr); /* Set the global service. */ g_impl = service; } Result ProgramRegistryImpl::RegisterProgram(u64 process_id, u64 program_id, u8 storage_id, const ams::sf::InBuffer &data, s64 data_size, const ams::sf::InBuffer &desc, s64 desc_size) { /* Check pre-conditions. */ AMS_ASSERT(g_impl != nullptr); /* Check that we're allowed to register. */ R_UNLESS(fssrv::impl::IsInitialProgram(m_process_id), fs::ResultPermissionDenied()); /* Check buffer sizes. */ R_UNLESS(data.GetSize() >= static_cast<size_t>(data_size), fs::ResultInvalidSize()); R_UNLESS(desc.GetSize() >= static_cast<size_t>(desc_size), fs::ResultInvalidSize()); /* Register the program. */ R_RETURN(g_impl->RegisterProgramInfo(process_id, program_id, storage_id, data.GetPointer(), data_size, desc.GetPointer(), desc_size)); } Result ProgramRegistryImpl::UnregisterProgram(u64 process_id) { /* Check pre-conditions. */ AMS_ASSERT(g_impl != nullptr); /* Check that we're allowed to register. */ R_UNLESS(fssrv::impl::IsInitialProgram(m_process_id), fs::ResultPermissionDenied()); /* Unregister the program. */ R_RETURN(g_impl->UnregisterProgramInfo(process_id)); } Result ProgramRegistryImpl::SetCurrentProcess(const ams::sf::ClientProcessId &client_pid) { /* Set our process id. */ m_process_id = client_pid.GetValue().value; R_SUCCEED(); } Result ProgramRegistryImpl::SetEnabledProgramVerification(bool en) { /* TODO: How to deal with this backwards compat? */ AMS_ABORT("TODO: SetEnabledProgramVerification"); AMS_UNUSED(en); } }
2,925
C++
.cpp
64
39.5625
188
0.676988
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,411
fssrv_nca_crypto_configuration.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssrv/fssrv_nca_crypto_configuration.cpp
/* * Copyright (c) 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 { namespace { constexpr inline const u8 HeaderSign1KeyModulusDev[fssystem::NcaCryptoConfiguration::Header1SignatureKeyGenerationMax + 1][fssystem::NcaCryptoConfiguration::Rsa2048KeyModulusSize] = { { 0xD8, 0xF1, 0x18, 0xEF, 0x32, 0x72, 0x4C, 0xA7, 0x47, 0x4C, 0xB9, 0xEA, 0xB3, 0x04, 0xA8, 0xA4, 0xAC, 0x99, 0x08, 0x08, 0x04, 0xBF, 0x68, 0x57, 0xB8, 0x43, 0x94, 0x2B, 0xC7, 0xB9, 0x66, 0x49, 0x85, 0xE5, 0x8A, 0x9B, 0xC1, 0x00, 0x9A, 0x6A, 0x8D, 0xD0, 0xEF, 0xCE, 0xFF, 0x86, 0xC8, 0x5C, 0x5D, 0xE9, 0x53, 0x7B, 0x19, 0x2A, 0xA8, 0xC0, 0x22, 0xD1, 0xF3, 0x22, 0x0A, 0x50, 0xF2, 0x2B, 0x65, 0x05, 0x1B, 0x9E, 0xEC, 0x61, 0xB5, 0x63, 0xA3, 0x6F, 0x3B, 0xBA, 0x63, 0x3A, 0x53, 0xF4, 0x49, 0x2F, 0xCF, 0x03, 0xCC, 0xD7, 0x50, 0x82, 0x1B, 0x29, 0x4F, 0x08, 0xDE, 0x1B, 0x6D, 0x47, 0x4F, 0xA8, 0xB6, 0x6A, 0x26, 0xA0, 0x83, 0x3F, 0x1A, 0xAF, 0x83, 0x8F, 0x0E, 0x17, 0x3F, 0xFE, 0x44, 0x1C, 0x56, 0x94, 0x2E, 0x49, 0x83, 0x83, 0x03, 0xE9, 0xB6, 0xAD, 0xD5, 0xDE, 0xE3, 0x2D, 0xA1, 0xD9, 0x66, 0x20, 0x5D, 0x1F, 0x5E, 0x96, 0x5D, 0x5B, 0x55, 0x0D, 0xD4, 0xB4, 0x77, 0x6E, 0xAE, 0x1B, 0x69, 0xF3, 0xA6, 0x61, 0x0E, 0x51, 0x62, 0x39, 0x28, 0x63, 0x75, 0x76, 0xBF, 0xB0, 0xD2, 0x22, 0xEF, 0x98, 0x25, 0x02, 0x05, 0xC0, 0xD7, 0x6A, 0x06, 0x2C, 0xA5, 0xD8, 0x5A, 0x9D, 0x7A, 0xA4, 0x21, 0x55, 0x9F, 0xF9, 0x3E, 0xBF, 0x16, 0xF6, 0x07, 0xC2, 0xB9, 0x6E, 0x87, 0x9E, 0xB5, 0x1C, 0xBE, 0x97, 0xFA, 0x82, 0x7E, 0xED, 0x30, 0xD4, 0x66, 0x3F, 0xDE, 0xD8, 0x1B, 0x4B, 0x15, 0xD9, 0xFB, 0x2F, 0x50, 0xF0, 0x9D, 0x1D, 0x52, 0x4C, 0x1C, 0x4D, 0x8D, 0xAE, 0x85, 0x1E, 0xEA, 0x7F, 0x86, 0xF3, 0x0B, 0x7B, 0x87, 0x81, 0x98, 0x23, 0x80, 0x63, 0x4F, 0x2F, 0xB0, 0x62, 0xCC, 0x6E, 0xD2, 0x46, 0x13, 0x65, 0x2B, 0xD6, 0x44, 0x33, 0x59, 0xB5, 0x8F, 0xB9, 0x4A, 0xA9 }, { 0x9A, 0xBC, 0x88, 0xBD, 0x0A, 0xBE, 0xD7, 0x0C, 0x9B, 0x42, 0x75, 0x65, 0x38, 0x5E, 0xD1, 0x01, 0xCD, 0x12, 0xAE, 0xEA, 0xE9, 0x4B, 0xDB, 0xB4, 0x5E, 0x36, 0x10, 0x96, 0xDA, 0x3D, 0x2E, 0x66, 0xD3, 0x99, 0x13, 0x8A, 0xBE, 0x67, 0x41, 0xC8, 0x93, 0xD9, 0x3E, 0x42, 0xCE, 0x34, 0xCE, 0x96, 0xFA, 0x0B, 0x23, 0xCC, 0x2C, 0xDF, 0x07, 0x3F, 0x3B, 0x24, 0x4B, 0x12, 0x67, 0x3A, 0x29, 0x36, 0xA3, 0xAA, 0x06, 0xF0, 0x65, 0xA5, 0x85, 0xBA, 0xFD, 0x12, 0xEC, 0xF1, 0x60, 0x67, 0xF0, 0x8F, 0xD3, 0x5B, 0x01, 0x1B, 0x1E, 0x84, 0xA3, 0x5C, 0x65, 0x36, 0xF9, 0x23, 0x7E, 0xF3, 0x26, 0x38, 0x64, 0x98, 0xBA, 0xE4, 0x19, 0x91, 0x4C, 0x02, 0xCF, 0xC9, 0x6D, 0x86, 0xEC, 0x1D, 0x41, 0x69, 0xDD, 0x56, 0xEA, 0x5C, 0xA3, 0x2A, 0x58, 0xB4, 0x39, 0xCC, 0x40, 0x31, 0xFD, 0xFB, 0x42, 0x74, 0xF8, 0xEC, 0xEA, 0x00, 0xF0, 0xD9, 0x28, 0xEA, 0xFA, 0x2D, 0x00, 0xE1, 0x43, 0x53, 0xC6, 0x32, 0xF4, 0xA2, 0x07, 0xD4, 0x5F, 0xD4, 0xCB, 0xAC, 0xCA, 0xFF, 0xDF, 0x84, 0xD2, 0x86, 0x14, 0x3C, 0xDE, 0x22, 0x75, 0xA5, 0x73, 0xFF, 0x68, 0x07, 0x4A, 0xF9, 0x7C, 0x2C, 0xCC, 0xDE, 0x45, 0xB6, 0x54, 0x82, 0x90, 0x36, 0x1F, 0x2C, 0x51, 0x96, 0xC5, 0x0A, 0x53, 0x5B, 0xF0, 0x8B, 0x4A, 0xAA, 0x3B, 0x68, 0x97, 0x19, 0x17, 0x1F, 0x01, 0xB8, 0xED, 0xB9, 0x9A, 0x5E, 0x08, 0xC5, 0x20, 0x1E, 0x6A, 0x09, 0xF0, 0xE9, 0x73, 0xA3, 0xBE, 0x10, 0x06, 0x02, 0xE9, 0xFB, 0x85, 0xFA, 0x5F, 0x01, 0xAC, 0x60, 0xE0, 0xED, 0x7D, 0xB9, 0x49, 0xA8, 0x9E, 0x98, 0x7D, 0x91, 0x40, 0x05, 0xCF, 0xF9, 0x1A, 0xFC, 0x40, 0x22, 0xA8, 0x96, 0x5B, 0xB0, 0xDC, 0x7A, 0xF5, 0xB7, 0xE9, 0x91, 0x4C, 0x49 } }; constexpr inline const u8 HeaderSign1KeyModulusProd[fssystem::NcaCryptoConfiguration::Header1SignatureKeyGenerationMax + 1][fssystem::NcaCryptoConfiguration::Rsa2048KeyModulusSize] = { { 0xBF, 0xBE, 0x40, 0x6C, 0xF4, 0xA7, 0x80, 0xE9, 0xF0, 0x7D, 0x0C, 0x99, 0x61, 0x1D, 0x77, 0x2F, 0x96, 0xBC, 0x4B, 0x9E, 0x58, 0x38, 0x1B, 0x03, 0xAB, 0xB1, 0x75, 0x49, 0x9F, 0x2B, 0x4D, 0x58, 0x34, 0xB0, 0x05, 0xA3, 0x75, 0x22, 0xBE, 0x1A, 0x3F, 0x03, 0x73, 0xAC, 0x70, 0x68, 0xD1, 0x16, 0xB9, 0x04, 0x46, 0x5E, 0xB7, 0x07, 0x91, 0x2F, 0x07, 0x8B, 0x26, 0xDE, 0xF6, 0x00, 0x07, 0xB2, 0xB4, 0x51, 0xF8, 0x0D, 0x0A, 0x5E, 0x58, 0xAD, 0xEB, 0xBC, 0x9A, 0xD6, 0x49, 0xB9, 0x64, 0xEF, 0xA7, 0x82, 0xB5, 0xCF, 0x6D, 0x70, 0x13, 0xB0, 0x0F, 0x85, 0xF6, 0xA9, 0x08, 0xAA, 0x4D, 0x67, 0x66, 0x87, 0xFA, 0x89, 0xFF, 0x75, 0x90, 0x18, 0x1E, 0x6B, 0x3D, 0xE9, 0x8A, 0x68, 0xC9, 0x26, 0x04, 0xD9, 0x80, 0xCE, 0x3F, 0x5E, 0x92, 0xCE, 0x01, 0xFF, 0x06, 0x3B, 0xF2, 0xC1, 0xA9, 0x0C, 0xCE, 0x02, 0x6F, 0x16, 0xBC, 0x92, 0x42, 0x0A, 0x41, 0x64, 0xCD, 0x52, 0xB6, 0x34, 0x4D, 0xAE, 0xC0, 0x2E, 0xDE, 0xA4, 0xDF, 0x27, 0x68, 0x3C, 0xC1, 0xA0, 0x60, 0xAD, 0x43, 0xF3, 0xFC, 0x86, 0xC1, 0x3E, 0x6C, 0x46, 0xF7, 0x7C, 0x29, 0x9F, 0xFA, 0xFD, 0xF0, 0xE3, 0xCE, 0x64, 0xE7, 0x35, 0xF2, 0xF6, 0x56, 0x56, 0x6F, 0x6D, 0xF1, 0xE2, 0x42, 0xB0, 0x83, 0x40, 0xA5, 0xC3, 0x20, 0x2B, 0xCC, 0x9A, 0xAE, 0xCA, 0xED, 0x4D, 0x70, 0x30, 0xA8, 0x70, 0x1C, 0x70, 0xFD, 0x13, 0x63, 0x29, 0x02, 0x79, 0xEA, 0xD2, 0xA7, 0xAF, 0x35, 0x28, 0x32, 0x1C, 0x7B, 0xE6, 0x2F, 0x1A, 0xAA, 0x40, 0x7E, 0x32, 0x8C, 0x27, 0x42, 0xFE, 0x82, 0x78, 0xEC, 0x0D, 0xEB, 0xE6, 0x83, 0x4B, 0x6D, 0x81, 0x04, 0x40, 0x1A, 0x9E, 0x9A, 0x67, 0xF6, 0x72, 0x29, 0xFA, 0x04, 0xF0, 0x9D, 0xE4, 0xF4, 0x03 }, { 0xAD, 0xE3, 0xE1, 0xFA, 0x04, 0x35, 0xE5, 0xB6, 0xDD, 0x49, 0xEA, 0x89, 0x29, 0xB1, 0xFF, 0xB6, 0x43, 0xDF, 0xCA, 0x96, 0xA0, 0x4A, 0x13, 0xDF, 0x43, 0xD9, 0x94, 0x97, 0x96, 0x43, 0x65, 0x48, 0x70, 0x58, 0x33, 0xA2, 0x7D, 0x35, 0x7B, 0x96, 0x74, 0x5E, 0x0B, 0x5C, 0x32, 0x18, 0x14, 0x24, 0xC2, 0x58, 0xB3, 0x6C, 0x22, 0x7A, 0xA1, 0xB7, 0xCB, 0x90, 0xA7, 0xA3, 0xF9, 0x7D, 0x45, 0x16, 0xA5, 0xC8, 0xED, 0x8F, 0xAD, 0x39, 0x5E, 0x9E, 0x4B, 0x51, 0x68, 0x7D, 0xF8, 0x0C, 0x35, 0xC6, 0x3F, 0x91, 0xAE, 0x44, 0xA5, 0x92, 0x30, 0x0D, 0x46, 0xF8, 0x40, 0xFF, 0xD0, 0xFF, 0x06, 0xD2, 0x1C, 0x7F, 0x96, 0x18, 0xDC, 0xB7, 0x1D, 0x66, 0x3E, 0xD1, 0x73, 0xBC, 0x15, 0x8A, 0x2F, 0x94, 0xF3, 0x00, 0xC1, 0x83, 0xF1, 0xCD, 0xD7, 0x81, 0x88, 0xAB, 0xDF, 0x8C, 0xEF, 0x97, 0xDD, 0x1B, 0x17, 0x5F, 0x58, 0xF6, 0x9A, 0xE9, 0xE8, 0xC2, 0x2F, 0x38, 0x15, 0xF5, 0x21, 0x07, 0xF8, 0x37, 0x90, 0x5D, 0x2E, 0x02, 0x40, 0x24, 0x15, 0x0D, 0x25, 0xB7, 0x26, 0x5D, 0x09, 0xCC, 0x4C, 0xF4, 0xF2, 0x1B, 0x94, 0x70, 0x5A, 0x9E, 0xEE, 0xED, 0x77, 0x77, 0xD4, 0x51, 0x99, 0xF5, 0xDC, 0x76, 0x1E, 0xE3, 0x6C, 0x8C, 0xD1, 0x12, 0xD4, 0x57, 0xD1, 0xB6, 0x83, 0xE4, 0xE4, 0xFE, 0xDA, 0xE9, 0xB4, 0x3B, 0x33, 0xE5, 0x37, 0x8A, 0xDF, 0xB5, 0x7F, 0x89, 0xF1, 0x9B, 0x9E, 0xB0, 0x15, 0xB2, 0x3A, 0xFE, 0xEA, 0x61, 0x84, 0x5B, 0x7D, 0x4B, 0x23, 0x12, 0x0B, 0x83, 0x12, 0xF2, 0x22, 0x6B, 0xB9, 0x22, 0x96, 0x4B, 0x26, 0x0B, 0x63, 0x5E, 0x96, 0x57, 0x52, 0xA3, 0x67, 0x64, 0x22, 0xCA, 0xD0, 0x56, 0x3E, 0x74, 0xB5, 0x98, 0x1F, 0x0D, 0xF8, 0xB3, 0x34, 0xE6, 0x98, 0x68, 0x5A, 0xAD } }; constexpr inline const ::ams::fssystem::NcaCryptoConfiguration DefaultNcaCryptoConfigurationDev = { /* Header1 Signature Key Moduli */ { HeaderSign1KeyModulusDev[0], HeaderSign1KeyModulusDev[1] }, /* Header 1 Signature Key Public Exponent */ { 0x01, 0x00, 0x01 }, /* Key Area Encryption Key Sources */ { /* Application */ { 0x7F, 0x59, 0x97, 0x1E, 0x62, 0x9F, 0x36, 0xA1, 0x30, 0x98, 0x06, 0x6F, 0x21, 0x44, 0xC3, 0x0D }, /* Ocean */ { 0x32, 0x7D, 0x36, 0x08, 0x5A, 0xD1, 0x75, 0x8D, 0xAB, 0x4E, 0x6F, 0xBA, 0xA5, 0x55, 0xD8, 0x82 }, /* System */ { 0x87, 0x45, 0xF1, 0xBB, 0xA6, 0xBE, 0x79, 0x64, 0x7D, 0x04, 0x8B, 0xA6, 0x7B, 0x5F, 0xDA, 0x4A }, }, /* Header Encryption Key Source */ { 0x1F, 0x12, 0x91, 0x3A, 0x4A, 0xCB, 0xF0, 0x0D, 0x4C, 0xDE, 0x3A, 0xF6, 0xD5, 0x23, 0x88, 0x2A }, /* Encrypted Header Encryption Key */ { { 0x5A, 0x3E, 0xD8, 0x4F, 0xDE, 0xC0, 0xD8, 0x26, 0x31, 0xF7, 0xE2, 0x5D, 0x19, 0x7B, 0xF5, 0xD0 }, { 0x1C, 0x9B, 0x7B, 0xFA, 0xF6, 0x28, 0x18, 0x3D, 0x71, 0xF6, 0x4D, 0x73, 0xF1, 0x50, 0xB9, 0xD2 } }, /* Key Generation Function */ nullptr, /* Decrypt Aes Xts Eternal Function */ nullptr, /* Encrypt Aes Xts Eternal Function */ nullptr, /* Decrypt Aes Ctr Function */ nullptr, /* Decrypt Aes Ctr External Function */ nullptr, /* Verify Sign1 Function */ nullptr, /* Plaintext Header Available */ false, /* Software Key Available */ true, }; constexpr inline const ::ams::fssystem::NcaCryptoConfiguration DefaultNcaCryptoConfigurationProd = { /* Header1 Signature Key Moduli */ { HeaderSign1KeyModulusProd[0], HeaderSign1KeyModulusProd[1] }, /* Header 1 Signature Key Public Exponent */ { 0x01, 0x00, 0x01 }, /* Key Area Encryption Key Sources */ { /* Application */ { 0x7F, 0x59, 0x97, 0x1E, 0x62, 0x9F, 0x36, 0xA1, 0x30, 0x98, 0x06, 0x6F, 0x21, 0x44, 0xC3, 0x0D }, /* Ocean */ { 0x32, 0x7D, 0x36, 0x08, 0x5A, 0xD1, 0x75, 0x8D, 0xAB, 0x4E, 0x6F, 0xBA, 0xA5, 0x55, 0xD8, 0x82 }, /* System */ { 0x87, 0x45, 0xF1, 0xBB, 0xA6, 0xBE, 0x79, 0x64, 0x7D, 0x04, 0x8B, 0xA6, 0x7B, 0x5F, 0xDA, 0x4A }, }, /* Header Encryption Key Source */ { 0x1F, 0x12, 0x91, 0x3A, 0x4A, 0xCB, 0xF0, 0x0D, 0x4C, 0xDE, 0x3A, 0xF6, 0xD5, 0x23, 0x88, 0x2A }, /* Encrypted Header Encryption Key */ { { 0x5A, 0x3E, 0xD8, 0x4F, 0xDE, 0xC0, 0xD8, 0x26, 0x31, 0xF7, 0xE2, 0x5D, 0x19, 0x7B, 0xF5, 0xD0 }, { 0x1C, 0x9B, 0x7B, 0xFA, 0xF6, 0x28, 0x18, 0x3D, 0x71, 0xF6, 0x4D, 0x73, 0xF1, 0x50, 0xB9, 0xD2 } }, /* Key Generation Function */ nullptr, /* Decrypt Aes Xts Eternal Function */ nullptr, /* Encrypt Aes Xts Eternal Function */ nullptr, /* Decrypt Aes Ctr Function */ nullptr, /* Decrypt Aes Ctr External Function */ nullptr, /* Verify Sign1 Function */ nullptr, /* Plaintext Header Available */ false, /* Software Key Available */ true, }; } const ::ams::fssystem::NcaCryptoConfiguration *GetDefaultNcaCryptoConfiguration(bool prod) { return prod ? std::addressof(DefaultNcaCryptoConfigurationProd) : std::addressof(DefaultNcaCryptoConfigurationDev); } }
12,354
C++
.cpp
175
57.097143
192
0.574699
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,412
fssrv_utility.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssrv/impl/fssrv_utility.cpp
/* * Copyright (c) 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 "fssrv_utility.hpp" #if defined(ATMOSPHERE_OS_WINDOWS) #include <stratosphere/windows.hpp> #elif defined(ATMOSPHERE_OS_LINUX) #include <unistd.h> #elif defined(ATMOSPHERE_OS_MACOS) #include <unistd.h> #include <mach-o/dyld.h> #include <sys/param.h> #endif namespace ams::fssystem { class PathOnExecutionDirectory { private: char m_path[fs::EntryNameLengthMax + 1]; public: PathOnExecutionDirectory() { #if defined(ATMOSPHERE_OS_WINDOWS) { /* Get the module file name. */ wchar_t module_file_name[fs::EntryNameLengthMax + 1]; if (::GetModuleFileNameW(0, module_file_name, util::size(module_file_name)) == 0) { AMS_FS_R_ABORT_UNLESS(fs::ResultUnexpectedInPathOnExecutionDirectoryA()); } /* Split the path. */ wchar_t drive_name[3]; wchar_t dir_name[fs::EntryNameLengthMax + 1]; ::_wsplitpath_s(module_file_name, drive_name, util::size(drive_name), dir_name, util::size(dir_name), nullptr, 0, nullptr, 0); /* Print the drive and directory. */ wchar_t path[fs::EntryNameLengthMax + 1]; ::swprintf_s(path, util::size(path), L"%s%s", drive_name, dir_name); /* Convert to utf-8. */ const auto res = ::WideCharToMultiByte(CP_UTF8, 0, path, -1, m_path, util::size(m_path), nullptr, nullptr); if (res == 0) { AMS_FS_R_ABORT_UNLESS(fs::ResultUnexpectedInPathOnExecutionDirectoryB()); } } #elif defined(ATMOSPHERE_OS_LINUX) { char full_path[PATH_MAX] = {}; if (::readlink("/proc/self/exe", full_path, sizeof(full_path)) == -1) { AMS_FS_R_ABORT_UNLESS(fs::ResultUnexpectedInPathOnExecutionDirectoryA()); } const int len = std::strlen(full_path); if (len >= static_cast<int>(sizeof(m_path))) { AMS_FS_R_ABORT_UNLESS(fs::ResultUnexpectedInPathOnExecutionDirectoryB()); } std::memcpy(m_path, full_path, len + 1); for (int i = len - 1; i >= 0; --i) { if (m_path[i] == '/') { m_path[i + 1] = 0; break; } } } #elif defined(ATMOSPHERE_OS_MACOS) { char full_path[MAXPATHLEN] = {}; uint32_t size = sizeof(full_path); if (_NSGetExecutablePath(full_path, std::addressof(size)) != 0) { AMS_FS_R_ABORT_UNLESS(fs::ResultUnexpectedInPathOnExecutionDirectoryA()); } const int len = std::strlen(full_path); if (len >= static_cast<int>(sizeof(m_path))) { AMS_FS_R_ABORT_UNLESS(fs::ResultUnexpectedInPathOnExecutionDirectoryB()); } std::memcpy(m_path, full_path, len + 1); for (int i = len - 1; i >= 0; --i) { if (m_path[i] == '/') { m_path[i + 1] = 0; break; } } } #else AMS_ABORT("TODO: Unknown OS for PathOnExecutionDirectory"); #endif const auto len = std::strlen(m_path); if (m_path[len - 1] != '/' && m_path[len - 1] != '\\') { if (len + 1 >= sizeof(m_path)) { AMS_FS_R_ABORT_UNLESS(fs::ResultUnexpectedInPathOnExecutionDirectoryB()); } m_path[len] = '/'; m_path[len + 1] = 0; } } const char *Get() const { return m_path; } }; class PathOnWorkingDirectory { private: char m_path[fs::EntryNameLengthMax + 1]; public: PathOnWorkingDirectory() { #if defined(ATMOSPHERE_OS_WINDOWS) { /* Get the current directory. */ wchar_t current_directory[fs::EntryNameLengthMax + 1]; if (::GetCurrentDirectoryW(util::size(current_directory), current_directory) == 0) { AMS_FS_R_ABORT_UNLESS(fs::ResultUnexpectedInPathOnExecutionDirectoryB()); } /* Convert to utf-8. */ const auto res = ::WideCharToMultiByte(CP_UTF8, 0, current_directory, -1, m_path, util::size(m_path), nullptr, nullptr); if (res == 0) { AMS_FS_R_ABORT_UNLESS(fs::ResultUnexpectedInPathOnExecutionDirectoryB()); } } #elif defined(ATMOSPHERE_OS_LINUX) { char full_path[PATH_MAX] = {}; if (::getcwd(full_path, sizeof(full_path)) == nullptr) { AMS_FS_R_ABORT_UNLESS(fs::ResultUnexpectedInPathOnExecutionDirectoryB()); } const int len = std::strlen(full_path); if (len >= static_cast<int>(sizeof(m_path))) { AMS_FS_R_ABORT_UNLESS(fs::ResultUnexpectedInPathOnExecutionDirectoryB()); } std::memcpy(m_path, full_path, len + 1); } #elif defined(ATMOSPHERE_OS_MACOS) { char full_path[MAXPATHLEN] = {}; if (::getcwd(full_path, sizeof(full_path)) == nullptr) { AMS_FS_R_ABORT_UNLESS(fs::ResultUnexpectedInPathOnExecutionDirectoryB()); } const int len = std::strlen(full_path); if (len >= static_cast<int>(sizeof(m_path))) { AMS_FS_R_ABORT_UNLESS(fs::ResultUnexpectedInPathOnExecutionDirectoryB()); } std::memcpy(m_path, full_path, len + 1); } #else AMS_ABORT("TODO: Unknown OS for PathOnWorkingDirectory"); #endif const auto len = std::strlen(m_path); if (m_path[len - 1] != '/' && m_path[len - 1] != '\\') { if (len + 1 >= sizeof(m_path)) { AMS_FS_R_ABORT_UNLESS(fs::ResultUnexpectedInPathOnExecutionDirectoryB()); } m_path[len] = '/'; m_path[len + 1] = 0; } } const char *Get() const { return m_path; } }; } namespace ams::fssrv::impl { const char *GetExecutionDirectoryPath() { AMS_FUNCTION_LOCAL_STATIC(fssystem::PathOnExecutionDirectory, s_path_on_execution_directory); return s_path_on_execution_directory.Get(); } const char *GetWorkingDirectoryPath() { AMS_FUNCTION_LOCAL_STATIC(fssystem::PathOnWorkingDirectory, s_path_on_working_directory); return s_path_on_working_directory.Get(); } }
8,164
C++
.cpp
174
31.011494
146
0.495353
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,413
fssrv_file_system_proxy_service_object.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssrv/impl/fssrv_file_system_proxy_service_object.cpp
/* * Copyright (c) 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 "fssrv_allocator_for_service_framework.hpp" namespace ams::fssrv::impl { namespace { using FileSystemProxyServiceFactory = ams::sf::ObjectFactory<AllocatorForServiceFramework::Policy>; using ProgramRegistryServiceFactory = ams::sf::ObjectFactory<AllocatorForServiceFramework::Policy>; using FileSystemProxyForLoaderServiceFactory = ams::sf::ObjectFactory<AllocatorForServiceFramework::Policy>; } ams::sf::EmplacedRef<fssrv::sf::IFileSystemProxy, fssrv::FileSystemProxyImpl> GetFileSystemProxyServiceObject() { return FileSystemProxyServiceFactory::CreateSharedEmplaced<fssrv::sf::IFileSystemProxy, fssrv::FileSystemProxyImpl>(); } ams::sf::SharedPointer<fssrv::sf::IProgramRegistry> GetProgramRegistryServiceObject() { return ProgramRegistryServiceFactory::CreateSharedEmplaced<fssrv::sf::IProgramRegistry, fssrv::ProgramRegistryImpl>(); } ams::sf::SharedPointer<fssrv::sf::IProgramRegistry> GetInvalidProgramRegistryServiceObject() { return ProgramRegistryServiceFactory::CreateSharedEmplaced<fssrv::sf::IProgramRegistry, fssrv::InvalidProgramRegistryImpl>(); } ams::sf::SharedPointer<fssrv::sf::IFileSystemProxyForLoader> GetFileSystemProxyForLoaderServiceObject() { return FileSystemProxyForLoaderServiceFactory ::CreateSharedEmplaced<fssrv::sf::IFileSystemProxyForLoader, fssrv::FileSystemProxyImpl>(); } ams::sf::SharedPointer<fssrv::sf::IFileSystemProxyForLoader> GetInvalidFileSystemProxyForLoaderServiceObject() { return FileSystemProxyForLoaderServiceFactory ::CreateSharedEmplaced<fssrv::sf::IFileSystemProxyForLoader, fssrv::InvalidFileSystemProxyImplForLoader>(); } }
2,392
C++
.cpp
39
56.846154
161
0.781904
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,414
fssrv_program_info.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssrv/impl/fssrv_program_info.cpp
/* * Copyright (c) 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 "fssrv_program_info.hpp" namespace ams::fssrv::impl { namespace { alignas(0x10) constinit std::byte g_static_buffer_for_program_info_for_initial_process[0x80] = {}; template<typename T> class StaticAllocatorForProgramInfoForInitialProcess : public std::allocator<T> { public: StaticAllocatorForProgramInfoForInitialProcess() { /* ... */ } template<typename U> StaticAllocatorForProgramInfoForInitialProcess(const StaticAllocatorForProgramInfoForInitialProcess<U> &) { /* ... */ } template<typename U> struct rebind { using other = StaticAllocatorForProgramInfoForInitialProcess<U>; }; [[nodiscard]] T *allocate(::std::size_t n) { AMS_ABORT_UNLESS(sizeof(T) * n <= sizeof(g_static_buffer_for_program_info_for_initial_process)); return reinterpret_cast<T *>(std::addressof(g_static_buffer_for_program_info_for_initial_process)); } void deallocate(T *p, ::std::size_t n) { AMS_UNUSED(p, n); } }; constexpr const u32 FileAccessControlForInitialProgram[0x1C / sizeof(u32)] = {0x00000001, 0x00000000, 0x80000000, 0x0000001C, 0x00000000, 0x0000001C, 0x00000000}; constexpr const u32 FileAccessControlDescForInitialProgram[0x2C / sizeof(u32)] = {0x00000001, 0x00000000, 0x80000000, 0x00000000, 0x00000000, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, 0x00000000, 0xFFFFFFFF, 0xFFFFFFFF}; #if defined(ATMOSPHERE_OS_HORIZON) constinit os::SdkMutex g_mutex; constinit bool g_initialized = false; constinit u64 g_initial_process_id_min = 0; constinit u64 g_initial_process_id_max = 0; constinit u64 g_current_process_id = 0; ALWAYS_INLINE void InitializeInitialAndCurrentProcessId() { if (AMS_UNLIKELY(!g_initialized)) { std::scoped_lock lk(g_mutex); if (AMS_LIKELY(!g_initialized)) { /* Get initial process id range. */ R_ABORT_UNLESS(svc::GetSystemInfo(std::addressof(g_initial_process_id_min), svc::SystemInfoType_InitialProcessIdRange, svc::InvalidHandle, svc::InitialProcessIdRangeInfo_Minimum)); R_ABORT_UNLESS(svc::GetSystemInfo(std::addressof(g_initial_process_id_max), svc::SystemInfoType_InitialProcessIdRange, svc::InvalidHandle, svc::InitialProcessIdRangeInfo_Maximum)); AMS_ABORT_UNLESS(0 < g_initial_process_id_min); AMS_ABORT_UNLESS(g_initial_process_id_min <= g_initial_process_id_max); /* Get current procss id. */ R_ABORT_UNLESS(svc::GetProcessId(std::addressof(g_current_process_id), svc::PseudoHandle::CurrentProcess)); /* Set initialized. */ g_initialized = true; } } } #endif } std::shared_ptr<ProgramInfo> ProgramInfo::GetProgramInfoForInitialProcess() { class ProgramInfoHelper : public ProgramInfo { public: ProgramInfoHelper(const void *data, s64 data_size, const void *desc, s64 desc_size) : ProgramInfo(data, data_size, desc, desc_size) { /* ... */ } }; AMS_FUNCTION_LOCAL_STATIC(std::shared_ptr<ProgramInfo>, s_initial_program_info, std::allocate_shared<ProgramInfoHelper>(StaticAllocatorForProgramInfoForInitialProcess<char>{}, FileAccessControlForInitialProgram, sizeof(FileAccessControlForInitialProgram), FileAccessControlDescForInitialProgram, sizeof(FileAccessControlDescForInitialProgram))); return s_initial_program_info; } bool IsInitialProgram(u64 process_id) { #if defined(ATMOSPHERE_OS_HORIZON) /* Initialize/sanity check. */ InitializeInitialAndCurrentProcessId(); AMS_ABORT_UNLESS(g_initial_process_id_min > 0); /* Check process id in range. */ return g_initial_process_id_min <= process_id && process_id <= g_initial_process_id_max; #elif defined(ATMOSPHERE_OS_WINDOWS) || defined(ATMOSPHERE_OS_LINUX) || defined(ATMOSPHERE_OS_MACOS) AMS_UNUSED(process_id); return true; #else #error "Unknown os for fssrv::impl::IsInitialProgram" #endif } bool IsCurrentProcess(u64 process_id) { #if defined(ATMOSPHERE_OS_HORIZON) /* Initialize. */ InitializeInitialAndCurrentProcessId(); return process_id == g_current_process_id; #elif defined(ATMOSPHERE_OS_WINDOWS) || defined(ATMOSPHERE_OS_LINUX) || defined(ATMOSPHERE_OS_MACOS) AMS_UNUSED(process_id); return true; #else #error "Unknown os for fssrv::impl::IsCurrentProcess" #endif } }
5,542
C++
.cpp
99
45.565657
353
0.657929
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,415
fssrv_program_registry_manager.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssrv/impl/fssrv_program_registry_manager.cpp
/* * Copyright (c) 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 "fssrv_program_registry_manager.hpp" namespace ams::fssrv::impl { Result ProgramRegistryManager::RegisterProgram(u64 process_id, u64 program_id, u8 storage_id, const void *data, s64 data_size, const void *desc, s64 desc_size) { /* Allocate a new node. */ std::unique_ptr<ProgramInfoNode> new_node(new ProgramInfoNode()); R_UNLESS(new_node != nullptr, fs::ResultAllocationMemoryFailedInProgramRegistryManagerA()); /* Create a new program info. */ { /* Allocate the new info. */ auto new_info = fssystem::AllocateShared<ProgramInfo>(process_id, program_id, storage_id, data, data_size, desc, desc_size); R_UNLESS(new_info != nullptr, fs::ResultAllocationMemoryFailedInProgramRegistryManagerA()); /* Set the info in the node. */ new_node->program_info = std::move(new_info); } /* Acquire exclusive access to the registry. */ std::scoped_lock lk(m_mutex); /* Check that the process isn't already in the registry. */ for (const auto &node : m_program_info_list) { R_UNLESS(!node.program_info->Contains(process_id), fs::ResultInvalidArgument()); } /* Add the node to the registry. */ m_program_info_list.push_back(*new_node.release()); R_SUCCEED(); } Result ProgramRegistryManager::UnregisterProgram(u64 process_id) { /* Acquire exclusive access to the registry. */ std::scoped_lock lk(m_mutex); /* Try to find and remove the process's node. */ for (auto &node : m_program_info_list) { if (node.program_info->Contains(process_id)) { m_program_info_list.erase(m_program_info_list.iterator_to(node)); delete std::addressof(node); R_SUCCEED(); } } /* We couldn't find/unregister the process's node. */ R_THROW(fs::ResultInvalidArgument()); } Result ProgramRegistryManager::GetProgramInfo(std::shared_ptr<ProgramInfo> *out, u64 process_id) { /* Acquire exclusive access to the registry. */ std::scoped_lock lk(m_mutex); /* Check if we're getting permissions for an initial program. */ if (IsInitialProgram(process_id)) { *out = ProgramInfo::GetProgramInfoForInitialProcess(); R_SUCCEED(); } /* Find a matching node. */ for (const auto &node : m_program_info_list) { if (node.program_info->Contains(process_id)) { *out = node.program_info; R_SUCCEED(); } } /* We didn't find the program info. */ R_THROW(fs::ResultProgramInfoNotFound()); } Result ProgramRegistryManager::GetProgramInfoByProgramId(std::shared_ptr<ProgramInfo> *out, u64 program_id) { /* Acquire exclusive access to the registry. */ std::scoped_lock lk(m_mutex); /* Find a matching node. */ for (const auto &node : m_program_info_list) { if (node.program_info->GetProgramIdValue() == program_id) { *out = node.program_info; R_SUCCEED(); } } /* We didn't find the program info. */ R_THROW(fs::ResultProgramInfoNotFound()); } }
3,987
C++
.cpp
86
37.813953
165
0.631376
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,416
fssrv_local_file_system_creator.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssrv/fscreator/fssrv_local_file_system_creator.cpp
/* * Copyright (c) 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::fscreator { Result LocalFileSystemCreator::Create(std::shared_ptr<fs::fsa::IFileSystem> *out, const fs::Path &path, bool case_sensitive, bool ensure_root, Result on_path_not_found) { /* Check that we're configured for development. */ R_UNLESS(m_is_development, fs::ResultPermissionDeniedForCreateHostFileSystem()); /* Allocate a local filesystem. */ auto local_fs = fs::AllocateShared<fssystem::LocalFileSystem>(); R_UNLESS(local_fs != nullptr, fs::ResultAllocationMemoryFailedInLocalFileSystemCreatorA()); /* If we're supposed to make sure the root path exists, do so. */ if (ensure_root) { /* Sanity check that the path will be possible to create. */ AMS_ASSERT(!path.IsEmpty()); /* Initialize the local fs with an empty path. */ fs::Path empty_path; R_TRY(empty_path.InitializeAsEmpty()); R_TRY(local_fs->Initialize(empty_path, fssystem::PathCaseSensitiveMode_CaseInsensitive)); /* Ensure the directory exists. */ if (const Result ensure_result = fssystem::EnsureDirectory(local_fs.get(), path); R_FAILED(ensure_result)) { if (R_SUCCEEDED(on_path_not_found)) { R_THROW(ensure_result); } else { R_THROW(on_path_not_found); } } } /* Initialize the local filesystem. */ R_TRY_CATCH(local_fs->Initialize(path, case_sensitive ? fssystem::PathCaseSensitiveMode_CaseSensitive : fssystem::PathCaseSensitiveMode_CaseInsensitive)) { R_CATCH(fs::ResultPathNotFound) { if (R_SUCCEEDED(on_path_not_found)) { R_THROW(R_CURRENT_RESULT); } else { R_THROW(on_path_not_found); } } } R_END_TRY_CATCH; /* Set the output fs. */ *out = std::move(local_fs); R_SUCCEED(); } }
2,677
C++
.cpp
55
39.472727
174
0.633372
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,417
fssrv_storage_on_nca_creator.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssrv/fscreator/fssrv_storage_on_nca_creator.cpp
/* * Copyright (c) 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::fscreator { Result StorageOnNcaCreator::Create(std::shared_ptr<fs::IStorage> *out, std::shared_ptr<fssystem::IAsynchronousAccessSplitter> *out_splitter, fssystem::NcaFsHeaderReader *out_header_reader, std::shared_ptr<fssystem::NcaReader> nca_reader, s32 index) { /* Create a fs driver. */ fssystem::NcaFileSystemDriver nca_fs_driver(nca_reader, m_allocator, m_buffer_manager, m_hash_generator_factory_selector); /* Open the storage. */ std::shared_ptr<fs::IStorage> storage; std::shared_ptr<fssystem::IAsynchronousAccessSplitter> splitter; R_TRY(nca_fs_driver.OpenStorage(std::addressof(storage), std::addressof(splitter), out_header_reader, index)); /* Set the out storage. */ *out = std::move(storage); *out_splitter = std::move(splitter); R_SUCCEED(); } Result StorageOnNcaCreator::CreateWithPatch(std::shared_ptr<fs::IStorage> *out, std::shared_ptr<fssystem::IAsynchronousAccessSplitter> *out_splitter, fssystem::NcaFsHeaderReader *out_header_reader, std::shared_ptr<fssystem::NcaReader> original_nca_reader, std::shared_ptr<fssystem::NcaReader> current_nca_reader, s32 index) { /* Create a fs driver. */ fssystem::NcaFileSystemDriver nca_fs_driver(original_nca_reader, current_nca_reader, m_allocator, m_buffer_manager, m_hash_generator_factory_selector); /* Open the storage. */ std::shared_ptr<fs::IStorage> storage; std::shared_ptr<fssystem::IAsynchronousAccessSplitter> splitter; R_TRY(nca_fs_driver.OpenStorage(std::addressof(storage), std::addressof(splitter), out_header_reader, index)); /* Set the out storage. */ *out = std::move(storage); *out_splitter = std::move(splitter); R_SUCCEED(); } Result StorageOnNcaCreator::CreateNcaReader(std::shared_ptr<fssystem::NcaReader> *out, std::shared_ptr<fs::IStorage> storage) { /* Create a reader. */ std::shared_ptr reader = fssystem::AllocateShared<fssystem::NcaReader>(); R_UNLESS(reader != nullptr, fs::ResultAllocationMemoryFailedInStorageOnNcaCreatorB()); /* Initialize the reader. */ R_TRY(reader->Initialize(std::move(storage), m_nca_crypto_cfg, m_nca_compression_cfg, m_hash_generator_factory_selector)); /* Set the output. */ *out = std::move(reader); R_SUCCEED(); } #if !defined(ATMOSPHERE_BOARD_NINTENDO_NX) Result StorageOnNcaCreator::CreateWithContext(std::shared_ptr<fs::IStorage> *out, std::shared_ptr<fssystem::IAsynchronousAccessSplitter> *out_splitter, fssystem::NcaFsHeaderReader *out_header_reader, void *ctx, std::shared_ptr<fssystem::NcaReader> nca_reader, s32 index) { /* Create a fs driver. */ fssystem::NcaFileSystemDriver nca_fs_driver(nca_reader, m_allocator, m_buffer_manager, m_hash_generator_factory_selector); /* Open the storage. */ std::shared_ptr<fs::IStorage> storage; std::shared_ptr<fssystem::IAsynchronousAccessSplitter> splitter; R_TRY(nca_fs_driver.OpenStorageWithContext(std::addressof(storage), std::addressof(splitter), out_header_reader, index, static_cast<fssystem::NcaFileSystemDriver::StorageContext *>(ctx))); /* Set the out storage. */ *out = std::move(storage); *out_splitter = std::move(splitter); R_SUCCEED(); } Result StorageOnNcaCreator::CreateWithPatchWithContext(std::shared_ptr<fs::IStorage> *out, std::shared_ptr<fssystem::IAsynchronousAccessSplitter> *out_splitter, fssystem::NcaFsHeaderReader *out_header_reader, void *ctx, std::shared_ptr<fssystem::NcaReader> original_nca_reader, std::shared_ptr<fssystem::NcaReader> current_nca_reader, s32 index) { /* Create a fs driver. */ fssystem::NcaFileSystemDriver nca_fs_driver(original_nca_reader, current_nca_reader, m_allocator, m_buffer_manager, m_hash_generator_factory_selector); /* Open the storage. */ std::shared_ptr<fs::IStorage> storage; std::shared_ptr<fssystem::IAsynchronousAccessSplitter> splitter; R_TRY(nca_fs_driver.OpenStorageWithContext(std::addressof(storage), std::addressof(splitter), out_header_reader, index, static_cast<fssystem::NcaFileSystemDriver::StorageContext *>(ctx))); /* Set the out storage. */ *out = std::move(storage); *out_splitter = std::move(splitter); R_SUCCEED(); } Result StorageOnNcaCreator::CreateByRawStorage(std::shared_ptr<fs::IStorage> *out, std::shared_ptr<fssystem::IAsynchronousAccessSplitter> *out_splitter, const fssystem::NcaFsHeaderReader *header_reader, std::shared_ptr<fs::IStorage> raw_storage, void *ctx, std::shared_ptr<fssystem::NcaReader> nca_reader) { /* Create a fs driver. */ fssystem::NcaFileSystemDriver nca_fs_driver(nca_reader, m_allocator, m_buffer_manager, m_hash_generator_factory_selector); /* Open the storage. */ auto *storage_ctx = static_cast<fssystem::NcaFileSystemDriver::StorageContext *>(ctx); R_TRY(nca_fs_driver.CreateStorageByRawStorage(out, header_reader, std::move(raw_storage), storage_ctx)); /* Update the splitter. */ if (storage_ctx->compressed_storage != nullptr) { *out_splitter = storage_ctx->compressed_storage; } R_SUCCEED(); } #endif }
6,025
C++
.cpp
90
59.733333
351
0.704937
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,418
fssrv_rom_file_system_creator.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssrv/fscreator/fssrv_rom_file_system_creator.cpp
/* * Copyright (c) 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::fscreator { namespace { class RomFileSystemWithBuffer : public ::ams::fssystem::RomFsFileSystem { private: void *m_meta_cache_buffer; size_t m_meta_cache_buffer_size; MemoryResource *m_allocator; public: explicit RomFileSystemWithBuffer(MemoryResource *mr) : m_meta_cache_buffer(nullptr), m_allocator(mr) { /* ... */ } ~RomFileSystemWithBuffer() { if (m_meta_cache_buffer != nullptr) { m_allocator->Deallocate(m_meta_cache_buffer, m_meta_cache_buffer_size); } } Result Initialize(std::shared_ptr<fs::IStorage> storage) { /* Check if the buffer is eligible for cache. */ size_t buffer_size = 0; if (R_FAILED(RomFsFileSystem::GetRequiredWorkingMemorySize(std::addressof(buffer_size), storage.get())) || buffer_size == 0 || buffer_size >= 128_KB) { R_RETURN(RomFsFileSystem::Initialize(std::move(storage), nullptr, 0, false)); } /* Allocate a buffer. */ m_meta_cache_buffer = m_allocator->Allocate(buffer_size); if (m_meta_cache_buffer == nullptr) { R_RETURN(RomFsFileSystem::Initialize(std::move(storage), nullptr, 0, false)); } /* Initialize with cache buffer. */ m_meta_cache_buffer_size = buffer_size; R_RETURN(RomFsFileSystem::Initialize(std::move(storage), m_meta_cache_buffer, m_meta_cache_buffer_size, true)); } }; } Result RomFileSystemCreator::Create(std::shared_ptr<fs::fsa::IFileSystem> *out, std::shared_ptr<fs::IStorage> storage) { /* Allocate a filesystem. */ std::shared_ptr fs = fssystem::AllocateShared<RomFileSystemWithBuffer>(m_allocator); R_UNLESS(fs != nullptr, fs::ResultAllocationMemoryFailedInRomFileSystemCreatorA()); /* Initialize the filesystem. */ R_TRY(fs->Initialize(std::move(storage))); /* Set the output. */ *out = std::move(fs); R_SUCCEED(); } }
2,955
C++
.cpp
58
39.5
171
0.601733
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,419
fssrv_subdirectory_file_system_creator.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssrv/fscreator/fssrv_subdirectory_file_system_creator.cpp
/* * Copyright (c) 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::fscreator { Result SubDirectoryFileSystemCreator::Create(std::shared_ptr<fs::fsa::IFileSystem> *out, std::shared_ptr<fs::fsa::IFileSystem> base_fs, const fs::Path &path) { /* Verify that we can the directory on the base filesystem. */ { std::unique_ptr<fs::fsa::IDirectory> sub_dir; R_TRY(base_fs->OpenDirectory(std::addressof(sub_dir), path, fs::OpenDirectoryMode_Directory)); } /* Allocate a SubDirectoryFileSystem. */ auto sub_dir_fs = fs::AllocateShared<fssystem::SubDirectoryFileSystem>(std::move(base_fs)); R_UNLESS(sub_dir_fs != nullptr, fs::ResultAllocationMemoryFailedInSubDirectoryFileSystemCreatorA()); /* Initialize the new filesystem. */ R_TRY(sub_dir_fs->Initialize(path)); /* Return the new filesystem. */ *out = std::move(sub_dir_fs); R_SUCCEED(); } }
1,579
C++
.cpp
33
42.606061
163
0.698701
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,420
fssrv_partition_file_system_creator.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fssrv/fscreator/fssrv_partition_file_system_creator.cpp
/* * Copyright (c) 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::fscreator { Result PartitionFileSystemCreator::Create(std::shared_ptr<fs::fsa::IFileSystem> *out, std::shared_ptr<fs::IStorage> storage) { /* Allocate a filesystem. */ std::shared_ptr fs = fssystem::AllocateShared<fssystem::PartitionFileSystem>(); R_UNLESS(fs != nullptr, fs::ResultAllocationMemoryFailedInPartitionFileSystemCreatorA()); /* Initialize the filesystem. */ R_TRY(fs->Initialize(std::move(storage))); /* Set the output. */ *out = std::move(fs); R_SUCCEED(); } }
1,237
C++
.cpp
28
39.928571
130
0.711794
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,421
crypto_csrng.os.horizon.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/crypto/crypto_csrng.os.horizon.cpp
/* * Copyright (c) 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::crypto { namespace { constinit bool g_initialized = false; constinit os::SdkMutex g_lock; void InitializeCsrng() { AMS_ASSERT(!g_initialized); R_ABORT_UNLESS(sm::Initialize()); R_ABORT_UNLESS(::csrngInitialize()); } } void GenerateCryptographicallyRandomBytes(void *dst, size_t dst_size) { if (AMS_UNLIKELY(!g_initialized)) { std::scoped_lock lk(g_lock); if (AMS_LIKELY(!g_initialized)) { InitializeCsrng(); g_initialized = true; } } R_ABORT_UNLESS(::csrngGetRandomBytes(dst, dst_size)); } }
1,355
C++
.cpp
37
30.243243
76
0.658518
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,422
crypto_csrng.os.windows.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/crypto/crypto_csrng.os.windows.cpp
/* * Copyright (c) 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/windows.hpp> #include <ntstatus.h> #include <bcrypt.h> namespace ams::crypto { void GenerateCryptographicallyRandomBytes(void *dst, size_t dst_size) { const auto status = ::BCryptGenRandom(nullptr, static_cast<PUCHAR>(dst), dst_size, BCRYPT_USE_SYSTEM_PREFERRED_RNG); AMS_ABORT_UNLESS(status == STATUS_SUCCESS); } }
1,029
C++
.cpp
25
38.52
124
0.749251
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false