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
7,533
fssystem_subdirectory_filesystem.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/fssystem/fssystem_subdirectory_filesystem.hpp
/* * 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/>. */ #pragma once #include <stratosphere/fs/fs_common.hpp> #include <stratosphere/fs/fsa/fs_ifile.hpp> #include <stratosphere/fs/fsa/fs_idirectory.hpp> #include <stratosphere/fs/fsa/fs_ifilesystem.hpp> #include <stratosphere/fs/impl/fs_newable.hpp> namespace ams::fssystem { /* ACCURATE_TO_VERSION: 13.4.0.0 */ class SubDirectoryFileSystem : public fs::fsa::IFileSystem, public fs::impl::Newable { NON_COPYABLE(SubDirectoryFileSystem); private: std::shared_ptr<fs::fsa::IFileSystem> m_shared_fs; fs::fsa::IFileSystem * const m_base_fs; fs::Path m_root_path; public: SubDirectoryFileSystem(std::shared_ptr<fs::fsa::IFileSystem> fs) : m_shared_fs(std::move(fs)), m_base_fs(m_shared_fs.get()), m_root_path() { /* ... */ } SubDirectoryFileSystem(fs::fsa::IFileSystem *fs) : m_shared_fs(), m_base_fs(fs), m_root_path() { /* ... */ } Result Initialize(const fs::Path &path) { R_RETURN(m_root_path.Initialize(path)); } private: Result ResolveFullPath(fs::Path *out, const fs::Path &path) { R_RETURN(out->Combine(m_root_path, path)); } public: virtual Result DoCreateFile(const fs::Path &path, s64 size, int option) override { fs::Path full_path; R_TRY(this->ResolveFullPath(std::addressof(full_path), path)); R_RETURN(m_base_fs->CreateFile(full_path, size, option)); } virtual Result DoDeleteFile(const fs::Path &path) override { fs::Path full_path; R_TRY(this->ResolveFullPath(std::addressof(full_path), path)); R_RETURN(m_base_fs->DeleteFile(full_path)); } virtual Result DoCreateDirectory(const fs::Path &path) override { fs::Path full_path; R_TRY(this->ResolveFullPath(std::addressof(full_path), path)); R_RETURN(m_base_fs->CreateDirectory(full_path)); } virtual Result DoDeleteDirectory(const fs::Path &path) override { fs::Path full_path; R_TRY(this->ResolveFullPath(std::addressof(full_path), path)); R_RETURN(m_base_fs->DeleteDirectory(full_path)); } virtual Result DoDeleteDirectoryRecursively(const fs::Path &path) override { fs::Path full_path; R_TRY(this->ResolveFullPath(std::addressof(full_path), path)); R_RETURN(m_base_fs->DeleteDirectoryRecursively(full_path)); } virtual Result DoRenameFile(const fs::Path &old_path, const fs::Path &new_path) override { fs::Path old_full_path; fs::Path new_full_path; R_TRY(this->ResolveFullPath(std::addressof(old_full_path), old_path)); R_TRY(this->ResolveFullPath(std::addressof(new_full_path), new_path)); R_RETURN(m_base_fs->RenameFile(old_full_path, new_full_path)); } virtual Result DoRenameDirectory(const fs::Path &old_path, const fs::Path &new_path) override { fs::Path old_full_path; fs::Path new_full_path; R_TRY(this->ResolveFullPath(std::addressof(old_full_path), old_path)); R_TRY(this->ResolveFullPath(std::addressof(new_full_path), new_path)); R_RETURN(m_base_fs->RenameDirectory(old_full_path, new_full_path)); } virtual Result DoGetEntryType(fs::DirectoryEntryType *out, const fs::Path &path) override { fs::Path full_path; R_TRY(this->ResolveFullPath(std::addressof(full_path), path)); R_RETURN(m_base_fs->GetEntryType(out, full_path)); } virtual Result DoOpenFile(std::unique_ptr<fs::fsa::IFile> *out_file, const fs::Path &path, fs::OpenMode mode) override { fs::Path full_path; R_TRY(this->ResolveFullPath(std::addressof(full_path), path)); R_RETURN(m_base_fs->OpenFile(out_file, full_path, mode)); } virtual Result DoOpenDirectory(std::unique_ptr<fs::fsa::IDirectory> *out_dir, const fs::Path &path, fs::OpenDirectoryMode mode) override { fs::Path full_path; R_TRY(this->ResolveFullPath(std::addressof(full_path), path)); R_RETURN(m_base_fs->OpenDirectory(out_dir, full_path, mode)); } virtual Result DoCommit() override { R_RETURN(m_base_fs->Commit()); } virtual Result DoGetFreeSpaceSize(s64 *out, const fs::Path &path) override { fs::Path full_path; R_TRY(this->ResolveFullPath(std::addressof(full_path), path)); R_RETURN(m_base_fs->GetFreeSpaceSize(out, full_path)); } virtual Result DoGetTotalSpaceSize(s64 *out, const fs::Path &path) override { fs::Path full_path; R_TRY(this->ResolveFullPath(std::addressof(full_path), path)); R_RETURN(m_base_fs->GetTotalSpaceSize(out, full_path)); } virtual Result DoCleanDirectoryRecursively(const fs::Path &path) override { fs::Path full_path; R_TRY(this->ResolveFullPath(std::addressof(full_path), path)); R_RETURN(m_base_fs->CleanDirectoryRecursively(full_path)); } virtual Result DoGetFileTimeStampRaw(fs::FileTimeStampRaw *out, const fs::Path &path) override { fs::Path full_path; R_TRY(this->ResolveFullPath(std::addressof(full_path), path)); R_RETURN(m_base_fs->GetFileTimeStampRaw(out, full_path)); } virtual Result DoQueryEntry(char *dst, size_t dst_size, const char *src, size_t src_size, fs::fsa::QueryId query, const fs::Path &path) override { fs::Path full_path; R_TRY(this->ResolveFullPath(std::addressof(full_path), path)); R_RETURN(m_base_fs->QueryEntry(dst, dst_size, src, src_size, query, full_path)); } /* These aren't accessible as commands. */ virtual Result DoCommitProvisionally(s64 counter) override { R_RETURN(m_base_fs->CommitProvisionally(counter)); } virtual Result DoRollback() override { R_RETURN(m_base_fs->Rollback()); } virtual Result DoFlush() override { R_RETURN(m_base_fs->Flush()); } }; }
7,370
C++
.h
138
40.688406
158
0.593077
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
7,534
fssystem_speed_emulation_configuration.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/fssystem/fssystem_speed_emulation_configuration.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/fs/fs_speed_emulation.hpp> namespace ams::fssystem { /* ACCURATE_TO_VERSION: Unknown */ class SpeedEmulationConfiguration { public: static void SetSpeedEmulationMode(::ams::fs::SpeedEmulationMode mode); static ::ams::fs::SpeedEmulationMode GetSpeedEmulationMode(); }; }
1,012
C++
.h
26
35.538462
82
0.739308
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
7,535
fssystem_compressed_storage.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/fssystem/fssystem_compressed_storage.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/fssystem/fssystem_asynchronous_access.hpp> #include <stratosphere/fssystem/fssystem_bucket_tree.hpp> #include <stratosphere/fssystem/fssystem_compression_common.hpp> #include <stratosphere/fs/fs_i_buffer_manager.hpp> #include <stratosphere/fssystem/impl/fssystem_block_cache_manager.hpp> namespace ams::fssystem { /* ACCURATE_TO_VERSION: 13.4.0.0 */ class CompressedStorage : public ::ams::fs::IStorage, public ::ams::fssystem::IAsynchronousAccessSplitter, public ::ams::fs::impl::Newable { NON_COPYABLE(CompressedStorage); NON_MOVEABLE(CompressedStorage); public: static constexpr size_t NodeSize = 16_KB; using IAllocator = BucketTree::IAllocator; struct Entry { s64 virt_offset; s64 phys_offset; CompressionType compression_type; s32 phys_size; s64 GetPhysicalSize() const { return this->phys_size; } }; static_assert(util::is_pod<Entry>::value); static_assert(sizeof(Entry) == 0x18); public: static constexpr s64 QueryNodeStorageSize(s32 entry_count) { return BucketTree::QueryNodeStorageSize(NodeSize, sizeof(Entry), entry_count); } static constexpr s64 QueryEntryStorageSize(s32 entry_count) { return BucketTree::QueryEntryStorageSize(NodeSize, sizeof(Entry), entry_count); } private: class CompressedStorageCore { NON_COPYABLE(CompressedStorageCore); NON_MOVEABLE(CompressedStorageCore); private: size_t m_block_size_max; size_t m_continuous_reading_size_max; BucketTree m_table; fs::SubStorage m_data_storage; GetDecompressorFunction m_get_decompressor_function; public: CompressedStorageCore() : m_table(), m_data_storage() { /* ... */ } ~CompressedStorageCore() { this->Finalize(); } public: Result Initialize(MemoryResource *bktr_allocator, fs::SubStorage data_storage, fs::SubStorage node_storage, fs::SubStorage entry_storage, s32 bktr_entry_count, size_t block_size_max, size_t continuous_reading_size_max, GetDecompressorFunction get_decompressor) { /* Check pre-conditions. */ AMS_ASSERT(bktr_allocator != nullptr); AMS_ASSERT(0 < block_size_max); AMS_ASSERT(block_size_max <= continuous_reading_size_max); AMS_ASSERT(get_decompressor != nullptr); /* Initialize our entry table. */ R_TRY(m_table.Initialize(bktr_allocator, node_storage, entry_storage, NodeSize, sizeof(Entry), bktr_entry_count)); /* Set our other fields. */ m_block_size_max = block_size_max; m_continuous_reading_size_max = continuous_reading_size_max; m_data_storage = data_storage; m_get_decompressor_function = get_decompressor; R_SUCCEED(); } void Finalize() { if (this->IsInitialized()) { m_table.Finalize(); m_data_storage = fs::SubStorage(); } } fs::IStorage *GetDataStorage() { return std::addressof(m_data_storage); } Result GetDataStorageSize(s64 *out) { /* Check pre-conditions. */ AMS_ASSERT(out != nullptr); /* Get size. */ R_RETURN(m_data_storage.GetSize(out)); } BucketTree &GetEntryTable() { return m_table; } Result GetEntryList(Entry *out_entries, s32 *out_read_count, s32 max_entry_count, s64 offset, s64 size) { /* Check pre-conditions. */ AMS_ASSERT(offset >= 0); AMS_ASSERT(size >= 0); AMS_ASSERT(this->IsInitialized()); /* Check that we can output the count. */ R_UNLESS(out_read_count != nullptr, fs::ResultNullptrArgument()); /* Check that we have anything to read at all. */ R_SUCCEED_IF(size == 0); /* Check that either we have a buffer, or this is to determine how many we need. */ if (max_entry_count != 0) { R_UNLESS(out_entries != nullptr, fs::ResultNullptrArgument()); } /* Get the table offsets. */ BucketTree::Offsets table_offsets; R_TRY(m_table.GetOffsets(std::addressof(table_offsets))); /* Validate arguments. */ 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>()->virt_offset; R_UNLESS(0 <= entry_offset && table_offsets.IsInclude(entry_offset), fs::ResultUnexpectedInCompressedStorageA()); } /* Get the entries. */ const auto end_offset = offset + size; s32 read_count = 0; while (visitor.Get<Entry>()->virt_offset < end_offset) { /* If we should be setting the output, do so. */ if (max_entry_count != 0) { /* Ensure we only read as many entries as we can. */ if (read_count >= max_entry_count) { break; } /* Set the current output entry. */ out_entries[read_count] = *visitor.Get<Entry>(); } /* Increase the read count. */ ++read_count; /* If we're at the end, we're done. */ if (!visitor.CanMoveNext()) { break; } /* Move to the next entry. */ R_TRY(visitor.MoveNext()); } /* Set the output read count. */ *out_read_count = read_count; R_SUCCEED(); } Result GetSize(s64 *out) { /* Check pre-conditions. */ AMS_ASSERT(out != nullptr); /* Get our table offsets. */ BucketTree::Offsets offsets; R_TRY(m_table.GetOffsets(std::addressof(offsets))); /* Set the output. */ *out = offsets.end_offset; R_SUCCEED(); } Result Invalidate() { /* Invalidate our entry table. */ R_TRY(m_table.InvalidateCache()); /* Invalidate our data storage. */ R_TRY(m_data_storage.OperateRange(fs::OperationId::Invalidate, 0, std::numeric_limits<s64>::max())); R_SUCCEED(); } Result OperatePerEntry(s64 offset, s64 size, auto f) { /* Check pre-conditions. */ AMS_ASSERT(offset >= 0); AMS_ASSERT(size >= 0); AMS_ASSERT(this->IsInitialized()); /* Succeed if there's nothing to operate on. */ R_SUCCEED_IF(size == 0); /* Get the table offsets. */ BucketTree::Offsets table_offsets; R_TRY(m_table.GetOffsets(std::addressof(table_offsets))); /* Validate arguments. */ 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>()->virt_offset; R_UNLESS(0 <= entry_offset && table_offsets.IsInclude(entry_offset), fs::ResultUnexpectedInCompressedStorageA()); } /* Prepare to operate in chunks. */ 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.virt_offset; R_UNLESS(cur_entry_offset <= cur_offset, fs::ResultUnexpectedInCompressedStorageA()); /* Get and validate the next entry offset. */ s64 next_entry_offset; if (visitor.CanMoveNext()) { R_TRY(visitor.MoveNext()); next_entry_offset = visitor.Get<Entry>()->virt_offset; R_UNLESS(table_offsets.IsInclude(next_entry_offset), fs::ResultUnexpectedInCompressedStorageA()); } else { next_entry_offset = table_offsets.end_offset; } R_UNLESS(cur_offset < next_entry_offset, fs::ResultUnexpectedInCompressedStorageA()); /* 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); AMS_ASSERT(data_size > 0); /* Determine how much is left. */ const auto remaining_size = end_offset - cur_offset; const auto cur_size = std::min<s64>(remaining_size, data_size - data_offset); AMS_ASSERT(cur_size <= size); /* Get the data storage size. */ s64 storage_size = 0; R_TRY(m_data_storage.GetSize(std::addressof(storage_size))); /* Check that our read remains naively physically in bounds. */ R_UNLESS(0 <= cur_entry.phys_offset && cur_entry.phys_offset <= storage_size, fs::ResultUnexpectedInCompressedStorageC()); /* If we have any compression, verify that we remain physically in bounds. */ if (cur_entry.compression_type != CompressionType_None) { R_UNLESS(cur_entry.phys_offset + cur_entry.GetPhysicalSize() <= storage_size, fs::ResultUnexpectedInCompressedStorageC()); } /* Check that block alignment requirements are met. */ if (CompressionTypeUtility::IsBlockAlignmentRequired(cur_entry.compression_type)) { R_UNLESS(util::IsAligned(cur_entry.phys_offset, CompressionBlockAlignment), fs::ResultUnexpectedInCompressedStorageA()); } /* Invoke the operator. */ bool is_continuous = true; R_TRY(f(std::addressof(is_continuous), cur_entry, data_size, data_offset, cur_size)); /* If not continuous, we're done. */ if (!is_continuous) { break; } /* Advance. */ cur_offset += cur_size; } R_SUCCEED(); } Result OperateRange(s64 offset, s64 size, auto f) { /* Get the table offsets. */ BucketTree::Offsets table_offsets; R_TRY(m_table.GetOffsets(std::addressof(table_offsets))); /* Validate arguments. */ R_UNLESS(table_offsets.IsInclude(offset, size), fs::ResultOutOfRange()); /* If our table is empty, we have nothing to operate on. */ R_SUCCEED_IF(m_table.IsEmpty()); /* Operate on the range. */ s64 required_access_physical_offset = 0; s64 required_access_physical_size = 0; R_TRY(this->OperatePerEntry(offset, size, [&] (bool *out_continuous, const Entry &entry, s64 virtual_data_size, s64 data_offset, s64 read_size) -> Result { AMS_UNUSED(virtual_data_size); /* Determine the physical extents. */ s64 physical_offset, physical_size; if (CompressionTypeUtility::IsRandomAccessible(entry.compression_type)) { physical_offset = entry.phys_offset + data_offset; physical_size = read_size; } else { physical_offset = entry.phys_offset; physical_size = entry.GetPhysicalSize(); } /* If we have a pending data storage operation, perform it if we have to. */ const s64 required_access_physical_end = required_access_physical_offset + required_access_physical_size; if (required_access_physical_size > 0) { /* Check that we can can coalesce this operation with the previous one; if we can't, we need to perform it. */ if (!(required_access_physical_end <= physical_offset && physical_offset <= util::AlignUp(required_access_physical_end, CompressionBlockAlignment))) { R_TRY(f(required_access_physical_offset, required_access_physical_size)); required_access_physical_size = 0; } } /* If we need to access the data storage, update our storage access parameters. */ if (CompressionTypeUtility::IsDataStorageAccessRequired(entry.compression_type)) { /* Update the required access parameters. */ if (required_access_physical_size > 0) { required_access_physical_size += physical_size + (physical_offset - required_access_physical_end); } else { required_access_physical_offset = physical_offset; required_access_physical_size = physical_size; } } else { /* Verify that we're allowed to be operating on the non-data-storage-access type. */ R_UNLESS(entry.compression_type == CompressionType_Zeros, fs::ResultUnexpectedInCompressedStorageB()); } /* We're always continuous. */ *out_continuous = true; R_SUCCEED(); })); /* If we have a pending operation, perform it. */ if (required_access_physical_size > 0) { R_TRY(f(required_access_physical_offset, required_access_physical_size)); } R_SUCCEED(); } Result QueryAppropriateOffsetForAsynchronousAccess(s64 *out, s64 offset, s64 access_size, s64 alignment_size) { /* Check pre-conditions. */ AMS_ASSERT(offset >= 0); AMS_ASSERT(this->IsInitialized()); /* Check that we can write to the output. */ R_UNLESS(out != nullptr, fs::ResultNullptrArgument()); /* Get the table offsets. */ BucketTree::Offsets table_offsets; R_TRY(m_table.GetOffsets(std::addressof(table_offsets))); /* Validate arguments. */ R_UNLESS(table_offsets.IsInclude(offset, 1), fs::ResultOutOfRange()); /* Operate on the range. */ s64 required_access_physical_offset = 0; s64 required_access_physical_size = 0; s64 required_access_physical_end = 0; s64 appropriate_virtual_offset = offset; R_TRY(this->OperatePerEntry(offset, table_offsets.end_offset - offset, [&] (bool *out_continuous, const Entry &entry, s64 virtual_data_size, s64 data_offset, s64 read_size) -> Result { AMS_UNUSED(virtual_data_size); /* Determine the physical extents. */ s64 physical_offset, physical_size; if (CompressionTypeUtility::IsRandomAccessible(entry.compression_type)) { physical_offset = entry.phys_offset + data_offset; physical_size = read_size; } else { physical_offset = entry.phys_offset; physical_size = entry.GetPhysicalSize(); } /* If we don't need to access the data storage, update our storage access parameters simply. */ if (!CompressionTypeUtility::IsDataStorageAccessRequired(entry.compression_type)) { /* Verify that we're allowed to be operating on the non-data-storage-access type. */ R_UNLESS(entry.compression_type == CompressionType_Zeros, fs::ResultUnexpectedInCompressedStorageB()); /* No access is required, so we can advance the offset freely. */ appropriate_virtual_offset += read_size; /* A read to zeros is always continuous. */ *out_continuous = true; R_SUCCEED(); } /* Update the required access parameters. */ if (required_access_physical_size > 0) { /* Check that we can can coalesce this operation with the previous one; if we can't, we need to account for the gap. */ if ((required_access_physical_end <= physical_offset && physical_offset <= util::AlignUp(required_access_physical_end, CompressionBlockAlignment))) { const s64 gap_size = physical_offset - required_access_physical_end; if (required_access_physical_size + gap_size > access_size) { *out_continuous = false; R_SUCCEED(); } required_access_physical_size += gap_size; } } else { required_access_physical_offset = physical_offset; } /* If we're within the access bounds, we want to continue on. */ if (physical_size + required_access_physical_size <= access_size) { required_access_physical_size += physical_size; required_access_physical_end = physical_offset + physical_size; appropriate_virtual_offset += read_size; *out_continuous = true; R_SUCCEED(); } /* We're no longer within the access bounds, so we won't be continuous. */ *out_continuous = false; /* Ensure we account for block alignment. */ if (CompressionTypeUtility::IsBlockAlignmentRequired(entry.compression_type)) { if (appropriate_virtual_offset == offset) { appropriate_virtual_offset += read_size; access_size = std::max<s64>(access_size, read_size); } } else { /* Get the default splitter. */ auto * const default_splitter = fssystem::IAsynchronousAccessSplitter::GetDefaultAsynchronousAccessSplitter(); /* Query for an appropriate offset. */ s64 appropriate_physical_offset = 0; R_TRY(default_splitter->QueryAppropriateOffset(std::addressof(appropriate_physical_offset), physical_offset, access_size - required_access_physical_size, alignment_size)); /* Use it, if we should. */ if (const auto gap_size = appropriate_physical_offset - physical_offset; gap_size > 0) { appropriate_virtual_offset += gap_size; required_access_physical_size += gap_size; } } R_SUCCEED(); })); /* Check that the offset is actually appropriate. */ AMS_ASSERT(offset <= appropriate_virtual_offset && appropriate_virtual_offset <= table_offsets.end_offset); AMS_ASSERT(0 <= required_access_physical_size && required_access_physical_size <= access_size); /* Set the output. */ *out = appropriate_virtual_offset; R_SUCCEED(); } Result QueryRange(void *dst, size_t dst_size, s64 offset, s64 size) { /* Check arguments. */ R_UNLESS(dst != nullptr, fs::ResultNullptrArgument()); R_UNLESS(dst_size == sizeof(fs::QueryRangeInfo), fs::ResultInvalidArgument()); /* If we have nothing to query, succeed immediately. */ R_SUCCEED_IF(size <= 0); /* Operate on the range. */ fs::QueryRangeInfo full_info; full_info.Clear(); R_TRY(this->OperateRange(offset, size, [&](s64 offset, s64 size) -> Result { /* Operate on our data storage. */ fs::QueryRangeInfo cur_info; R_TRY(m_data_storage.OperateRange(std::addressof(cur_info), sizeof(cur_info), fs::OperationId::QueryRange, offset, size, nullptr, 0)); /* Merge the info. */ full_info.Merge(cur_info); R_SUCCEED(); })); R_SUCCEED(); } public: using ReadImplFunction = util::IFunction<Result(void *, size_t)>; using ReadFunction = util::IFunction<Result(size_t, const ReadImplFunction &)>; public: Result Read(s64 offset, s64 size, const ReadFunction &read_func) { /* Check pre-conditions. */ AMS_ASSERT(offset >= 0); AMS_ASSERT(this->IsInitialized()); /* Succeed immediately, if we have nothing to read. */ R_SUCCEED_IF(size == 0); /* Declare read lambda. */ constexpr int EntriesCountMax = 0x80; struct Entries { CompressionType compression_type; u32 gap_from_prev; u32 physical_size; u32 virtual_size; }; Entries entries[EntriesCountMax]; s32 entry_count = 0; Entry prev_entry = { .virt_offset = -1, }; bool will_allocate_pooled_buffer = false; s64 required_access_physical_offset = 0; s64 required_access_physical_size = 0; auto PerformRequiredRead = [&]() -> Result { /* If there are no entries, we have nothing to do. */ R_SUCCEED_IF(entry_count == 0); /* Get the remaining size in a convenient form. */ const size_t total_required_size = static_cast<size_t>(required_access_physical_size); /* Perform the read based on whether we need to allocate a buffer. */ if (will_allocate_pooled_buffer) { /* Allocate a pooled buffer. */ fssystem::PooledBuffer pooled_buffer; if (pooled_buffer.GetAllocatableSizeMax() >= total_required_size) { pooled_buffer.Allocate(total_required_size, m_block_size_max); } else { pooled_buffer.AllocateParticularlyLarge(std::min<size_t>(total_required_size, PooledBuffer::GetAllocatableParticularlyLargeSizeMax()), m_block_size_max); } /* Read each of the entries. */ for (s32 entry_idx = 0; entry_idx < entry_count; ++entry_idx) { /* Determine the current read size. */ bool will_use_pooled_buffer = false; const size_t cur_read_size = [&] () ALWAYS_INLINE_LAMBDA -> size_t { if (const size_t target_entry_size = static_cast<size_t>(entries[entry_idx].physical_size) + static_cast<size_t>(entries[entry_idx].gap_from_prev); target_entry_size <= pooled_buffer.GetSize()) { /* We'll be using the pooled buffer. */ will_use_pooled_buffer = true; /* Determine how much we can read. */ const size_t max_size = std::min<size_t>(required_access_physical_size, pooled_buffer.GetSize()); size_t read_size = 0; for (auto n = entry_idx; n < entry_count; ++n) { const size_t cur_entry_size = static_cast<size_t>(entries[n].physical_size) + static_cast<size_t>(entries[n].gap_from_prev); if (read_size + cur_entry_size > max_size) { break; } read_size += cur_entry_size; } return read_size; } else { /* If we don't fit, we must be uncompressed. */ AMS_ASSERT(entries[entry_idx].compression_type == CompressionType_None); /* We can perform the whole of an uncompressed read directly. */ return entries[entry_idx].virtual_size; } }(); /* Perform the read based on whether or not we'll use the pooled buffer. */ if (will_use_pooled_buffer) { /* Read the compressed data into the pooled buffer. */ auto * const buffer = pooled_buffer.GetBuffer(); R_TRY(m_data_storage.Read(required_access_physical_offset, buffer, cur_read_size)); /* Temporarily increase our thread priority, while we decompress the data. */ ScopedThreadPriorityChanger cp(+1, ScopedThreadPriorityChanger::Mode::Relative); /* Decompress the data. */ size_t buffer_offset; for (buffer_offset = 0; entry_idx < entry_count && ((static_cast<size_t>(entries[entry_idx].physical_size) + static_cast<size_t>(entries[entry_idx].gap_from_prev)) == 0 || buffer_offset < cur_read_size); buffer_offset += entries[entry_idx++].physical_size) { /* Advance by the relevant gap. */ buffer_offset += entries[entry_idx].gap_from_prev; const auto compression_type = entries[entry_idx].compression_type; switch (compression_type) { case CompressionType_None: { /* Check that we can remain within bounds. */ AMS_ASSERT(buffer_offset + entries[entry_idx].virtual_size <= cur_read_size); /* Perform no decompression. */ R_TRY(read_func(entries[entry_idx].virtual_size, util::MakeIFunction([&] (void *dst, size_t dst_size) -> Result { /* Check that the size is valid. */ AMS_ASSERT(dst_size == entries[entry_idx].virtual_size); AMS_UNUSED(dst_size); /* We have no compression, so just copy the data out. */ std::memcpy(dst, buffer + buffer_offset, entries[entry_idx].virtual_size); R_SUCCEED(); }))); } break; case CompressionType_Zeros: { /* Check that we can remain within bounds. */ AMS_ASSERT(buffer_offset <= cur_read_size); /* Zero the memory. */ R_TRY(read_func(entries[entry_idx].virtual_size, util::MakeIFunction([&] (void *dst, size_t dst_size) -> Result { /* Check that the size is valid. */ AMS_ASSERT(dst_size == entries[entry_idx].virtual_size); AMS_UNUSED(dst_size); /* The data is zeroes, so zero the buffer. */ std::memset(dst, 0, entries[entry_idx].virtual_size); R_SUCCEED(); }))); } break; default: { /* Check that we can remain within bounds. */ AMS_ASSERT(buffer_offset + entries[entry_idx].physical_size <= cur_read_size); /* Get the decompressor. */ const auto decompressor = this->GetDecompressor(compression_type); R_UNLESS(decompressor != nullptr, fs::ResultUnexpectedInCompressedStorageB()); /* Decompress the data. */ R_TRY(read_func(entries[entry_idx].virtual_size, util::MakeIFunction([&] (void *dst, size_t dst_size) -> Result { /* Check that the size is valid. */ AMS_ASSERT(dst_size == entries[entry_idx].virtual_size); AMS_UNUSED(dst_size); /* Perform the decompression. */ R_RETURN(decompressor(dst, entries[entry_idx].virtual_size, buffer + buffer_offset, entries[entry_idx].physical_size)); }))); } break; } } /* Check that we processed the correct amount of data. */ AMS_ASSERT(buffer_offset == cur_read_size); } else { /* Account for the gap from the previous entry. */ required_access_physical_offset += entries[entry_idx].gap_from_prev; required_access_physical_size -= entries[entry_idx].gap_from_prev; /* We don't need the buffer (as the data is uncompressed), so just execute the read. */ R_TRY(read_func(cur_read_size, util::MakeIFunction([&] (void *dst, size_t dst_size) -> Result { /* Check that the size is valid. */ AMS_ASSERT(dst_size == cur_read_size); AMS_UNUSED(dst_size); /* Perform the read. */ R_RETURN(m_data_storage.Read(required_access_physical_offset, dst, cur_read_size)); }))); } /* Advance on. */ required_access_physical_offset += cur_read_size; required_access_physical_size -= cur_read_size; } /* Verify that we have nothing remaining to read. */ AMS_ASSERT(required_access_physical_size == 0); R_SUCCEED(); } else { /* We don't need a buffer, so just execute the read. */ R_TRY(read_func(total_required_size, util::MakeIFunction([&] (void *dst, size_t dst_size) -> Result { /* Check that the size is valid. */ AMS_ASSERT(dst_size == total_required_size); AMS_UNUSED(dst_size); /* Perform the read. */ R_RETURN(m_data_storage.Read(required_access_physical_offset, dst, total_required_size)); }))); } R_SUCCEED(); }; R_TRY(this->OperatePerEntry(offset, size, [&] (bool *out_continuous, const Entry &entry, s64 virtual_data_size, s64 data_offset, s64 read_size) -> Result { /* Determine the physical extents. */ s64 physical_offset, physical_size; if (CompressionTypeUtility::IsRandomAccessible(entry.compression_type)) { physical_offset = entry.phys_offset + data_offset; physical_size = read_size; } else { physical_offset = entry.phys_offset; physical_size = entry.GetPhysicalSize(); } /* If we have a pending data storage operation, perform it if we have to. */ const s64 required_access_physical_end = required_access_physical_offset + required_access_physical_size; if (required_access_physical_size > 0) { const bool required_by_gap = !(required_access_physical_end <= physical_offset && physical_offset <= util::AlignUp(required_access_physical_end, CompressionBlockAlignment)); const bool required_by_continuous_size = ((physical_size + physical_offset) - required_access_physical_end) + required_access_physical_size > static_cast<s64>(m_continuous_reading_size_max); const bool required_by_entry_count = entry_count == EntriesCountMax; if (required_by_gap || required_by_continuous_size || required_by_entry_count) { /* Check that our planned access is sane. */ AMS_ASSERT(!will_allocate_pooled_buffer || required_access_physical_size <= static_cast<s64>(m_continuous_reading_size_max)); /* Perform the required read. */ R_TRY(PerformRequiredRead()); /* Reset our requirements. */ prev_entry.virt_offset = -1; required_access_physical_size = 0; entry_count = 0; will_allocate_pooled_buffer = false; } } /* Sanity check that we're within bounds on entries. */ AMS_ASSERT(entry_count < EntriesCountMax); /* Determine if a buffer allocation is needed. */ if (entry.compression_type != CompressionType_None || (prev_entry.virt_offset >= 0 && entry.virt_offset - prev_entry.virt_offset != entry.phys_offset - prev_entry.phys_offset)) { will_allocate_pooled_buffer = true; } /* If we need to access the data storage, update our required access parameters. */ if (CompressionTypeUtility::IsDataStorageAccessRequired(entry.compression_type)) { /* If the data is compressed, ensure the access is sane. */ if (entry.compression_type != CompressionType_None) { R_UNLESS(data_offset == 0, fs::ResultInvalidOffset()); R_UNLESS(virtual_data_size == read_size, fs::ResultInvalidSize()); R_UNLESS(entry.GetPhysicalSize() <= static_cast<s64>(m_block_size_max), fs::ResultUnexpectedInCompressedStorageD()); } /* Update the required access parameters. */ s64 gap_from_prev; if (required_access_physical_size > 0) { gap_from_prev = physical_offset - required_access_physical_end; } else { gap_from_prev = 0; required_access_physical_offset = physical_offset; } required_access_physical_size += physical_size + gap_from_prev; /* Create an entry to access the data storage. */ entries[entry_count++] = { .compression_type = entry.compression_type, .gap_from_prev = static_cast<u32>(gap_from_prev), .physical_size = static_cast<u32>(physical_size), .virtual_size = static_cast<u32>(read_size), }; } else { /* Verify that we're allowed to be operating on the non-data-storage-access type. */ R_UNLESS(entry.compression_type == CompressionType_Zeros, fs::ResultUnexpectedInCompressedStorageB()); /* If we have entries, create a fake entry for the zero region. */ if (entry_count != 0) { /* We need to have a physical size. */ R_UNLESS(entry.GetPhysicalSize() != 0, fs::ResultUnexpectedInCompressedStorageD()); /* Create a fake entry. */ entries[entry_count++] = { .compression_type = CompressionType_Zeros, .gap_from_prev = 0, .physical_size = 0, .virtual_size = static_cast<u32>(read_size), }; } else { /* We have no entries, so we can just perform the read. */ R_TRY(read_func(static_cast<size_t>(read_size), util::MakeIFunction([&] (void *dst, size_t dst_size) -> Result { /* Check the space we should zero is correct. */ AMS_ASSERT(dst_size == static_cast<size_t>(read_size)); AMS_UNUSED(dst_size); /* Zero the memory. */ std::memset(dst, 0, read_size); R_SUCCEED(); }))); } } /* Set the previous entry. */ prev_entry = entry; /* We're continuous. */ *out_continuous = true; R_SUCCEED(); })); /* If we still have a pending access, perform it. */ if (required_access_physical_size != 0) { R_TRY(PerformRequiredRead()); } R_SUCCEED(); } private: DecompressorFunction GetDecompressor(CompressionType type) const { /* Check that we can get a decompressor for the type. */ if (CompressionTypeUtility::IsUnknownType(type)) { return nullptr; } /* Get the decompressor. */ return m_get_decompressor_function(type); } bool IsInitialized() const { return m_table.IsInitialized(); } }; class CacheManager { NON_COPYABLE(CacheManager); NON_MOVEABLE(CacheManager); private: struct Range { s64 offset; size_t size; s64 GetEndOffset() const { return this->offset + this->size; } bool IsIncluded(s64 ofs) const { return this->offset <= ofs && ofs < this->GetEndOffset(); } }; static_assert(util::is_pod<Range>::value); struct CacheEntry { Range range; fs::IBufferManager::CacheHandle handle; uintptr_t memory_address; u32 memory_size; bool is_valid; bool is_cached; u16 lru_counter; void Invalidate() { /* ... */ } bool IsAllocated() const { return this->is_valid && this->handle != 0; } bool IsIncluded(s64 offset) const { return this->is_valid && this->range.IsIncluded(offset); } bool IsWriteBack() const { return false; } }; static_assert(util::is_pod<CacheEntry>::value); struct AccessRange { s64 virtual_offset; s64 virtual_size; u32 physical_size; bool is_block_alignment_required; s64 GetEndVirtualOffset() const { return this->virtual_offset + this->virtual_size; } }; static_assert(util::is_pod<AccessRange>::value); using BlockCacheManager = ::ams::fssystem::impl::BlockCacheManager<CacheEntry, fs::IBufferManager>; using CacheIndex = BlockCacheManager::CacheIndex; private: size_t m_cache_size_unk_0; size_t m_cache_size_unk_1; os::SdkMutex m_mutex; BlockCacheManager m_block_cache_manager; s64 m_storage_size = 0; public: CacheManager() = default; ~CacheManager() { this->Finalize(); } public: Result Initialize(fs::IBufferManager *cache_allocator, s64 storage_size, size_t cache_size_0, size_t cache_size_1, size_t max_cache_entries) { /* Initialize our block cache manager. */ R_TRY(m_block_cache_manager.Initialize(cache_allocator, max_cache_entries)); /* Set our fields. */ m_cache_size_unk_0 = cache_size_0; m_cache_size_unk_1 = cache_size_1; m_storage_size = storage_size; R_SUCCEED(); } void Finalize() { /* If necessary, invalidate anything we have cached. */ if (m_block_cache_manager.IsInitialized()) { this->Invalidate(); } /* Finalize our block cache manager. */ m_block_cache_manager.Finalize(); } void Invalidate() { /* Acquire exclusive access to our manager. */ std::scoped_lock lk(m_mutex); /* Invalidate all entries. */ return m_block_cache_manager.Invalidate(); } Result Read(CompressedStorageCore &core, s64 offset, void *buffer, size_t size) { /* If we have nothing to read, succeed. */ R_SUCCEED_IF(size == 0); /* Check that we have a buffer to read into. */ R_UNLESS(buffer != nullptr, fs::ResultNullptrArgument()); /* Check that the read is in bounds. */ R_UNLESS(offset <= m_storage_size, fs::ResultInvalidOffset()); /* Determine how much we can read. */ const size_t read_size = std::min<size_t>(size, m_storage_size - offset); /* Create head/tail ranges. */ AccessRange head_range = {}; AccessRange tail_range = {}; bool is_tail_set = false; /* Operate to determine the head range. */ R_TRY(core.OperatePerEntry(offset, 1, [&] (bool *out_continuous, const Entry &entry, s64 virtual_data_size, s64 data_offset, s64 data_read_size) -> Result { AMS_UNUSED(data_offset, data_read_size); /* Set the head range. */ head_range = { .virtual_offset = entry.virt_offset, .virtual_size = virtual_data_size, .physical_size = static_cast<u32>(entry.phys_size), .is_block_alignment_required = CompressionTypeUtility::IsBlockAlignmentRequired(entry.compression_type), }; /* If required, set the tail range. */ if (static_cast<s64>(offset + read_size) <= entry.virt_offset + virtual_data_size) { tail_range = { .virtual_offset = entry.virt_offset, .virtual_size = virtual_data_size, .physical_size = static_cast<u32>(entry.phys_size), .is_block_alignment_required = CompressionTypeUtility::IsBlockAlignmentRequired(entry.compression_type), }; is_tail_set = true; } /* We only want to determine the head range, so we're not continuous. */ *out_continuous = false; R_SUCCEED(); })); /* If necessary, determine the tail range. */ if (!is_tail_set) { R_TRY(core.OperatePerEntry(offset + read_size - 1, 1, [&] (bool *out_continuous, const Entry &entry, s64 virtual_data_size, s64 data_offset, s64 data_read_size) -> Result { AMS_UNUSED(data_offset, data_read_size); /* Set the tail range. */ tail_range = { .virtual_offset = entry.virt_offset, .virtual_size = virtual_data_size, .physical_size = static_cast<u32>(entry.phys_size), .is_block_alignment_required = CompressionTypeUtility::IsBlockAlignmentRequired(entry.compression_type), }; /* We only want to determine the tail range, so we're not continuous. */ *out_continuous = false; R_SUCCEED(); })); } /* Begin performing the accesses. */ s64 cur_offset = offset; size_t cur_size = read_size; char *cur_dst = static_cast<char *>(buffer); /* If we can use the head/tail cache, do so. */ if (m_block_cache_manager.GetCount() > 0) { /* Read the head cache. */ R_TRY(this->ReadHeadCache(core, cur_offset, cur_dst, cur_size, head_range, tail_range)); /* If we're now done, succeed. */ R_SUCCEED_IF(cur_size == 0); /* Read the tail cache. */ R_TRY(this->ReadTailCache(core, cur_offset, cur_dst, cur_size, head_range, tail_range)); /* If we're now done, succeed. */ R_SUCCEED_IF(cur_size == 0); } /* Determine our alignment. */ const bool head_unaligned = head_range.is_block_alignment_required && (cur_offset != head_range.virtual_offset || static_cast<s64>(cur_size) < head_range.virtual_size); const bool tail_unaligned = [&] () ALWAYS_INLINE_LAMBDA -> bool { if (tail_range.is_block_alignment_required) { if (static_cast<s64>(cur_size + cur_offset) == tail_range.GetEndVirtualOffset()) { return false; } else if (!head_unaligned) { return true; } else { return head_range.GetEndVirtualOffset() < static_cast<s64>(cur_size + cur_offset); } } else { return false; } }(); /* Determine start/end offsets. */ const s64 start_offset = head_range.is_block_alignment_required ? head_range.virtual_offset : cur_offset; const s64 end_offset = tail_range.is_block_alignment_required ? tail_range.GetEndVirtualOffset() : cur_offset + cur_size; /* Perform the read. */ bool is_burst_reading = false; R_TRY(core.Read(start_offset, end_offset - start_offset, util::MakeIFunction([&] (size_t size_buffer_required, const CompressedStorageCore::ReadImplFunction &read_impl) -> Result { /* Determine whether we're burst reading. */ const AccessRange *unaligned_range = nullptr; if (!is_burst_reading) { /* Check whether we're using head, tail, or none as unaligned. */ if (head_unaligned && head_range.virtual_offset <= cur_offset && cur_offset < head_range.GetEndVirtualOffset()) { unaligned_range = std::addressof(head_range); } else if (tail_unaligned && tail_range.virtual_offset <= cur_offset && cur_offset < tail_range.GetEndVirtualOffset()) { unaligned_range = std::addressof(tail_range); } else { is_burst_reading = true; } } AMS_ASSERT((is_burst_reading ^ (unaligned_range != nullptr))); /* Perform reading by burst, or not. */ if (is_burst_reading) { /* Check that the access is valid for burst reading. */ AMS_ASSERT(size_buffer_required <= cur_size); /* Perform the read. */ R_TRY(read_impl(cur_dst, size_buffer_required)); /* Advance. */ cur_dst += size_buffer_required; cur_offset += size_buffer_required; cur_size -= size_buffer_required; /* Determine whether we're going to continue burst reading. */ const s64 offset_aligned = tail_unaligned ? tail_range.virtual_offset : end_offset; AMS_ASSERT(cur_offset <= offset_aligned); if (offset_aligned <= cur_offset) { is_burst_reading = false; } } else { /* We're not burst reading, so we have some unaligned range. */ AMS_ASSERT(unaligned_range != nullptr); /* Check that the size is correct. */ AMS_ASSERT(size_buffer_required == static_cast<size_t>(unaligned_range->virtual_size)); /* Get a pooled buffer for our read. */ fssystem::PooledBuffer pooled_buffer; pooled_buffer.Allocate(size_buffer_required, size_buffer_required); /* Perform read. */ R_TRY(read_impl(pooled_buffer.GetBuffer(), size_buffer_required)); /* Copy the data we read to the destination. */ const size_t skip_size = cur_offset - unaligned_range->virtual_offset; const size_t copy_size = std::min<size_t>(cur_size, unaligned_range->GetEndVirtualOffset() - cur_offset); std::memcpy(cur_dst, pooled_buffer.GetBuffer() + skip_size, copy_size); /* Advance. */ cur_dst += copy_size; cur_offset += copy_size; cur_size -= copy_size; /* If we should, cache what we read. */ if (m_block_cache_manager.GetCount() > 0 && unaligned_range->physical_size > m_cache_size_unk_1) { CacheEntry entry; for (s64 ofs = unaligned_range->virtual_offset; ofs < unaligned_range->GetEndVirtualOffset(); ofs += entry.range.size) { /* Find or allocate buffer. */ fs::IBufferManager::MemoryRange memory_range; R_TRY(this->FindOrAllocateBuffer(std::addressof(memory_range), std::addressof(entry), ofs, unaligned_range->GetEndVirtualOffset() - ofs)); /* If not cached, cache the data. */ if (!entry.is_cached) { std::memcpy(reinterpret_cast<void *>(memory_range.first), pooled_buffer.GetBuffer() + (ofs - unaligned_range->virtual_offset), entry.range.size); entry.is_cached = true; } /* Store the associated buffer. */ this->StoreAssociateBuffer(memory_range, entry); } } } R_SUCCEED(); }))); R_SUCCEED(); } private: Result FindBuffer(fs::IBufferManager::MemoryRange *out, CacheEntry *out_entry, s64 offset) { /* Check pre-conditions. */ AMS_ASSERT(m_block_cache_manager.IsInitialized()); AMS_ASSERT(out != nullptr); AMS_ASSERT(out_entry != nullptr); /* Acquire exclusive access to our entries. */ std::scoped_lock lk(m_mutex); /* Find the buffer. */ R_RETURN(this->FindBufferImpl(out, out_entry, offset)); } Result FindBufferImpl(fs::IBufferManager::MemoryRange *out, CacheEntry *out_entry, s64 offset) { /* Check pre-conditions. */ AMS_ASSERT(m_mutex.IsLockedByCurrentThread()); /* Get our block cache count */ const auto count = m_block_cache_manager.GetCount(); /* Try to find the buffer. */ CacheIndex index; for (index = 0; index < count; ++index) { if (const auto &buffer = m_block_cache_manager[index]; buffer.IsAllocated() && buffer.IsIncluded(offset)) { break; } } /* Set the output. */ if (index != count) { /* Acquire the entry. */ m_block_cache_manager.AcquireCacheEntry(out_entry, out, index); if (out->first == 0) { *out = {}; *out_entry = {}; } } else { *out = {}; *out_entry = {}; } R_SUCCEED(); } Result FindOrAllocateBuffer(fs::IBufferManager::MemoryRange *out, CacheEntry *out_entry, s64 offset, size_t max_range_size) { /* Check pre-conditions. */ AMS_ASSERT(m_block_cache_manager.IsInitialized()); AMS_ASSERT(out != nullptr); AMS_ASSERT(out_entry != nullptr); /* Acquire exclusive access to our block cache manager. */ std::scoped_lock lk(m_mutex); /* Try to find the buffer. */ R_TRY(this->FindBufferImpl(out, out_entry, offset)); /* Determine the range size. */ const size_t range_size = std::min<size_t>(max_range_size, m_cache_size_unk_0); /* If necessary, allocate. */ if (out->first == 0) { R_TRY(fssystem::buffers::AllocateBufferUsingBufferManagerContext(out, m_block_cache_manager.GetAllocator(), range_size, fs::IBufferManager::BufferAttribute(0x20), [] (const fs::IBufferManager::MemoryRange &buffer) -> bool { return buffer.first != 0; }, AMS_CURRENT_FUNCTION_NAME)); /* Set the entry for the allocated buffer. */ out_entry->is_valid = out->first != 0; out_entry->is_cached = false; out_entry->handle = 0; out_entry->memory_address = 0; out_entry->memory_size = 0; out_entry->range.offset = offset; out_entry->range.size = range_size; out_entry->lru_counter = 0; } /* Check that the result is valid. */ AMS_ASSERT(out_entry->range.size <= out->second); R_SUCCEED(); } Result ReadHeadCache(CompressedStorageCore &core, s64 &offset, char *&buffer, size_t &size, AccessRange &head_range, const AccessRange &tail_range) { /* Check pre-conditions. */ AMS_ASSERT(buffer != nullptr); /* Read until we're done with the head cache */ while (head_range.virtual_size > 0 && head_range.virtual_offset < tail_range.GetEndVirtualOffset()) { /* Cache the access extents. */ s64 access_offset = offset; char *access_buf = buffer; size_t access_size = size; /* Determine the current access extents. */ s64 cur_offset = head_range.virtual_offset + util::AlignDown<s64>(access_offset - head_range.virtual_offset, m_cache_size_unk_0); while (cur_offset < head_range.GetEndVirtualOffset() && cur_offset < static_cast<s64>(offset + size)) { /* Find the relevant entry. */ fs::IBufferManager::MemoryRange memory_range = {}; CacheEntry entry = {}; R_TRY(this->FindBuffer(std::addressof(memory_range), std::addressof(entry), cur_offset)); /* If the entry isn't cached, we're done. */ R_SUCCEED_IF(!entry.is_cached); /* Otherwise, copy the cacheed data. */ const size_t copy_size = std::min<size_t>(access_size, entry.range.GetEndOffset() - access_offset); std::memcpy(access_buf, reinterpret_cast<const void *>(memory_range.first + access_offset - entry.range.offset), copy_size); /* Advance. */ access_buf += copy_size; access_offset += copy_size; access_size -= copy_size; cur_offset += entry.range.size; /* Store the associated buffer. */ this->StoreAssociateBuffer(memory_range, entry); } /* Update the output extents. */ buffer = access_buf; offset = access_offset; size = access_size; /* Determine the new head range. */ AccessRange new_head_range = { .virtual_offset = head_range.GetEndVirtualOffset(), .virtual_size = 0, .physical_size = 0, .is_block_alignment_required = true, }; if (head_range.GetEndVirtualOffset() == tail_range.virtual_offset) { /* We can use the tail range directly. */ new_head_range.virtual_size = tail_range.virtual_size; new_head_range.physical_size = tail_range.physical_size; new_head_range.is_block_alignment_required = tail_range.is_block_alignment_required; } else if (head_range.GetEndVirtualOffset() < tail_range.GetEndVirtualOffset()) { /* We need to find the new head range. */ R_TRY(core.OperatePerEntry(new_head_range.virtual_offset, 1, [&] (bool *out_continuous, const Entry &entry, s64 virtual_data_size, s64 data_offset, s64 data_read_size) -> Result { AMS_UNUSED(data_offset, data_read_size); /* If we can, use the current entry. */ if (entry.virt_offset < tail_range.GetEndVirtualOffset()) { new_head_range = { .virtual_offset = entry.virt_offset, .virtual_size = virtual_data_size, .physical_size = static_cast<u32>(entry.phys_size), .is_block_alignment_required = CompressionTypeUtility::IsBlockAlignmentRequired(entry.compression_type), }; } /* We only want to determine the new head range, so we're not continuous. */ *out_continuous = false; R_SUCCEED(); })); } /* Update the head range. */ head_range = new_head_range; } R_SUCCEED(); } Result ReadTailCache(CompressedStorageCore &core, s64 offset, char *buffer, size_t &size, const AccessRange &head_range, AccessRange &tail_range) { /* Check pre-conditions. */ AMS_ASSERT(buffer != nullptr); /* Read until we're done with the tail cache */ while (tail_range.virtual_offset >= offset) { /* Loop reading, while we can. */ const s64 dst_end_offset = offset + size; s64 cur_offset = tail_range.virtual_offset; while (cur_offset < dst_end_offset) { /* Find the relevant entry. */ fs::IBufferManager::MemoryRange memory_range = {}; CacheEntry entry = {}; R_TRY(this->FindBuffer(std::addressof(memory_range), std::addressof(entry), cur_offset)); /* If the entry isn't cached, we're done. */ R_SUCCEED_IF(!entry.is_cached); /* Sanity check our current access. */ AMS_ASSERT(offset <= entry.range.offset); /* Copy the cacheed data. */ const s64 cur_end_offset = std::min<s64>(dst_end_offset, entry.range.GetEndOffset()); std::memcpy(buffer + entry.range.offset - offset, reinterpret_cast<const void *>(memory_range.first), cur_end_offset - entry.range.offset); /* Advance. */ cur_offset += entry.range.size; /* Store the associated buffer. */ this->StoreAssociateBuffer(memory_range, entry); } /* Update the output extents. */ size -= std::min<s64>(dst_end_offset, tail_range.GetEndVirtualOffset()) - tail_range.virtual_offset; /* Update the tail range. */ bool new_tail_found = false; if (tail_range.virtual_offset - 1 >= 0) { /* We need to find the new tail range. */ R_TRY(core.OperatePerEntry(tail_range.virtual_offset - 1, 1, [&] (bool *out_continuous, const Entry &entry, s64 virtual_data_size, s64 data_offset, s64 data_read_size) -> Result { AMS_UNUSED(data_offset, data_read_size); /* If we can, use the current entry. */ if (head_range.virtual_offset != entry.virt_offset) { tail_range = { .virtual_offset = entry.virt_offset, .virtual_size = virtual_data_size, .physical_size = static_cast<u32>(entry.phys_size), .is_block_alignment_required = CompressionTypeUtility::IsBlockAlignmentRequired(entry.compression_type), }; new_tail_found = true; } /* We only want to determine the new head range, so we're not continuous. */ *out_continuous = false; R_SUCCEED(); })); } /* If we didn't find a new tail, write a default (and we're done). */ if (!new_tail_found) { tail_range = { .virtual_offset = tail_range.virtual_offset, .virtual_size = 0, .physical_size = 0, .is_block_alignment_required = true, }; break; } } R_SUCCEED(); } void StoreAssociateBuffer(const fs::IBufferManager::MemoryRange &memory_range, const CacheEntry &entry) { /* Check pre-conditions. */ AMS_ASSERT(m_block_cache_manager.GetCount() > 0); /* Acquire exclusive access to our manager. */ std::scoped_lock lk(m_mutex); /* Get empty cache index. */ CacheIndex empty_index, lru_index; m_block_cache_manager.GetEmptyCacheEntryIndex(std::addressof(empty_index), std::addressof(lru_index)); /* If nothing is empty, invalidate the least recently used entry. */ if (empty_index == BlockCacheManager::InvalidCacheIndex) { m_block_cache_manager.InvalidateCacheEntry(lru_index); empty_index = lru_index; } /* Set the entry. */ m_block_cache_manager.SetCacheEntry(empty_index, entry, memory_range); } }; private: CompressedStorageCore m_core; CacheManager m_cache_manager; public: CompressedStorage() = default; virtual ~CompressedStorage() { this->Finalize(); } Result Initialize(MemoryResource *bktr_allocator, fs::IBufferManager *cache_allocator, fs::SubStorage data_storage, fs::SubStorage node_storage, fs::SubStorage entry_storage, s32 bktr_entry_count, size_t block_size_max, size_t continuous_reading_size_max, GetDecompressorFunction get_decompressor, size_t cache_size_0, size_t cache_size_1, s32 max_cache_entries) { /* Initialize our core. */ R_TRY(m_core.Initialize(bktr_allocator, data_storage, node_storage, entry_storage, bktr_entry_count, block_size_max, continuous_reading_size_max, get_decompressor)); /* Get our core size. */ s64 core_size = 0; R_TRY(m_core.GetSize(std::addressof(core_size))); /* Initialize our cache manager. */ R_TRY(m_cache_manager.Initialize(cache_allocator, core_size, cache_size_0, cache_size_1, max_cache_entries)); R_SUCCEED(); } void Finalize() { m_cache_manager.Finalize(); m_core.Finalize(); } fs::IStorage *GetDataStorage() { return m_core.GetDataStorage(); } Result GetDataStorageSize(s64 *out) { R_RETURN(m_core.GetDataStorageSize(out)); } Result GetEntryList(Entry *out_entries, s32 *out_read_count, s32 max_entry_count, s64 offset, s64 size) { R_RETURN(m_core.GetEntryList(out_entries, out_read_count, max_entry_count, offset, size)); } fssystem::BucketTree &GetEntryTable() { return m_core.GetEntryTable(); } public: virtual Result QueryAppropriateOffset(s64 *out, s64 offset, s64 access_size, s64 alignment_size) override { R_RETURN(m_core.QueryAppropriateOffsetForAsynchronousAccess(out, offset, access_size, alignment_size)); } public: virtual Result Read(s64 offset, void *buffer, size_t size) override { R_RETURN(m_cache_manager.Read(m_core, offset, buffer, 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 { AMS_UNUSED(src, src_size); /* Check pre-conditions. */ AMS_ASSERT(offset >= 0); AMS_ASSERT(size >= 0); /* Perform the operation. */ switch (op_id) { case fs::OperationId::Invalidate: m_cache_manager.Invalidate(); R_TRY(m_core.Invalidate()); break; case fs::OperationId::QueryRange: R_TRY(m_core.QueryRange(dst, dst_size, offset, size)); break; default: R_THROW(fs::ResultUnsupportedOperateRangeForCompressedStorage()); } R_SUCCEED(); } virtual Result GetSize(s64 *out) override { R_RETURN(m_core.GetSize(out)); } virtual Result Flush() override { R_SUCCEED(); } virtual Result Write(s64 offset, const void *buffer, size_t size) override { AMS_UNUSED(offset, buffer, size); R_THROW(fs::ResultUnsupportedWriteForCompressedStorage()); } virtual Result SetSize(s64 size) override { AMS_UNUSED(size); /* NOTE: Is Nintendo returning the wrong result here? */ R_THROW(fs::ResultUnsupportedSetSizeForIndirectStorage()); } }; }
82,329
C++
.h
1,191
39.967254
376
0.432952
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
7,536
fssystem_thread_priority_changer.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/fssystem/fssystem_thread_priority_changer.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/os.hpp> namespace ams::fssystem { /* ACCURATE_TO_VERSION: Unknown */ class ScopedThreadPriorityChanger { public: enum class Mode { Absolute, Relative, }; private: os::ThreadType *m_thread; s32 m_priority; public: ALWAYS_INLINE explicit ScopedThreadPriorityChanger(s32 priority, Mode mode) : m_thread(os::GetCurrentThread()), m_priority(0) { const auto result_priority = std::min((mode == Mode::Relative) ? os::GetThreadPriority(m_thread) + priority : priority, os::LowestSystemThreadPriority); m_priority = os::ChangeThreadPriority(m_thread, result_priority); } ALWAYS_INLINE ~ScopedThreadPriorityChanger() { os::ChangeThreadPriority(m_thread, m_priority); } }; class ScopedThreadPriorityChangerByAccessPriority { public: enum class AccessMode { Read, Write, }; private: static s32 GetThreadPriorityByAccessPriority(AccessMode mode); private: ScopedThreadPriorityChanger m_scoped_changer; public: ALWAYS_INLINE explicit ScopedThreadPriorityChangerByAccessPriority(AccessMode mode) : m_scoped_changer(GetThreadPriorityByAccessPriority(mode), ScopedThreadPriorityChanger::Mode::Absolute) { /* ... */ } }; }
2,177
C++
.h
54
32.055556
202
0.6547
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
7,537
fssystem_block_cache_manager.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/fssystem/impl/fssystem_block_cache_manager.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/fs/impl/fs_newable.hpp> namespace ams::fssystem::impl { /* ACCURATE_TO_VERSION: 13.4.0.0 */ template<typename CacheEntryType, typename AllocatorType> class BlockCacheManager { NON_COPYABLE(BlockCacheManager); NON_MOVEABLE(BlockCacheManager); public: using MemoryRange = typename AllocatorType::MemoryRange; using CacheIndex = s32; using BufferAttribute = typename AllocatorType::BufferAttribute; static constexpr CacheIndex InvalidCacheIndex = -1; using CacheEntry = CacheEntryType; static_assert(util::is_pod<CacheEntry>::value); private: AllocatorType *m_allocator = nullptr; std::unique_ptr<CacheEntry[], ::ams::fs::impl::Deleter> m_entries{}; s32 m_max_cache_entry_count = 0; public: constexpr BlockCacheManager() = default; public: Result Initialize(AllocatorType *allocator, s32 max_entries) { /* Check pre-conditions. */ AMS_ASSERT(m_allocator == nullptr); AMS_ASSERT(m_entries == nullptr); AMS_ASSERT(allocator != nullptr); /* Setup our entries buffer, if necessary. */ if (max_entries > 0) { /* Create the entries. */ m_entries = fs::impl::MakeUnique<CacheEntry[]>(static_cast<size_t>(max_entries)); R_UNLESS(m_entries != nullptr, fs::ResultAllocationMemoryFailedMakeUnique()); /* Clear the entries. */ std::memset(m_entries.get(), 0, sizeof(CacheEntry) * max_entries); } /* Set fields. */ m_allocator = allocator; m_max_cache_entry_count = max_entries; R_SUCCEED(); } void Finalize() { /* Reset all fields. */ m_entries.reset(nullptr); m_allocator = nullptr; m_max_cache_entry_count = 0; } bool IsInitialized() const { return m_allocator != nullptr; } AllocatorType *GetAllocator() { return m_allocator; } s32 GetCount() const { return m_max_cache_entry_count; } void AcquireCacheEntry(CacheEntry *out_entry, MemoryRange *out_range, CacheIndex index) { /* Check pre-conditions. */ AMS_ASSERT(this->IsInitialized()); AMS_ASSERT(index < this->GetCount()); /* Get the entry. */ auto &entry = m_entries[index]; /* Set the out range. */ if (entry.IsWriteBack()) { *out_range = AllocatorType::MakeMemoryRange(entry.memory_address, entry.memory_size); } else { *out_range = m_allocator->AcquireCache(entry.handle); } /* Set the out entry. */ *out_entry = entry; /* Sanity check. */ AMS_ASSERT(out_entry->is_valid); AMS_ASSERT(out_entry->is_cached); /* Clear our local entry. */ entry.is_valid = false; entry.handle = 0; entry.memory_address = 0; entry.memory_size = 0; entry.lru_counter = 0; /* Update the out entry. */ out_entry->is_valid = true; out_entry->handle = 0; out_entry->memory_address = 0; out_entry->memory_size = 0; out_entry->lru_counter = 0; } bool ExistsRedundantCacheEntry(const CacheEntry &entry) const { /* Check pre-conditions. */ AMS_ASSERT(this->IsInitialized()); /* Iterate over all entries, checking if any contain our extents. */ for (auto i = 0; i < this->GetCount(); ++i) { if (const auto &cur_entry = m_entries[i]; cur_entry.IsAllocated()) { if (cur_entry.range.offset < entry.range.GetEndOffset() && entry.range.offset < cur_entry.range.GetEndOffset()) { return true; } } } return false; } void GetEmptyCacheEntryIndex(CacheIndex *out_empty, CacheIndex *out_lru) { /* Find empty and lru indices. */ CacheIndex empty = InvalidCacheIndex, lru = InvalidCacheIndex; for (auto i = 0; i < this->GetCount(); ++i) { if (auto &entry = m_entries[i]; entry.is_valid) { /* Get/Update the lru counter. */ if (entry.lru_counter != std::numeric_limits<decltype(entry.lru_counter)>::max()) { ++entry.lru_counter; } /* Update the lru index. */ if (lru == InvalidCacheIndex || m_entries[lru].lru_counter < entry.lru_counter) { lru = i; } } else { /* The entry is invalid, so we can update the empty index. */ if (empty == InvalidCacheIndex) { empty = i; } } } /* Set the output. */ *out_empty = empty; *out_lru = lru; } void Invalidate() { /* Check pre-conditions. */ AMS_ASSERT(this->IsInitialized()); /* Invalidate all entries. */ for (auto i = 0; i < this->GetCount(); ++i) { if (m_entries[i].is_valid) { this->InvalidateCacheEntry(i); } } } void InvalidateCacheEntry(CacheIndex index) { /* Check pre-conditions. */ AMS_ASSERT(this->IsInitialized()); AMS_ASSERT(index < this->GetCount()); /* Get the entry. */ auto &entry = m_entries[index]; AMS_ASSERT(entry.is_valid); /* If necessary, perform write-back. */ if (entry.IsWriteBack()) { AMS_ASSERT(entry.memory_address != 0 && entry.handle == 0); m_allocator->DeallocateBuffer(AllocatorType::MakeMemoryRange(entry.memory_address, entry.memory_size)); } else { AMS_ASSERT(entry.memory_address == 0 && entry.handle != 0); if (const auto memory_range = m_allocator->AcquireCache(entry.handle); memory_range.first) { m_allocator->DeallocateBuffer(memory_range); } } /* Set entry as invalid. */ entry.is_valid = false; entry.Invalidate(); } void RegisterCacheEntry(CacheIndex index, const MemoryRange &memory_range, const BufferAttribute &attribute) { /* Check pre-conditions. */ AMS_ASSERT(this->IsInitialized()); /* Register the entry. */ if (auto &entry = m_entries[index]; entry.IsWriteBack()) { entry.handle = 0; entry.memory_address = memory_range.first; entry.memory_size = memory_range.second; } else { entry.handle = m_allocator->RegisterCache(memory_range, attribute); entry.memory_address = 0; entry.memory_size = 0; } } void ReleaseCacheEntry(CacheEntry *entry, const MemoryRange &memory_range) { /* Check pre-conditions. */ AMS_ASSERT(this->IsInitialized()); /* Release the entry. */ m_allocator->DeallocateBuffer(memory_range); entry->is_valid = false; entry->is_cached = false; } void ReleaseCacheEntry(CacheIndex index, const MemoryRange &memory_range) { return this->ReleaseCacheEntry(std::addressof(m_entries[index]), memory_range); } bool SetCacheEntry(CacheIndex index, const CacheEntry &entry, const MemoryRange &memory_range, const BufferAttribute &attr) { /* Check pre-conditions. */ AMS_ASSERT(this->IsInitialized()); AMS_ASSERT(0 <= index && index < this->GetCount()); /* Write the entry. */ m_entries[index] = entry; /* Sanity check. */ AMS_ASSERT(entry.is_valid); AMS_ASSERT(entry.is_cached); AMS_ASSERT(entry.handle == 0); AMS_ASSERT(entry.memory_address == 0); /* Register or release. */ if (this->ExistsRedundantCacheEntry(entry)) { this->ReleaseCacheEntry(index, memory_range); return false; } else { this->RegisterCacheEntry(index, memory_range, attr); return true; } } bool SetCacheEntry(CacheIndex index, const CacheEntry &entry, const MemoryRange &memory_range) { const BufferAttribute attr{}; return this->SetCacheEntry(index, entry, memory_range, attr); } void SetFlushing(CacheIndex index, bool en) { if constexpr (requires { m_entries[index].is_flushing; }) { m_entries[index].is_flushing = en; } } void SetWriteBack(CacheIndex index, bool en) { if constexpr (requires { m_entries[index].is_write_back; }) { m_entries[index].is_write_back = en; } } const CacheEntry &operator[](CacheIndex index) const { /* Check pre-conditions. */ AMS_ASSERT(this->IsInitialized()); AMS_ASSERT(0 <= index && index < this->GetCount()); return m_entries[index]; } }; }
11,180
C++
.h
232
32.288793
137
0.505275
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
7,538
fssystem_i_save_file_system_driver.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/fssystem/save/fssystem_i_save_file_system_driver.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> namespace ams::fssystem::save { /* TODO */ }
723
C++
.h
20
34.1
76
0.748571
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
7,539
fssystem_buffer_manager_utils.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/fssystem/buffers/fssystem_buffer_manager_utils.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/os.hpp> #include <stratosphere/fs/fs_i_buffer_manager.hpp> namespace ams::fssystem::buffers { namespace impl { constexpr inline auto RetryWait = TimeSpan::FromMilliSeconds(10); } /* ACCURATE_TO_VERSION: Unknown */ template<typename F, typename OnFailure> Result DoContinuouslyUntilBufferIsAllocated(F f, OnFailure on_failure, const char *function_name) { constexpr auto BufferAllocationRetryLogCountMax = 10; constexpr auto BufferAllocationRetryLogInterval = 100; for (auto count = 1; true; count++) { R_TRY_CATCH(f()) { R_CATCH(fs::ResultBufferAllocationFailed) { if ((1 <= count && count <= BufferAllocationRetryLogCountMax) || ((count % BufferAllocationRetryLogInterval) == 0)) { /* TODO: Log */ AMS_UNUSED(function_name); } R_TRY(on_failure()); os::SleepThread(impl::RetryWait); continue; } } R_END_TRY_CATCH; R_SUCCEED(); } } template<typename F> Result DoContinuouslyUntilBufferIsAllocated(F f, const char *function_name) { R_TRY(DoContinuouslyUntilBufferIsAllocated(f, []() ALWAYS_INLINE_LAMBDA { R_SUCCEED(); }, function_name)); R_SUCCEED(); } /* ACCURATE_TO_VERSION: Unknown */ class BufferManagerContext { private: bool m_needs_blocking; public: constexpr BufferManagerContext() : m_needs_blocking(false) { /* ... */ } public: bool IsNeedBlocking() const { return m_needs_blocking; } void SetNeedBlocking(bool need) { m_needs_blocking = need; } }; void RegisterBufferManagerContext(const BufferManagerContext *context); BufferManagerContext *GetBufferManagerContext(); void EnableBlockingBufferManagerAllocation(); /* ACCURATE_TO_VERSION: Unknown */ class ScopedBufferManagerContextRegistration { private: BufferManagerContext m_cur_context; const BufferManagerContext *m_old_context; public: ALWAYS_INLINE explicit ScopedBufferManagerContextRegistration() { m_old_context = GetBufferManagerContext(); if (m_old_context != nullptr) { m_cur_context = *m_old_context; } RegisterBufferManagerContext(std::addressof(m_cur_context)); } ALWAYS_INLINE ~ScopedBufferManagerContextRegistration() { RegisterBufferManagerContext(m_old_context); } }; /* ACCURATE_TO_VERSION: Unknown */ template<typename IsValidBufferFunction> Result AllocateBufferUsingBufferManagerContext(fs::IBufferManager::MemoryRange *out, fs::IBufferManager *buffer_manager, size_t size, const fs::IBufferManager::BufferAttribute attribute, IsValidBufferFunction is_valid_buffer, const char *func_name) { AMS_ASSERT(out != nullptr); AMS_ASSERT(buffer_manager != nullptr); AMS_ASSERT(func_name != nullptr); /* Clear the output. */ *out = fs::IBufferManager::MakeMemoryRange(0, 0); /* Get the context. */ auto context = GetBufferManagerContext(); auto AllocateBufferImpl = [=]() -> Result { auto buffer = buffer_manager->AllocateBuffer(size, attribute); if (!is_valid_buffer(buffer)) { if (buffer.first != 0) { buffer_manager->DeallocateBuffer(buffer.first, buffer.second); } R_THROW(fs::ResultBufferAllocationFailed()); } *out = buffer; R_SUCCEED(); }; if (context == nullptr || !context->IsNeedBlocking()) { /* If there's no context (or we don't need to block), just allocate the buffer. */ R_TRY(AllocateBufferImpl()); } else { /* Otherwise, try to allocate repeatedly. */ R_TRY(DoContinuouslyUntilBufferIsAllocated(AllocateBufferImpl, func_name)); } AMS_ASSERT(out->first != 0); R_SUCCEED(); } }
4,892
C++
.h
110
34.9
254
0.62949
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
7,540
fssystem_file_system_buffer_manager.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/fssystem/buffers/fssystem_file_system_buffer_manager.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/lmem.hpp> #include <stratosphere/fs/fs_memory_management.hpp> #include <stratosphere/fs/fs_i_buffer_manager.hpp> #include <stratosphere/fssystem/buffers/fssystem_file_system_buddy_heap.hpp> namespace ams::fssystem { /* ACCURATE_TO_VERSION: Unknown */ class FileSystemBufferManager : public fs::IBufferManager { NON_COPYABLE(FileSystemBufferManager); NON_MOVEABLE(FileSystemBufferManager); public: using BuddyHeap = FileSystemBuddyHeap; private: class CacheHandleTable { NON_COPYABLE(CacheHandleTable); NON_MOVEABLE(CacheHandleTable); private: class Entry { private: CacheHandle m_handle; uintptr_t m_address; size_t m_size; BufferAttribute m_attr; public: constexpr void Initialize(CacheHandle h, uintptr_t a, size_t sz, BufferAttribute t) { m_handle = h; m_address = a; m_size = sz; m_attr = t; } constexpr CacheHandle GetHandle() const { return m_handle; } constexpr uintptr_t GetAddress() const { return m_address; } constexpr size_t GetSize() const { return m_size; } constexpr BufferAttribute GetBufferAttribute() const { return m_attr; } }; class AttrInfo : public util::IntrusiveListBaseNode<AttrInfo>, public ::ams::fs::impl::Newable { NON_COPYABLE(AttrInfo); NON_MOVEABLE(AttrInfo); private: s32 m_level; s32 m_cache_count; size_t m_cache_size; public: constexpr AttrInfo(s32 l, s32 cc, size_t cs) : m_level(l), m_cache_count(cc), m_cache_size(cs) { /* ... */ } constexpr s32 GetLevel() const { return m_level; } constexpr s32 GetCacheCount() const { return m_cache_count; } constexpr void IncrementCacheCount() { ++m_cache_count; } constexpr void DecrementCacheCount() { --m_cache_count; } constexpr size_t GetCacheSize() const { return m_cache_size; } constexpr void AddCacheSize(size_t diff) { m_cache_size += diff; } constexpr void SubtractCacheSize(size_t diff) { AMS_ASSERT(m_cache_size >= diff); m_cache_size -= diff; } using Newable::operator new; using Newable::operator delete; static ALWAYS_INLINE void *operator new(size_t, void *p) noexcept { return p; } static ALWAYS_INLINE void operator delete(void *, size_t, void*) noexcept { /* ... */ } }; using AttrListTraits = util::IntrusiveListBaseTraits<AttrInfo>; using AttrList = typename AttrListTraits::ListType; private: std::unique_ptr<char[], ::ams::fs::impl::Deleter> m_internal_entry_buffer; char *m_external_entry_buffer; size_t m_entry_buffer_size; Entry *m_entries; s32 m_entry_count; s32 m_entry_count_max; AttrList m_attr_list; char *m_external_attr_info_buffer; s32 m_external_attr_info_count; s32 m_cache_count_min; size_t m_cache_size_min; size_t m_total_cache_size; CacheHandle m_current_handle; public: static constexpr size_t QueryWorkBufferSize(s32 max_cache_count) { AMS_ASSERT(max_cache_count > 0); const auto entry_size = sizeof(Entry) * max_cache_count; const auto attr_list_size = sizeof(AttrInfo) * 0x100; return util::AlignUp(entry_size + attr_list_size + alignof(Entry) + alignof(AttrInfo), 8); } public: CacheHandleTable() : m_internal_entry_buffer(), m_external_entry_buffer(), m_entry_buffer_size(), m_entries(), m_entry_count(), m_entry_count_max(), m_attr_list(), m_external_attr_info_buffer(), m_external_attr_info_count(), m_cache_count_min(), m_cache_size_min(), m_total_cache_size(), m_current_handle() { /* ... */ } ~CacheHandleTable() { this->Finalize(); } Result Initialize(s32 max_cache_count); Result Initialize(s32 max_cache_count, void *work, size_t work_size) { const auto aligned_entry_buf = util::AlignUp(reinterpret_cast<uintptr_t>(work), alignof(Entry)); m_external_entry_buffer = reinterpret_cast<char *>(aligned_entry_buf); m_entry_buffer_size = sizeof(Entry) * max_cache_count; const auto aligned_attr_info_buf = util::AlignUp(reinterpret_cast<uintptr_t>(m_external_entry_buffer + m_entry_buffer_size), alignof(AttrInfo)); const auto work_end = reinterpret_cast<uintptr_t>(work) + work_size; m_external_attr_info_buffer = reinterpret_cast<char *>(aligned_attr_info_buf); m_external_attr_info_count = static_cast<s32>((work_end - aligned_attr_info_buf) / sizeof(AttrInfo)); R_SUCCEED(); } void Finalize(); bool Register(CacheHandle *out, uintptr_t address, size_t size, const BufferAttribute &attr); bool Unregister(uintptr_t *out_address, size_t *out_size, CacheHandle handle); bool UnregisterOldest(uintptr_t *out_address, size_t *out_size, const BufferAttribute &attr, size_t required_size = 0); CacheHandle PublishCacheHandle(); size_t GetTotalCacheSize() const; private: void UnregisterCore(uintptr_t *out_address, size_t *out_size, Entry *entry); Entry *AcquireEntry(uintptr_t address, size_t size, const BufferAttribute &attr); void ReleaseEntry(Entry *entry); AttrInfo *FindAttrInfo(const BufferAttribute &attr); s32 GetCacheCountMin(const BufferAttribute &attr) { AMS_UNUSED(attr); return m_cache_count_min; } size_t GetCacheSizeMin(const BufferAttribute &attr) { AMS_UNUSED(attr); return m_cache_size_min; } }; private: BuddyHeap m_buddy_heap; CacheHandleTable m_cache_handle_table; size_t m_total_size; size_t m_peak_free_size; size_t m_peak_total_allocatable_size; size_t m_retried_count; mutable os::SdkMutex m_mutex; public: static constexpr size_t QueryWorkBufferSize(s32 max_cache_count, s32 max_order) { const auto buddy_size = FileSystemBuddyHeap::QueryWorkBufferSize(max_order); const auto table_size = CacheHandleTable::QueryWorkBufferSize(max_cache_count); return buddy_size + table_size; } public: FileSystemBufferManager() : m_total_size(), m_peak_free_size(), m_peak_total_allocatable_size(), m_retried_count(), m_mutex() { /* ... */ } virtual ~FileSystemBufferManager() { /* ... */ } Result Initialize(s32 max_cache_count, uintptr_t address, size_t buffer_size, size_t block_size) { AMS_ASSERT(buffer_size > 0); R_TRY(m_cache_handle_table.Initialize(max_cache_count)); R_TRY(m_buddy_heap.Initialize(address, buffer_size, block_size)); m_total_size = m_buddy_heap.GetTotalFreeSize(); m_peak_free_size = m_total_size; m_peak_total_allocatable_size = m_total_size; R_SUCCEED(); } Result Initialize(s32 max_cache_count, uintptr_t address, size_t buffer_size, size_t block_size, s32 max_order) { AMS_ASSERT(buffer_size > 0); R_TRY(m_cache_handle_table.Initialize(max_cache_count)); R_TRY(m_buddy_heap.Initialize(address, buffer_size, block_size, max_order)); m_total_size = m_buddy_heap.GetTotalFreeSize(); m_peak_free_size = m_total_size; m_peak_total_allocatable_size = m_total_size; R_SUCCEED(); } Result Initialize(s32 max_cache_count, uintptr_t address, size_t buffer_size, size_t block_size, void *work, size_t work_size) { const auto table_size = CacheHandleTable::QueryWorkBufferSize(max_cache_count); const auto buddy_size = work_size - table_size; AMS_ASSERT(work_size > table_size); const auto table_buffer = static_cast<char *>(work); const auto buddy_buffer = table_buffer + table_size; R_TRY(m_cache_handle_table.Initialize(max_cache_count, table_buffer, table_size)); R_TRY(m_buddy_heap.Initialize(address, buffer_size, block_size, buddy_buffer, buddy_size)); m_total_size = m_buddy_heap.GetTotalFreeSize(); m_peak_free_size = m_total_size; m_peak_total_allocatable_size = m_total_size; R_SUCCEED(); } Result Initialize(s32 max_cache_count, uintptr_t address, size_t buffer_size, size_t block_size, s32 max_order, void *work, size_t work_size) { const auto table_size = CacheHandleTable::QueryWorkBufferSize(max_cache_count); const auto buddy_size = work_size - table_size; AMS_ASSERT(work_size > table_size); const auto table_buffer = static_cast<char *>(work); const auto buddy_buffer = table_buffer + table_size; R_TRY(m_cache_handle_table.Initialize(max_cache_count, table_buffer, table_size)); R_TRY(m_buddy_heap.Initialize(address, buffer_size, block_size, max_order, buddy_buffer, buddy_size)); m_total_size = m_buddy_heap.GetTotalFreeSize(); m_peak_free_size = m_total_size; m_peak_total_allocatable_size = m_total_size; R_SUCCEED(); } void Finalize() { m_buddy_heap.Finalize(); m_cache_handle_table.Finalize(); } private: virtual const fs::IBufferManager::MemoryRange DoAllocateBuffer(size_t size, const BufferAttribute &attr) override; virtual void DoDeallocateBuffer(uintptr_t address, size_t size) override; virtual CacheHandle DoRegisterCache(uintptr_t address, size_t size, const BufferAttribute &attr) override; virtual const fs::IBufferManager::MemoryRange DoAcquireCache(CacheHandle handle) override; virtual size_t DoGetTotalSize() const override; virtual size_t DoGetFreeSize() const override; virtual size_t DoGetTotalAllocatableSize() const override; virtual size_t DoGetFreeSizePeak() const override; virtual size_t DoGetTotalAllocatableSizePeak() const override; virtual size_t DoGetRetriedCount() const override; virtual void DoClearPeak() override; private: const fs::IBufferManager::MemoryRange AllocateBufferImpl(size_t size, const BufferAttribute &attr); void DeallocateBufferImpl(uintptr_t address, size_t size); CacheHandle RegisterCacheImpl(uintptr_t address, size_t size, const BufferAttribute &attr); const fs::IBufferManager::MemoryRange AcquireCacheImpl(CacheHandle handle); size_t GetFreeSizeImpl() const; size_t GetTotalAllocatableSizeImpl() const; size_t GetFreeSizePeakImpl() const; size_t GetTotalAllocatableSizePeakImpl() const; size_t GetRetriedCountImpl() const; void ClearPeakImpl(); }; }
14,487
C++
.h
248
39.427419
328
0.528491
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
7,541
fssystem_file_system_buddy_heap.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/fssystem/buffers/fssystem_file_system_buddy_heap.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/fs/impl/fs_newable.hpp> #include <stratosphere/fs/fs_i_buffer_manager.hpp> namespace ams::fssystem { /* ACCURATE_TO_VERSION: Unknown */ class FileSystemBuddyHeap { NON_COPYABLE(FileSystemBuddyHeap); NON_MOVEABLE(FileSystemBuddyHeap); public: static constexpr size_t BufferAlignment = sizeof(void *); static constexpr size_t BlockSizeMin = 2 * sizeof(void *); static constexpr s32 OrderUpperLimit = BITSIZEOF(s32) - 1; private: class PageList; struct PageEntry { PageEntry *next; }; static_assert(util::is_pod<PageEntry>::value); static_assert(sizeof(PageEntry) <= BlockSizeMin); class PageList : public ::ams::fs::impl::Newable { NON_COPYABLE(PageList); NON_MOVEABLE(PageList); private: PageEntry *m_first_page_entry; PageEntry *m_last_page_entry; s32 m_entry_count; public: constexpr PageList() : m_first_page_entry(), m_last_page_entry(), m_entry_count() { /* ... */ } constexpr bool IsEmpty() const { return m_entry_count == 0; } constexpr s32 GetSize() const { return m_entry_count; } constexpr const PageEntry *GetFront() const { return m_first_page_entry; } public: PageEntry *PopFront(); void PushBack(PageEntry *page_entry); bool Remove(PageEntry *page_entry); }; private: size_t m_block_size; s32 m_order_max; uintptr_t m_heap_start; size_t m_heap_size; PageList *m_free_lists; size_t m_total_free_size; PageList *m_external_free_lists; std::unique_ptr<PageList[]> m_internal_free_lists; public: static constexpr s32 GetBlockCountFromOrder(s32 order) { AMS_ASSERT(0 <= order); AMS_ASSERT(order < OrderUpperLimit); return (1 << order); } static constexpr size_t QueryWorkBufferSize(s32 order_max) { AMS_ASSERT(0 < order_max && order_max < OrderUpperLimit); return util::AlignUp(sizeof(PageList) * (order_max + 1) + alignof(PageList), alignof(u64)); } static constexpr s32 QueryOrderMax(size_t size, size_t block_size) { AMS_ASSERT(size >= block_size); AMS_ASSERT(block_size >= BlockSizeMin); AMS_ASSERT(util::IsPowerOfTwo(block_size)); const auto block_count = static_cast<s32>(util::AlignUp(size, block_size) / block_size); for (auto order = 1; true; order++) { if (block_count <= GetBlockCountFromOrder(order)) { return order; } } } public: constexpr FileSystemBuddyHeap() : m_block_size(), m_order_max(), m_heap_start(), m_heap_size(), m_free_lists(), m_total_free_size(), m_external_free_lists(), m_internal_free_lists() { /* ... */ } Result Initialize(uintptr_t address, size_t size, size_t block_size, s32 order_max); Result Initialize(uintptr_t address, size_t size, size_t block_size) { R_RETURN(this->Initialize(address, size, block_size, QueryOrderMax(size, block_size))); } Result Initialize(uintptr_t address, size_t size, size_t block_size, s32 order_max, void *work, size_t work_size) { AMS_ASSERT(work_size >= QueryWorkBufferSize(order_max)); AMS_UNUSED(work_size); const auto aligned_work = util::AlignUp(reinterpret_cast<uintptr_t>(work), alignof(PageList)); m_external_free_lists = reinterpret_cast<PageList *>(aligned_work); R_RETURN(this->Initialize(address, size, block_size, order_max)); } Result Initialize(uintptr_t address, size_t size, size_t block_size, void *work, size_t work_size) { R_RETURN(this->Initialize(address, size, block_size, QueryOrderMax(size, block_size), work, work_size)); } void Finalize(); void *AllocateByOrder(s32 order); void Free(void *ptr, s32 order); size_t GetTotalFreeSize() const; size_t GetAllocatableSizeMax() const; void Dump() const; s32 GetOrderFromBytes(size_t size) const { AMS_ASSERT(m_free_lists != nullptr); return this->GetOrderFromBlockCount(this->GetBlockCountFromSize(size)); } size_t GetBytesFromOrder(s32 order) const { AMS_ASSERT(m_free_lists != nullptr); AMS_ASSERT(0 <= order); AMS_ASSERT(order <= this->GetOrderMax()); return (this->GetBlockSize() << order); } s32 GetOrderMax() const { AMS_ASSERT(m_free_lists != nullptr); return m_order_max; } size_t GetBlockSize() const { AMS_ASSERT(m_free_lists != nullptr); return m_block_size; } s32 GetPageBlockCountMax() const { AMS_ASSERT(m_free_lists != nullptr); return 1 << this->GetOrderMax(); } size_t GetPageSizeMax() const { AMS_ASSERT(m_free_lists != nullptr); return this->GetPageBlockCountMax() * this->GetBlockSize(); } private: void DivideBuddies(PageEntry *page_entry, s32 required_order, s32 chosen_order); void JoinBuddies(PageEntry *page_entry, s32 order); PageEntry *GetBuddy(PageEntry *page_entry, s32 order); PageEntry *GetFreePageEntry(s32 order); s32 GetOrderFromBlockCount(s32 block_count) const; s32 GetBlockCountFromSize(size_t size) const { const size_t bsize = this->GetBlockSize(); return static_cast<s32>(util::AlignUp(size, bsize) / bsize); } uintptr_t GetAddressFromPageEntry(const PageEntry &page_entry) const { const uintptr_t address = reinterpret_cast<uintptr_t>(std::addressof(page_entry)); AMS_ASSERT(m_heap_start <= address); AMS_ASSERT(address < m_heap_start + m_heap_size); AMS_ASSERT(util::IsAligned(address - m_heap_start, this->GetBlockSize())); return address; } PageEntry *GetPageEntryFromAddress(uintptr_t address) const { AMS_ASSERT(m_heap_start <= address); AMS_ASSERT(address < m_heap_start + m_heap_size); return reinterpret_cast<PageEntry *>(m_heap_start + util::AlignDown(address - m_heap_start, this->GetBlockSize())); } s32 GetIndexFromPageEntry(const PageEntry &page_entry) const { const uintptr_t address = reinterpret_cast<uintptr_t>(std::addressof(page_entry)); AMS_ASSERT(m_heap_start <= address); AMS_ASSERT(address < m_heap_start + m_heap_size); AMS_ASSERT(util::IsAligned(address - m_heap_start, this->GetBlockSize())); return static_cast<s32>((address - m_heap_start) / this->GetBlockSize()); } bool IsAlignedToOrder(const PageEntry *page_entry, s32 order) const { return util::IsAligned(GetIndexFromPageEntry(*page_entry), GetBlockCountFromOrder(order)); } }; }
8,447
C++
.h
162
38.790123
207
0.579719
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
7,542
sf_std_allocation_policy.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/sf/sf_std_allocation_policy.hpp
/* * 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/>. */ #pragma once #include <stratosphere/sf/sf_common.hpp> #include <stratosphere/sf/sf_allocation_policies.hpp> namespace ams::sf { template<template<typename> class StdAllocator> class StdAllocationPolicy { public: static constexpr bool HasStatefulAllocator = false; using Allocator = impl::StatelessDummyAllocator; template<typename T> struct StatelessAllocator { static void *Allocate(size_t size) { return StdAllocator<T>().allocate(size / sizeof(T)); } static void Deallocate(void *ptr, size_t size) { StdAllocator<T>().deallocate(static_cast<T *>(ptr), size / sizeof(T)); } }; template<typename T> static void *AllocateAligned(size_t size, size_t align) { AMS_UNUSED(align); return StdAllocator<T>().allocate(size / sizeof(T)); } template<typename T> static void DeallocateAligned(void *ptr, size_t size, size_t align) { AMS_UNUSED(align); StdAllocator<T>().deallocate(static_cast<T *>(ptr), size / sizeof(T)); } }; }
1,880
C++
.h
45
33.244444
90
0.63388
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
7,543
sf_service_object.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/sf/sf_service_object.hpp
/* * 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/>. */ #pragma once #include <stratosphere/sf/sf_common.hpp> #include <stratosphere/sf/sf_out.hpp> #include <stratosphere/sf/sf_shared_object.hpp> namespace ams::sf { class IServiceObject : public ISharedObject { public: virtual ~IServiceObject() { /* ... */ } }; template<typename T> concept IsServiceObject = std::derived_from<T, IServiceObject>; #if AMS_SF_MITM_SUPPORTED class IMitmServiceObject : public IServiceObject { public: virtual ~IMitmServiceObject() { /* ... */ } }; class MitmServiceImplBase { protected: std::shared_ptr<::Service> m_forward_service; sm::MitmProcessInfo m_client_info; public: MitmServiceImplBase(std::shared_ptr<::Service> &&s, const sm::MitmProcessInfo &c) : m_forward_service(std::move(s)), m_client_info(c) { /* ... */ } }; template<typename T> concept IsMitmServiceObject = IsServiceObject<T> && std::derived_from<T, IMitmServiceObject>; template<typename T> concept IsMitmServiceImpl = requires (std::shared_ptr<::Service> &&s, const sm::MitmProcessInfo &c) { { T(std::forward<std::shared_ptr<::Service>>(s), c) }; { T::ShouldMitm(c) } -> std::same_as<bool>; }; #else template<typename T> concept IsMitmServiceObject = false; #endif }
2,070
C++
.h
50
34.74
163
0.653904
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
7,544
sf_mem_utility.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/sf/sf_mem_utility.hpp
/* * 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/>. */ #pragma once #include <stratosphere/sf/sf_common.hpp> #include <stratosphere/mem.hpp> namespace ams::sf { class StandardAllocatorMemoryResource : public MemoryResource { private: mem::StandardAllocator *m_standard_allocator; public: explicit StandardAllocatorMemoryResource(mem::StandardAllocator *sa) : m_standard_allocator(sa) { /* ... */ } mem::StandardAllocator *GetAllocator() const { return m_standard_allocator; } private: virtual void *AllocateImpl(size_t size, size_t alignment) override { return m_standard_allocator->Allocate(size, alignment); } virtual void DeallocateImpl(void *buffer, size_t size, size_t alignment) override { AMS_UNUSED(size, alignment); return m_standard_allocator->Free(buffer); } virtual bool IsEqualImpl(const MemoryResource &resource) const override { return this == std::addressof(resource); } }; }
1,683
C++
.h
38
37.368421
121
0.68315
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
7,545
sf_lmem_utility.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/sf/sf_lmem_utility.hpp
/* * 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/>. */ #pragma once #include <stratosphere/sf/sf_common.hpp> #include <stratosphere/lmem.hpp> namespace ams::sf { class ExpHeapMemoryResource : public MemoryResource { private: lmem::HeapHandle m_handle; public: constexpr ExpHeapMemoryResource() : m_handle() { /* ... */ } constexpr explicit ExpHeapMemoryResource(lmem::HeapHandle h) : m_handle(h) { /* ... */ } void Attach(lmem::HeapHandle h) { AMS_ABORT_UNLESS(m_handle == lmem::HeapHandle()); m_handle = h; } lmem::HeapHandle GetHandle() const { return m_handle; } private: virtual void *AllocateImpl(size_t size, size_t alignment) override { return lmem::AllocateFromExpHeap(m_handle, size, static_cast<int>(alignment)); } virtual void DeallocateImpl(void *buffer, size_t size, size_t alignment) override { AMS_UNUSED(size, alignment); return lmem::FreeToExpHeap(m_handle, buffer); } virtual bool IsEqualImpl(const MemoryResource &resource) const override { return this == std::addressof(resource); } }; class UnitHeapMemoryResource : public MemoryResource { private: lmem::HeapHandle m_handle; public: constexpr UnitHeapMemoryResource() : m_handle() { /* ... */ } constexpr explicit UnitHeapMemoryResource(lmem::HeapHandle h) : m_handle(h) { /* ... */ } void Attach(lmem::HeapHandle h) { AMS_ABORT_UNLESS(m_handle == lmem::HeapHandle()); m_handle = h; } lmem::HeapHandle GetHandle() const { return m_handle; } private: virtual void *AllocateImpl(size_t size, size_t alignment) override { AMS_ASSERT(size <= lmem::GetUnitHeapUnitSize(m_handle)); AMS_ASSERT(alignment <= static_cast<size_t>(lmem::GetUnitHeapAlignment(m_handle))); AMS_UNUSED(size, alignment); return lmem::AllocateFromUnitHeap(m_handle); } virtual void DeallocateImpl(void *buffer, size_t size, size_t alignment) override { AMS_UNUSED(size, alignment); return lmem::FreeToUnitHeap(m_handle, buffer); } virtual bool IsEqualImpl(const MemoryResource &resource) const override { return this == std::addressof(resource); } }; }
3,179
C++
.h
69
36.072464
101
0.617447
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
7,546
sf_object_factory.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/sf/sf_object_factory.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/sf/sf_common.hpp> #include <stratosphere/sf/impl/sf_impl_template_base.hpp> #include <stratosphere/sf/sf_object_impl_factory.hpp> #include <stratosphere/sf/sf_memory_resource.hpp> #include <stratosphere/sf/sf_default_allocation_policy.hpp> namespace ams::sf { namespace impl { template<typename> struct IsSmartPointer : public std::false_type{}; template<typename T> struct IsSmartPointer<SharedPointer<T>> : public std::true_type{}; template<typename T> struct IsSmartPointer<std::shared_ptr<T>> : public std::true_type{}; template<typename T, typename D> struct IsSmartPointer<std::unique_ptr<T, D>> : public std::true_type{}; template<typename Impl> struct UnmanagedEmplaceImplHolderBaseGetter { using Type = Impl; }; template<typename Impl> requires (std::is_abstract<Impl>::value) struct UnmanagedEmplaceImplHolderBaseGetter<Impl> { class Impl2 : public Impl { public: using Impl::Impl; private: constexpr virtual void AddReference() override { /* ... */ } constexpr virtual void Release() override { /* ... */ } }; using Type = Impl2; }; template<typename Impl> class UnmanagedEmplacedImplHolder { template<typename, typename, typename, typename, typename> friend class impl::ImplTemplateBaseT; private: using Impl2 = typename UnmanagedEmplaceImplHolderBaseGetter<Impl>::Type; static_assert(!std::is_abstract<Impl2>::value); private: Impl2 m_impl; private: template<typename... Args> constexpr explicit UnmanagedEmplacedImplHolder(Args &&... args) : m_impl(std::forward<Args>(args)...) { /* ... */ } public: static constexpr Impl *GetImplPointer(UnmanagedEmplacedImplHolder *holder) { return std::addressof(holder->m_impl); } }; template<typename Impl> class EmplacedImplHolder : private Impl { template<typename, typename, typename, typename, typename> friend class impl::ImplTemplateBaseT; private: template<typename... Args> constexpr explicit EmplacedImplHolder(Args &&... args) : Impl(std::forward<Args>(args)...) { /* ... */ } public: static constexpr Impl *GetImplPointer(EmplacedImplHolder *holder) { return holder; } template<typename Interface> static constexpr Impl *GetEmplacedImplPointerImpl(const SharedPointer<Interface> &sp) { using Base = impl::ImplTemplateBase<Interface, Interface, EmplacedImplHolder, EmplacedImplHolder>; return static_cast<Base *>(sp.Get()); } }; template<typename Impl> requires (IsSmartPointer<Impl>::value) class EmplacedImplHolder<Impl> : private Impl { template<typename, typename, typename, typename, typename> friend class impl::ImplTemplateBaseT; private: template<typename... Args> constexpr explicit EmplacedImplHolder(Args &&... args) : Impl(std::forward<Args>(args)...) { /* ... */ } public: static constexpr auto *GetImplPointer(EmplacedImplHolder *holder) { return static_cast<Impl *>(holder)->operator ->(); } template<typename Interface> static constexpr Impl *GetEmplacedImplPointerImpl(const SharedPointer<Interface> &sp) { using Base = impl::ImplTemplateBase<Interface, Interface, EmplacedImplHolder, EmplacedImplHolder>; return static_cast<Base *>(sp.Get()); } }; template<typename T> using SmartPointerHolder = EmplacedImplHolder<T>; template<typename T> class ManagedPointerHolder { template<typename, typename, typename, typename, typename> friend class impl::ImplTemplateBaseT; private: T *m_p; private: constexpr explicit ManagedPointerHolder(T *p) : m_p(p) { /* ... */ } constexpr ~ManagedPointerHolder() { m_p->Release(); } static constexpr T *GetImplPointer(ManagedPointerHolder *holder) { return holder->m_p; } }; template<typename T> class UnmanagedPointerHolder { template<typename, typename, typename, typename, typename> friend class impl::ImplTemplateBaseT; private: T *m_p; private: constexpr explicit UnmanagedPointerHolder(T *p) : m_p(p) { /* ... */ } static constexpr T *GetImplPointer(UnmanagedPointerHolder *holder) { return holder->m_p; } }; } template<typename Interface, typename Impl> class UnmanagedServiceObject final : public impl::ImplTemplateBase<Interface, Interface, impl::UnmanagedEmplacedImplHolder<Impl>, impl::UnmanagedEmplacedImplHolder<Impl>> { private: using ImplBase = impl::ImplTemplateBase<Interface, Interface, impl::UnmanagedEmplacedImplHolder<Impl>, impl::UnmanagedEmplacedImplHolder<Impl>>; public: using ImplBase::ImplBase; constexpr virtual void AddReference() override { /* ... */ } constexpr virtual void Release() override { /* ... */ } constexpr Impl &GetImpl() { return *impl::UnmanagedEmplacedImplHolder<Impl>::GetImplPointer(this); } constexpr SharedPointer<Interface> GetShared() { return SharedPointer<Interface>(this, false); } }; template<typename Interface, typename T> class UnmanagedServiceObjectByPointer final : public impl::ImplTemplateBase<Interface, Interface, impl::UnmanagedPointerHolder<T>, impl::UnmanagedPointerHolder<T>> { private: using ImplBase = impl::ImplTemplateBase<Interface, Interface, impl::UnmanagedPointerHolder<T>, impl::UnmanagedPointerHolder<T>>; public: constexpr explicit UnmanagedServiceObjectByPointer(T *ptr) : ImplBase(ptr) { /* ... */ } constexpr virtual void AddReference() override { /* ... */ } constexpr virtual void Release() override { /* ... */ } constexpr SharedPointer<Interface> GetShared() { return SharedPointer<Interface>(this, false); } }; template<typename Policy> class ObjectFactory; template<typename Interface, typename Impl> class EmplacedRef : public SharedPointer<Interface> { template<typename> friend class ObjectFactory; private: constexpr explicit EmplacedRef(Interface *ptr, bool incref) : SharedPointer<Interface>(ptr, incref) { /* ... */ } public: constexpr EmplacedRef() { /* ... */ } constexpr Impl &GetImpl() const { return *impl::EmplacedImplHolder<Impl>::template GetEmplacedImplPointerImpl<Interface>(*this); } }; template<typename Policy> requires (!IsStatefulPolicy<Policy>) class ObjectFactory<Policy> { private: template<typename Interface, typename Holder, typename T> static constexpr SharedPointer<Interface> CreateSharedForPointer(T t) { using Base = impl::ImplTemplateBase<Interface, Interface, Holder, Holder>; return SharedPointer<Interface>(ObjectImplFactory<Base, Policy>::Create(std::forward<T>(t)), false); } public: template<typename Interface, typename Impl, typename... Args> static constexpr EmplacedRef<Interface, Impl> CreateSharedEmplaced(Args &&... args) { using Base = impl::ImplTemplateBase<Interface, Interface, impl::EmplacedImplHolder<Impl>, impl::EmplacedImplHolder<Impl>>; return EmplacedRef<Interface, Impl>(ObjectImplFactory<Base, Policy>::Create(std::forward<Args>(args)...), false); } template<typename T, typename... Args> static constexpr SharedPointer<T> CreateUserSharedObject(Args &&... args) { return SharedPointer<T>(ObjectImplFactory<T, Policy>::Create(std::forward<Args>(args)...), false); } template<typename Impl, typename Interface> static constexpr Impl *GetEmplacedImplPointer(const SharedPointer<Interface> &sp) { return impl::EmplacedImplHolder<Impl>::template GetEmplacedImplPointerImpl<Interface>(sp); } template<typename Interface, typename Smart> static constexpr SharedPointer<Interface> CreateShared(Smart &&sp) { return CreateSharedForPointer<Interface, impl::SmartPointerHolder<typename std::decay<decltype(sp)>::type>>(std::forward<Smart>(sp)); } template<typename Interface, typename T> static constexpr SharedPointer<Interface> CreateShared(T *p) { return CreateSharedForPointer<Interface, impl::ManagedPointerHolder<T>>(p); } template<typename Interface, typename T> static constexpr SharedPointer<Interface> CreateSharedWithoutManagement(T *p) { return CreateSharedForPointer<Interface, impl::UnmanagedPointerHolder<T>>(p); } }; template<typename Policy> requires (IsStatefulPolicy<Policy>) class ObjectFactory<Policy> { public: using Allocator = typename Policy::Allocator; private: template<typename Interface, typename Holder, typename T> static constexpr SharedPointer<Interface> CreateSharedForPointer(Allocator *a, T t) { using Base = impl::ImplTemplateBase<Interface, Interface, Holder, Holder>; return SharedPointer<Interface>(ObjectImplFactory<Base, Policy>::Create(a, std::forward<T>(t)), false); } public: template<typename Interface, typename Impl, typename... Args> static constexpr EmplacedRef<Interface, Impl> CreateSharedEmplaced(Allocator *a, Args &&... args) { using Base = impl::ImplTemplateBase<Interface, Interface, impl::EmplacedImplHolder<Impl>, impl::EmplacedImplHolder<Impl>>; return EmplacedRef<Interface, Impl>(ObjectImplFactory<Base, Policy>::Create(a, std::forward<Args>(args)...), false); } template<typename T, typename... Args> static constexpr SharedPointer<T> CreateUserSharedObject(Allocator *a, Args &&... args) { return SharedPointer<T>(ObjectImplFactory<T, Policy>::Create(a, std::forward<Args>(args)...), false); } template<typename Impl, typename Interface> static constexpr Impl *GetEmplacedImplPointer(const SharedPointer<Interface> &sp) { return impl::EmplacedImplHolder<Impl>::template GetEmplacedImplPointerImpl<Interface>(sp); } template<typename Interface, typename Smart> static constexpr SharedPointer<Interface> CreateShared(Allocator *a, Smart &&sp) { return CreateSharedForPointer<Interface, impl::SmartPointerHolder<typename std::decay<decltype(sp)>::type>>(a, std::forward<Smart>(sp)); } template<typename Interface, typename T> static constexpr SharedPointer<Interface> CreateShared(Allocator *a, T *p) { return CreateSharedForPointer<Interface, impl::ManagedPointerHolder<T>>(a, p); } template<typename Interface, typename T> static constexpr SharedPointer<Interface> CreateSharedWithoutManagement(Allocator *a, T *p) { return CreateSharedForPointer<Interface, impl::UnmanagedPointerHolder<T>>(a, p); } }; template<typename Policy> class StatefulObjectFactory { public: using Allocator = typename Policy::Allocator; private: using StaticObjectFactory = ObjectFactory<Policy>; private: Allocator *m_allocator; public: constexpr explicit StatefulObjectFactory(Allocator *a) : m_allocator(a) { /* ... */ } template<typename Interface, typename Impl, typename... Args> constexpr EmplacedRef<Interface, Impl> CreateSharedEmplaced(Args &&... args) { return StaticObjectFactory::template CreateSharedEmplaced<Interface, Impl>(m_allocator, std::forward<Args>(args)...); } template<typename Impl, typename Interface> static constexpr Impl *GetEmplacedImplPointer(const SharedPointer<Interface> &sp) { return StaticObjectFactory::template GetEmplacedImplPointer<Impl, Interface>(sp); } template<typename Interface, typename Smart> constexpr SharedPointer<Interface> CreateShared(Allocator *a, Smart &&sp) { AMS_UNUSED(a); return StaticObjectFactory::template CreateShared<Interface>(m_allocator, std::forward<Smart>(sp)); } template<typename Interface, typename T> constexpr SharedPointer<Interface> CreateShared(Allocator *a, T *p) { AMS_UNUSED(a); return StaticObjectFactory::template CreateShared<Interface>(m_allocator, p); } template<typename Interface, typename T> constexpr SharedPointer<Interface> CreateSharedWithoutManagement(Allocator *a, T *p) { AMS_UNUSED(a); return StaticObjectFactory::template CreateSharedWithoutManagement<Interface>(m_allocator, p); } }; using DefaultObjectFactory = ObjectFactory<DefaultAllocationPolicy>; using MemoryResourceObjectFactory = ObjectFactory<MemoryResourceAllocationPolicy>; template<typename Interface, typename Impl, typename... Args> inline EmplacedRef<Interface, Impl> CreateSharedObjectEmplaced(Args &&... args) { return DefaultObjectFactory::CreateSharedEmplaced<Interface, Impl>(std::forward<Args>(args)...); } template<typename Interface, typename Impl, typename... Args> inline EmplacedRef<Interface, Impl> CreateSharedObjectEmplaced(MemoryResource *mr, Args &&... args) { return MemoryResourceObjectFactory::CreateSharedEmplaced<Interface, Impl>(mr, std::forward<Args>(args)...); } template<typename Interface, typename Smart> inline SharedPointer<Interface> CreateSharedObject(Smart &&sp) { return DefaultObjectFactory::CreateShared<Interface, Smart>(std::forward<Smart>(sp)); } template<typename Interface, typename Smart> inline SharedPointer<Interface> CreateSharedObject(MemoryResource *mr, Smart &&sp) { return MemoryResourceObjectFactory::CreateShared<Interface, Smart>(mr, std::forward<Smart>(sp)); } template<typename Interface, typename T> inline SharedPointer<Interface> CreateSharedObject(T *ptr) { return DefaultObjectFactory::CreateShared<Interface, T>(std::move(ptr)); } template<typename Interface, typename T> inline SharedPointer<Interface> CreateSharedObjectWithoutManagement(T *ptr) { return DefaultObjectFactory::CreateSharedWithoutManagement<Interface, T>(std::move(ptr)); } template<typename Interface, typename T> inline SharedPointer<Interface> CreateSharedObjectWithoutManagement(MemoryResource *mr, T *ptr) { return DefaultObjectFactory::CreateSharedWithoutManagement<Interface, T>(mr, std::move(ptr)); } }
16,586
C++
.h
297
44.393939
176
0.65036
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
7,547
sf_standard_allocation_policy.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/sf/sf_standard_allocation_policy.hpp
/* * 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/>. */ #pragma once #include <stratosphere/sf/sf_default_allocation_policy.hpp> namespace ams::sf { using StandardAllocationPolicy = DefaultAllocationPolicy; }
794
C++
.h
20
37.7
76
0.76943
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
7,548
sf_mitm_dispatch.h
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/sf/sf_mitm_dispatch.h
/* * 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/>. */ #pragma once #include <stratosphere/sf/sf_mitm_config.hpp> #if AMS_SF_MITM_SUPPORTED #include <switch.h> #ifdef __cplusplus extern "C" { #endif typedef struct { Handle target_session; u32 context; SfBufferAttrs buffer_attrs; SfBuffer buffers[8]; bool in_send_pid; u32 in_num_objects; const Service* in_objects[8]; u32 in_num_handles; Handle in_handles[8]; u32 out_num_objects; Service* out_objects; SfOutHandleAttrs out_handle_attrs; Handle* out_handles; u64 override_pid; } SfMitmDispatchParams; NX_INLINE Result serviceMitmDispatchImpl( Service* s, u32 request_id, const void* in_data, u32 in_data_size, void* out_data, u32 out_data_size, SfMitmDispatchParams disp ) { // Make a copy of the service struct, so that the compiler can assume that it won't be modified by function calls. Service srv = *s; void* in = serviceMakeRequest(&srv, request_id, disp.context, in_data_size, disp.in_send_pid, disp.buffer_attrs, disp.buffers, disp.in_num_objects, disp.in_objects, disp.in_num_handles, disp.in_handles); if (in_data_size) __builtin_memcpy(in, in_data, in_data_size); if (disp.in_send_pid && disp.override_pid) { const u64 pid = (disp.override_pid & 0x0000FFFFFFFFFFFFul) | 0xFFFE000000000000ul; __builtin_memcpy((u8 *)armGetTls() + 0xC, &pid, sizeof(pid)); } Result rc = svcSendSyncRequest(disp.target_session == INVALID_HANDLE ? s->session : disp.target_session); if (R_SUCCEEDED(rc)) { void* out = NULL; rc = serviceParseResponse(&srv, out_data_size, &out, disp.out_num_objects, disp.out_objects, disp.out_handle_attrs, disp.out_handles); if (R_SUCCEEDED(rc) && out_data && out_data_size) __builtin_memcpy(out_data, out, out_data_size); } return rc; } #define serviceMitmDispatch(_s,_rid,...) \ serviceMitmDispatchImpl((_s),(_rid),NULL,0,NULL,0,(SfMitmDispatchParams){ __VA_ARGS__ }) #define serviceMitmDispatchIn(_s,_rid,_in,...) \ serviceMitmDispatchImpl((_s),(_rid),&(_in),sizeof(_in),NULL,0,(SfMitmDispatchParams){ __VA_ARGS__ }) #define serviceMitmDispatchOut(_s,_rid,_out,...) \ serviceMitmDispatchImpl((_s),(_rid),NULL,0,&(_out),sizeof(_out),(SfMitmDispatchParams){ __VA_ARGS__ }) #define serviceMitmDispatchInOut(_s,_rid,_in,_out,...) \ serviceMitmDispatchImpl((_s),(_rid),&(_in),sizeof(_in),&(_out),sizeof(_out),(SfMitmDispatchParams){ __VA_ARGS__ }) #ifdef __cplusplus } #endif #endif
3,214
C++
.h
82
34.634146
118
0.686174
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
7,549
sf_memory_resource.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/sf/sf_memory_resource.hpp
/* * 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/>. */ #pragma once #include <stratosphere/sf/sf_common.hpp> #include <stratosphere/sf/sf_allocation_policies.hpp> namespace ams::sf { struct MemoryResourceAllocationPolicy { static constexpr bool HasStatefulAllocator = true; using Allocator = MemoryResource; static void *AllocateAligned(MemoryResource *mr, size_t size, size_t align) { return mr->allocate(size, align); } static void DeallocateAligned(MemoryResource *mr, void *ptr, size_t size, size_t align) { return mr->deallocate(ptr, size, align); } }; template<typename T> struct MemoryResourceStaticAllocator { static constinit inline MemoryResource *g_memory_resource = nullptr; static constexpr void Initialize(MemoryResource *mr) { g_memory_resource = mr; } struct Policy { static constexpr bool HasStatefulAllocator = false; using Allocator = MemoryResource; template<typename> using StatelessAllocator = Allocator; template<typename> static void *AllocateAligned(size_t size, size_t align) { return g_memory_resource->allocate(size, align); } template<typename> static void DeallocateAligned(void *ptr, size_t size, size_t align) { g_memory_resource->deallocate(ptr, size, align); } }; }; }
2,089
C++
.h
51
33.686275
97
0.674063
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
7,550
sf_exp_heap_allocator.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/sf/sf_exp_heap_allocator.hpp
/* * 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/>. */ #pragma once #include <stratosphere/sf/sf_common.hpp> #include <stratosphere/sf/sf_allocation_policies.hpp> namespace ams::sf { struct ExpHeapAllocator { using Policy = StatefulAllocationPolicy<ExpHeapAllocator>; lmem::HeapHandle _handle; os::SdkMutexType _mutex; void Attach(lmem::HeapHandle h) { this->_handle = h; os::InitializeSdkMutex(std::addressof(this->_mutex)); } void Detach() { this->_handle = {}; } void *Allocate(size_t size) { os::LockSdkMutex(std::addressof(this->_mutex)); auto ptr = lmem::AllocateFromExpHeap(this->_handle, size); os::UnlockSdkMutex(std::addressof(this->_mutex)); return ptr; } void Deallocate(void *ptr, size_t size) { AMS_UNUSED(size); os::LockSdkMutex(std::addressof(this->_mutex)); lmem::FreeToExpHeap(this->_handle, ptr); os::UnlockSdkMutex(std::addressof(this->_mutex)); } }; static_assert(util::is_pod<ExpHeapAllocator>::value); template<size_t Size, typename Tag = void> struct ExpHeapStaticAllocator { using Policy = StatelessAllocationPolicy<ExpHeapStaticAllocator<Size, Tag>>; struct Globals { ExpHeapAllocator allocator; alignas(0x10) std::byte buffer[Size == 0 ? 1 : Size]; }; static constinit inline Globals _globals = {}; static void Initialize(int option) { _globals.allocator.Attach(lmem::CreateExpHeap(std::addressof(_globals.buffer), Size, option)); } static void Initialize(lmem::HeapHandle handle) { _globals.allocator.Attach(handle); } static void *Allocate(size_t size) { return _globals.allocator.Allocate(size); } static void Deallocate(void *ptr, size_t size) { return _globals.allocator.Deallocate(ptr, size); } }; }
2,642
C++
.h
66
32.318182
106
0.644783
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
7,551
sf_types.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/sf/sf_types.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #if defined(ATMOSPHERE_OS_WINDOWS) || defined(ATMOSPHERE_OS_LINUX) || defined(ATMOSPHERE_OS_MACOS) #ifdef __cplusplus extern "C" { #endif #if defined(ATMOSPHERE_COMPILER_CLANG) #define AMS_SF_HIPC_PARSE_IMPL_CONSTEXPR ALWAYS_INLINE #else #define AMS_SF_HIPC_PARSE_IMPL_CONSTEXPR constexpr ALWAYS_INLINE #endif #define HIPC_AUTO_RECV_STATIC UINT8_MAX #define HIPC_RESPONSE_NO_PID UINT32_MAX typedef struct HipcMetadata { u32 type; u32 num_send_statics; u32 num_send_buffers; u32 num_recv_buffers; u32 num_exch_buffers; u32 num_data_words; u32 num_recv_statics; // also accepts HIPC_AUTO_RECV_STATIC u32 send_pid; u32 num_copy_handles; u32 num_move_handles; } HipcMetadata; typedef struct HipcHeader { u32 type : 16; u32 num_send_statics : 4; u32 num_send_buffers : 4; u32 num_recv_buffers : 4; u32 num_exch_buffers : 4; u32 num_data_words : 10; u32 recv_static_mode : 4; u32 padding : 6; u32 recv_list_offset : 11; // Unused. u32 has_special_header : 1; } HipcHeader; typedef struct HipcSpecialHeader { u32 send_pid : 1; u32 num_copy_handles : 4; u32 num_move_handles : 4; u32 padding : 23; } HipcSpecialHeader; typedef struct HipcStaticDescriptor { u32 index : 6; u32 address_high : 6; u32 address_mid : 4; u32 size : 16; u32 address_low; } HipcStaticDescriptor; typedef struct HipcBufferDescriptor { u32 size_low; u32 address_low; u32 mode : 2; u32 address_high : 22; u32 size_high : 4; u32 address_mid : 4; } HipcBufferDescriptor; typedef struct HipcRecvListEntry { u32 address_low; u32 address_high : 16; u32 size : 16; } HipcRecvListEntry; typedef struct HipcRequest { HipcStaticDescriptor* send_statics; HipcBufferDescriptor* send_buffers; HipcBufferDescriptor* recv_buffers; HipcBufferDescriptor* exch_buffers; u32* data_words; HipcRecvListEntry* recv_list; u32* copy_handles; u32* move_handles; } HipcRequest; typedef struct HipcParsedRequest { HipcMetadata meta; HipcRequest data; u64 pid; } HipcParsedRequest; typedef struct HipcResponse { u64 pid; u32 num_statics; u32 num_data_words; u32 num_copy_handles; u32 num_move_handles; HipcStaticDescriptor* statics; u32* data_words; u32* copy_handles; u32* move_handles; } HipcResponse; typedef enum HipcBufferMode { HipcBufferMode_Normal = 0, HipcBufferMode_NonSecure = 1, HipcBufferMode_Invalid = 2, HipcBufferMode_NonDevice = 3, } HipcBufferMode; AMS_SF_HIPC_PARSE_IMPL_CONSTEXPR HipcStaticDescriptor hipcMakeSendStatic(const void* buffer, size_t size, u8 index) { return (HipcStaticDescriptor){ .index = index, .address_high = (u32)((uintptr_t)buffer >> 36), .address_mid = (u32)((uintptr_t)buffer >> 32), .size = (u32)size, .address_low = (u32)(uintptr_t)buffer, }; } AMS_SF_HIPC_PARSE_IMPL_CONSTEXPR HipcBufferDescriptor hipcMakeBuffer(const void* buffer, size_t size, HipcBufferMode mode) { return (HipcBufferDescriptor){ .size_low = (u32)size, .address_low = (u32)(uintptr_t)buffer, .mode = mode, .address_high = (u32)((uintptr_t)buffer >> 36), .size_high = (u32)(size >> 32), .address_mid = (u32)((uintptr_t)buffer >> 32), }; } AMS_SF_HIPC_PARSE_IMPL_CONSTEXPR HipcRecvListEntry hipcMakeRecvStatic(void* buffer, size_t size) { return (HipcRecvListEntry){ .address_low = (u32)((uintptr_t)buffer), .address_high = (u32)((uintptr_t)buffer >> 32), .size = (u32)size, }; } AMS_SF_HIPC_PARSE_IMPL_CONSTEXPR void* hipcGetStaticAddress(const HipcStaticDescriptor* desc) { return (void*)(desc->address_low | ((uintptr_t)desc->address_mid << 32) | ((uintptr_t)desc->address_high << 36)); } AMS_SF_HIPC_PARSE_IMPL_CONSTEXPR size_t hipcGetStaticSize(const HipcStaticDescriptor* desc) { return desc->size; } AMS_SF_HIPC_PARSE_IMPL_CONSTEXPR void* hipcGetBufferAddress(const HipcBufferDescriptor* desc) { return (void*)(desc->address_low | ((uintptr_t)desc->address_mid << 32) | ((uintptr_t)desc->address_high << 36)); } AMS_SF_HIPC_PARSE_IMPL_CONSTEXPR size_t hipcGetBufferSize(const HipcBufferDescriptor* desc) { return desc->size_low | ((size_t)desc->size_high << 32); } AMS_SF_HIPC_PARSE_IMPL_CONSTEXPR HipcRequest hipcCalcRequestLayout(HipcMetadata meta, void* base) { // Copy handles u32* copy_handles = NULL; if (meta.num_copy_handles) { copy_handles = (u32*)base; base = copy_handles + meta.num_copy_handles; } // Move handles u32* move_handles = NULL; if (meta.num_move_handles) { move_handles = (u32*)base; base = move_handles + meta.num_move_handles; } // Send statics HipcStaticDescriptor* send_statics = NULL; if (meta.num_send_statics) { send_statics = (HipcStaticDescriptor*)base; base = send_statics + meta.num_send_statics; } // Send buffers HipcBufferDescriptor* send_buffers = NULL; if (meta.num_send_buffers) { send_buffers = (HipcBufferDescriptor*)base; base = send_buffers + meta.num_send_buffers; } // Recv buffers HipcBufferDescriptor* recv_buffers = NULL; if (meta.num_recv_buffers) { recv_buffers = (HipcBufferDescriptor*)base; base = recv_buffers + meta.num_recv_buffers; } // Exch buffers HipcBufferDescriptor* exch_buffers = NULL; if (meta.num_exch_buffers) { exch_buffers = (HipcBufferDescriptor*)base; base = exch_buffers + meta.num_exch_buffers; } // Data words u32* data_words = NULL; if (meta.num_data_words) { data_words = (u32*)base; base = data_words + meta.num_data_words; } // Recv list HipcRecvListEntry* recv_list = NULL; if (meta.num_recv_statics) recv_list = (HipcRecvListEntry*)base; return (HipcRequest){ .send_statics = send_statics, .send_buffers = send_buffers, .recv_buffers = recv_buffers, .exch_buffers = exch_buffers, .data_words = data_words, .recv_list = recv_list, .copy_handles = copy_handles, .move_handles = move_handles, }; } AMS_SF_HIPC_PARSE_IMPL_CONSTEXPR HipcRequest hipcMakeRequest(void* base, HipcMetadata meta) { // Write message header bool has_special_header = meta.send_pid || meta.num_copy_handles || meta.num_move_handles; HipcHeader* hdr = (HipcHeader*)base; base = hdr+1; *hdr = (HipcHeader){ .type = meta.type, .num_send_statics = meta.num_send_statics, .num_send_buffers = meta.num_send_buffers, .num_recv_buffers = meta.num_recv_buffers, .num_exch_buffers = meta.num_exch_buffers, .num_data_words = meta.num_data_words, .recv_static_mode = meta.num_recv_statics ? (meta.num_recv_statics != HIPC_AUTO_RECV_STATIC ? 2u + meta.num_recv_statics : 2u) : 0u, .padding = 0, .recv_list_offset = 0, .has_special_header = has_special_header, }; // Write special header if (has_special_header) { HipcSpecialHeader* sphdr = (HipcSpecialHeader*)base; base = sphdr+1; *sphdr = (HipcSpecialHeader){ .send_pid = meta.send_pid, .num_copy_handles = meta.num_copy_handles, .num_move_handles = meta.num_move_handles, }; if (meta.send_pid) base = (u8*)base + sizeof(u64); } // Calculate layout return hipcCalcRequestLayout(meta, base); } #define hipcMakeRequestInline(_base,...) hipcMakeRequest((_base),(HipcMetadata){ __VA_ARGS__ }) AMS_SF_HIPC_PARSE_IMPL_CONSTEXPR HipcParsedRequest hipcParseRequest(void* base) { // Parse message header HipcHeader hdr = {}; __builtin_memcpy(&hdr, base, sizeof(hdr)); base = (u8*)base + sizeof(hdr); u32 num_recv_statics = 0; u64 pid = 0; // Parse recv static mode if (hdr.recv_static_mode) { if (hdr.recv_static_mode == 2u) num_recv_statics = HIPC_AUTO_RECV_STATIC; else if (hdr.recv_static_mode > 2u) num_recv_statics = hdr.recv_static_mode - 2u; } // Parse special header HipcSpecialHeader sphdr = {}; if (hdr.has_special_header) { __builtin_memcpy(&sphdr, base, sizeof(sphdr)); base = (u8*)base + sizeof(sphdr); // Read PID descriptor if (sphdr.send_pid) { pid = *(u64*)base; base = (u8*)base + sizeof(u64); } } const HipcMetadata meta = { .type = hdr.type, .num_send_statics = hdr.num_send_statics, .num_send_buffers = hdr.num_send_buffers, .num_recv_buffers = hdr.num_recv_buffers, .num_exch_buffers = hdr.num_exch_buffers, .num_data_words = hdr.num_data_words, .num_recv_statics = num_recv_statics, .send_pid = sphdr.send_pid, .num_copy_handles = sphdr.num_copy_handles, .num_move_handles = sphdr.num_move_handles, }; return (HipcParsedRequest){ .meta = meta, .data = hipcCalcRequestLayout(meta, base), .pid = pid, }; } AMS_SF_HIPC_PARSE_IMPL_CONSTEXPR HipcResponse hipcParseResponse(void* base) { // Parse header HipcHeader hdr = {}; __builtin_memcpy(&hdr, base, sizeof(hdr)); base = (u8*)base + sizeof(hdr); // Initialize response HipcResponse response = {}; response.num_statics = hdr.num_send_statics; response.num_data_words = hdr.num_data_words; response.pid = HIPC_RESPONSE_NO_PID; // Parse special header if (hdr.has_special_header) { HipcSpecialHeader sphdr = {}; __builtin_memcpy(&sphdr, base, sizeof(sphdr)); base = (u8*)base + sizeof(sphdr); // Update response response.num_copy_handles = sphdr.num_copy_handles; response.num_move_handles = sphdr.num_move_handles; // Parse PID descriptor if (sphdr.send_pid) { response.pid = *(u64*)base; base = (u8*)base + sizeof(u64); } } // Copy handles response.copy_handles = (u32*)base; base = response.copy_handles + response.num_copy_handles; // Move handles response.move_handles = (u32*)base; base = response.move_handles + response.num_move_handles; // Send statics response.statics = (HipcStaticDescriptor*)base; base = response.statics + response.num_statics; // Data words response.data_words = (u32*)base; return response; } typedef enum CmifCommandType { CmifCommandType_Invalid = 0, CmifCommandType_LegacyRequest = 1, CmifCommandType_Close = 2, CmifCommandType_LegacyControl = 3, CmifCommandType_Request = 4, CmifCommandType_Control = 5, CmifCommandType_RequestWithContext = 6, CmifCommandType_ControlWithContext = 7, } CmifCommandType; typedef enum CmifDomainRequestType { CmifDomainRequestType_Invalid = 0, CmifDomainRequestType_SendMessage = 1, CmifDomainRequestType_Close = 2, } CmifDomainRequestType; typedef struct CmifInHeader { u32 magic; u32 version; u32 command_id; u32 token; } CmifInHeader; typedef struct CmifOutHeader { u32 magic; u32 version; Result result; u32 token; } CmifOutHeader; typedef struct CmifDomainInHeader { u8 type; u8 num_in_objects; u16 data_size; u32 object_id; u32 padding; u32 token; } CmifDomainInHeader; typedef struct CmifDomainOutHeader { u32 num_out_objects; u32 padding[3]; } CmifDomainOutHeader; typedef struct CmifRequestFormat { u32 object_id; u32 request_id; u32 context; u32 data_size; u32 server_pointer_size; u32 num_in_auto_buffers; u32 num_out_auto_buffers; u32 num_in_buffers; u32 num_out_buffers; u32 num_inout_buffers; u32 num_in_pointers; u32 num_out_pointers; u32 num_out_fixed_pointers; u32 num_objects; u32 num_handles; u32 send_pid; } CmifRequestFormat; typedef struct CmifRequest { HipcRequest hipc; void* data; u16* out_pointer_sizes; u32* objects; u32 server_pointer_size; u32 cur_in_ptr_id; } CmifRequest; typedef struct CmifResponse { void* data; u32* objects; u32* copy_handles; u32* move_handles; } CmifResponse; enum { SfBufferAttr_In = BIT(0), SfBufferAttr_Out = BIT(1), SfBufferAttr_HipcMapAlias = BIT(2), SfBufferAttr_HipcPointer = BIT(3), SfBufferAttr_FixedSize = BIT(4), SfBufferAttr_HipcAutoSelect = BIT(5), SfBufferAttr_HipcMapTransferAllowsNonSecure = BIT(6), SfBufferAttr_HipcMapTransferAllowsNonDevice = BIT(7), }; typedef struct SfBufferAttrs { u32 attr0; u32 attr1; u32 attr2; u32 attr3; u32 attr4; u32 attr5; u32 attr6; u32 attr7; } SfBufferAttrs; typedef struct SfBuffer { const void* ptr; size_t size; } SfBuffer; typedef enum SfOutHandleAttr { SfOutHandleAttr_None = 0, SfOutHandleAttr_HipcCopy = 1, SfOutHandleAttr_HipcMove = 2, } SfOutHandleAttr; typedef struct SfOutHandleAttrs { SfOutHandleAttr attr0; SfOutHandleAttr attr1; SfOutHandleAttr attr2; SfOutHandleAttr attr3; SfOutHandleAttr attr4; SfOutHandleAttr attr5; SfOutHandleAttr attr6; SfOutHandleAttr attr7; } SfOutHandleAttrs; #ifdef __cplusplus } #endif #endif
14,483
C++
.h
438
27.93379
142
0.654718
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
7,552
sf_buffers.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/sf/sf_buffers.hpp
/* * 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/>. */ #pragma once #include <stratosphere/sf/sf_common.hpp> #include <stratosphere/sf/sf_out.hpp> #include <stratosphere/sf/cmif/sf_cmif_pointer_and_size.hpp> #include <stratosphere/sf/sf_buffer_tags.hpp> namespace ams::sf { enum class BufferTransferMode { MapAlias, Pointer, AutoSelect, }; namespace impl { /* Buffer utilities. */ struct BufferBaseTag{}; template<BufferTransferMode TransferMode> constexpr inline u32 BufferTransferModeAttributes = [] { if constexpr (TransferMode == BufferTransferMode::MapAlias) { return SfBufferAttr_HipcMapAlias; } else if constexpr (TransferMode == BufferTransferMode::Pointer) { return SfBufferAttr_HipcPointer; } else if constexpr(TransferMode == BufferTransferMode::AutoSelect) { return SfBufferAttr_HipcAutoSelect; } else { static_assert(false, "Invalid BufferTransferMode"); } }(); } template<typename T> constexpr inline bool IsLargeData = std::is_base_of<sf::LargeData, T>::value; template<typename T> constexpr inline bool IsLargeData<Out<T>> = IsLargeData<T>; template<typename T> constexpr inline size_t LargeDataSize = sizeof(T); template<typename T> constexpr inline size_t LargeDataSize<Out<T>> = sizeof(T); template<typename T> constexpr inline BufferTransferMode PreferredTransferMode = [] { constexpr bool prefers_map_alias = std::is_base_of<PrefersMapAliasTransferMode, T>::value; constexpr bool prefers_pointer = std::is_base_of<PrefersPointerTransferMode, T>::value; constexpr bool prefers_auto_select = std::is_base_of<PrefersAutoSelectTransferMode, T>::value; if constexpr (prefers_map_alias) { static_assert(!prefers_pointer && !prefers_auto_select, "Type T must only prefer one transfer mode."); return BufferTransferMode::MapAlias; } else if constexpr (prefers_pointer) { static_assert(!prefers_map_alias && !prefers_auto_select, "Type T must only prefer one transfer mode."); return BufferTransferMode::Pointer; } else if constexpr (prefers_auto_select) { static_assert(!prefers_map_alias && !prefers_pointer, "Type T must only prefer one transfer mode."); return BufferTransferMode::AutoSelect; } else if constexpr (IsLargeData<T>) { return BufferTransferMode::Pointer; } else { return BufferTransferMode::MapAlias; } }(); template<typename T> constexpr inline BufferTransferMode PreferredTransferMode<Out<T>> = PreferredTransferMode<T>; namespace impl { class BufferBase : public BufferBaseTag { public: static constexpr u32 AdditionalAttributes = 0; private: const cmif::PointerAndSize m_pas; protected: constexpr uintptr_t GetAddressImpl() const { return m_pas.GetAddress(); } template<typename Entry> constexpr inline size_t GetSizeImpl() const { return m_pas.GetSize() / sizeof(Entry); } public: constexpr BufferBase() : m_pas() { /* ... */ } constexpr BufferBase(const cmif::PointerAndSize &pas) : m_pas(pas) { /* ... */ } constexpr BufferBase(uintptr_t ptr, size_t sz) : m_pas(ptr, sz) { /* ... */ } }; class InBufferBase : public BufferBase { public: using BaseType = BufferBase; static constexpr u32 AdditionalAttributes = BaseType::AdditionalAttributes | SfBufferAttr_In; public: constexpr InBufferBase() : BaseType() { /* ... */ } constexpr InBufferBase(const cmif::PointerAndSize &pas) : BaseType(pas) { /* ... */ } constexpr InBufferBase(uintptr_t ptr, size_t sz) : BaseType(ptr, sz) { /* ... */ } InBufferBase(const void *ptr, size_t sz) : BaseType(reinterpret_cast<uintptr_t>(ptr), sz) { /* ... */ } InBufferBase(const u8 *ptr, size_t sz) : BaseType(reinterpret_cast<uintptr_t>(ptr), sz) { /* ... */ } }; class OutBufferBase : public BufferBase { public: using BaseType = BufferBase; static constexpr u32 AdditionalAttributes = BaseType::AdditionalAttributes | SfBufferAttr_Out; public: constexpr OutBufferBase() : BaseType() { /* ... */ } constexpr OutBufferBase(const cmif::PointerAndSize &pas) : BaseType(pas) { /* ... */ } constexpr OutBufferBase(uintptr_t ptr, size_t sz) : BaseType(ptr, sz) { /* ... */ } OutBufferBase(void *ptr, size_t sz) : BaseType(reinterpret_cast<uintptr_t>(ptr), sz) { /* ... */ } OutBufferBase(u8 *ptr, size_t sz) : BaseType(reinterpret_cast<uintptr_t>(ptr), sz) { /* ... */ } }; template<BufferTransferMode TMode, u32 ExtraAttributes = 0> class InBufferImpl : public InBufferBase { public: using BaseType = InBufferBase; static constexpr BufferTransferMode TransferMode = TMode; static constexpr u32 AdditionalAttributes = BaseType::AdditionalAttributes | ExtraAttributes; public: constexpr InBufferImpl() : BaseType() { /* ... */ } constexpr InBufferImpl(const cmif::PointerAndSize &pas) : BaseType(pas) { /* ... */ } constexpr InBufferImpl(uintptr_t ptr, size_t sz) : BaseType(ptr, sz) { /* ... */ } InBufferImpl(const void *ptr, size_t sz) : BaseType(reinterpret_cast<uintptr_t>(ptr), sz) { /* ... */ } InBufferImpl(const u8 *ptr, size_t sz) : BaseType(reinterpret_cast<uintptr_t>(ptr), sz) { /* ... */ } constexpr const u8 *GetPointer() const { return reinterpret_cast<const u8 *>(this->GetAddressImpl()); } constexpr size_t GetSize() const { return this->GetSizeImpl<u8>(); } }; template<BufferTransferMode TMode, u32 ExtraAttributes = 0> class OutBufferImpl : public OutBufferBase { public: using BaseType = OutBufferBase; static constexpr BufferTransferMode TransferMode = TMode; static constexpr u32 AdditionalAttributes = BaseType::AdditionalAttributes | ExtraAttributes; public: constexpr OutBufferImpl() : BaseType() { /* ... */ } constexpr OutBufferImpl(const cmif::PointerAndSize &pas) : BaseType(pas) { /* ... */ } constexpr OutBufferImpl(uintptr_t ptr, size_t sz) : BaseType(ptr, sz) { /* ... */ } OutBufferImpl(void *ptr, size_t sz) : BaseType(reinterpret_cast<uintptr_t>(ptr), sz) { /* ... */ } OutBufferImpl(u8 *ptr, size_t sz) : BaseType(reinterpret_cast<uintptr_t>(ptr), sz) { /* ... */ } constexpr u8 *GetPointer() const { return reinterpret_cast<u8 *>(this->GetAddressImpl()); } constexpr size_t GetSize() const { return this->GetSizeImpl<u8>(); } }; template<typename T, BufferTransferMode TMode = PreferredTransferMode<T>> struct InArrayImpl : public InBufferBase { public: using BaseType = InBufferBase; static constexpr BufferTransferMode TransferMode = TMode; static constexpr u32 AdditionalAttributes = BaseType::AdditionalAttributes; public: constexpr InArrayImpl() : BaseType() { /* ... */ } constexpr InArrayImpl(const cmif::PointerAndSize &pas) : BaseType(pas) { /* ... */ } InArrayImpl(const T *ptr, size_t num_elements) : BaseType(reinterpret_cast<uintptr_t>(ptr), num_elements * sizeof(T)) { /* ... */ } constexpr const T *GetPointer() const { return reinterpret_cast<const T *>(this->GetAddressImpl()); } constexpr size_t GetSize() const { return this->GetSizeImpl<T>(); } constexpr const T &operator[](size_t i) const { return this->GetPointer()[i]; } constexpr explicit operator Span<const T>() const { return {this->GetPointer(), this->GetSize()}; } constexpr Span<const T> ToSpan() const { return {this->GetPointer(), this->GetSize()}; } }; template<typename T, BufferTransferMode TMode = PreferredTransferMode<T>> struct OutArrayImpl : public OutBufferBase { public: using BaseType = OutBufferBase; static constexpr BufferTransferMode TransferMode = TMode; static constexpr u32 AdditionalAttributes = BaseType::AdditionalAttributes; public: constexpr OutArrayImpl() : BaseType() { /* ... */ } constexpr OutArrayImpl(const cmif::PointerAndSize &pas) : BaseType(pas) { /* ... */ } OutArrayImpl(T *ptr, size_t num_elements) : BaseType(reinterpret_cast<uintptr_t>(ptr), num_elements * sizeof(T)) { /* ... */ } constexpr T *GetPointer() const { return reinterpret_cast<T *>(this->GetAddressImpl()); } constexpr size_t GetSize() const { return this->GetSizeImpl<T>(); } constexpr T &operator[](size_t i) const { return this->GetPointer()[i]; } constexpr explicit operator Span<T>() const { return {this->GetPointer(), this->GetSize()}; } constexpr Span<T> ToSpan() const { return {this->GetPointer(), this->GetSize()}; } }; } /* Buffer Types. */ using InBuffer = typename impl::InBufferImpl<BufferTransferMode::MapAlias>; using InMapAliasBuffer = typename impl::InBufferImpl<BufferTransferMode::MapAlias>; using InPointerBuffer = typename impl::InBufferImpl<BufferTransferMode::Pointer>; using InAutoSelectBuffer = typename impl::InBufferImpl<BufferTransferMode::AutoSelect>; using InNonSecureBuffer = typename impl::InBufferImpl<BufferTransferMode::MapAlias, SfBufferAttr_HipcMapTransferAllowsNonSecure>; using InNonDeviceBuffer = typename impl::InBufferImpl<BufferTransferMode::MapAlias, SfBufferAttr_HipcMapTransferAllowsNonDevice>; using InNonSecureAutoSelectBuffer = typename impl::InBufferImpl<BufferTransferMode::AutoSelect, SfBufferAttr_HipcMapTransferAllowsNonSecure>; using OutBuffer = typename impl::OutBufferImpl<BufferTransferMode::MapAlias>; using OutMapAliasBuffer = typename impl::OutBufferImpl<BufferTransferMode::MapAlias>; using OutPointerBuffer = typename impl::OutBufferImpl<BufferTransferMode::Pointer>; using OutAutoSelectBuffer = typename impl::OutBufferImpl<BufferTransferMode::AutoSelect>; using OutNonSecureBuffer = typename impl::OutBufferImpl<BufferTransferMode::MapAlias, SfBufferAttr_HipcMapTransferAllowsNonSecure>; using OutNonDeviceBuffer = typename impl::OutBufferImpl<BufferTransferMode::MapAlias, SfBufferAttr_HipcMapTransferAllowsNonDevice>; using OutNonSecureAutoSelectBuffer = typename impl::OutBufferImpl<BufferTransferMode::AutoSelect, SfBufferAttr_HipcMapTransferAllowsNonSecure>; template<typename T> using InArray = typename impl::InArrayImpl<T>; template<typename T> using InMapAliasArray = typename impl::InArrayImpl<T, BufferTransferMode::MapAlias>; template<typename T> using InPointerArray = typename impl::InArrayImpl<T, BufferTransferMode::Pointer>; template<typename T> using InAutoSelectArray = typename impl::InArrayImpl<T, BufferTransferMode::AutoSelect>; template<typename T> using OutArray = typename impl::OutArrayImpl<T>; template<typename T> using OutMapAliasArray = typename impl::OutArrayImpl<T, BufferTransferMode::MapAlias>; template<typename T> using OutPointerArray = typename impl::OutArrayImpl<T, BufferTransferMode::Pointer>; template<typename T> using OutAutoSelectArray = typename impl::OutArrayImpl<T, BufferTransferMode::AutoSelect>; /* Attribute serialization structs. */ template<typename T> constexpr inline bool IsBuffer = [] { const bool is_buffer = std::is_base_of<impl::BufferBaseTag, T>::value; const bool is_large_data = IsLargeData<T>; static_assert(!(is_buffer && is_large_data), "Invalid sf::IsBuffer state"); return is_buffer || is_large_data; }(); template<typename T> constexpr inline u32 BufferAttributes = [] { static_assert(IsBuffer<T>, "BufferAttributes requires IsBuffer"); if constexpr (std::is_base_of<impl::BufferBaseTag, T>::value) { return impl::BufferTransferModeAttributes<T::TransferMode> | T::AdditionalAttributes; } else if constexpr (IsLargeData<T>) { u32 attr = SfBufferAttr_FixedSize | impl::BufferTransferModeAttributes<PreferredTransferMode<T>>; if constexpr (std::is_base_of<impl::OutBaseTag, T>::value) { attr |= SfBufferAttr_Out; } else { attr |= SfBufferAttr_In; } return attr; } else { static_assert(!std::is_same<T, T>::value, "Invalid BufferAttributes<T>"); } }(); }
14,843
C++
.h
265
43.649057
147
0.610778
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
7,553
sf_mitm_config.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/sf/sf_mitm_config.hpp
/* * 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/>. */ #pragma once #if defined(ATMOSPHERE_OS_HORIZON) #define AMS_SF_MITM_SUPPORTED 1 #else #define AMS_SF_MITM_SUPPORTED 0 #endif
770
C++
.h
21
34.52381
76
0.757697
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
7,554
sf_out.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/sf/sf_out.hpp
/* * 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/>. */ #pragma once #include <stratosphere/sf/sf_common.hpp> #include <stratosphere/sf/cmif/sf_cmif_pointer_and_size.hpp> namespace ams::sf { namespace impl { struct OutBaseTag{}; } template<typename> struct IsOutForceEnabled : public std::false_type{}; template<> struct IsOutForceEnabled<::ams::Result> : public std::true_type{}; template<typename T> concept OutEnabled = (std::is_trivial<T>::value || IsOutForceEnabled<T>::value) && !std::is_pointer<T>::value; template<typename T> class Out : public impl::OutBaseTag { static_assert(OutEnabled<T>); public: static constexpr size_t TypeSize = sizeof(T); private: T *m_ptr; public: constexpr Out(uintptr_t p) : m_ptr(reinterpret_cast<T *>(p)) { /* ... */ } constexpr Out(T *p) : m_ptr(p) { /* ... */ } constexpr Out(const cmif::PointerAndSize &pas) : m_ptr(reinterpret_cast<T *>(pas.GetAddress())) { /* TODO: Is AMS_ABORT_UNLESS(pas.GetSize() >= sizeof(T)); necessary? */ } template<typename U> requires (std::integral<T> && std::is_enum<U>::value && std::same_as<typename std::underlying_type<U>::type, T>) constexpr Out(U *p) : m_ptr(reinterpret_cast<T *>(p)) { static_assert(sizeof(U) == sizeof(T)); static_assert(alignof(U) == alignof(T)); } void SetValue(const T& value) const { *m_ptr = value; } const T &GetValue() const { return *m_ptr; } T *GetPointer() const { return m_ptr; } /* Convenience operators. */ T &operator*() const { return *m_ptr; } T *operator->() const { return m_ptr; } }; template<typename T> class Out<T *> { static_assert(!std::is_same<T, T>::value, "Invalid sf::Out<T> (Raw Pointer)"); }; }
2,616
C++
.h
63
33.714286
183
0.603625
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
7,555
sf_allocation_policies.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/sf/sf_allocation_policies.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> namespace ams::sf { namespace impl { struct StatelessDummyAllocator; } template<typename A> class StatelessAllocationPolicy { public: static constexpr bool HasStatefulAllocator = false; using Allocator = impl::StatelessDummyAllocator; template<typename> using StatelessAllocator = A; template<typename> static void *AllocateAligned(size_t size, size_t align) { AMS_UNUSED(align); return A().Allocate(size); } template<typename> static void DeallocateAligned(void *ptr, size_t size, size_t align) { AMS_UNUSED(align); A().Deallocate(ptr, size); } }; template<template<typename> typename A> class StatelessTypedAllocationPolicy { public: static constexpr bool HasStatefulAllocator = false; using Allocator = impl::StatelessDummyAllocator; template<typename T> using StatelessAllocator = A<T>; template<typename T> static void *AllocateAligned(size_t size, size_t align) { AMS_UNUSED(align); return StatelessAllocator<T>().Allocate(size); } template<typename T> static void DeallocateAligned(void *ptr, size_t size, size_t align) { AMS_UNUSED(align); StatelessAllocator<T>().Deallocate(ptr, size); } }; template<typename A> class StatefulAllocationPolicy { public: static constexpr bool HasStatefulAllocator = true; using Allocator = A; static void *AllocateAligned(Allocator *allocator, size_t size, size_t align) { AMS_UNUSED(align); return allocator->Allocate(size); } static void DeallocateAligned(Allocator *allocator, void *ptr, size_t size, size_t align) { AMS_UNUSED(align); allocator->Deallocate(ptr, size); } }; template<typename T> concept IsStatefulPolicy = T::HasStatefulAllocator; }
2,871
C++
.h
74
29.418919
103
0.626844
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
7,556
sf_buffer_tags.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/sf/sf_buffer_tags.hpp
/* * 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/>. */ #pragma once namespace ams::sf { /* Helper structs for serialization of buffers. */ struct LargeData{}; struct PrefersMapAliasTransferMode{}; struct PrefersPointerTransferMode{}; struct PrefersAutoSelectTransferMode{}; }
881
C++
.h
23
35.608696
76
0.757327
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
7,557
sf_fs_inline_context.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/sf/sf_fs_inline_context.hpp
/* * 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/>. */ #pragma once #include <stratosphere/sf/sf_common.hpp> namespace ams::os { struct ThreadType; } namespace ams::sf { u8 GetFsInlineContext(os::ThreadType *thread); u8 SetFsInlineContext(os::ThreadType *thread, u8 ctx); }
873
C++
.h
24
34
76
0.755344
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
7,558
sf_common.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/sf/sf_common.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/ams.hpp> #include <stratosphere/os.hpp> #include <stratosphere/sm/sm_types.hpp> #include <stratosphere/sf/sf_types.hpp> #include <stratosphere/sf/sf_mitm_config.hpp>
860
C++
.h
22
37.454545
76
0.767303
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
7,559
sf_shared_object.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/sf/sf_shared_object.hpp
/* * 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/>. */ #pragma once #include <stratosphere/sf/sf_common.hpp> #include <stratosphere/sf/sf_mitm_config.hpp> #include <stratosphere/sf/sf_out.hpp> namespace ams::sf { class ISharedObject { NON_COPYABLE(ISharedObject); NON_MOVEABLE(ISharedObject); protected: constexpr ISharedObject() { /* ... */ } ~ISharedObject() { /* ... */ } public: constexpr virtual void AddReference() = 0; constexpr virtual void Release() = 0; }; namespace impl { class SharedPointerBase { private: ISharedObject *m_ptr; private: constexpr void AddReferenceImpl() const { if (m_ptr != nullptr) { m_ptr->AddReference(); } } constexpr void ReleaseImpl() const { if (m_ptr != nullptr) { m_ptr->Release(); } } public: constexpr SharedPointerBase() : m_ptr(nullptr) { /* ... */ } constexpr SharedPointerBase(ISharedObject *ptr, bool incref) : m_ptr(ptr) { if (incref) { this->AddReferenceImpl(); } } constexpr ~SharedPointerBase() { this->ReleaseImpl(); } constexpr SharedPointerBase(const SharedPointerBase &rhs) : m_ptr(rhs.m_ptr) { this->AddReferenceImpl(); } constexpr SharedPointerBase(SharedPointerBase &&rhs) : m_ptr(rhs.m_ptr) { rhs.m_ptr = nullptr; } constexpr SharedPointerBase &operator=(const SharedPointerBase &rhs) { SharedPointerBase tmp(rhs); tmp.swap(*this); return *this; } constexpr SharedPointerBase &operator=(SharedPointerBase &&rhs) { SharedPointerBase tmp(std::move(rhs)); tmp.swap(*this); return *this; } constexpr void swap(SharedPointerBase &rhs) { std::swap(m_ptr, rhs.m_ptr); } constexpr ISharedObject *Detach() { ISharedObject *ret = m_ptr; m_ptr = nullptr; return ret; } constexpr ISharedObject *Get() const { return m_ptr; } }; } template<typename I> class SharedPointer { template<typename> friend class ::ams::sf::SharedPointer; template<typename> friend class ::ams::sf::Out; public: using Interface = I; private: impl::SharedPointerBase m_base; public: constexpr SharedPointer() : m_base() { /* ... */ } constexpr SharedPointer(std::nullptr_t) : m_base() { /* ... */ } constexpr SharedPointer(Interface *ptr, bool incref) : m_base(static_cast<ISharedObject *>(ptr), incref) { /* ... */ } constexpr SharedPointer(const SharedPointer &rhs) : m_base(rhs.m_base) { /* ... */ } constexpr SharedPointer(SharedPointer &&rhs) : m_base(std::move(rhs.m_base)) { /* ... */ } template<typename U> requires std::derived_from<U, Interface> constexpr SharedPointer(const SharedPointer<U> &rhs) : m_base(rhs.m_base) { /* ... */ } template<typename U> requires std::derived_from<U, Interface> constexpr SharedPointer(SharedPointer<U> &&rhs) : m_base(std::move(rhs.m_base)) { /* ... */ } constexpr SharedPointer &operator=(std::nullptr_t) { SharedPointer().swap(*this); return *this; } constexpr SharedPointer &operator=(const SharedPointer &rhs) { SharedPointer tmp(rhs); tmp.swap(*this); return *this; } constexpr SharedPointer &operator=(SharedPointer &&rhs) { SharedPointer tmp(std::move(rhs)); tmp.swap(*this); return *this; } template<typename U> requires std::derived_from<U, Interface> constexpr SharedPointer &operator=(const SharedPointer<U> &rhs) { SharedPointer tmp(rhs); tmp.swap(*this); return *this; } template<typename U> requires std::derived_from<U, Interface> constexpr SharedPointer &operator=(SharedPointer<U> &&rhs) { SharedPointer tmp(std::move(rhs)); tmp.swap(*this); return *this; } constexpr void swap(SharedPointer &rhs) { m_base.swap(rhs.m_base); } constexpr Interface *Detach() { return static_cast<Interface *>(m_base.Detach()); } constexpr void Reset() { *this = nullptr; } constexpr Interface *Get() const { return static_cast<Interface *>(m_base.Get()); } constexpr Interface *operator->() const { AMS_ASSERT(this->Get() != nullptr); return this->Get(); } constexpr bool operator!() const { return this->Get() == nullptr; } constexpr bool operator==(std::nullptr_t) const { return this->Get() == nullptr; } constexpr bool operator!=(std::nullptr_t) const { return this->Get() != nullptr; } }; template<typename Interface> constexpr void Swap(SharedPointer<Interface> &lhs, SharedPointer<Interface> &rhs) { lhs.swap(rhs); } constexpr inline void ReleaseSharedObject(ISharedObject *ptr) { ptr->Release(); } }
6,719
C++
.h
162
28.253086
130
0.525234
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
7,560
sf_native_handle.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/sf/sf_native_handle.hpp
/* * 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/>. */ #pragma once #include <stratosphere/os/os_native_handle.hpp> #include <stratosphere/sf/sf_common.hpp> #include <stratosphere/sf/sf_out.hpp> namespace ams::sf { class NativeHandle { protected: NON_COPYABLE(NativeHandle); private: os::NativeHandle m_handle; bool m_managed; public: constexpr NativeHandle() : m_handle(os::InvalidNativeHandle), m_managed(false) { /* ... */ } constexpr NativeHandle(os::NativeHandle handle, bool managed) : m_handle(handle), m_managed(managed) { /* ... */ } constexpr NativeHandle(NativeHandle &&rhs) : m_handle(rhs.m_handle), m_managed(rhs.m_managed) { rhs.m_managed = false; rhs.m_handle = os::InvalidNativeHandle; } constexpr NativeHandle &operator=(NativeHandle &&rhs) { NativeHandle(std::move(rhs)).swap(*this); return *this; } constexpr ~NativeHandle() { if (m_managed) { os::CloseNativeHandle(m_handle); } } constexpr void Detach() { m_managed = false; m_handle = os::InvalidNativeHandle; } constexpr void Swap(NativeHandle &rhs) { std::swap(m_handle, rhs.m_handle); std::swap(m_managed, rhs.m_managed); } constexpr ALWAYS_INLINE void swap(NativeHandle &rhs) { return Swap(rhs); } constexpr NativeHandle GetShared() const { return NativeHandle(m_handle, false); } constexpr os::NativeHandle GetOsHandle() const { return m_handle; } constexpr bool IsManaged() const { return m_managed; } constexpr void Reset() { NativeHandle().swap(*this); } }; class CopyHandle : public NativeHandle { public: using NativeHandle::NativeHandle; using NativeHandle::operator=; }; class MoveHandle : public NativeHandle { public: using NativeHandle::NativeHandle; using NativeHandle::operator=; }; constexpr ALWAYS_INLINE void swap(NativeHandle &lhs, NativeHandle &rhs) { lhs.swap(rhs); } template<> class Out<CopyHandle> { private: NativeHandle *m_ptr; public: Out(NativeHandle *p) : m_ptr(p) { /* ... */ } void SetValue(NativeHandle v) const { *m_ptr = std::move(v); } ALWAYS_INLINE void SetValue(os::NativeHandle os_handle, bool managed) const { return this->SetValue(NativeHandle(os_handle, managed)); } NativeHandle &operator*() const { return *m_ptr; } }; template<> class Out<MoveHandle> { private: NativeHandle *m_ptr; public: Out(NativeHandle *p) : m_ptr(p) { /* ... */ } void SetValue(NativeHandle v) const { *m_ptr = std::move(v); } ALWAYS_INLINE void SetValue(os::NativeHandle os_handle, bool managed) const { return this->SetValue(NativeHandle(os_handle, managed)); } NativeHandle &operator*() const { return *m_ptr; } }; using OutCopyHandle = Out<CopyHandle>; using OutMoveHandle = Out<MoveHandle>; }
4,235
C++
.h
114
26.684211
126
0.56665
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
7,561
sf_default_allocation_policy.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/sf/sf_default_allocation_policy.hpp
/* * 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/>. */ #pragma once #include <stratosphere/sf/sf_common.hpp> #include <stratosphere/sf/sf_allocation_policies.hpp> namespace ams::sf { namespace impl { void *DefaultAllocateImpl(size_t size, size_t align, size_t offset); void DefaultDeallocateImpl(void *ptr, size_t size, size_t align, size_t offset); template<typename T> class DefaultAllocationPolicyAllocator { private: struct Holder { MemoryResource *allocator; alignas(alignof(T)) std::byte storage[sizeof(T)]; }; public: void *Allocate(size_t size) { AMS_ASSERT(size == sizeof(T)); AMS_UNUSED(size); return DefaultAllocateImpl(sizeof(Holder), alignof(Holder), AMS_OFFSETOF(Holder, storage)); } void Deallocate(void *ptr, size_t size) { AMS_ASSERT(size == sizeof(T)); AMS_UNUSED(size); return DefaultDeallocateImpl(ptr, sizeof(Holder), alignof(Holder), AMS_OFFSETOF(Holder, storage)); } }; } using DefaultAllocationPolicy = StatelessTypedAllocationPolicy<impl::DefaultAllocationPolicyAllocator>; MemoryResource *GetGlobalDefaultMemoryResource(); MemoryResource *GetCurrentEffectiveMemoryResource(); MemoryResource *GetCurrentMemoryResource(); MemoryResource *GetNewDeleteMemoryResource(); MemoryResource *SetGlobalDefaultMemoryResource(MemoryResource *mr); MemoryResource *SetCurrentMemoryResource(MemoryResource *mr); class ScopedCurrentMemoryResourceSetter { NON_COPYABLE(ScopedCurrentMemoryResourceSetter); NON_MOVEABLE(ScopedCurrentMemoryResourceSetter); private: MemoryResource *m_prev; public: explicit ScopedCurrentMemoryResourceSetter(MemoryResource *mr); ~ScopedCurrentMemoryResourceSetter(); }; }
2,632
C++
.h
59
35.881356
118
0.67499
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
7,562
sf_object_impl_factory.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/sf/sf_object_impl_factory.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/sf/sf_common.hpp> #include <stratosphere/sf/sf_allocation_policies.hpp> #include <stratosphere/sf/impl/sf_service_object_impl.hpp> namespace ams::sf { namespace impl { struct StatelessDummyAllocator{}; template<typename Base, typename Policy> class ObjectImplFactoryWithStatelessAllocator { public: class Object; using Allocator = StatelessDummyAllocator; using StatelessAllocator = typename Policy::template StatelessAllocator<Object>; class Object final : private ::ams::sf::impl::ServiceObjectImplBase2, public Base { NON_COPYABLE(Object); NON_MOVEABLE(Object); friend class ObjectImplFactoryWithStatelessAllocator; private: template<typename... Args> explicit Object(Args &&... args) : Base(std::forward<Args>(args)...) { /* ... */ } static void *operator new(size_t size) { return Policy::template AllocateAligned<Object>(size, alignof(Object)); } static void operator delete(void *ptr, size_t size) { return Policy::template DeallocateAligned<Object>(ptr, size, alignof(Object)); } static void *operator new(size_t size, Allocator *); static void operator delete(void *ptr, Allocator *); void DisposeImpl() { delete this; } public: void AddReference() { ServiceObjectImplBase2::AddReferenceImpl(); } void Release() { if (ServiceObjectImplBase2::ReleaseImpl()) { this->DisposeImpl(); } } Allocator *GetAllocator() const { return nullptr; } }; template<typename... Args> static Object *Create(Args &&... args) { return new Object(std::forward<Args>(args)...); } template<typename... Args> static Object *Create(Allocator *, Args &&... args) { return new Object(std::forward<Args>(args)...); } }; template<typename Base, typename Policy> class ObjectImplFactoryWithStatefulAllocator { public: using Allocator = typename Policy::Allocator; class Object final : private ::ams::sf::impl::ServiceObjectImplBase2, public Base { NON_COPYABLE(Object); NON_MOVEABLE(Object); friend class ObjectImplFactoryWithStatefulAllocator; private: Allocator *m_allocator; private: template<typename... Args> explicit Object(Args &&... args) : Base(std::forward<Args>(args)...) { /* ... */ } static void *operator new(size_t size); static void operator delete(void *ptr, size_t size) { AMS_UNUSED(ptr, size); } static void *operator new(size_t size, Allocator *a) { return Policy::AllocateAligned(a, size, alignof(Object)); } static void operator delete(void *ptr, Allocator *a) { return Policy::DeallocateAligned(a, ptr, sizeof(Object), alignof(Object)); } void DisposeImpl() { Allocator *a = this->GetAllocator(); std::destroy_at(this); operator delete(this, a); } public: void AddReference() { ServiceObjectImplBase2::AddReferenceImpl(); } void Release() { if (ServiceObjectImplBase2::ReleaseImpl()) { this->DisposeImpl(); } } Allocator *GetAllocator() const { return m_allocator; } }; template<typename... Args> static Object *Create(Allocator *a, Args &&... args) { auto *ptr = new (a) Object(std::forward<Args>(args)...); if (ptr != nullptr) { ptr->m_allocator = a; } return ptr; } }; } template<typename Base, typename Policy> class ObjectImplFactory; template<typename Base, typename Policy> requires (!IsStatefulPolicy<Policy>) class ObjectImplFactory<Base, Policy> : public impl::ObjectImplFactoryWithStatelessAllocator<Base, Policy>{}; template<typename Base, typename Policy> requires (IsStatefulPolicy<Policy>) class ObjectImplFactory<Base, Policy> : public impl::ObjectImplFactoryWithStatefulAllocator<Base, Policy>{}; }
6,245
C++
.h
127
31.267717
113
0.505994
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
7,563
sf_hipc_server_session_manager.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/sf/hipc/sf_hipc_server_session_manager.hpp
/* * 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/>. */ #pragma once #include <stratosphere/sf/sf_common.hpp> #include <stratosphere/sf/sf_mitm_config.hpp> #include <stratosphere/sf/sf_service_object.hpp> #include <stratosphere/sf/cmif/sf_cmif_pointer_and_size.hpp> #include <stratosphere/sf/cmif/sf_cmif_service_object_holder.hpp> #include <stratosphere/sf/hipc/sf_hipc_api.hpp> namespace ams::sf::cmif { struct ServiceDispatchContext; } namespace ams::sf::hipc { class ServerSessionManager; class ServerManagerBase; namespace impl { class HipcManagerImpl; } class ServerSession : public os::MultiWaitHolderType { friend class ServerSessionManager; friend class ServerManagerBase; friend class impl::HipcManagerImpl; NON_COPYABLE(ServerSession); NON_MOVEABLE(ServerSession); private: cmif::ServiceObjectHolder m_srv_obj_holder; cmif::PointerAndSize m_pointer_buffer; cmif::PointerAndSize m_saved_message; #if AMS_SF_MITM_SUPPORTED util::TypedStorage<std::shared_ptr<::Service>> m_forward_service; #endif os::NativeHandle m_session_handle; bool m_is_closed; bool m_has_received; const bool m_has_forward_service; public: ServerSession(os::NativeHandle h, cmif::ServiceObjectHolder &&obj) : m_srv_obj_holder(std::move(obj)), m_session_handle(h), m_has_forward_service(false) { hipc::AttachMultiWaitHolderForReply(this, h); m_is_closed = false; m_has_received = false; #if AMS_SF_MITM_SUPPORTED AMS_ABORT_UNLESS(!this->IsMitmSession()); #endif } ~ServerSession() { #if AMS_SF_MITM_SUPPORTED if (m_has_forward_service) { util::DestroyAt(m_forward_service); } #endif } #if AMS_SF_MITM_SUPPORTED ServerSession(os::NativeHandle h, cmif::ServiceObjectHolder &&obj, std::shared_ptr<::Service> &&fsrv) : m_srv_obj_holder(std::move(obj)), m_session_handle(h), m_has_forward_service(true) { hipc::AttachMultiWaitHolderForReply(this, h); m_is_closed = false; m_has_received = false; util::ConstructAt(m_forward_service, std::move(fsrv)); AMS_ABORT_UNLESS(util::GetReference(m_forward_service) != nullptr); } ALWAYS_INLINE bool IsMitmSession() const { return m_has_forward_service; } Result ForwardRequest(const cmif::ServiceDispatchContext &ctx) const; static inline void ForwardServiceDeleter(Service *srv) { serviceClose(srv); delete srv; } static inline std::shared_ptr<::Service> CreateForwardService() { return std::shared_ptr<::Service>(new ::Service(), ForwardServiceDeleter); } #endif }; class ServerSessionManager { private: template<typename Constructor> Result CreateSessionImpl(ServerSession **out, const Constructor &ctor) { /* Allocate session. */ ServerSession *session_memory = this->AllocateSession(); R_UNLESS(session_memory != nullptr, sf::hipc::ResultOutOfSessionMemory()); ON_RESULT_FAILURE { this->DestroySession(session_memory); }; /* Register session. */ R_TRY(ctor(session_memory)); /* Save new session to output. */ *out = session_memory; R_SUCCEED(); } void DestroySession(ServerSession *session); Result ProcessRequestImpl(ServerSession *session, const cmif::PointerAndSize &in_message, const cmif::PointerAndSize &out_message); virtual void RegisterServerSessionToWait(ServerSession *session) = 0; protected: Result DispatchRequest(cmif::ServiceObjectHolder &&obj, ServerSession *session, const cmif::PointerAndSize &in_message, const cmif::PointerAndSize &out_message); virtual Result DispatchManagerRequest(ServerSession *session, const cmif::PointerAndSize &in_message, const cmif::PointerAndSize &out_message); protected: virtual ServerSession *AllocateSession() = 0; virtual void FreeSession(ServerSession *session) = 0; virtual cmif::PointerAndSize GetSessionPointerBuffer(const ServerSession *session) const = 0; virtual cmif::PointerAndSize GetSessionSavedMessageBuffer(const ServerSession *session) const = 0; Result ReceiveRequestImpl(ServerSession *session, const cmif::PointerAndSize &message); void CloseSessionImpl(ServerSession *session); Result RegisterSessionImpl(ServerSession *session_memory, os::NativeHandle session_handle, cmif::ServiceObjectHolder &&obj); Result AcceptSessionImpl(ServerSession *session_memory, os::NativeHandle port_handle, cmif::ServiceObjectHolder &&obj); #if AMS_SF_MITM_SUPPORTED Result RegisterMitmSessionImpl(ServerSession *session_memory, os::NativeHandle mitm_session_handle, cmif::ServiceObjectHolder &&obj, std::shared_ptr<::Service> &&fsrv); Result AcceptMitmSessionImpl(ServerSession *session_memory, os::NativeHandle mitm_port_handle, cmif::ServiceObjectHolder &&obj, std::shared_ptr<::Service> &&fsrv); #endif Result ReceiveRequest(ServerSession *session, const cmif::PointerAndSize &message) { R_RETURN(this->ReceiveRequestImpl(session, message)); } Result RegisterSession(ServerSession **out, os::NativeHandle session_handle, cmif::ServiceObjectHolder &&obj) { auto ctor = [&](ServerSession *session_memory) -> Result { R_RETURN(this->RegisterSessionImpl(session_memory, session_handle, std::forward<cmif::ServiceObjectHolder>(obj))); }; R_RETURN(this->CreateSessionImpl(out, ctor)); } Result AcceptSession(ServerSession **out, os::NativeHandle port_handle, cmif::ServiceObjectHolder &&obj) { auto ctor = [&](ServerSession *session_memory) -> Result { R_RETURN(this->AcceptSessionImpl(session_memory, port_handle, std::forward<cmif::ServiceObjectHolder>(obj))); }; R_RETURN(this->CreateSessionImpl(out, ctor)); } #if AMS_SF_MITM_SUPPORTED Result RegisterMitmSession(ServerSession **out, os::NativeHandle mitm_session_handle, cmif::ServiceObjectHolder &&obj, std::shared_ptr<::Service> &&fsrv) { auto ctor = [&](ServerSession *session_memory) -> Result { R_RETURN(this->RegisterMitmSessionImpl(session_memory, mitm_session_handle, std::forward<cmif::ServiceObjectHolder>(obj), std::forward<std::shared_ptr<::Service>>(fsrv))); }; R_RETURN(this->CreateSessionImpl(out, ctor)); } Result AcceptMitmSession(ServerSession **out, os::NativeHandle mitm_port_handle, cmif::ServiceObjectHolder &&obj, std::shared_ptr<::Service> &&fsrv) { auto ctor = [&](ServerSession *session_memory) -> Result { R_RETURN(this->AcceptMitmSessionImpl(session_memory, mitm_port_handle, std::forward<cmif::ServiceObjectHolder>(obj), std::forward<std::shared_ptr<::Service>>(fsrv))); }; R_RETURN(this->CreateSessionImpl(out, ctor)); } #endif public: Result RegisterSession(os::NativeHandle session_handle, cmif::ServiceObjectHolder &&obj); Result AcceptSession(os::NativeHandle port_handle, cmif::ServiceObjectHolder &&obj); #if AMS_SF_MITM_SUPPORTED Result RegisterMitmSession(os::NativeHandle session_handle, cmif::ServiceObjectHolder &&obj, std::shared_ptr<::Service> &&fsrv); Result AcceptMitmSession(os::NativeHandle mitm_port_handle, cmif::ServiceObjectHolder &&obj, std::shared_ptr<::Service> &&fsrv); #endif template<typename Interface> Result AcceptSession(os::NativeHandle port_handle, SharedPointer<Interface> obj) { R_RETURN(this->AcceptSession(port_handle, cmif::ServiceObjectHolder(std::move(obj)))); } #if AMS_SF_MITM_SUPPORTED template<typename Interface> Result AcceptMitmSession(os::NativeHandle mitm_port_handle, SharedPointer<Interface> obj, std::shared_ptr<::Service> &&fsrv) { R_RETURN(this->AcceptMitmSession(mitm_port_handle, cmif::ServiceObjectHolder(std::move(obj)), std::forward<std::shared_ptr<::Service>>(fsrv))); } #endif Result ProcessRequest(ServerSession *session, const cmif::PointerAndSize &message); virtual ServerSessionManager *GetSessionManagerByTag(u32 tag) { /* This is unused. */ AMS_UNUSED(tag); return this; } }; }
9,873
C++
.h
172
45.337209
200
0.640774
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
7,564
sf_hipc_server_domain_session_manager.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/sf/hipc/sf_hipc_server_domain_session_manager.hpp
/* * 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/>. */ #pragma once #include <stratosphere/sf/hipc/sf_hipc_server_session_manager.hpp> #include <stratosphere/sf/cmif/sf_cmif_domain_manager.hpp> namespace ams::sf::hipc { class ServerDomainSessionManager : public ServerSessionManager, private cmif::ServerDomainManager { protected: using cmif::ServerDomainManager::DomainEntryStorage; using cmif::ServerDomainManager::DomainStorage; protected: virtual Result DispatchManagerRequest(ServerSession *session, const cmif::PointerAndSize &in_message, const cmif::PointerAndSize &out_message) override final; public: ServerDomainSessionManager(DomainEntryStorage *entry_storage, size_t entry_count) : ServerDomainManager(entry_storage, entry_count) { /* ... */ } inline cmif::DomainServiceObject *AllocateDomainServiceObject() { return cmif::ServerDomainManager::AllocateDomainServiceObject(); } }; }
1,599
C++
.h
32
44.625
170
0.738156
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
7,565
sf_hipc_api.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/sf/hipc/sf_hipc_api.hpp
/* * 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/>. */ #pragma once #include <stratosphere/sf/sf_common.hpp> #include <stratosphere/sf/cmif/sf_cmif_pointer_and_size.hpp> namespace ams::sf::hipc { void *GetMessageBufferOnTls(); constexpr size_t TlsMessageBufferSize = 0x100; #if defined(ATMOSPHERE_OS_HORIZON) ALWAYS_INLINE void *GetMessageBufferOnTls() { return svc::GetThreadLocalRegion()->message_buffer; } #endif enum class ReceiveResult { Success, Closed, NeedsRetry, }; void AttachMultiWaitHolderForAccept(os::MultiWaitHolderType *holder, os::NativeHandle port); void AttachMultiWaitHolderForReply(os::MultiWaitHolderType *holder, os::NativeHandle request); Result Receive(ReceiveResult *out_recv_result, os::NativeHandle session_handle, const cmif::PointerAndSize &message_buffer); Result Receive(bool *out_closed, os::NativeHandle session_handle, const cmif::PointerAndSize &message_buffer); Result Reply(os::NativeHandle session_handle, const cmif::PointerAndSize &message_buffer); Result CreateSession(os::NativeHandle *out_server_handle, os::NativeHandle *out_client_handle); }
1,767
C++
.h
38
42.526316
128
0.756694
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
7,566
sf_hipc_server_manager.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/sf/hipc/sf_hipc_server_manager.hpp
/* * 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/>. */ #pragma once #include <stratosphere/sf/sf_mitm_config.hpp> #include <stratosphere/sf/hipc/sf_hipc_server_domain_session_manager.hpp> #include <stratosphere/sm.hpp> namespace ams::sf::hipc { struct DefaultServerManagerOptions { static constexpr size_t PointerBufferSize = 0; static constexpr size_t MaxDomains = 0; static constexpr size_t MaxDomainObjects = 0; static constexpr bool CanDeferInvokeRequest = false; static constexpr bool CanManageMitmServers = false; }; static constexpr size_t ServerSessionCountMax = 0x40; static_assert(ServerSessionCountMax == 0x40, "ServerSessionCountMax isn't 0x40 somehow, this assert is a reminder that this will break lots of things"); template<size_t, typename, size_t> class ServerManager; class ServerManagerBase : public ServerDomainSessionManager { NON_COPYABLE(ServerManagerBase); NON_MOVEABLE(ServerManagerBase); public: #if AMS_SF_MITM_SUPPORTED using MitmQueryFunction = bool (*)(const sm::MitmProcessInfo &); #endif private: enum class UserDataTag : uintptr_t { Server = 1, Session = 2, #if AMS_SF_MITM_SUPPORTED MitmServer = 3, #endif }; protected: using ServerDomainSessionManager::DomainEntryStorage; using ServerDomainSessionManager::DomainStorage; protected: class Server : public os::MultiWaitHolderType { friend class ServerManagerBase; template<size_t, typename, size_t> friend class ServerManager; NON_COPYABLE(Server); NON_MOVEABLE(Server); private: cmif::ServiceObjectHolder m_static_object; os::NativeHandle m_port_handle; sm::ServiceName m_service_name; int m_index; bool m_service_managed; #if AMS_SF_MITM_SUPPORTED bool m_is_mitm_server; #endif public: #if AMS_SF_MITM_SUPPORTED void AcknowledgeMitmSession(std::shared_ptr<::Service> *out_fsrv, sm::MitmProcessInfo *out_client_info) { /* Check mitm server. */ AMS_ABORT_UNLESS(m_is_mitm_server); /* Create forward service. */ *out_fsrv = ServerSession::CreateForwardService(); /* Get client info. */ R_ABORT_UNLESS(sm::mitm::AcknowledgeSession(out_fsrv->get(), out_client_info, m_service_name)); } #endif }; protected: static constinit inline bool g_is_any_deferred_supported = false; #if AMS_SF_MITM_SUPPORTED static constinit inline bool g_is_any_mitm_supported = false; #endif private: /* Multiple wait management. */ os::MultiWaitType m_multi_wait; os::Event m_request_stop_event; os::MultiWaitHolderType m_request_stop_event_holder; os::Event m_notify_event; os::MultiWaitHolderType m_notify_event_holder; os::SdkMutex m_selection_mutex; os::SdkMutex m_deferred_list_mutex; os::MultiWaitType m_deferred_list; /* Boolean values. */ const bool m_is_defer_supported; const bool m_is_mitm_supported; private: virtual void RegisterServerSessionToWait(ServerSession *session) override final; void LinkToDeferredList(os::MultiWaitHolderType *holder); void LinkDeferred(); bool WaitAndProcessImpl(); Result ProcessForServer(os::MultiWaitHolderType *holder); Result ProcessForSession(os::MultiWaitHolderType *holder); #if AMS_SF_MITM_SUPPORTED Result ProcessForMitmServer(os::MultiWaitHolderType *holder); #endif void RegisterServerImpl(Server *server, os::NativeHandle port_handle, bool is_mitm_server) { server->m_port_handle = port_handle; hipc::AttachMultiWaitHolderForAccept(server, port_handle); #if AMS_SF_MITM_SUPPORTED server->m_is_mitm_server = is_mitm_server; if (is_mitm_server) { /* Mitm server. */ AMS_ABORT_UNLESS(this->CanManageMitmServers()); os::SetMultiWaitHolderUserData(server, static_cast<uintptr_t>(UserDataTag::MitmServer)); } else { /* Non-mitm server. */ os::SetMultiWaitHolderUserData(server, static_cast<uintptr_t>(UserDataTag::Server)); } #else AMS_UNUSED(is_mitm_server); os::SetMultiWaitHolderUserData(server, static_cast<uintptr_t>(UserDataTag::Server)); #endif os::LinkMultiWaitHolder(std::addressof(m_multi_wait), server); } void RegisterServerImpl(int index, cmif::ServiceObjectHolder &&static_holder, os::NativeHandle port_handle, bool is_mitm_server) { /* Allocate server memory. */ auto *server = this->AllocateServer(); AMS_ABORT_UNLESS(server != nullptr); server->m_service_managed = false; if (static_holder) { server->m_static_object = std::move(static_holder); } else { server->m_index = index; } this->RegisterServerImpl(server, port_handle, is_mitm_server); } Result RegisterServerImpl(int index, cmif::ServiceObjectHolder &&static_holder, sm::ServiceName service_name, size_t max_sessions) { /* Register service. */ os::NativeHandle port_handle; R_TRY(sm::RegisterService(&port_handle, service_name, max_sessions, false)); /* Allocate server memory. */ auto *server = this->AllocateServer(); AMS_ABORT_UNLESS(server != nullptr); server->m_service_managed = true; server->m_service_name = service_name; if (static_holder) { server->m_static_object = std::move(static_holder); } else { server->m_index = index; } this->RegisterServerImpl(server, port_handle, false); R_SUCCEED(); } #if AMS_SF_MITM_SUPPORTED Result InstallMitmServerImpl(os::NativeHandle *out_port_handle, sm::ServiceName service_name, MitmQueryFunction query_func); #endif protected: virtual Server *AllocateServer() = 0; virtual void DestroyServer(Server *server) = 0; virtual Result OnNeedsToAccept(int port_index, Server *server) { AMS_UNUSED(port_index, server); AMS_ABORT("OnNeedsToAccept must be overridden when using indexed ports"); } template<typename Interface> Result AcceptImpl(Server *server, SharedPointer<Interface> p) { R_RETURN(ServerSessionManager::AcceptSession(server->m_port_handle, std::move(p))); } #if AMS_SF_MITM_SUPPORTED template<typename Interface> Result AcceptMitmImpl(Server *server, SharedPointer<Interface> p, std::shared_ptr<::Service> forward_service) { AMS_ABORT_UNLESS(this->CanManageMitmServers()); R_RETURN(ServerSessionManager::AcceptMitmSession(server->m_port_handle, std::move(p), std::move(forward_service))); } template<typename Interface> Result RegisterMitmServerImpl(int index, cmif::ServiceObjectHolder &&static_holder, sm::ServiceName service_name) { /* Install mitm service. */ os::NativeHandle port_handle; R_TRY(this->InstallMitmServerImpl(&port_handle, service_name, &Interface::ShouldMitm)); /* Allocate server memory. */ auto *server = this->AllocateServer(); AMS_ABORT_UNLESS(server != nullptr); server->m_service_managed = true; server->m_service_name = service_name; if (static_holder) { server->m_static_object = std::move(static_holder); } else { server->m_index = index; } this->RegisterServerImpl(server, port_handle, true); R_SUCCEED(); } #endif public: ServerManagerBase(DomainEntryStorage *entry_storage, size_t entry_count, bool defer_supported, bool mitm_supported) : ServerDomainSessionManager(entry_storage, entry_count), m_request_stop_event(os::EventClearMode_ManualClear), m_notify_event(os::EventClearMode_ManualClear), m_selection_mutex(), m_deferred_list_mutex(), m_is_defer_supported(defer_supported), m_is_mitm_supported(mitm_supported) { /* Link multi-wait holders. */ os::InitializeMultiWait(std::addressof(m_multi_wait)); os::InitializeMultiWaitHolder(std::addressof(m_request_stop_event_holder), m_request_stop_event.GetBase()); os::LinkMultiWaitHolder(std::addressof(m_multi_wait), std::addressof(m_request_stop_event_holder)); os::InitializeMultiWaitHolder(std::addressof(m_notify_event_holder), m_notify_event.GetBase()); os::LinkMultiWaitHolder(std::addressof(m_multi_wait), std::addressof(m_notify_event_holder)); os::InitializeMultiWait(std::addressof(m_deferred_list)); } virtual ~ServerManagerBase() = default; static ALWAYS_INLINE bool CanAnyDeferInvokeRequest() { return g_is_any_deferred_supported; } ALWAYS_INLINE bool CanDeferInvokeRequest() const { return CanAnyDeferInvokeRequest() && m_is_defer_supported; } #if AMS_SF_MITM_SUPPORTED static ALWAYS_INLINE bool CanAnyManageMitmServers() { return g_is_any_mitm_supported; } ALWAYS_INLINE bool CanManageMitmServers() const { return CanAnyManageMitmServers() && m_is_mitm_supported; } #else static consteval bool CanAnyManageMitmServers() { return false; } static consteval bool CanManageMitmServers() { return false; } #endif template<typename Interface> void RegisterObjectForServer(SharedPointer<Interface> static_object, os::NativeHandle port_handle) { this->RegisterServerImpl(0, cmif::ServiceObjectHolder(std::move(static_object)), port_handle, false); } template<typename Interface> Result RegisterObjectForServer(SharedPointer<Interface> static_object, sm::ServiceName service_name, size_t max_sessions) { R_RETURN(this->RegisterServerImpl(0, cmif::ServiceObjectHolder(std::move(static_object)), service_name, max_sessions)); } void RegisterServer(int port_index, os::NativeHandle port_handle) { this->RegisterServerImpl(port_index, cmif::ServiceObjectHolder(), port_handle, false); } Result RegisterServer(int port_index, sm::ServiceName service_name, size_t max_sessions) { R_RETURN(this->RegisterServerImpl(port_index, cmif::ServiceObjectHolder(), service_name, max_sessions)); } /* Processing. */ os::MultiWaitHolderType *WaitSignaled(); void ResumeProcessing(); void RequestStopProcessing(); void AddUserMultiWaitHolder(os::MultiWaitHolderType *holder); Result Process(os::MultiWaitHolderType *holder); void WaitAndProcess(); void LoopProcess(); }; template<size_t MaxServers, typename ManagerOptions = DefaultServerManagerOptions, size_t MaxSessions = ServerSessionCountMax - MaxServers> class ServerManager : public ServerManagerBase { NON_COPYABLE(ServerManager); NON_MOVEABLE(ServerManager); static_assert(MaxServers <= ServerSessionCountMax, "MaxServers can never be larger than ServerSessionCountMax (0x40)."); static_assert(MaxSessions <= ServerSessionCountMax, "MaxSessions can never be larger than ServerSessionCountMax (0x40)."); static_assert(MaxServers + MaxSessions <= ServerSessionCountMax, "MaxServers + MaxSessions can never be larger than ServerSessionCountMax (0x40)."); private: static constexpr inline bool DomainCountsValid = [] { if constexpr (ManagerOptions::MaxDomains > 0) { return ManagerOptions::MaxDomainObjects > 0; } else { return ManagerOptions::MaxDomainObjects == 0; } }(); static_assert(DomainCountsValid, "Invalid Domain Counts"); #if !(AMS_SF_MITM_SUPPORTED) static_assert(!ManagerOptions::CanManageMitmServers); #endif protected: using ServerManagerBase::DomainEntryStorage; using ServerManagerBase::DomainStorage; private: /* Resource storage. */ os::SdkMutex m_resource_mutex; util::TypedStorage<Server> m_server_storages[MaxServers]; bool m_server_allocated[MaxServers]; util::TypedStorage<ServerSession> m_session_storages[MaxSessions]; bool m_session_allocated[MaxSessions]; u8 m_pointer_buffer_storage[0x10 + (MaxSessions * ManagerOptions::PointerBufferSize)]; #if AMS_SF_MITM_SUPPORTED u8 m_saved_message_storage[0x10 + (MaxSessions * ((ManagerOptions::CanDeferInvokeRequest || ManagerOptions::CanManageMitmServers) ? hipc::TlsMessageBufferSize : 0))]; #else u8 m_saved_message_storage[0x10 + (MaxSessions * ((ManagerOptions::CanDeferInvokeRequest) ? hipc::TlsMessageBufferSize : 0))]; #endif uintptr_t m_pointer_buffers_start; uintptr_t m_saved_messages_start; /* Domain resources. */ DomainStorage m_domain_storages[ManagerOptions::MaxDomains]; bool m_domain_allocated[ManagerOptions::MaxDomains]; DomainEntryStorage m_domain_entry_storages[ManagerOptions::MaxDomainObjects]; private: constexpr inline size_t GetServerIndex(const Server *server) const { const size_t i = server - GetPointer(m_server_storages[0]); AMS_ABORT_UNLESS(i < MaxServers); return i; } constexpr inline size_t GetSessionIndex(const ServerSession *session) const { const size_t i = session - GetPointer(m_session_storages[0]); AMS_ABORT_UNLESS(i < MaxSessions); return i; } constexpr inline cmif::PointerAndSize GetObjectBySessionIndex(const ServerSession *session, uintptr_t start, size_t size) const { return cmif::PointerAndSize(start + this->GetSessionIndex(session) * size, size); } protected: virtual ServerSession *AllocateSession() override final { if constexpr (MaxSessions > 0) { std::scoped_lock lk(m_resource_mutex); for (size_t i = 0; i < MaxSessions; i++) { if (!m_session_allocated[i]) { m_session_allocated[i] = true; return GetPointer(m_session_storages[i]); } } } return nullptr; } virtual void FreeSession(ServerSession *session) override final { std::scoped_lock lk(m_resource_mutex); const size_t index = this->GetSessionIndex(session); AMS_ABORT_UNLESS(m_session_allocated[index]); m_session_allocated[index] = false; } virtual Server *AllocateServer() override final { if constexpr (MaxServers > 0) { std::scoped_lock lk(m_resource_mutex); for (size_t i = 0; i < MaxServers; i++) { if (!m_server_allocated[i]) { m_server_allocated[i] = true; return GetPointer(m_server_storages[i]); } } } return nullptr; } virtual void DestroyServer(Server *server) override final { std::scoped_lock lk(m_resource_mutex); const size_t index = this->GetServerIndex(server); AMS_ABORT_UNLESS(m_server_allocated[index]); { os::UnlinkMultiWaitHolder(server); os::FinalizeMultiWaitHolder(server); if (server->m_service_managed) { #if AMS_SF_MITM_SUPPORTED if constexpr (ManagerOptions::CanManageMitmServers) { if (server->m_is_mitm_server) { R_ABORT_UNLESS(sm::mitm::UninstallMitm(server->m_service_name)); } else { R_ABORT_UNLESS(sm::UnregisterService(server->m_service_name)); } } else { R_ABORT_UNLESS(sm::UnregisterService(server->m_service_name)); } #else R_ABORT_UNLESS(sm::UnregisterService(server->m_service_name)); #endif os::CloseNativeHandle(server->m_port_handle); } } m_server_allocated[index] = false; } virtual void *AllocateDomain() override final { std::scoped_lock lk(m_resource_mutex); for (size_t i = 0; i < ManagerOptions::MaxDomains; i++) { if (!m_domain_allocated[i]) { m_domain_allocated[i] = true; return GetPointer(m_domain_storages[i]); } } return nullptr; } virtual void FreeDomain(void *domain) override final { std::scoped_lock lk(m_resource_mutex); DomainStorage *ptr = static_cast<DomainStorage *>(domain); const size_t index = ptr - m_domain_storages; AMS_ABORT_UNLESS(index < ManagerOptions::MaxDomains); AMS_ABORT_UNLESS(m_domain_allocated[index]); m_domain_allocated[index] = false; } virtual cmif::PointerAndSize GetSessionPointerBuffer(const ServerSession *session) const override final { if constexpr (ManagerOptions::PointerBufferSize > 0) { return this->GetObjectBySessionIndex(session, m_pointer_buffers_start, ManagerOptions::PointerBufferSize); } else { return cmif::PointerAndSize(); } } virtual cmif::PointerAndSize GetSessionSavedMessageBuffer(const ServerSession *session) const override final { if constexpr (ManagerOptions::CanDeferInvokeRequest || ManagerOptions::CanManageMitmServers) { return this->GetObjectBySessionIndex(session, m_saved_messages_start, hipc::TlsMessageBufferSize); } else { return cmif::PointerAndSize(); } } public: ServerManager() : ServerManagerBase(m_domain_entry_storages, ManagerOptions::MaxDomainObjects, ManagerOptions::CanDeferInvokeRequest, ManagerOptions::CanManageMitmServers), m_resource_mutex() { /* Clear storages. */ #define SF_SM_MEMCLEAR(obj) if constexpr (sizeof(obj) > 0) { std::memset(obj, 0, sizeof(obj)); } SF_SM_MEMCLEAR(m_server_storages); SF_SM_MEMCLEAR(m_server_allocated); SF_SM_MEMCLEAR(m_session_storages); SF_SM_MEMCLEAR(m_session_allocated); SF_SM_MEMCLEAR(m_pointer_buffer_storage); SF_SM_MEMCLEAR(m_saved_message_storage); SF_SM_MEMCLEAR(m_domain_allocated); #undef SF_SM_MEMCLEAR /* Set resource starts. */ m_pointer_buffers_start = util::AlignUp(reinterpret_cast<uintptr_t>(m_pointer_buffer_storage), 0x10); m_saved_messages_start = util::AlignUp(reinterpret_cast<uintptr_t>(m_saved_message_storage), 0x10); /* Update globals. */ if constexpr (ManagerOptions::CanDeferInvokeRequest) { ServerManagerBase::g_is_any_deferred_supported = true; } #if AMS_SF_MITM_SUPPORTED if constexpr (ManagerOptions::CanManageMitmServers) { ServerManagerBase::g_is_any_mitm_supported = true; } #endif } ~ServerManager() { /* Close all sessions. */ if constexpr (MaxSessions > 0) { for (size_t i = 0; i < MaxSessions; i++) { if (m_session_allocated[i]) { this->CloseSessionImpl(GetPointer(m_session_storages[i])); } } } /* Close all servers. */ if constexpr (MaxServers > 0) { for (size_t i = 0; i < MaxServers; i++) { if (m_server_allocated[i]) { this->DestroyServer(GetPointer(m_server_storages[i])); } } } } public: #if AMS_SF_MITM_SUPPORTED template<typename Interface, bool Enable = ManagerOptions::CanManageMitmServers, typename = typename std::enable_if<Enable>::type> Result RegisterMitmServer(int port_index, sm::ServiceName service_name) { AMS_ABORT_UNLESS(this->CanManageMitmServers()); R_RETURN(this->template RegisterMitmServerImpl<Interface>(port_index, cmif::ServiceObjectHolder(), service_name)); } #endif }; }
23,685
C++
.h
444
37.873874
205
0.574998
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
7,567
sf_service_object_impl.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/sf/impl/sf_service_object_impl.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> namespace ams::sf::impl { class ServiceObjectImplBase2 { private: std::atomic<u32> m_ref_count; protected: constexpr ServiceObjectImplBase2() : m_ref_count(1) { /* ... */ } void AddReferenceImpl() { const auto prev = m_ref_count.fetch_add(1); AMS_ABORT_UNLESS(prev < std::numeric_limits<u32>::max()); } bool ReleaseImpl() { const auto prev = m_ref_count.fetch_sub(1); AMS_ABORT_UNLESS(prev != 0); return prev == 1; } }; }
1,274
C++
.h
34
30.735294
77
0.636437
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
7,568
sf_impl_autogen_impl_macros.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/sf/impl/sf_impl_autogen_impl_macros.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/sf/impl/sf_impl_autogen_interface_macros.hpp> #include <stratosphere/sf/impl/sf_impl_template_base.hpp> namespace ams::sf::impl { #define AMS_SF_IMPL_DEFINE_IMPL_SYNC_METHOD(CLASSNAME, CMD_ID, RETURN, NAME, ARGS, ARGNAMES, VERSION_MIN, VERSION_MAX) \ virtual RETURN AMS_SF_IMPL_SYNC_FUNCTION_NAME(NAME) ARGS override { \ return ImplGetter::GetImplPointer(static_cast<ImplHolder *>(this))->NAME ARGNAMES; \ } #define AMS_SF_DEFINE_INTERFACE_WITH_DEFAULT_BASE(NAMESPACE, INTERFACE, BASE, CMD_MACRO, INTF_ID) \ namespace NAMESPACE { \ \ AMS_SF_DEFINE_INTERFACE_IMPL(BASE, INTERFACE, CMD_MACRO, INTF_ID) \ \ } \ \ namespace ams::sf::impl { \ \ template<typename Base, typename ImplHolder, typename ImplGetter, typename Root> \ class ImplTemplateBaseT<::NAMESPACE::INTERFACE, Base, ImplHolder, ImplGetter, Root> : public Base, public ImplHolder { \ public: \ template<typename... Args> \ constexpr explicit ImplTemplateBaseT(Args &&...args) : ImplHolder(std::forward<Args>(args)...) { } \ private: \ CMD_MACRO(CLASSNAME, AMS_SF_IMPL_DEFINE_IMPL_SYNC_METHOD) \ }; \ \ } #define AMS_SF_DEFINE_INTERFACE(NAMESPACE, INTERFACE, CMD_MACRO, INTF_ID) \ AMS_SF_DEFINE_INTERFACE_WITH_DEFAULT_BASE(NAMESPACE, INTERFACE, ::ams::sf::IServiceObject, CMD_MACRO, INTF_ID) #define AMS_SF_DEFINE_MITM_INTERFACE(NAMESPACE, INTERFACE, CMD_MACRO, INTF_ID) \ AMS_SF_DEFINE_INTERFACE_WITH_DEFAULT_BASE(NAMESPACE, INTERFACE, ::ams::sf::IMitmServiceObject, CMD_MACRO, INTF_ID) #define AMS_SF_DEFINE_INTERFACE_WITH_BASE(NAMESPACE, INTERFACE, BASE, CMD_MACRO, INTF_ID) \ namespace NAMESPACE { \ \ AMS_SF_DEFINE_INTERFACE_IMPL(BASE, INTERFACE, CMD_MACRO, INTF_ID) \ \ } \ \ namespace ams::sf::impl { \ \ template<typename Base, typename ImplHolder, typename ImplGetter, typename Root> \ class ImplTemplateBaseT<::NAMESPACE::INTERFACE, Base, ImplHolder, ImplGetter, Root> : public ImplTemplateBaseT<BASE, Base, ImplHolder, ImplGetter, Root> { \ private: \ using BaseImplTemplateBase = ImplTemplateBaseT<BASE, Base, ImplHolder, ImplGetter, Root>; \ public: \ template<typename... Args> \ constexpr explicit ImplTemplateBaseT(Args &&...args) : BaseImplTemplateBase(std::forward<Args>(args)...) { } \ private: \ CMD_MACRO(CLASSNAME, AMS_SF_IMPL_DEFINE_IMPL_SYNC_METHOD) \ }; \ \ } }
7,419
C++
.h
69
78.188406
168
0.297698
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
7,569
sf_impl_autogen_interface_macros.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/sf/impl/sf_impl_autogen_interface_macros.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> namespace ams::sf::impl { struct SyncFunctionTraits { public: template<typename R, typename C, typename... A> static std::tuple<A...> GetArgsImpl(R(C::*)(A...)); }; template<auto F> using SyncFunctionArgsType = decltype(SyncFunctionTraits::GetArgsImpl(F)); template<typename T> struct TypeTag{}; template<size_t First, size_t... Ix> static constexpr inline size_t ParameterCount = sizeof...(Ix); #define AMS_SF_IMPL_SYNC_FUNCTION_NAME(FUNCNAME) \ _ams_sf_sync_##FUNCNAME #define AMS_SF_IMPL_DEFINE_INTERFACE_SYNC_METHOD(CLASSNAME, CMD_ID, RETURN, NAME, ARGS, ARGNAMES, VERSION_MIN, VERSION_MAX) \ virtual RETURN AMS_SF_IMPL_SYNC_FUNCTION_NAME(NAME) ARGS = 0; #define AMS_SF_IMPL_EXTRACT_INTERFACE_SYNC_METHOD_ARGUMENTS(CLASSNAME, CMD_ID, RETURN, NAME, ARGS, ARGNAMES, VERSION_MIN, VERSION_MAX) \ using NAME##ArgumentsType = ::ams::sf::impl::SyncFunctionArgsType<&CLASSNAME::AMS_SF_IMPL_SYNC_FUNCTION_NAME(NAME)>; #define AMS_SF_IMPL_DEFINE_INTERFACE_METHOD(CLASSNAME, CMD_ID, RETURN, NAME, ARGS, ARGNAMES, VERSION_MIN, VERSION_MAX) \ ALWAYS_INLINE RETURN NAME ARGS { \ return this->AMS_SF_IMPL_SYNC_FUNCTION_NAME(NAME) ARGNAMES; \ } #define AMS_SF_IMPL_DEFINE_INTERFACE_SERVICE_COMMAND_META_HOLDER(CLASSNAME, CMD_ID, RETURN, NAME, ARGS, ARGNAMES, VERSION_MIN, VERSION_MAX) \ template<typename Interface, typename A> struct NAME##ServiceCommandMetaHolder; \ \ template<typename Interface, typename ...Arguments> \ requires std::same_as<std::tuple<Arguments...>, NAME##ArgumentsType> \ struct NAME##ServiceCommandMetaHolder<Interface, std::tuple<Arguments...>> { \ static constexpr auto Value = ::ams::sf::impl::MakeServiceCommandMeta<VERSION_MIN, VERSION_MAX, CMD_ID, &Interface::AMS_SF_IMPL_SYNC_FUNCTION_NAME(NAME), RETURN, Interface, Arguments...>(); \ }; #define AMS_SF_IMPL_GET_NULL_FOR_PARAMETER_COUNT(CLASSNAME, CMD_ID, RETURN, NAME, ARGS, ARGNAMES, VERSION_MIN, VERSION_MAX) \ , 0 #define AMS_SF_IMPL_DEFINE_CMIF_SERVICE_COMMAND_META_TABLE_ENTRY(CLASSNAME, CMD_ID, RETURN, NAME, ARGS, ARGNAMES, VERSION_MIN, VERSION_MAX) \ NAME##ServiceCommandMetaHolder<Interface, NAME##ArgumentsType>::Value, template<typename...> struct Print; #define AMS_SF_IMPL_DEFINE_INTERFACE(BASECLASS, CLASSNAME, CMD_MACRO, INTF_ID) \ class CLASSNAME : public BASECLASS { \ public: \ static constexpr u32 InterfaceIdForDebug = INTF_ID; \ private: \ CMD_MACRO(CLASSNAME, AMS_SF_IMPL_DEFINE_INTERFACE_SYNC_METHOD) \ public: \ CMD_MACRO(CLASSNAME, AMS_SF_IMPL_EXTRACT_INTERFACE_SYNC_METHOD_ARGUMENTS) \ public: \ CMD_MACRO(CLASSNAME, AMS_SF_IMPL_DEFINE_INTERFACE_METHOD) \ private: \ CMD_MACRO(CLASSNAME, AMS_SF_IMPL_DEFINE_INTERFACE_SERVICE_COMMAND_META_HOLDER) \ public: \ template<typename Interface> \ static constexpr inline ::ams::sf::cmif::ServiceDispatchTable s_CmifServiceDispatchTable { \ [] { \ constexpr size_t CurSize = ::ams::sf::impl::ParameterCount<0 CMD_MACRO(CLASSNAME, AMS_SF_IMPL_GET_NULL_FOR_PARAMETER_COUNT) >; \ std::array<::ams::sf::cmif::ServiceCommandMeta, CurSize> cur_entries { CMD_MACRO(CLASSNAME, AMS_SF_IMPL_DEFINE_CMIF_SERVICE_COMMAND_META_TABLE_ENTRY) }; \ \ constexpr const auto &BaseEntries = ::ams::sf::cmif::ServiceDispatchTraits<BASECLASS>::DispatchTable.GetEntries(); \ constexpr size_t BaseSize = BaseEntries.size(); \ \ constexpr size_t CombinedSize = BaseSize + CurSize; \ \ std::array<size_t, CombinedSize> map{}; \ for (size_t i = 0; i < CombinedSize; ++i) { map[i] = i; } \ \ for (size_t i = 1; i < CombinedSize; ++i) { \ size_t j = i; \ while (j > 0) { \ const auto li = map[j]; \ const auto ri = map[j - 1]; \ \ const auto &lhs = (li < BaseSize) ? BaseEntries[li] : cur_entries[li - BaseSize]; \ const auto &rhs = (ri < BaseSize) ? BaseEntries[ri] : cur_entries[ri - BaseSize]; \ \ if (!(rhs > lhs)) { \ break; \ } \ \ std::swap(map[j], map[j - 1]); \ \ --j; \ } \ } \ \ std::array<::ams::sf::cmif::ServiceCommandMeta, CombinedSize> combined_entries{}; \ for (size_t i = 0; i < CombinedSize; ++i) { \ if (map[i] < BaseSize) { \ combined_entries[i] = BaseEntries[map[i]]; \ } else { \ combined_entries[i] = cur_entries[map[i] - BaseSize]; \ } \ } \ \ return ::ams::sf::cmif::ServiceDispatchTable<Interface::InterfaceIdForDebug, CombinedSize> { combined_entries }; \ }() \ }; \ }; #define AMS_SF_IMPL_DEFINE_CONCEPT_HELPERS(CLASSNAME, CMD_ID, RETURN, NAME, ARGS, ARGNAMES, VERSION_MIN, VERSION_MAX) \ template<typename T, typename... Args> \ concept Is##CLASSNAME##__##NAME##Impl = requires (T &t, Args &&... args) { \ { t.NAME(std::forward<Args>(args)...) } -> std::same_as<RETURN>; \ }; \ \ template<typename T, typename A> \ struct Is##CLASSNAME##__##NAME##Holder : std::false_type{}; \ \ template<typename T, typename... Args> requires std::same_as<std::tuple<Args...>, CLASSNAME::NAME##ArgumentsType> \ struct Is##CLASSNAME##__##NAME##Holder<T, std::tuple<Args...>> : std::bool_constant<Is##CLASSNAME##__##NAME##Impl<T, Args...>>{}; \ \ template<typename T> \ static constexpr inline bool Is##CLASSNAME##__##NAME = Is##CLASSNAME##__##NAME##Holder<T, CLASSNAME::NAME##ArgumentsType>::value; #define AMS_SF_IMPL_CHECK_CONCEPT_HELPER(CLASSNAME, CMD_ID, RETURN, NAME, ARGS, ARGNAMES, VERSION_MIN, VERSION_MAX) \ Is##CLASSNAME##__##NAME<T> && #define AMS_SF_IMPL_DEFINE_CONCEPT(CLASSNAME, CMD_MACRO) \ CMD_MACRO(CLASSNAME, AMS_SF_IMPL_DEFINE_CONCEPT_HELPERS) \ \ template<typename T> \ concept Is##CLASSNAME = CMD_MACRO(CLASSNAME, AMS_SF_IMPL_CHECK_CONCEPT_HELPER) true; #define AMS_SF_DEFINE_INTERFACE_IMPL(BASECLASS, CLASSNAME, CMD_MACRO, INTF_ID) \ AMS_SF_IMPL_DEFINE_INTERFACE(BASECLASS, CLASSNAME, CMD_MACRO, INTF_ID) \ AMS_SF_IMPL_DEFINE_CONCEPT(CLASSNAME, CMD_MACRO) \ static_assert(Is##CLASSNAME<CLASSNAME>); #define AMS_SF_METHOD_INFO_7(CLASSNAME, HANDLER, CMD_ID, RETURN, NAME, ARGS, ARGNAMES) \ HANDLER(CLASSNAME, CMD_ID, RETURN, NAME, ARGS, ARGNAMES, hos::Version_Min, hos::Version_Max) #define AMS_SF_METHOD_INFO_8(CLASSNAME, HANDLER, CMD_ID, RETURN, NAME, ARGS, ARGNAMES, VERSION_MIN) \ HANDLER(CLASSNAME, CMD_ID, RETURN, NAME, ARGS, ARGNAMES, VERSION_MIN, hos::Version_Max) #define AMS_SF_METHOD_INFO_9(CLASSNAME, HANDLER, CMD_ID, RETURN, NAME, ARGS, ARGNAMES, VERSION_MIN, VERSION_MAX) \ HANDLER(CLASSNAME, CMD_ID, RETURN, NAME, ARGS, ARGNAMES, VERSION_MIN, VERSION_MAX) #define AMS_SF_METHOD_INFO_X(_, _0, _1, _2, _3, _4, _5, _6, _7, _8, FUNC, ...) FUNC #define AMS_SF_METHOD_INFO(...) \ AMS_SF_METHOD_INFO_X(, ## __VA_ARGS__, AMS_SF_METHOD_INFO_9(__VA_ARGS__), AMS_SF_METHOD_INFO_8(__VA_ARGS__), AMS_SF_METHOD_INFO_7(__VA_ARGS__)) }
18,116
C++
.h
147
94.727891
203
0.283852
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
7,570
sf_impl_template_base.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/sf/impl/sf_impl_template_base.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> namespace ams::sf::impl { template<typename Interface, typename Base, typename ImplHolder, typename ImplGetter, typename Root> class ImplTemplateBaseT; template<typename Interface, typename Base, typename ImplHolder, typename ImplGetter> class ImplTemplateBase : public ImplTemplateBaseT<Interface, Base, ImplHolder, ImplGetter, Interface> { private: using BaseImpl = ImplTemplateBaseT<Interface, Base, ImplHolder, ImplGetter, Interface>; public: using BaseImpl::BaseImpl; }; }
1,213
C++
.h
28
39.535714
107
0.750212
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
7,571
sf_impl_command_serialization.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/sf/impl/sf_impl_command_serialization.hpp
/* * 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/>. */ #pragma once #include <stratosphere/sf/sf_common.hpp> #include <stratosphere/sf/sf_service_object.hpp> #include <stratosphere/sf/sf_out.hpp> #include <stratosphere/sf/sf_buffers.hpp> #include <stratosphere/sf/sf_native_handle.hpp> #include <stratosphere/sf/cmif/sf_cmif_pointer_and_size.hpp> #include <stratosphere/sf/cmif/sf_cmif_service_dispatch.hpp> #include <stratosphere/sf/cmif/sf_cmif_service_object_holder.hpp> #include <stratosphere/sf/cmif/sf_cmif_domain_api.hpp> #include <stratosphere/sf/hipc/sf_hipc_api.hpp> #include <stratosphere/sf/hipc/sf_hipc_server_session_manager.hpp> /* Serialization classes. */ namespace ams::sf { namespace impl { struct ProcessIdHolder { os::ProcessId process_id; constexpr explicit operator os::ProcessId() const { return this->process_id; } constexpr os::ProcessId GetValue() const { return this->process_id; } constexpr void SetValue(const os::ProcessId &p) { this->process_id = p; } }; } struct ClientProcessId : public impl::ProcessIdHolder {}; static_assert(std::is_trivial<ClientProcessId>::value && sizeof(ClientProcessId) == sizeof(os::ProcessId), "ClientProcessId"); struct ClientAppletResourceUserId : public impl::ProcessIdHolder {}; static_assert(std::is_trivial<ClientAppletResourceUserId >::value && sizeof(ClientAppletResourceUserId ) == sizeof(os::ProcessId), "ClientAppletResourceUserId"); namespace impl { constexpr inline Result MarshalProcessId(ClientProcessId &client, const os::ProcessId &client_process_id) { client.SetValue(client_process_id); R_SUCCEED(); } constexpr inline Result MarshalProcessId(ClientAppletResourceUserId &client, const os::ProcessId &client_process_id) { if (client.GetValue() != client_process_id && client.GetValue() != os::ProcessId{}) { R_THROW(sf::ResultPreconditionViolation()); } R_SUCCEED(); } } namespace impl { struct OutObjectTag{}; template<size_t, size_t> class InOutObjectHolder; } template<typename ServiceImpl> requires std::derived_from<ServiceImpl, IServiceObject> class Out<SharedPointer<ServiceImpl>> : public impl::OutObjectTag { template<typename> friend class Out; public: using Interface = ServiceImpl; private: impl::SharedPointerBase *m_out; cmif::DomainObjectId *m_object_id; private: Out(impl::SharedPointerBase *p, cmif::DomainObjectId *o = nullptr) : m_out(p), m_object_id(o) { /* ... */ } public: Out(const Out &rhs) : m_out(rhs.m_out), m_object_id(rhs.m_object_id) { /* ... */ } Out(SharedPointer<ServiceImpl> *out, cmif::DomainObjectId *o = nullptr) : m_out(std::addressof(out->m_base)), m_object_id(o) { /* .... */ } template<typename U> requires std::derived_from<U, ServiceImpl> Out(Out<SharedPointer<U>> out) : m_out(out.m_out), m_object_id(out.m_object_id) { /* ... */ } template<typename U> requires std::derived_from<U, ServiceImpl> Out(SharedPointer<U> *out, cmif::DomainObjectId *o = nullptr) : m_out(std::addressof(out->m_base)), m_object_id(o) { /* .... */ } void SetValue(SharedPointer<ServiceImpl> s, cmif::DomainObjectId new_object_id = cmif::InvalidDomainObjectId) { *m_out = std::move(s.m_base); if (new_object_id != cmif::InvalidDomainObjectId) { AMS_ABORT_UNLESS(m_object_id != nullptr); *m_object_id = new_object_id; } } template<typename U> requires std::derived_from<U, ServiceImpl> void SetValue(SharedPointer<U> s, cmif::DomainObjectId new_object_id = cmif::InvalidDomainObjectId) { *m_out = std::move(s.m_base); if (new_object_id != cmif::InvalidDomainObjectId) { AMS_ABORT_UNLESS(m_object_id != nullptr); *m_object_id = new_object_id; } } class DerefProxy { template<typename> friend class Out; private: Out &m_target; private: explicit DerefProxy(Out &t) : m_target(t) { /* ... */ } public: DerefProxy &operator=(SharedPointer<ServiceImpl> p) { m_target.SetValue(std::move(p)); return *this; } template<typename U> requires std::derived_from<U, ServiceImpl> DerefProxy &operator=(SharedPointer<U> p) { m_target.SetValue(std::move(p)); return *this; } }; DerefProxy operator *() { return DerefProxy(*this); } template<typename U> Out<SharedPointer<U>> DownCast() { return Out<SharedPointer<U>>(m_out, m_object_id); } }; } #if defined(ATMOSPHERE_OS_HORIZON) namespace ams::sf::impl { /* Machinery for filtering type lists. */ template<class, class> struct TupleCat; template<class... First, class... Second> struct TupleCat<std::tuple<First...>, std::tuple<Second...>> { using type = std::tuple<First..., Second...>; }; template<template <typename> typename Cond> struct TupleFilter { private: template<typename, typename> struct ImplType; template<typename Res> struct ImplType<Res, std::tuple<>> { using type = Res; }; template<typename Res, typename T, typename... Ts> struct ImplType<Res, std::tuple<T, Ts...>> { using type = typename std::conditional<Cond<T>::value, typename ImplType<typename TupleCat<Res, std::tuple<T>>::type, std::tuple<Ts...>>::type, typename ImplType<Res, std::tuple<Ts...>>::type >::type; }; public: template<typename T> using FilteredType = typename ImplType<std::tuple<>, T>::type; }; enum class ArgumentType { InData, OutData, Buffer, InHandle, OutHandle, InObject, OutObject, }; template<typename T> struct IsInObject : public std::false_type{}; template<typename T> struct IsInObject<sf::SharedPointer<T>> : public std::true_type { static_assert(std::is_base_of<sf::IServiceObject, T>::value, "Invalid IsInObject<sf::SharedPointer<T>>"); }; template<typename T> constexpr inline ArgumentType GetArgumentType = [] { static_assert(!std::same_as<T, sf::NativeHandle>); static_assert(!std::same_as<T, sf::Out<sf::NativeHandle>>); if constexpr (sf::IsBuffer<T>) { return ArgumentType::Buffer; } else if constexpr (IsInObject<T>::value) { return ArgumentType::InObject; } else if constexpr (std::is_base_of<sf::impl::OutObjectTag, T>::value) { return ArgumentType::OutObject; } else if constexpr (std::same_as<T, sf::CopyHandle> || std::same_as<T, sf::MoveHandle>) { return ArgumentType::InHandle; } else if constexpr (std::same_as<T, sf::OutCopyHandle> || std::same_as<T, sf::OutMoveHandle>) { return ArgumentType::OutHandle; } else if constexpr (std::is_base_of<sf::impl::OutBaseTag, T>::value) { return ArgumentType::OutData; } else if constexpr (std::is_trivial<T>::value && !std::is_pointer<T>::value) { return ArgumentType::InData; } else if constexpr (std::is_same<T, ::ams::Result>::value) { return ArgumentType::InData; } else { static_assert(!std::is_same<T, T>::value, "Invalid ArgumentType<T>"); } }(); template<typename T, ArgumentType ArgT> struct ArgumentTypeFilter : public std::bool_constant<GetArgumentType<T> == ArgT>{}; template<typename T, typename U> struct TypeEqualityFilter : public std::bool_constant<std::is_same<T, U>::value>{}; /* Argument type filters. */ template<typename T> using InDataFilter = ArgumentTypeFilter<T, ArgumentType::InData>; template<typename T> using OutDataFilter = ArgumentTypeFilter<T, ArgumentType::OutData>; template<typename T> using BufferFilter = ArgumentTypeFilter<T, ArgumentType::Buffer>; template<typename T> using InHandleFilter = ArgumentTypeFilter<T, ArgumentType::InHandle>; template<typename T> using OutHandleFilter = ArgumentTypeFilter<T, ArgumentType::OutHandle>; template<typename T> using InObjectFilter = ArgumentTypeFilter<T, ArgumentType::InObject>; template<typename T> using OutObjectFilter = ArgumentTypeFilter<T, ArgumentType::OutObject>; template<typename T> struct ProcessIdHolderFilter : public std::bool_constant<std::is_base_of<sf::impl::ProcessIdHolder, T>::value>{}; /* Handle kind filters. */ template<typename T> using InMoveHandleFilter = TypeEqualityFilter<T, sf::MoveHandle>; template<typename T> using InCopyHandleFilter = TypeEqualityFilter<T, sf::CopyHandle>; template<typename T> using OutMoveHandleFilter = TypeEqualityFilter<T, sf::Out<sf::MoveHandle>>; template<typename T> using OutCopyHandleFilter = TypeEqualityFilter<T, sf::Out<sf::CopyHandle>>; template<typename> struct BufferAttributeArrayGetter; template<typename ...Ts> struct BufferAttributeArrayGetter<std::tuple<Ts...>> { static constexpr std::array<u32, sizeof...(Ts)> value = { BufferAttributes<Ts>..., }; }; template<> struct BufferAttributeArrayGetter<std::tuple<>> { static constexpr std::array<u32, 0> value{}; }; template<auto Predicate> struct BufferAttributeCounter { template<size_t Size> static constexpr size_t GetCount(const std::array<u32, Size> &attributes_array) { size_t count = 0; for (size_t i = 0; i < Size; i++) { if (Predicate(attributes_array[i])) { count++; } } return count; } }; NX_CONSTEXPR size_t InHipcMapAliasBufferPredicate(const u32 attribute) { if ((attribute & SfBufferAttr_In) && !(attribute & SfBufferAttr_Out)) { return (attribute & SfBufferAttr_HipcMapAlias) || (attribute & SfBufferAttr_HipcAutoSelect); } else { return false; } } NX_CONSTEXPR size_t OutHipcMapAliasBufferPredicate(const u32 attribute) { if (!(attribute & SfBufferAttr_In) && (attribute & SfBufferAttr_Out)) { return (attribute & SfBufferAttr_HipcMapAlias) || (attribute & SfBufferAttr_HipcAutoSelect); } else { return false; } } NX_CONSTEXPR size_t InHipcPointerBufferPredicate(const u32 attribute) { if ((attribute & SfBufferAttr_In) && !(attribute & SfBufferAttr_Out)) { return (attribute & SfBufferAttr_HipcPointer) || (attribute & SfBufferAttr_HipcAutoSelect); } else { return false; } } NX_CONSTEXPR size_t OutHipcPointerBufferPredicate(const u32 attribute) { if (!(attribute & SfBufferAttr_In) && (attribute & SfBufferAttr_Out)) { return (attribute & SfBufferAttr_HipcPointer) || (attribute & SfBufferAttr_HipcAutoSelect); } else { return false; } } NX_CONSTEXPR size_t FixedSizeOutHipcPointerBufferPredicate(const u32 attribute) { return OutHipcPointerBufferPredicate(attribute) && (attribute & SfBufferAttr_FixedSize); } template<typename> struct RawDataOffsetCalculator; template<typename... Ts> struct RawDataOffsetCalculator<std::tuple<Ts...>> { private: template<typename T> struct LayoutHelper { static_assert(GetArgumentType<T> == ArgumentType::InData, "LayoutHelper InData"); static constexpr size_t Alignment = alignof(T); static constexpr size_t Size = sizeof(T); }; template<typename T> struct LayoutHelper<Out<T>> { static_assert(GetArgumentType<T> == ArgumentType::InData, "LayoutHelper OutData"); static constexpr size_t Alignment = alignof(T); static constexpr size_t Size = sizeof(T); }; static constexpr void StableSort(std::array<size_t, sizeof...(Ts)> &map, const std::array<size_t, sizeof...(Ts)> &values) { /* Use insertion sort, which is stable and optimal for small numbers of parameters. */ for (size_t i = 1; i < sizeof...(Ts); i++) { for (size_t j = i; j > 0 && values[map[j-1]] > values[map[j]]; j--) { std::swap(map[j], map[j-1]); } } } public: static constexpr std::array<size_t, sizeof...(Ts)+1> Offsets = [] { std::array<size_t, sizeof...(Ts)+1> offsets{}; offsets[0] = 0; if constexpr (sizeof...(Ts) > 0) { /* Get size, alignment for each type. */ const std::array<size_t, sizeof...(Ts)> sizes = { LayoutHelper<Ts>::Size... }; const std::array<size_t, sizeof...(Ts)> aligns = { LayoutHelper<Ts>::Alignment... }; /* We want to sort...by alignment. */ std::array<size_t, sizeof...(Ts)> map = {}; for (size_t i = 0; i < sizeof...(Ts); i++) { map[i] = i; } StableSort(map, aligns); /* Iterate over sorted sizes. */ size_t cur_offset = 0; for (size_t i : map) { cur_offset = util::AlignUp(cur_offset, aligns[i]); offsets[i] = cur_offset; cur_offset += sizes[i]; } offsets[sizeof...(Ts)] = cur_offset; } return offsets; }(); }; struct ArgumentSerializationInfo { /* Type used to select from below fields. */ ArgumentType arg_type; /* Raw data indexing. */ size_t in_raw_data_index; size_t out_raw_data_index; /* Buffer indexing. */ size_t buffer_index; size_t send_map_alias_index; size_t recv_map_alias_index; size_t send_pointer_index; size_t recv_pointer_index; size_t unfixed_recv_pointer_index; size_t fixed_size; /* Handle indexing. */ size_t in_move_handle_index; size_t in_copy_handle_index; size_t out_move_handle_index; size_t out_copy_handle_index; /* Object indexing. */ size_t in_object_index; size_t out_object_index; }; template<typename T> using DecayForCommandMetaArguments = typename std::conditional<(sf::IsLargeData<typename std::decay<T>::type> && !std::is_base_of<impl::OutBaseTag, typename std::decay<T>::type>::value), T, typename std::conditional<(std::same_as<T, sf::MoveHandle &&> || std::same_as<T, sf::CopyHandle &&>), typename std::decay<T>::type &, typename std::decay<T>::type>::type>::type; template<typename... Arguments> struct CommandMetaInfo { public: using ArgsTypeForInvoke = std::tuple<DecayForCommandMetaArguments<Arguments>...>; using ArgsType = std::tuple<typename std::decay<Arguments>::type...>; using InDatas = TupleFilter<InDataFilter>::FilteredType<ArgsType>; using OutDatas = TupleFilter<OutDataFilter>::FilteredType<ArgsType>; using Buffers = TupleFilter<BufferFilter>::FilteredType<ArgsType>; using InHandles = TupleFilter<InHandleFilter>::FilteredType<ArgsType>; using OutHandles = TupleFilter<OutHandleFilter>::FilteredType<ArgsType>; using InObjects = TupleFilter<InObjectFilter>::FilteredType<ArgsType>; using OutObjects = TupleFilter<OutObjectFilter>::FilteredType<ArgsType>; /* Not kept separate from InDatas when processing, for reasons. */ using InProcessIdHolders = TupleFilter<ProcessIdHolderFilter>::FilteredType<InDatas>; /* TODO: Support OutProcessIdHolders? */ static constexpr size_t NumInDatas = std::tuple_size<InDatas>::value; static constexpr size_t NumOutDatas = std::tuple_size<OutDatas>::value; static constexpr size_t NumBuffers = std::tuple_size<Buffers>::value; static constexpr size_t NumInHandles = std::tuple_size<InHandles>::value; static constexpr size_t NumOutHandles = std::tuple_size<OutHandles>::value; static constexpr size_t NumInObjects = std::tuple_size<InObjects>::value; static constexpr size_t NumOutObjects = std::tuple_size<OutObjects>::value; static constexpr size_t NumInProcessIdHolders = std::tuple_size<InProcessIdHolders>::value; static constexpr bool HasInProcessIdHolder = NumInProcessIdHolders >= 1; template<typename T> static constexpr bool IsInProcessIdHolder = GetArgumentType<T> == ArgumentType::InData && std::is_base_of<sf::impl::ProcessIdHolder, T>::value; template<size_t I> static constexpr bool IsInProcessIdHolderIndex = I < std::tuple_size<ArgsType>::value && IsInProcessIdHolder<typename std::tuple_element<I, ArgsType>::type>; static_assert(NumBuffers <= 8, "Methods must take in <= 8 Buffers"); static_assert(NumInHandles <= 8, "Methods must take in <= 8 Handles"); static_assert(NumOutHandles + NumOutObjects <= 8, "Methods must output <= 8 Handles"); /* Buffer marshalling. */ static constexpr std::array<u32, NumBuffers> BufferAttributes = BufferAttributeArrayGetter<Buffers>::value; static constexpr size_t NumInHipcMapAliasBuffers = BufferAttributeCounter<InHipcMapAliasBufferPredicate>::GetCount(BufferAttributes); static constexpr size_t NumOutHipcMapAliasBuffers = BufferAttributeCounter<OutHipcMapAliasBufferPredicate>::GetCount(BufferAttributes); static constexpr size_t NumInHipcPointerBuffers = BufferAttributeCounter<InHipcPointerBufferPredicate>::GetCount(BufferAttributes); static constexpr size_t NumOutHipcPointerBuffers = BufferAttributeCounter<OutHipcPointerBufferPredicate>::GetCount(BufferAttributes); static constexpr size_t NumFixedSizeOutHipcPointerBuffers = BufferAttributeCounter<FixedSizeOutHipcPointerBufferPredicate>::GetCount(BufferAttributes); static constexpr size_t NumUnfixedSizeOutHipcPointerBuffers = NumOutHipcPointerBuffers - NumFixedSizeOutHipcPointerBuffers; /* In/Out data marshalling. */ static constexpr std::array<size_t, NumInDatas+1> InDataOffsets = RawDataOffsetCalculator<InDatas>::Offsets; static constexpr size_t InDataSize = util::AlignUp(InDataOffsets[NumInDatas], alignof(u16)); static constexpr std::array<size_t, NumOutDatas+1> OutDataOffsets = RawDataOffsetCalculator<OutDatas>::Offsets; static constexpr size_t UnalignedOutDataSize = OutDataOffsets[NumOutDatas]; static constexpr size_t OutDataSize = util::AlignUp(OutDataOffsets[NumOutDatas], alignof(u32)); static constexpr size_t OutDataAlign = [] { if constexpr (std::tuple_size<OutDatas>::value) { return alignof(typename std::tuple_element<0, OutDatas>::type); } return static_cast<size_t>(0); }(); /* Handle marshalling. */ static constexpr size_t NumInMoveHandles = std::tuple_size<TupleFilter<InMoveHandleFilter>::FilteredType<InHandles>>::value; static constexpr size_t NumInCopyHandles = std::tuple_size<TupleFilter<InCopyHandleFilter>::FilteredType<InHandles>>::value; static constexpr size_t NumOutMoveHandles = std::tuple_size<TupleFilter<OutMoveHandleFilter>::FilteredType<OutHandles>>::value; static constexpr size_t NumOutCopyHandles = std::tuple_size<TupleFilter<OutCopyHandleFilter>::FilteredType<OutHandles>>::value; static_assert(NumInMoveHandles + NumInCopyHandles == NumInHandles, "NumInMoveHandles + NumInCopyHandles == NumInHandles"); static_assert(NumOutMoveHandles + NumOutCopyHandles == NumOutHandles, "NumOutMoveHandles + NumOutCopyHandles == NumOutHandles"); /* Used by server message processor at runtime. */ static constexpr inline const cmif::ServerMessageRuntimeMetadata RuntimeMetadata = cmif::ServerMessageRuntimeMetadata{ .in_data_size = InDataSize, .unaligned_out_data_size = UnalignedOutDataSize, .in_headers_size = sizeof(CmifInHeader), .out_headers_size = sizeof(CmifOutHeader), .in_object_count = NumInObjects, .out_object_count = NumOutObjects, }; /* Construction of argument serialization structs. */ private: template<typename> struct ArgumentSerializationInfoConstructor; template<typename ...Ts> struct ArgumentSerializationInfoConstructor<std::tuple<Ts...>> { template<typename T> static constexpr ArgumentSerializationInfo ProcessUpdate(ArgumentSerializationInfo &current_info) { /* Save a copy of the current state to return. */ ArgumentSerializationInfo returned_info = current_info; /* Clear previous iteration's fixed size. */ returned_info.fixed_size = 0; current_info.fixed_size = 0; constexpr auto arg_type = GetArgumentType<T>; returned_info.arg_type = arg_type; if constexpr (arg_type == ArgumentType::InData) { /* New rawdata, so increment index. */ current_info.in_raw_data_index++; } else if constexpr (arg_type == ArgumentType::OutData) { /* New rawdata, so increment index. */ current_info.out_raw_data_index++; } else if constexpr (arg_type == ArgumentType::InHandle) { /* New InHandle, increment the appropriate index. */ if constexpr (std::is_same<T, sf::MoveHandle>::value) { current_info.in_move_handle_index++; } else if constexpr (std::is_same<T, sf::CopyHandle>::value) { current_info.in_copy_handle_index++; } else { static_assert(!std::is_same<T, T>::value, "Invalid InHandle kind"); } } else if constexpr (arg_type == ArgumentType::OutHandle) { /* New OutHandle, increment the appropriate index. */ if constexpr (std::is_same<T, sf::Out<sf::MoveHandle>>::value) { current_info.out_move_handle_index++; } else if constexpr (std::is_same<T, sf::Out<sf::CopyHandle>>::value) { current_info.out_copy_handle_index++; } else { static_assert(!std::is_same<T, T>::value, "Invalid OutHandle kind"); } } else if constexpr (arg_type == ArgumentType::InObject) { /* New InObject, increment the appropriate index. */ current_info.in_object_index++; } else if constexpr (arg_type == ArgumentType::OutObject) { /* New OutObject, increment the appropriate index. */ current_info.out_object_index++; } else if constexpr (arg_type == ArgumentType::Buffer) { /* New Buffer, increment the appropriate index. */ const auto attributes = BufferAttributes[current_info.buffer_index]; current_info.buffer_index++; if (attributes & SfBufferAttr_HipcMapAlias) { if (attributes & SfBufferAttr_In) { current_info.send_map_alias_index++; } else if (attributes & SfBufferAttr_Out) { current_info.recv_map_alias_index++; } } else if (attributes & SfBufferAttr_HipcPointer) { if (attributes & SfBufferAttr_In) { current_info.send_pointer_index++; } else if (attributes & SfBufferAttr_Out) { current_info.recv_pointer_index++; if (!(attributes & SfBufferAttr_FixedSize)) { current_info.unfixed_recv_pointer_index++; } else { returned_info.fixed_size = LargeDataSize<T>; } } } else if (attributes & SfBufferAttr_HipcAutoSelect) { if (attributes & SfBufferAttr_In) { current_info.send_map_alias_index++; current_info.send_pointer_index++; } else if (attributes & SfBufferAttr_Out) { current_info.recv_map_alias_index++; current_info.recv_pointer_index++; if (!(attributes & SfBufferAttr_FixedSize)) { current_info.unfixed_recv_pointer_index++; } else { returned_info.fixed_size = LargeDataSize<T>; } } } } else { static_assert(!std::is_same<T, T>::value, "Invalid ArgumentType<T>"); } return returned_info; } static constexpr std::array<ArgumentSerializationInfo, sizeof...(Ts)> ArgumentSerializationInfos = [] { ArgumentSerializationInfo current_info = {}; return std::array<ArgumentSerializationInfo, sizeof...(Ts)>{ ProcessUpdate<Ts>(current_info)... }; }(); }; public: static constexpr std::array<ArgumentSerializationInfo, std::tuple_size<ArgsType>::value> ArgumentSerializationInfos = ArgumentSerializationInfoConstructor<ArgsType>::ArgumentSerializationInfos; }; template<size_t _Size, size_t _Align> class OutRawHolder { public: static constexpr size_t Size = _Size; static constexpr size_t Align = _Align ? _Align : alignof(u8); private: alignas(Align) u8 m_data[Size]; public: constexpr OutRawHolder() : m_data() { /* ... */ } template<size_t Offset, size_t TypeSize> constexpr inline uintptr_t GetAddress() const { static_assert(Offset <= Size, "Offset <= Size"); static_assert(TypeSize <= Size, "TypeSize <= Size"); static_assert(Offset + TypeSize <= Size, "Offset + TypeSize <= Size"); return reinterpret_cast<uintptr_t>(std::addressof(m_data[Offset])); } constexpr inline void CopyTo(void *dst) const { if constexpr (Size > 0) { std::memcpy(dst, m_data, Size); } } }; template<size_t _NumMove, size_t _NumCopy> class InHandleHolder { public: static constexpr size_t NumMove = _NumMove; static constexpr size_t NumCopy = _NumCopy; private: MoveHandle m_move_handles[NumMove]; CopyHandle m_copy_handles[NumCopy]; public: constexpr InHandleHolder() : m_move_handles(), m_copy_handles() { /* ... */ } template<size_t Index> constexpr inline MoveHandle &SetMoveHandle(os::NativeHandle os_handle) { static_assert(Index < NumMove); m_move_handles[Index] = sf::NativeHandle(os_handle, true); return m_move_handles[Index]; } template<size_t Index> constexpr inline CopyHandle &SetCopyHandle(os::NativeHandle os_handle) { static_assert(Index < NumCopy); m_copy_handles[Index] = sf::NativeHandle(os_handle, true); return m_copy_handles[Index]; } }; template<size_t _NumMove, size_t _NumCopy> class OutHandleHolder { public: static constexpr size_t NumMove = _NumMove; static constexpr size_t NumCopy = _NumCopy; private: NativeHandle m_move_handles[NumMove]; NativeHandle m_copy_handles[NumCopy]; public: constexpr OutHandleHolder() : m_move_handles(), m_copy_handles() { /* ... */ } template<size_t Index> constexpr inline NativeHandle *GetMoveHandlePointer() { static_assert(Index < NumMove, "Index < NumMove"); return m_move_handles + Index; } template<size_t Index> constexpr inline NativeHandle *GetCopyHandlePointer() { static_assert(Index < NumCopy, "Index < NumCopy"); return m_copy_handles + Index; } constexpr inline void CopyTo(const cmif::ServiceDispatchContext &ctx, const HipcRequest &response, const size_t num_out_object_handles) { ctx.handles_to_close->num_handles = 0; #define _SF_OUT_HANDLE_HOLDER_WRITE_COPY_HANDLE(n) do { if constexpr (NumCopy > n) { const auto handle = m_copy_handles[n].GetOsHandle(); response.copy_handles[n] = handle; if (m_copy_handles[n].IsManaged()) { ctx.handles_to_close->handles[ctx.handles_to_close->num_handles++] = handle; } m_copy_handles[n].Detach(); } } while (0) _SF_OUT_HANDLE_HOLDER_WRITE_COPY_HANDLE(0); _SF_OUT_HANDLE_HOLDER_WRITE_COPY_HANDLE(1); _SF_OUT_HANDLE_HOLDER_WRITE_COPY_HANDLE(2); _SF_OUT_HANDLE_HOLDER_WRITE_COPY_HANDLE(3); _SF_OUT_HANDLE_HOLDER_WRITE_COPY_HANDLE(4); _SF_OUT_HANDLE_HOLDER_WRITE_COPY_HANDLE(5); _SF_OUT_HANDLE_HOLDER_WRITE_COPY_HANDLE(6); _SF_OUT_HANDLE_HOLDER_WRITE_COPY_HANDLE(7); #undef _SF_OUT_HANDLE_HOLDER_WRITE_COPY_HANDLE #define _SF_OUT_HANDLE_HOLDER_WRITE_MOVE_HANDLE(n) do { if constexpr (NumMove > n) { response.move_handles[n + num_out_object_handles] = m_move_handles[n].GetOsHandle(); m_move_handles[n].Detach(); } } while (0) _SF_OUT_HANDLE_HOLDER_WRITE_MOVE_HANDLE(0); _SF_OUT_HANDLE_HOLDER_WRITE_MOVE_HANDLE(1); _SF_OUT_HANDLE_HOLDER_WRITE_MOVE_HANDLE(2); _SF_OUT_HANDLE_HOLDER_WRITE_MOVE_HANDLE(3); _SF_OUT_HANDLE_HOLDER_WRITE_MOVE_HANDLE(4); _SF_OUT_HANDLE_HOLDER_WRITE_MOVE_HANDLE(5); _SF_OUT_HANDLE_HOLDER_WRITE_MOVE_HANDLE(6); _SF_OUT_HANDLE_HOLDER_WRITE_MOVE_HANDLE(7); #undef _SF_OUT_HANDLE_HOLDER_WRITE_MOVE_HANDLE } }; template<size_t NumInObjects, size_t NumOutObjects> class InOutObjectHolder { private: std::array<cmif::ServiceObjectHolder, NumInObjects> m_in_object_holders; std::array<cmif::ServiceObjectHolder, NumOutObjects> m_out_object_holders; std::array<util::TypedStorage<SharedPointer<sf::IServiceObject>>, NumOutObjects> m_out_shared_pointers; std::array<cmif::DomainObjectId, NumOutObjects> m_out_object_ids; public: constexpr InOutObjectHolder() : m_in_object_holders(), m_out_object_holders() { #define _SF_IN_OUT_HOLDER_INITIALIZE_OBJECT_ID(n) if constexpr (NumOutObjects > n) { m_out_object_ids[n] = cmif::InvalidDomainObjectId; } _SF_IN_OUT_HOLDER_INITIALIZE_OBJECT_ID(0) _SF_IN_OUT_HOLDER_INITIALIZE_OBJECT_ID(1) _SF_IN_OUT_HOLDER_INITIALIZE_OBJECT_ID(2) _SF_IN_OUT_HOLDER_INITIALIZE_OBJECT_ID(3) _SF_IN_OUT_HOLDER_INITIALIZE_OBJECT_ID(4) _SF_IN_OUT_HOLDER_INITIALIZE_OBJECT_ID(5) _SF_IN_OUT_HOLDER_INITIALIZE_OBJECT_ID(6) _SF_IN_OUT_HOLDER_INITIALIZE_OBJECT_ID(7) #undef _SF_IN_OUT_HOLDER_INITIALIZE_OBJECT_ID } Result GetInObjects(const sf::cmif::ServerMessageProcessor *processor) { if constexpr (NumInObjects > 0) { R_TRY(processor->GetInObjects(m_in_object_holders.data())); } R_SUCCEED(); } template<typename ServiceImplTuple> constexpr inline Result ValidateInObjects() const { static_assert(std::tuple_size<ServiceImplTuple>::value == NumInObjects); #define _SF_IN_OUT_HOLDER_VALIDATE_IN_OBJECT(n) do { \ if constexpr (NumInObjects > n) { \ using SharedPointerType = typename std::tuple_element<n, ServiceImplTuple>::type; \ using ServiceImplType = typename SharedPointerType::Interface; \ R_UNLESS((m_in_object_holders[n].template IsServiceObjectValid<ServiceImplType>()), sf::cmif::ResultInvalidInObject()); \ } \ } while (0) _SF_IN_OUT_HOLDER_VALIDATE_IN_OBJECT(0); _SF_IN_OUT_HOLDER_VALIDATE_IN_OBJECT(1); _SF_IN_OUT_HOLDER_VALIDATE_IN_OBJECT(2); _SF_IN_OUT_HOLDER_VALIDATE_IN_OBJECT(3); _SF_IN_OUT_HOLDER_VALIDATE_IN_OBJECT(4); _SF_IN_OUT_HOLDER_VALIDATE_IN_OBJECT(5); _SF_IN_OUT_HOLDER_VALIDATE_IN_OBJECT(6); _SF_IN_OUT_HOLDER_VALIDATE_IN_OBJECT(7); #undef _SF_IN_OUT_HOLDER_VALIDATE_IN_OBJECT R_SUCCEED(); } template<size_t Index, typename Interface> SharedPointer<Interface> *GetOutObjectSharedPointer() { static_assert(sizeof(SharedPointer<Interface>) == sizeof(SharedPointer<sf::IServiceObject>)); return static_cast<SharedPointer<Interface> *>(static_cast<void *>(GetPointer(m_out_shared_pointers[Index]))); } template<size_t Index, typename Interface> Out<SharedPointer<Interface>> GetOutObject() { auto sp = std::construct_at(GetOutObjectSharedPointer<Index, Interface>()); return Out<SharedPointer<Interface>>(sp, std::addressof(m_out_object_ids[Index])); } template<size_t Index, typename Interface> void SetOutObject() { m_out_object_holders[Index] = cmif::ServiceObjectHolder(std::move(*GetOutObjectSharedPointer<Index, Interface>())); } constexpr void SetOutObjects(const cmif::ServiceDispatchContext &ctx, const HipcRequest &response) { if constexpr (NumOutObjects > 0) { ctx.processor->SetOutObjects(ctx, response, m_out_object_holders.data(), m_out_object_ids.data()); } } }; class HipcCommandProcessorCommon : public sf::cmif::ServerMessageProcessor { public: virtual void SetImplementationProcessor(sf::cmif::ServerMessageProcessor *) override final { /* ... */ } virtual void PrepareForErrorReply(const cmif::ServiceDispatchContext &ctx, cmif::PointerAndSize &out_raw_data, const cmif::ServerMessageRuntimeMetadata runtime_metadata) override final { const size_t raw_size = runtime_metadata.GetOutHeadersSize(); const auto response = hipcMakeRequestInline(ctx.out_message_buffer.GetPointer(), .type = CmifCommandType_Invalid, /* Really response */ .num_data_words = static_cast<u32>((util::AlignUp(raw_size, 0x4) + 0x10 /* padding */) / sizeof(u32)), ); out_raw_data = cmif::PointerAndSize(util::AlignUp(reinterpret_cast<uintptr_t>(response.data_words), 0x10), raw_size); } virtual Result GetInObjects(cmif::ServiceObjectHolder *in_objects) const override final { /* By default, InObjects aren't supported. */ AMS_UNUSED(in_objects); R_THROW(sf::ResultNotSupported()); } }; template<typename CommandMeta> struct HipcCommandProcessor : public HipcCommandProcessorCommon { public: virtual const cmif::ServerMessageRuntimeMetadata GetRuntimeMetadata() const override final { return CommandMeta::RuntimeMetadata; } virtual Result PrepareForProcess(const cmif::ServiceDispatchContext &ctx, const cmif::ServerMessageRuntimeMetadata runtime_metadata) const override final { const auto &meta = ctx.request.meta; bool is_request_valid = true; is_request_valid &= meta.send_pid == CommandMeta::HasInProcessIdHolder; is_request_valid &= meta.num_send_statics == CommandMeta::NumInHipcPointerBuffers; /* is_request_valid &= meta.num_recv_statics == CommandMeta::NumOutHipcPointerBuffers; */ is_request_valid &= meta.num_send_buffers == CommandMeta::NumInHipcMapAliasBuffers; is_request_valid &= meta.num_recv_buffers == CommandMeta::NumOutHipcMapAliasBuffers; is_request_valid &= meta.num_exch_buffers == 0; /* Exchange buffers aren't supported. */ is_request_valid &= meta.num_copy_handles == CommandMeta::NumInCopyHandles; is_request_valid &= meta.num_move_handles == CommandMeta::NumInMoveHandles; const size_t meta_raw_size = meta.num_data_words * sizeof(u32); const size_t command_raw_size = util::AlignUp(runtime_metadata.GetUnfixedOutPointerSizeOffset() + (CommandMeta::NumUnfixedSizeOutHipcPointerBuffers * sizeof(u16)), alignof(u32)); is_request_valid &= meta_raw_size >= command_raw_size; R_UNLESS(is_request_valid, sf::hipc::ResultInvalidCmifRequest()); R_SUCCEED(); } virtual HipcRequest PrepareForReply(const cmif::ServiceDispatchContext &ctx, cmif::PointerAndSize &out_raw_data, const cmif::ServerMessageRuntimeMetadata runtime_metadata) override final { const size_t raw_size = runtime_metadata.GetOutDataSize() + runtime_metadata.GetOutHeadersSize(); const auto response = hipcMakeRequestInline(ctx.out_message_buffer.GetPointer(), .type = CmifCommandType_Invalid, /* Really response */ .num_send_statics = CommandMeta::NumOutHipcPointerBuffers, .num_data_words = static_cast<u32>((util::AlignUp(raw_size, 0x4) + 0x10 /* padding */) / sizeof(u32)), .num_copy_handles = CommandMeta::NumOutCopyHandles, .num_move_handles = static_cast<u32>(CommandMeta::NumOutMoveHandles + runtime_metadata.GetOutObjectCount()), ); out_raw_data = cmif::PointerAndSize(util::AlignUp(reinterpret_cast<uintptr_t>(response.data_words), 0x10), raw_size); return response; } virtual void SetOutObjects(const cmif::ServiceDispatchContext &ctx, const HipcRequest &response, cmif::ServiceObjectHolder *out_objects, cmif::DomainObjectId *ids) override final { AMS_UNUSED(ids); #define _SF_IMPL_PROCESSOR_SET_OUT_OBJECT_IMPL(n) do { if constexpr (CommandMeta::NumOutObjects > n) { SetOutObjectImpl<n>(response, ctx.manager, std::move(out_objects[n])); } } while (0) _SF_IMPL_PROCESSOR_SET_OUT_OBJECT_IMPL(0); _SF_IMPL_PROCESSOR_SET_OUT_OBJECT_IMPL(1); _SF_IMPL_PROCESSOR_SET_OUT_OBJECT_IMPL(2); _SF_IMPL_PROCESSOR_SET_OUT_OBJECT_IMPL(3); _SF_IMPL_PROCESSOR_SET_OUT_OBJECT_IMPL(4); _SF_IMPL_PROCESSOR_SET_OUT_OBJECT_IMPL(5); _SF_IMPL_PROCESSOR_SET_OUT_OBJECT_IMPL(6); _SF_IMPL_PROCESSOR_SET_OUT_OBJECT_IMPL(7); #undef _SF_IMPL_PROCESSOR_SET_OUT_OBJECT_IMPL } /* Useful defines. */ using ArgsTypeForInvoke = typename CommandMeta::ArgsTypeForInvoke; using ArgsType = typename CommandMeta::ArgsType; using BufferArrayType = std::array<cmif::PointerAndSize, CommandMeta::NumBuffers>; using OutRawHolderType = OutRawHolder<CommandMeta::OutDataSize, CommandMeta::OutDataAlign>; using InHandleHolderType = InHandleHolder<CommandMeta::NumInMoveHandles, CommandMeta::NumInCopyHandles>; using OutHandleHolderType = OutHandleHolder<CommandMeta::NumOutMoveHandles, CommandMeta::NumOutCopyHandles>; using InOutObjectHolderType = InOutObjectHolder<CommandMeta::NumInObjects, CommandMeta::NumOutObjects>; /* Buffer processing. */ private: template<size_t Index> NX_CONSTEXPR void SetOutObjectImpl(const HipcRequest &response, hipc::ServerSessionManager *manager, cmif::ServiceObjectHolder &&object) { /* If no object, write os::InvalidNativeHandle. This is what official software does. */ if (!object) { response.move_handles[Index] = os::InvalidNativeHandle; return; } os::NativeHandle server_handle, client_handle; R_ABORT_UNLESS(sf::hipc::CreateSession(std::addressof(server_handle), std::addressof(client_handle))); R_ABORT_UNLESS(manager->RegisterSession(server_handle, std::move(object))); response.move_handles[Index] = client_handle; } template<u32 Attributes> NX_CONSTEXPR bool IsMapTransferModeValid(u32 mode) { static_assert(!((Attributes & SfBufferAttr_HipcMapTransferAllowsNonSecure) && (Attributes & SfBufferAttr_HipcMapTransferAllowsNonDevice)), "Invalid Attributes"); if constexpr (Attributes & SfBufferAttr_HipcMapTransferAllowsNonSecure) { return mode == HipcBufferMode_NonSecure; } else if constexpr (Attributes & SfBufferAttr_HipcMapTransferAllowsNonDevice) { return mode == HipcBufferMode_NonDevice; } else { return mode == HipcBufferMode_Normal; } } template<size_t BufferIndex> static constexpr inline size_t GetIndexFromBufferIndex = [] { for (size_t i = 0; i < CommandMeta::ArgumentSerializationInfos.size(); i++) { const auto Info = CommandMeta::ArgumentSerializationInfos[i]; if (Info.arg_type == ArgumentType::Buffer && Info.buffer_index == BufferIndex) { return i; } } return std::numeric_limits<size_t>::max(); }(); template<size_t BufferIndex, size_t Index = GetIndexFromBufferIndex<BufferIndex>> NX_CONSTEXPR void ProcessBufferImpl(const cmif::ServiceDispatchContext &ctx, cmif::PointerAndSize &buffer, bool &is_buffer_map_alias, bool &map_alias_buffers_valid, size_t &pointer_buffer_head, size_t &pointer_buffer_tail, const cmif::ServerMessageRuntimeMetadata runtime_metadata) { static_assert(Index != std::numeric_limits<size_t>::max(), "Invalid Index From Buffer Index"); constexpr auto Info = CommandMeta::ArgumentSerializationInfos[Index]; constexpr auto Attributes = CommandMeta::BufferAttributes[BufferIndex]; static_assert(BufferIndex == Info.buffer_index && Info.arg_type == ArgumentType::Buffer, "BufferIndex == Info.buffer_index && Info.arg_type == ArgumentType::Buffer"); if constexpr (Attributes & SfBufferAttr_HipcMapAlias) { is_buffer_map_alias = true; if constexpr (Attributes & SfBufferAttr_In) { const HipcBufferDescriptor *desc = std::addressof(ctx.request.data.send_buffers[Info.send_map_alias_index]); buffer = cmif::PointerAndSize(hipcGetBufferAddress(desc), hipcGetBufferSize(desc)); if (!IsMapTransferModeValid<Attributes>(static_cast<u32>(desc->mode))) { map_alias_buffers_valid = false; } } else if constexpr (Attributes & SfBufferAttr_Out) { const HipcBufferDescriptor *desc = std::addressof(ctx.request.data.recv_buffers[Info.recv_map_alias_index]); buffer = cmif::PointerAndSize(hipcGetBufferAddress(desc), hipcGetBufferSize(desc)); if (!IsMapTransferModeValid<Attributes>(static_cast<u32>(desc->mode))) { map_alias_buffers_valid = false; } } else { static_assert(Attributes != Attributes, "Invalid Buffer Attributes"); } } else if constexpr (Attributes & SfBufferAttr_HipcPointer) { is_buffer_map_alias = false; if constexpr (Attributes & SfBufferAttr_In) { const HipcStaticDescriptor *desc = std::addressof(ctx.request.data.send_statics[Info.send_pointer_index]); buffer = cmif::PointerAndSize(hipcGetStaticAddress(desc), hipcGetStaticSize(desc)); const size_t size = buffer.GetSize(); if (size) { pointer_buffer_tail = std::max(pointer_buffer_tail, buffer.GetAddress() + size); } } else if constexpr (Attributes & SfBufferAttr_Out) { if constexpr (Attributes & SfBufferAttr_FixedSize) { constexpr size_t size = Info.fixed_size; static_assert(size > 0, "FixedSize object must have non-zero size!"); pointer_buffer_head = util::AlignDown(pointer_buffer_head - size, 0x10); buffer = cmif::PointerAndSize(pointer_buffer_head, size); } else { const u16 *recv_pointer_sizes = reinterpret_cast<const u16 *>(reinterpret_cast<uintptr_t>(ctx.request.data.data_words) + runtime_metadata.GetUnfixedOutPointerSizeOffset()); const size_t size = static_cast<size_t>(recv_pointer_sizes[Info.unfixed_recv_pointer_index]); pointer_buffer_head = util::AlignDown(pointer_buffer_head - size, 0x10); buffer = cmif::PointerAndSize(pointer_buffer_head, size); } } else { static_assert(Attributes != Attributes, "Invalid Buffer Attributes"); } } else if constexpr (Attributes & SfBufferAttr_HipcAutoSelect) { if constexpr (Attributes & SfBufferAttr_In) { const HipcBufferDescriptor *map_desc = std::addressof(ctx.request.data.send_buffers[Info.send_map_alias_index]); const HipcStaticDescriptor *ptr_desc = std::addressof(ctx.request.data.send_statics[Info.send_pointer_index]); is_buffer_map_alias = hipcGetBufferAddress(map_desc) != 0; if (is_buffer_map_alias) { buffer = cmif::PointerAndSize(hipcGetBufferAddress(map_desc), hipcGetBufferSize(map_desc)); if (!IsMapTransferModeValid<Attributes>(static_cast<u32>(map_desc->mode))) { map_alias_buffers_valid = false; } } else { buffer = cmif::PointerAndSize(hipcGetStaticAddress(ptr_desc), hipcGetStaticSize(ptr_desc)); const size_t size = buffer.GetSize(); if (size) { pointer_buffer_tail = std::max(pointer_buffer_tail, buffer.GetAddress() + size); } } } else if constexpr (Attributes & SfBufferAttr_Out) { const HipcBufferDescriptor *map_desc = std::addressof(ctx.request.data.recv_buffers[Info.recv_map_alias_index]); is_buffer_map_alias = hipcGetBufferAddress(map_desc) != 0; if (is_buffer_map_alias) { buffer = cmif::PointerAndSize(hipcGetBufferAddress(map_desc), hipcGetBufferSize(map_desc)); if (!IsMapTransferModeValid<Attributes>(static_cast<u32>(map_desc->mode))) { map_alias_buffers_valid = false; } } else { if constexpr (Attributes & SfBufferAttr_FixedSize) { constexpr size_t size = Info.fixed_size; static_assert(size > 0, "FixedSize object must have non-zero size!"); pointer_buffer_head = util::AlignDown(pointer_buffer_head - size, 0x10); buffer = cmif::PointerAndSize(pointer_buffer_head, size); } else { const u16 *recv_pointer_sizes = reinterpret_cast<const u16 *>(reinterpret_cast<uintptr_t>(ctx.request.data.data_words) + runtime_metadata.GetUnfixedOutPointerSizeOffset()); const size_t size = static_cast<size_t>(recv_pointer_sizes[Info.unfixed_recv_pointer_index]); pointer_buffer_head = util::AlignDown(pointer_buffer_head - size, 0x10); buffer = cmif::PointerAndSize(pointer_buffer_head, size); } } } else { static_assert(Attributes != Attributes, "Invalid Buffer Attributes"); } } else { static_assert(Attributes != Attributes, "Invalid Buffer Attributes"); } } template<size_t BufferIndex, size_t Index = GetIndexFromBufferIndex<BufferIndex>> NX_CONSTEXPR void SetOutBufferImpl(const HipcRequest &response, const cmif::PointerAndSize &buffer, const bool is_buffer_map_alias) { static_assert(Index != std::numeric_limits<size_t>::max(), "Invalid Index From Buffer Index"); constexpr auto Info = CommandMeta::ArgumentSerializationInfos[Index]; constexpr auto Attributes = CommandMeta::BufferAttributes[BufferIndex]; static_assert(BufferIndex == Info.buffer_index && Info.arg_type == ArgumentType::Buffer, "BufferIndex == Info.buffer_index && Info.arg_type == ArgumentType::Buffer"); if constexpr (Attributes & SfBufferAttr_Out) { if constexpr (Attributes & SfBufferAttr_HipcPointer) { response.send_statics[Info.recv_pointer_index] = hipcMakeSendStatic(buffer.GetPointer(), buffer.GetSize(), Info.recv_pointer_index); } else if constexpr (Attributes & SfBufferAttr_HipcAutoSelect) { if (!is_buffer_map_alias) { response.send_statics[Info.recv_pointer_index] = hipcMakeSendStatic(buffer.GetPointer(), buffer.GetSize(), Info.recv_pointer_index); } else { response.send_statics[Info.recv_pointer_index] = hipcMakeSendStatic(nullptr, 0, Info.recv_pointer_index); } } } } public: NX_CONSTEXPR Result ProcessBuffers(const cmif::ServiceDispatchContext &ctx, BufferArrayType &buffers, std::array<bool, CommandMeta::NumBuffers> &is_buffer_map_alias, const cmif::ServerMessageRuntimeMetadata runtime_metadata) { bool map_alias_buffers_valid = true; size_t pointer_buffer_tail = ctx.pointer_buffer.GetAddress(); size_t pointer_buffer_head = pointer_buffer_tail + ctx.pointer_buffer.GetSize(); #define _SF_IMPL_PROCESSOR_PROCESS_BUFFER_IMPL(n) do { if constexpr (CommandMeta::NumBuffers > n) { ProcessBufferImpl<n>(ctx, buffers[n], is_buffer_map_alias[n], map_alias_buffers_valid, pointer_buffer_head, pointer_buffer_tail, runtime_metadata); } } while (0) _SF_IMPL_PROCESSOR_PROCESS_BUFFER_IMPL(0); _SF_IMPL_PROCESSOR_PROCESS_BUFFER_IMPL(1); _SF_IMPL_PROCESSOR_PROCESS_BUFFER_IMPL(2); _SF_IMPL_PROCESSOR_PROCESS_BUFFER_IMPL(3); _SF_IMPL_PROCESSOR_PROCESS_BUFFER_IMPL(4); _SF_IMPL_PROCESSOR_PROCESS_BUFFER_IMPL(5); _SF_IMPL_PROCESSOR_PROCESS_BUFFER_IMPL(6); _SF_IMPL_PROCESSOR_PROCESS_BUFFER_IMPL(7); #undef _SF_IMPL_PROCESSOR_PROCESS_BUFFER_IMPL R_UNLESS(map_alias_buffers_valid, sf::hipc::ResultInvalidCmifRequest()); if constexpr (CommandMeta::NumOutHipcPointerBuffers > 0) { R_UNLESS(pointer_buffer_tail <= pointer_buffer_head, sf::hipc::ResultPointerBufferTooSmall()); } R_SUCCEED(); } NX_CONSTEXPR void SetOutBuffers(const HipcRequest &response, const BufferArrayType &buffers, const std::array<bool, CommandMeta::NumBuffers> &is_buffer_map_alias) { #define _SF_IMPL_PROCESSOR_SET_OUT_BUFFER_IMPL(n) do { if constexpr (CommandMeta::NumBuffers > n) { SetOutBufferImpl<n>(response, buffers[n], is_buffer_map_alias[n]); } } while (0) _SF_IMPL_PROCESSOR_SET_OUT_BUFFER_IMPL(0); _SF_IMPL_PROCESSOR_SET_OUT_BUFFER_IMPL(1); _SF_IMPL_PROCESSOR_SET_OUT_BUFFER_IMPL(2); _SF_IMPL_PROCESSOR_SET_OUT_BUFFER_IMPL(3); _SF_IMPL_PROCESSOR_SET_OUT_BUFFER_IMPL(4); _SF_IMPL_PROCESSOR_SET_OUT_BUFFER_IMPL(5); _SF_IMPL_PROCESSOR_SET_OUT_BUFFER_IMPL(6); _SF_IMPL_PROCESSOR_SET_OUT_BUFFER_IMPL(7); #undef _SF_IMPL_PROCESSOR_SET_OUT_BUFFER_IMPL } /* Argument deserialization. */ private: template<size_t Index, typename T = typename std::tuple_element<Index, ArgsType>::type> NX_CONSTEXPR typename std::tuple_element<Index, ArgsTypeForInvoke>::type DeserializeArgumentImpl(const cmif::ServiceDispatchContext &ctx, const cmif::PointerAndSize &in_raw_data, const OutRawHolderType &out_raw_holder, const BufferArrayType &buffers, InHandleHolderType &in_handles_holder, OutHandleHolderType &out_handles_holder, InOutObjectHolderType &in_out_objects_holder) { constexpr auto Info = CommandMeta::ArgumentSerializationInfos[Index]; if constexpr (Info.arg_type == ArgumentType::InData) { /* New in rawdata. */ constexpr size_t Offset = CommandMeta::InDataOffsets[Info.in_raw_data_index]; if constexpr (!std::is_same<T, bool>::value) { return *reinterpret_cast<const T *>(in_raw_data.GetAddress() + Offset); } else { /* Special case bools. */ return *reinterpret_cast<const u8 *>(in_raw_data.GetAddress() + Offset) & 1; } } else if constexpr (Info.arg_type == ArgumentType::OutData) { /* New out rawdata. */ constexpr size_t Offset = CommandMeta::OutDataOffsets[Info.out_raw_data_index]; return T(out_raw_holder.template GetAddress<Offset, T::TypeSize>()); } else if constexpr (Info.arg_type == ArgumentType::InHandle) { /* New InHandle. */ using InvokeType = typename std::tuple_element<Index, ArgsTypeForInvoke>::type; if constexpr (std::is_same<T, sf::MoveHandle>::value) { static_assert(std::same_as<InvokeType, sf::MoveHandle &>); return in_handles_holder.template SetMoveHandle<Info.in_move_handle_index>(ctx.request.data.move_handles[Info.in_move_handle_index]); } else if constexpr (std::is_same<T, sf::CopyHandle>::value) { static_assert(std::same_as<InvokeType, sf::CopyHandle &>); return in_handles_holder.template SetCopyHandle<Info.in_copy_handle_index>(ctx.request.data.copy_handles[Info.in_copy_handle_index]); } else { static_assert(!std::is_same<T, T>::value, "Invalid InHandle kind"); } } else if constexpr (Info.arg_type == ArgumentType::OutHandle) { /* New OutHandle. */ if constexpr (std::is_same<T, sf::OutMoveHandle>::value) { return T(out_handles_holder.template GetMoveHandlePointer<Info.out_move_handle_index>()); } else if constexpr (std::is_same<T, sf::OutCopyHandle>::value) { return T(out_handles_holder.template GetCopyHandlePointer<Info.out_copy_handle_index>()); } else { static_assert(!std::is_same<T, T>::value, "Invalid OutHandle kind"); } } else if constexpr (Info.arg_type == ArgumentType::InObject) { /* New InObject. */ return in_out_objects_holder.template GetInObject<Info.in_object_index, typename T::Interface>(); } else if constexpr (Info.arg_type == ArgumentType::OutObject) { /* New OutObject. */ return in_out_objects_holder.template GetOutObject<Info.out_object_index, typename T::Interface>(); } else if constexpr (Info.arg_type == ArgumentType::Buffer) { /* Buffers were already processed earlier. */ if constexpr (sf::IsLargeData<T>) { /* Fake buffer. This is either InData or OutData, but serializing over buffers. */ constexpr auto Attributes = CommandMeta::BufferAttributes[Info.buffer_index]; if constexpr (Attributes & SfBufferAttr_In) { /* TODO: AMS_ABORT_UNLESS()? N does not bother. */ using InvokeType = typename std::tuple_element<Index, ArgsTypeForInvoke>::type; static_assert(std::same_as<InvokeType, const T &>); return *reinterpret_cast<const T *>(buffers[Info.buffer_index].GetAddress()); } else if constexpr (Attributes & SfBufferAttr_Out) { return T(buffers[Info.buffer_index]); } else { static_assert(!std::is_same<T, T>::value, "Invalid BufferAttributes for LargeData type."); } } else { /* Actual buffer! */ return T(buffers[Info.buffer_index]); } } else { static_assert(!std::is_same<T, T>::value, "Invalid ArgumentType<T>"); } } template<size_t... Is> NX_CONSTEXPR ArgsTypeForInvoke DeserializeArgumentsImpl(const cmif::ServiceDispatchContext &ctx, const cmif::PointerAndSize &in_raw_data, const OutRawHolderType &out_raw_holder, const BufferArrayType &buffers, InHandleHolderType &in_handles_holder, OutHandleHolderType &out_handles_holder, InOutObjectHolderType &in_out_objects_holder, std::index_sequence<Is...>) { return ArgsTypeForInvoke { DeserializeArgumentImpl<Is>(ctx, in_raw_data, out_raw_holder, buffers, in_handles_holder, out_handles_holder, in_out_objects_holder)..., }; } public: NX_CONSTEXPR ArgsTypeForInvoke DeserializeArguments(const cmif::ServiceDispatchContext &ctx, const cmif::PointerAndSize &in_raw_data, const OutRawHolderType &out_raw_holder, const BufferArrayType &buffers, InHandleHolderType &in_handles_holder, OutHandleHolderType &out_handles_holder, InOutObjectHolderType &in_out_objects_holder) { return DeserializeArgumentsImpl(ctx, in_raw_data, out_raw_holder, buffers, in_handles_holder, out_handles_holder, in_out_objects_holder, std::make_index_sequence<std::tuple_size<ArgsTypeForInvoke>::value>{}); } }; inline Result GetCmifOutHeaderPointer(CmifOutHeader **out_header_ptr, cmif::PointerAndSize &out_raw_data) { CmifOutHeader *header = static_cast<CmifOutHeader *>(out_raw_data.GetPointer()); R_UNLESS(out_raw_data.GetSize() >= sizeof(*header), sf::cmif::ResultInvalidHeaderSize()); out_raw_data = cmif::PointerAndSize(out_raw_data.GetAddress() + sizeof(*header), out_raw_data.GetSize() - sizeof(*header)); *out_header_ptr = header; R_SUCCEED(); } template<typename CommandMeta, typename... Arguments> constexpr Result InvokeServiceCommandImplCommon(CmifOutHeader **out_header_ptr, cmif::ServiceDispatchContext &ctx, const cmif::PointerAndSize &in_raw_data, Result (*invoke_impl)(sf::IServiceObject *, Arguments &&...)) { using ImplProcessorType = HipcCommandProcessor<CommandMeta>; using BufferArrayType = std::array<cmif::PointerAndSize, CommandMeta::NumBuffers>; using InHandleHolderType = InHandleHolder<CommandMeta::NumInMoveHandles, CommandMeta::NumInCopyHandles>; using OutHandleHolderType = OutHandleHolder<CommandMeta::NumOutMoveHandles, CommandMeta::NumOutCopyHandles>; using OutRawHolderType = OutRawHolder<CommandMeta::OutDataSize, CommandMeta::OutDataAlign>; using InOutObjectHolderType = InOutObjectHolder<CommandMeta::NumInObjects, CommandMeta::NumOutObjects>; /* Create a processor for us to work with. */ ImplProcessorType impl_processor; if (ctx.processor == nullptr) { /* In the non-domain case, this is our only processor. */ ctx.processor = std::addressof(impl_processor); } else { /* In the domain case, we already have a processor, so we should give it a pointer to our template implementation. */ ctx.processor->SetImplementationProcessor(std::addressof(impl_processor)); } /* Validate the metadata has the expected counts. */ const auto runtime_metadata = ctx.processor->GetRuntimeMetadata(); R_TRY(ctx.processor->PrepareForProcess(ctx, runtime_metadata)); /* Storage for output. */ BufferArrayType buffers; std::array<bool, CommandMeta::NumBuffers> is_buffer_map_alias = {}; OutRawHolderType out_raw_holder; OutHandleHolderType out_handles_holder; InOutObjectHolderType in_out_objects_holder; /* Process buffers. */ R_TRY(ImplProcessorType::ProcessBuffers(ctx, buffers, is_buffer_map_alias, runtime_metadata)); /* Process input/output objects. */ R_TRY(in_out_objects_holder.GetInObjects(ctx.processor)); R_TRY((in_out_objects_holder.template ValidateInObjects<typename CommandMeta::InObjects>())); /* Decoding/Invocation. */ { Result command_result; { InHandleHolderType in_handles_holder; typename CommandMeta::ArgsTypeForInvoke args_tuple = ImplProcessorType::DeserializeArguments(ctx, in_raw_data, out_raw_holder, buffers, in_handles_holder, out_handles_holder, in_out_objects_holder); /* Handle in process ID holder if relevant. */ if constexpr (CommandMeta::HasInProcessIdHolder) { /* TODO: More precise value than 32? */ static_assert(std::tuple_size<typename CommandMeta::ArgsTypeForInvoke>::value <= 32, "Commands must have <= 32 arguments"); const os::ProcessId process_id{ctx.request.pid}; #define _SF_IMPL_PROCESSOR_MARSHAL_PROCESS_ID(n) do { \ using ArgsTypeForInvoke = typename CommandMeta::ArgsTypeForInvoke; \ if constexpr (n < std::tuple_size<ArgsTypeForInvoke>::value) { \ if constexpr (CommandMeta::template IsInProcessIdHolderIndex<n>) { \ R_TRY(MarshalProcessId(std::get<n>(args_tuple), process_id)); \ } \ } \ } while (0) _SF_IMPL_PROCESSOR_MARSHAL_PROCESS_ID(0x00); _SF_IMPL_PROCESSOR_MARSHAL_PROCESS_ID(0x01); _SF_IMPL_PROCESSOR_MARSHAL_PROCESS_ID(0x02); _SF_IMPL_PROCESSOR_MARSHAL_PROCESS_ID(0x03); _SF_IMPL_PROCESSOR_MARSHAL_PROCESS_ID(0x04); _SF_IMPL_PROCESSOR_MARSHAL_PROCESS_ID(0x05); _SF_IMPL_PROCESSOR_MARSHAL_PROCESS_ID(0x06); _SF_IMPL_PROCESSOR_MARSHAL_PROCESS_ID(0x07); _SF_IMPL_PROCESSOR_MARSHAL_PROCESS_ID(0x08); _SF_IMPL_PROCESSOR_MARSHAL_PROCESS_ID(0x09); _SF_IMPL_PROCESSOR_MARSHAL_PROCESS_ID(0x0a); _SF_IMPL_PROCESSOR_MARSHAL_PROCESS_ID(0x0b); _SF_IMPL_PROCESSOR_MARSHAL_PROCESS_ID(0x0c); _SF_IMPL_PROCESSOR_MARSHAL_PROCESS_ID(0x0d); _SF_IMPL_PROCESSOR_MARSHAL_PROCESS_ID(0x0e); _SF_IMPL_PROCESSOR_MARSHAL_PROCESS_ID(0x0f); _SF_IMPL_PROCESSOR_MARSHAL_PROCESS_ID(0x10); _SF_IMPL_PROCESSOR_MARSHAL_PROCESS_ID(0x11); _SF_IMPL_PROCESSOR_MARSHAL_PROCESS_ID(0x12); _SF_IMPL_PROCESSOR_MARSHAL_PROCESS_ID(0x13); _SF_IMPL_PROCESSOR_MARSHAL_PROCESS_ID(0x14); _SF_IMPL_PROCESSOR_MARSHAL_PROCESS_ID(0x15); _SF_IMPL_PROCESSOR_MARSHAL_PROCESS_ID(0x16); _SF_IMPL_PROCESSOR_MARSHAL_PROCESS_ID(0x17); _SF_IMPL_PROCESSOR_MARSHAL_PROCESS_ID(0x18); _SF_IMPL_PROCESSOR_MARSHAL_PROCESS_ID(0x19); _SF_IMPL_PROCESSOR_MARSHAL_PROCESS_ID(0x1a); _SF_IMPL_PROCESSOR_MARSHAL_PROCESS_ID(0x1b); _SF_IMPL_PROCESSOR_MARSHAL_PROCESS_ID(0x1c); _SF_IMPL_PROCESSOR_MARSHAL_PROCESS_ID(0x1d); _SF_IMPL_PROCESSOR_MARSHAL_PROCESS_ID(0x1e); _SF_IMPL_PROCESSOR_MARSHAL_PROCESS_ID(0x1f); #undef _SF_IMPL_PROCESSOR_MARSHAL_PROCESS_ID } using TrueArgumentsTuple = std::tuple<Arguments...>; sf::IServiceObject * const this_ptr = ctx.srv_obj; command_result = [this_ptr, invoke_impl, &args_tuple]<size_t ...Ix>(std::index_sequence<Ix...>) ALWAYS_INLINE_LAMBDA { R_RETURN(invoke_impl(this_ptr, std::forward<typename std::tuple_element<Ix, TrueArgumentsTuple>::type>(std::get<Ix>(args_tuple))...)); }(std::make_index_sequence<std::tuple_size<typename CommandMeta::ArgsTypeForInvoke>::value>()); } if (R_FAILED(command_result)) { cmif::PointerAndSize out_raw_data; ctx.processor->PrepareForErrorReply(ctx, out_raw_data, runtime_metadata); R_TRY(GetCmifOutHeaderPointer(out_header_ptr, out_raw_data)); R_RETURN(command_result); } } /* Encode. */ cmif::PointerAndSize out_raw_data; const auto response = ctx.processor->PrepareForReply(ctx, out_raw_data, runtime_metadata); R_TRY(GetCmifOutHeaderPointer(out_header_ptr, out_raw_data)); /* Copy raw data output struct. */ R_UNLESS(out_raw_data.GetSize() >= OutRawHolderType::Size, sf::cmif::ResultInvalidOutRawSize()); out_raw_holder.CopyTo(out_raw_data.GetPointer()); /* Set output recvlist buffers. */ ImplProcessorType::SetOutBuffers(response, buffers, is_buffer_map_alias); /* Set out handles. */ out_handles_holder.CopyTo(ctx, response, runtime_metadata.GetOutObjectCount()); /* Set output objects. */ #define _SF_IMPL_PROCESSOR_MARSHAL_OUT_OBJECT(n) do { \ if constexpr (n < CommandMeta::NumOutObjects) { \ in_out_objects_holder.template SetOutObject<n, typename std::tuple_element_t<n, typename CommandMeta::OutObjects>::Interface>(); \ } \ } while (0) _SF_IMPL_PROCESSOR_MARSHAL_OUT_OBJECT(0); _SF_IMPL_PROCESSOR_MARSHAL_OUT_OBJECT(1); _SF_IMPL_PROCESSOR_MARSHAL_OUT_OBJECT(2); _SF_IMPL_PROCESSOR_MARSHAL_OUT_OBJECT(3); _SF_IMPL_PROCESSOR_MARSHAL_OUT_OBJECT(4); _SF_IMPL_PROCESSOR_MARSHAL_OUT_OBJECT(5); _SF_IMPL_PROCESSOR_MARSHAL_OUT_OBJECT(6); _SF_IMPL_PROCESSOR_MARSHAL_OUT_OBJECT(7); _SF_IMPL_PROCESSOR_MARSHAL_OUT_OBJECT(8); #undef _SF_IMPL_PROCESSOR_MARSHAL_OUT_OBJECT in_out_objects_holder.SetOutObjects(ctx, response); R_SUCCEED(); } template<auto ServiceCommandImpl, typename Return, typename ClassType, typename... Arguments> constexpr Result InvokeServiceCommandImpl(CmifOutHeader **out_header_ptr, cmif::ServiceDispatchContext &ctx, const cmif::PointerAndSize &in_raw_data) { using CommandMeta = CommandMetaInfo<Arguments...>; static_assert(std::is_base_of<sf::IServiceObject, ClassType>::value, "InvokeServiceCommandImpl: Service Commands must be ServiceObject member functions"); constexpr bool ReturnsResult = std::is_same<Return, Result>::value; constexpr bool ReturnsVoid = std::is_same<Return, void>::value; static_assert(ReturnsResult || ReturnsVoid, "Service Commands must return Result or void."); R_RETURN((InvokeServiceCommandImplCommon<CommandMeta, Arguments...>(out_header_ptr, ctx, in_raw_data, +[](sf::IServiceObject *srv_obj, Arguments &&... args) -> Result { if constexpr (ReturnsResult) { R_RETURN((static_cast<ClassType *>(srv_obj)->*ServiceCommandImpl)(std::forward<Arguments>(args)...)); } else { (static_cast<ClassType *>(srv_obj)->*ServiceCommandImpl)(std::forward<Arguments>(args)...); R_SUCCEED(); } }))); } } #elif defined(ATMOSPHERE_OS_WINDOWS) namespace ams::sf::impl { template<auto ServiceCommandImpl, typename Return, typename ClassType, typename... Arguments> inline Result InvokeServiceCommandImpl(CmifOutHeader **out_header_ptr, cmif::ServiceDispatchContext &ctx, const cmif::PointerAndSize &in_raw_data) { /* TODO: Is some kind of emulated serialization interesting/desirable? */ AMS_UNUSED(out_header_ptr, ctx, in_raw_data); AMS_ABORT("HIPC serialization not currently supported on Windows."); } } #elif defined(ATMOSPHERE_OS_LINUX) namespace ams::sf::impl { template<auto ServiceCommandImpl, typename Return, typename ClassType, typename... Arguments> inline Result InvokeServiceCommandImpl(CmifOutHeader **out_header_ptr, cmif::ServiceDispatchContext &ctx, const cmif::PointerAndSize &in_raw_data) { /* TODO: Is some kind of emulated serialization interesting/desirable? */ AMS_UNUSED(out_header_ptr, ctx, in_raw_data); AMS_ABORT("HIPC serialization not currently supported on Linux."); } } #elif defined(ATMOSPHERE_OS_MACOS) namespace ams::sf::impl { template<auto ServiceCommandImpl, typename Return, typename ClassType, typename... Arguments> inline Result InvokeServiceCommandImpl(CmifOutHeader **out_header_ptr, cmif::ServiceDispatchContext &ctx, const cmif::PointerAndSize &in_raw_data) { /* TODO: Is some kind of emulated serialization interesting/desirable? */ AMS_UNUSED(out_header_ptr, ctx, in_raw_data); AMS_ABORT("HIPC serialization not currently supported on macOS."); } } #else #error "Unknown OS for sf Command serialization." #endif namespace ams::sf::impl { template<hos::Version Low, hos::Version High, u32 CommandId, auto CommandImpl, typename Return, typename ClassType, typename... Arguments> consteval inline cmif::ServiceCommandMeta MakeServiceCommandMeta() { return { .hosver_low = Low, .hosver_high = High, .cmd_id = static_cast<u32>(CommandId), .handler = ::ams::sf::impl::InvokeServiceCommandImpl<CommandImpl, Return, ClassType, Arguments...>, }; } }
74,973
C++
.h
1,148
50.276132
390
0.599699
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
7,572
sf_cmif_server_message_processor.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/sf/cmif/sf_cmif_server_message_processor.hpp
/* * 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/>. */ #pragma once #include <stratosphere/sf/sf_service_object.hpp> #include <stratosphere/sf/cmif/sf_cmif_pointer_and_size.hpp> namespace ams::sf::cmif { /* Forward declare ServiceDispatchContext, ServiceObjectHolder. */ struct ServiceDispatchContext; class ServiceObjectHolder; struct DomainObjectId; /* This is needed for non-templated domain message processing. */ struct ServerMessageRuntimeMetadata { u16 in_data_size; u16 unaligned_out_data_size; u8 in_headers_size; u8 out_headers_size; u8 in_object_count; u8 out_object_count; constexpr size_t GetInDataSize() const { return static_cast<size_t>(this->in_data_size); } constexpr size_t GetOutDataSize() const { return static_cast<size_t>(util::AlignUp(this->unaligned_out_data_size, sizeof(u32))); } constexpr size_t GetUnalignedOutDataSize() const { return static_cast<size_t>(this->unaligned_out_data_size); } constexpr size_t GetInHeadersSize() const { return static_cast<size_t>(this->in_headers_size); } constexpr size_t GetOutHeadersSize() const { return static_cast<size_t>(this->out_headers_size); } constexpr size_t GetInObjectCount() const { return static_cast<size_t>(this->in_object_count); } constexpr size_t GetOutObjectCount() const { return static_cast<size_t>(this->out_object_count); } constexpr size_t GetUnfixedOutPointerSizeOffset() const { return this->GetInDataSize() + this->GetInHeadersSize() + 0x10 /* padding. */; } }; static_assert(util::is_pod<ServerMessageRuntimeMetadata>::value, "util::is_pod<ServerMessageRuntimeMetadata>::value"); static_assert(sizeof(ServerMessageRuntimeMetadata) == sizeof(u64), "sizeof(ServerMessageRuntimeMetadata)"); class ServerMessageProcessor { public: /* Used to enabled templated message processors. */ virtual void SetImplementationProcessor(ServerMessageProcessor *impl) = 0; virtual const ServerMessageRuntimeMetadata GetRuntimeMetadata() const = 0; virtual Result PrepareForProcess(const ServiceDispatchContext &ctx, const ServerMessageRuntimeMetadata runtime_metadata) const = 0; virtual Result GetInObjects(ServiceObjectHolder *in_objects) const = 0; virtual HipcRequest PrepareForReply(const cmif::ServiceDispatchContext &ctx, PointerAndSize &out_raw_data, const ServerMessageRuntimeMetadata runtime_metadata) = 0; virtual void PrepareForErrorReply(const cmif::ServiceDispatchContext &ctx, PointerAndSize &out_raw_data, const ServerMessageRuntimeMetadata runtime_metadata) = 0; virtual void SetOutObjects(const cmif::ServiceDispatchContext &ctx, const HipcRequest &response, ServiceObjectHolder *out_objects, DomainObjectId *ids) = 0; }; }
3,631
C++
.h
70
44.457143
176
0.707558
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
7,573
sf_cmif_pointer_and_size.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/sf/cmif/sf_cmif_pointer_and_size.hpp
/* * 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/>. */ #pragma once #include <stratosphere/sf/sf_common.hpp> namespace ams::sf::cmif { class PointerAndSize { private: uintptr_t m_pointer; size_t m_size; public: constexpr PointerAndSize() : m_pointer(0), m_size(0) { /* ... */ } constexpr PointerAndSize(uintptr_t ptr, size_t sz) : m_pointer(ptr), m_size(sz) { /* ... */ } PointerAndSize(void *ptr, size_t sz) : PointerAndSize(reinterpret_cast<uintptr_t>(ptr), sz) { /* ... */ } void *GetPointer() const { return reinterpret_cast<void *>(m_pointer); } constexpr uintptr_t GetAddress() const { return m_pointer; } constexpr size_t GetSize() const { return m_size; } }; }
1,460
C++
.h
37
32.378378
117
0.627825
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
7,574
sf_cmif_service_object_holder.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/sf/cmif/sf_cmif_service_object_holder.hpp
/* * 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/>. */ #pragma once #include <stratosphere/sf/sf_service_object.hpp> #include <stratosphere/sf/cmif/sf_cmif_service_dispatch.hpp> namespace ams::sf::cmif { class ServiceObjectHolder { private: SharedPointer<IServiceObject> m_srv; const ServiceDispatchMeta *m_dispatch_meta; private: /* Copy constructor. */ ServiceObjectHolder(const ServiceObjectHolder &o) : m_srv(o.m_srv), m_dispatch_meta(o.m_dispatch_meta) { /* ... */ } ServiceObjectHolder &operator=(const ServiceObjectHolder &o) = delete; public: /* Default constructor, null all members. */ ServiceObjectHolder() : m_srv(nullptr, false), m_dispatch_meta(nullptr) { /* ... */ } ~ServiceObjectHolder() { m_dispatch_meta = nullptr; } /* Ensure correct type id at runtime through template constructor. */ template<typename ServiceImpl> constexpr explicit ServiceObjectHolder(SharedPointer<ServiceImpl> &&s) : m_srv(std::move(s)), m_dispatch_meta(GetServiceDispatchMeta<ServiceImpl>()) { /* ... */ } /* Move constructor, assignment operator. */ ServiceObjectHolder(ServiceObjectHolder &&o) : m_srv(std::move(o.m_srv)), m_dispatch_meta(std::move(o.m_dispatch_meta)) { o.m_dispatch_meta = nullptr; } ServiceObjectHolder &operator=(ServiceObjectHolder &&o) { ServiceObjectHolder tmp(std::move(o)); tmp.swap(*this); return *this; } /* State management. */ void swap(ServiceObjectHolder &o) { m_srv.swap(o.m_srv); std::swap(m_dispatch_meta, o.m_dispatch_meta); } void Reset() { m_srv = nullptr; m_dispatch_meta = nullptr; } ServiceObjectHolder Clone() const { return ServiceObjectHolder(*this); } /* Boolean operators. */ explicit constexpr operator bool() const { return m_srv != nullptr; } constexpr bool operator!() const { return m_srv == nullptr; } /* Getters. */ constexpr uintptr_t GetServiceId() const { if (m_dispatch_meta) { return m_dispatch_meta->GetServiceId(); } return 0; } template<typename Interface> constexpr inline bool IsServiceObjectValid() const { return this->GetServiceId() == GetServiceDispatchMeta<Interface>()->GetServiceId(); } template<typename Interface> inline Interface *GetServiceObject() const { if (this->GetServiceId() == GetServiceDispatchMeta<Interface>()->GetServiceId()) { return static_cast<Interface *>(m_srv.Get()); } return nullptr; } inline sf::IServiceObject *GetServiceObjectUnsafe() const { return static_cast<sf::IServiceObject *>(m_srv.Get()); } /* Processing. */ Result ProcessMessage(ServiceDispatchContext &ctx, const cmif::PointerAndSize &in_raw_data) const; }; }
4,036
C++
.h
91
32.846154
162
0.583142
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
7,575
sf_cmif_domain_service_object.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/sf/cmif/sf_cmif_domain_service_object.hpp
/* * 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/>. */ #pragma once #include <stratosphere/sf/sf_mitm_config.hpp> #include <stratosphere/sf/cmif/sf_cmif_service_dispatch.hpp> #include <stratosphere/sf/cmif/sf_cmif_domain_api.hpp> #include <stratosphere/sf/cmif/sf_cmif_server_message_processor.hpp> namespace ams::sf::cmif { class DomainServiceObjectDispatchTable : public impl::ServiceDispatchTableBase { private: Result ProcessMessageImpl(ServiceDispatchContext &ctx, ServerDomainBase *domain, const cmif::PointerAndSize &in_raw_data) const; Result ProcessMessageForMitmImpl(ServiceDispatchContext &ctx, ServerDomainBase *domain, const cmif::PointerAndSize &in_raw_data) const; public: Result ProcessMessage(ServiceDispatchContext &ctx, const cmif::PointerAndSize &in_raw_data) const; Result ProcessMessageForMitm(ServiceDispatchContext &ctx, const cmif::PointerAndSize &in_raw_data) const; }; class DomainServiceObjectProcessor : public ServerMessageProcessor { private: ServerMessageProcessor *m_impl_processor; ServerDomainBase *m_domain; DomainObjectId *m_in_object_ids; DomainObjectId *m_out_object_ids; size_t m_num_in_objects; ServerMessageRuntimeMetadata m_impl_metadata; public: DomainServiceObjectProcessor(ServerDomainBase *d, DomainObjectId *in_obj_ids, size_t num_in_objs) : m_domain(d), m_in_object_ids(in_obj_ids), m_num_in_objects(num_in_objs) { AMS_ABORT_UNLESS(m_domain != nullptr); AMS_ABORT_UNLESS(m_in_object_ids != nullptr); m_impl_processor = nullptr; m_out_object_ids = nullptr; m_impl_metadata = {}; } constexpr size_t GetInObjectCount() const { return m_num_in_objects; } constexpr size_t GetOutObjectCount() const { return m_impl_metadata.GetOutObjectCount(); } constexpr size_t GetImplOutHeadersSize() const { return m_impl_metadata.GetOutHeadersSize(); } constexpr size_t GetImplOutDataTotalSize() const { return m_impl_metadata.GetUnalignedOutDataSize() + m_impl_metadata.GetOutHeadersSize(); } public: /* Used to enabled templated message processors. */ virtual void SetImplementationProcessor(ServerMessageProcessor *impl) override final { if (m_impl_processor == nullptr) { m_impl_processor = impl; } else { m_impl_processor->SetImplementationProcessor(impl); } m_impl_metadata = m_impl_processor->GetRuntimeMetadata(); } virtual const ServerMessageRuntimeMetadata GetRuntimeMetadata() const override final { const auto runtime_metadata = m_impl_processor->GetRuntimeMetadata(); return ServerMessageRuntimeMetadata { .in_data_size = static_cast<u16>(runtime_metadata.GetInDataSize() + runtime_metadata.GetInObjectCount() * sizeof(DomainObjectId)), .unaligned_out_data_size = static_cast<u16>(runtime_metadata.GetOutDataSize() + runtime_metadata.GetOutObjectCount() * sizeof(DomainObjectId)), .in_headers_size = static_cast<u8>(runtime_metadata.GetInHeadersSize() + sizeof(CmifDomainInHeader)), .out_headers_size = static_cast<u8>(runtime_metadata.GetOutHeadersSize() + sizeof(CmifDomainOutHeader)), .in_object_count = 0, .out_object_count = 0, }; } virtual Result PrepareForProcess(const ServiceDispatchContext &ctx, const ServerMessageRuntimeMetadata runtime_metadata) const override final; virtual Result GetInObjects(ServiceObjectHolder *in_objects) const override final; virtual HipcRequest PrepareForReply(const cmif::ServiceDispatchContext &ctx, PointerAndSize &out_raw_data, const ServerMessageRuntimeMetadata runtime_metadata) override final; virtual void PrepareForErrorReply(const cmif::ServiceDispatchContext &ctx, PointerAndSize &out_raw_data, const ServerMessageRuntimeMetadata runtime_metadata) override final; virtual void SetOutObjects(const cmif::ServiceDispatchContext &ctx, const HipcRequest &response, ServiceObjectHolder *out_objects, DomainObjectId *ids) override final; }; class DomainServiceObject : public IServiceObject, public ServerDomainBase { friend class DomainServiceObjectDispatchTable; public: static constexpr inline DomainServiceObjectDispatchTable s_CmifServiceDispatchTable{}; private: virtual ServerDomainBase *GetServerDomain() = 0; }; class MitmDomainServiceObject : public DomainServiceObject{}; static_assert(sizeof(DomainServiceObject) == sizeof(MitmDomainServiceObject)); template<> struct ServiceDispatchTraits<DomainServiceObject> { static_assert(std::is_base_of<sf::IServiceObject, DomainServiceObject>::value, "DomainServiceObject must derive from sf::IServiceObject"); #if AMS_SF_MITM_SUPPORTED static_assert(!std::is_base_of<sf::IMitmServiceObject, DomainServiceObject>::value, "DomainServiceObject must not derive from sf::IMitmServiceObject"); #endif using ProcessHandlerType = decltype(ServiceDispatchMeta::ProcessHandler); using DispatchTableType = DomainServiceObjectDispatchTable; static constexpr ProcessHandlerType ProcessHandlerImpl = &impl::ServiceDispatchTableBase::ProcessMessage<DispatchTableType>; static constexpr inline ServiceDispatchMeta Meta{std::addressof(DomainServiceObject::s_CmifServiceDispatchTable), ProcessHandlerImpl}; }; template<> struct ServiceDispatchTraits<MitmDomainServiceObject> { static_assert(std::is_base_of<DomainServiceObject, MitmDomainServiceObject>::value, "MitmDomainServiceObject must derive from DomainServiceObject"); using ProcessHandlerType = decltype(ServiceDispatchMeta::ProcessHandler); using DispatchTableType = DomainServiceObjectDispatchTable; static constexpr ProcessHandlerType ProcessHandlerImpl = &impl::ServiceDispatchTableBase::ProcessMessageForMitm<DispatchTableType>; static constexpr inline ServiceDispatchMeta Meta{std::addressof(DomainServiceObject::s_CmifServiceDispatchTable), ProcessHandlerImpl}; }; }
7,229
C++
.h
113
53.575221
187
0.70361
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
7,576
sf_cmif_domain_api.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/sf/cmif/sf_cmif_domain_api.hpp
/* * 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/>. */ #pragma once #include <stratosphere/sf/sf_common.hpp> #include <stratosphere/sf/cmif/sf_cmif_service_object_holder.hpp> namespace ams::sf::cmif { struct DomainObjectId { u32 value; constexpr void SetValue(u32 new_value) { this->value = new_value; } }; static_assert(std::is_trivial<DomainObjectId>::value && sizeof(DomainObjectId) == sizeof(u32), "DomainObjectId"); inline constexpr bool operator==(const DomainObjectId &lhs, const DomainObjectId &rhs) { return lhs.value == rhs.value; } inline constexpr bool operator!=(const DomainObjectId &lhs, const DomainObjectId &rhs) { return lhs.value != rhs.value; } inline constexpr bool operator<(const DomainObjectId &lhs, const DomainObjectId &rhs) { return lhs.value < rhs.value; } inline constexpr bool operator<=(const DomainObjectId &lhs, const DomainObjectId &rhs) { return lhs.value <= rhs.value; } inline constexpr bool operator>(const DomainObjectId &lhs, const DomainObjectId &rhs) { return lhs.value > rhs.value; } inline constexpr bool operator>=(const DomainObjectId &lhs, const DomainObjectId &rhs) { return lhs.value >= rhs.value; } constexpr inline const DomainObjectId InvalidDomainObjectId = { .value = 0 }; class ServerDomainBase { public: virtual Result ReserveIds(DomainObjectId *out_ids, size_t count) = 0; virtual void ReserveSpecificIds(const DomainObjectId *ids, size_t count) = 0; virtual void UnreserveIds(const DomainObjectId *ids, size_t count) = 0; virtual void RegisterObject(DomainObjectId id, ServiceObjectHolder &&obj) = 0; virtual ServiceObjectHolder UnregisterObject(DomainObjectId id) = 0; virtual ServiceObjectHolder GetObject(DomainObjectId id) = 0; }; }
2,512
C++
.h
53
41.773585
117
0.711129
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
7,577
sf_cmif_service_dispatch.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/sf/cmif/sf_cmif_service_dispatch.hpp
/* * 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/>. */ #pragma once #include <stratosphere/sf/sf_mitm_config.hpp> #include <stratosphere/sf/sf_service_object.hpp> #include <stratosphere/sf/cmif/sf_cmif_pointer_and_size.hpp> #include <stratosphere/sf/cmif/sf_cmif_server_message_processor.hpp> namespace ams::sf::hipc { class ServerSessionManager; class ServerSession; } namespace ams::sf::cmif { class ServerMessageProcessor; struct HandlesToClose { os::NativeHandle handles[8]; size_t num_handles; }; struct ServiceDispatchContext { sf::IServiceObject *srv_obj; hipc::ServerSessionManager *manager; hipc::ServerSession *session; ServerMessageProcessor *processor; HandlesToClose *handles_to_close; const PointerAndSize pointer_buffer; const PointerAndSize in_message_buffer; const PointerAndSize out_message_buffer; const HipcParsedRequest request; }; struct ServiceCommandMeta { hos::Version hosver_low; hos::Version hosver_high; u32 cmd_id; Result (*handler)(CmifOutHeader **out_header_ptr, ServiceDispatchContext &ctx, const cmif::PointerAndSize &in_raw_data); constexpr inline bool MatchesVersion(hos::Version hosver) const { const bool min_valid = this->hosver_low == hos::Version_Min; const bool max_valid = this->hosver_high == hos::Version_Max; return (min_valid || this->hosver_low <= hosver) && (max_valid || hosver <= this->hosver_high); } constexpr inline bool Matches(u32 cmd_id, hos::Version hosver) const { return this->cmd_id == cmd_id && this->MatchesVersion(hosver); } constexpr inline decltype(handler) GetHandler() const { return this->handler; } constexpr inline bool operator>(const ServiceCommandMeta &rhs) const { if (this->cmd_id > rhs.cmd_id) { return true; } else if (this->cmd_id == rhs.cmd_id && this->hosver_low > rhs.hosver_low) { return true; } else if (this->cmd_id == rhs.cmd_id && this->hosver_low == rhs.hosver_low && this->hosver_high == rhs.hosver_high){ return true; } else { return false; } } }; static_assert(util::is_pod<ServiceCommandMeta>::value && sizeof(ServiceCommandMeta) == 0x18, "sizeof(ServiceCommandMeta)"); namespace impl { class ServiceDispatchTableBase { protected: Result ProcessMessageImpl(ServiceDispatchContext &ctx, const cmif::PointerAndSize &in_raw_data, const ServiceCommandMeta *entries, const size_t entry_count, u32 interface_id_for_debug) const; Result ProcessMessageForMitmImpl(ServiceDispatchContext &ctx, const cmif::PointerAndSize &in_raw_data, const ServiceCommandMeta *entries, const size_t entry_count, u32 interface_id_for_debug) const; public: /* CRTP. */ template<typename T> Result ProcessMessage(ServiceDispatchContext &ctx, const cmif::PointerAndSize &in_raw_data) const { static_assert(std::is_base_of<ServiceDispatchTableBase, T>::value, "ServiceDispatchTableBase::Process<T>"); R_RETURN(static_cast<const T *>(this)->ProcessMessage(ctx, in_raw_data)); } template<typename T> Result ProcessMessageForMitm(ServiceDispatchContext &ctx, const cmif::PointerAndSize &in_raw_data) const { static_assert(std::is_base_of<ServiceDispatchTableBase, T>::value, "ServiceDispatchTableBase::ProcessForMitm<T>"); R_RETURN(static_cast<const T *>(this)->ProcessMessageForMitm(ctx, in_raw_data)); } }; template<u32 InterfaceIdForDebug, size_t N> class ServiceDispatchTableImpl : public ServiceDispatchTableBase { public: static constexpr size_t NumEntries = N; private: const std::array<ServiceCommandMeta, N> m_entries; public: explicit constexpr ServiceDispatchTableImpl(const std::array<ServiceCommandMeta, N> &e) : m_entries{e} { /* ... */ } Result ProcessMessage(ServiceDispatchContext &ctx, const cmif::PointerAndSize &in_raw_data) const { R_RETURN(this->ProcessMessageImpl(ctx, in_raw_data, m_entries.data(), m_entries.size(), InterfaceIdForDebug)); } Result ProcessMessageForMitm(ServiceDispatchContext &ctx, const cmif::PointerAndSize &in_raw_data) const { R_RETURN(this->ProcessMessageForMitmImpl(ctx, in_raw_data, m_entries.data(), m_entries.size(), InterfaceIdForDebug)); } constexpr const std::array<ServiceCommandMeta, N> &GetEntries() const { return m_entries; } }; } template<u32 InterfaceIdForDebug, size_t N> class ServiceDispatchTable : public impl::ServiceDispatchTableImpl<InterfaceIdForDebug, N> { public: explicit constexpr ServiceDispatchTable(const std::array<ServiceCommandMeta, N> &e) : impl::ServiceDispatchTableImpl<InterfaceIdForDebug, N>(e) { /* ... */ } }; struct ServiceDispatchMeta { const impl::ServiceDispatchTableBase *DispatchTable; Result (impl::ServiceDispatchTableBase::*ProcessHandler)(ServiceDispatchContext &, const cmif::PointerAndSize &) const; uintptr_t GetServiceId() const { return reinterpret_cast<uintptr_t>(this->DispatchTable); } }; template<typename T> requires sf::IsServiceObject<T> struct ServiceDispatchTraits { using ProcessHandlerType = decltype(ServiceDispatchMeta::ProcessHandler); static constexpr inline auto DispatchTable = T::template s_CmifServiceDispatchTable<T>; using DispatchTableType = decltype(DispatchTable); static constexpr ProcessHandlerType ProcessHandlerImpl = sf::IsMitmServiceObject<T> ? (&impl::ServiceDispatchTableBase::ProcessMessageForMitm<DispatchTableType>) : (&impl::ServiceDispatchTableBase::ProcessMessage<DispatchTableType>); static constexpr inline ServiceDispatchMeta Meta{std::addressof(DispatchTable), ProcessHandlerImpl}; }; template<> struct ServiceDispatchTraits<sf::IServiceObject> { static constexpr inline auto DispatchTable = ServiceDispatchTable<0, 0>(std::array<ServiceCommandMeta, 0>{}); }; #if AMS_SF_MITM_SUPPORTED template<> struct ServiceDispatchTraits<sf::IMitmServiceObject> { static constexpr inline auto DispatchTable = ServiceDispatchTable<0, 0>(std::array<ServiceCommandMeta, 0>{}); }; #endif template<typename T> constexpr ALWAYS_INLINE const ServiceDispatchMeta *GetServiceDispatchMeta() { return std::addressof(ServiceDispatchTraits<T>::Meta); } }
7,685
C++
.h
143
43.734266
214
0.665424
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
7,578
sf_cmif_inline_context.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/sf/cmif/sf_cmif_inline_context.hpp
/* * 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/>. */ #pragma once #include <stratosphere/sf/sf_common.hpp> namespace ams::sf::cmif { using InlineContext = u32; InlineContext GetInlineContext(); InlineContext SetInlineContext(InlineContext ctx); class ScopedInlineContextChanger { private: InlineContext m_prev_ctx; public: ALWAYS_INLINE explicit ScopedInlineContextChanger(InlineContext new_ctx) : m_prev_ctx(SetInlineContext(new_ctx)) { /* ... */ } ~ScopedInlineContextChanger() { SetInlineContext(m_prev_ctx); } }; }
1,179
C++
.h
29
36.482759
138
0.729021
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
7,579
sf_cmif_domain_manager.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/sf/cmif/sf_cmif_domain_manager.hpp
/* * 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/>. */ #pragma once #include <stratosphere/sf/sf_common.hpp> #include <stratosphere/sf/cmif/sf_cmif_domain_api.hpp> #include <stratosphere/sf/cmif/sf_cmif_domain_service_object.hpp> #include <stratosphere/sf/impl/sf_service_object_impl.hpp> namespace ams::sf::cmif { class ServerDomainManager { NON_COPYABLE(ServerDomainManager); NON_MOVEABLE(ServerDomainManager); private: class Domain; struct Entry { NON_COPYABLE(Entry); NON_MOVEABLE(Entry); util::IntrusiveListNode free_list_node; util::IntrusiveListNode domain_list_node; Domain *owner; ServiceObjectHolder object; explicit Entry() : owner(nullptr) { /* ... */ } }; class Domain final : public DomainServiceObject, private sf::impl::ServiceObjectImplBase2 { NON_COPYABLE(Domain); NON_MOVEABLE(Domain); private: using EntryList = typename util::IntrusiveListMemberTraits<&Entry::domain_list_node>::ListType; private: ServerDomainManager *m_manager; EntryList m_entries; public: explicit Domain(ServerDomainManager *m) : m_manager(m) { /* ... */ } ~Domain(); void DisposeImpl(); virtual void AddReference() override { ServiceObjectImplBase2::AddReferenceImpl(); } virtual void Release() override { if (ServiceObjectImplBase2::ReleaseImpl()) { this->DisposeImpl(); } } virtual ServerDomainBase *GetServerDomain() override final { return static_cast<ServerDomainBase *>(this); } virtual Result ReserveIds(DomainObjectId *out_ids, size_t count) override final; virtual void ReserveSpecificIds(const DomainObjectId *ids, size_t count) override final; virtual void UnreserveIds(const DomainObjectId *ids, size_t count) override final; virtual void RegisterObject(DomainObjectId id, ServiceObjectHolder &&obj) override final; virtual ServiceObjectHolder UnregisterObject(DomainObjectId id) override final; virtual ServiceObjectHolder GetObject(DomainObjectId id) override final; }; public: using DomainEntryStorage = util::TypedStorage<Entry>; using DomainStorage = util::TypedStorage<Domain>; private: class EntryManager { private: using EntryList = typename util::IntrusiveListMemberTraits<&Entry::free_list_node>::ListType; private: os::SdkMutex m_lock; EntryList m_free_list; Entry *m_entries; size_t m_num_entries; public: EntryManager(DomainEntryStorage *entry_storage, size_t entry_count); ~EntryManager(); Entry *AllocateEntry(); void FreeEntry(Entry *); void AllocateSpecificEntries(const DomainObjectId *ids, size_t count); inline DomainObjectId GetId(Entry *e) { const size_t index = e - m_entries; AMS_ABORT_UNLESS(index < m_num_entries); return DomainObjectId{ u32(index + 1) }; } inline Entry *GetEntry(DomainObjectId id) { if (id == InvalidDomainObjectId) { return nullptr; } const size_t index = id.value - 1; if (!(index < m_num_entries)) { return nullptr; } return m_entries + index; } }; private: os::SdkMutex m_entry_owner_lock; EntryManager m_entry_manager; private: virtual void *AllocateDomain() = 0; virtual void FreeDomain(void *) = 0; protected: ServerDomainManager(DomainEntryStorage *entry_storage, size_t entry_count) : m_entry_owner_lock(), m_entry_manager(entry_storage, entry_count) { /* ... */ } inline DomainServiceObject *AllocateDomainServiceObject() { void *storage = this->AllocateDomain(); if (storage == nullptr) { return nullptr; } return std::construct_at(static_cast<Domain *>(storage), this); } public: static void DestroyDomainServiceObject(DomainServiceObject *obj) { static_cast<Domain *>(obj)->DisposeImpl(); } }; }
5,749
C++
.h
120
32.691667
168
0.552505
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
7,580
socket_types.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/socket/socket_types.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> namespace ams::socket { using InAddrT = u32; using InPortT = u16; using SockLenT = u32; using NfdsT = u64; using FdMask = u64; constexpr inline unsigned int FdSetSize = 0x400; template<u32 A, u32 B, u32 C, u32 D> constexpr inline InAddrT EncodeInAddr = util::ConvertToBigEndian(InAddrT{(A << 24) | (B << 16) | (C << 8) | (D << 0)}); constexpr inline InAddrT InAddr_Any = EncodeInAddr< 0, 0, 0, 0>; constexpr inline InAddrT InAddr_Broadcast = EncodeInAddr<255, 255, 255, 255>; constexpr inline InAddrT InAddr_None = EncodeInAddr<255, 255, 255, 255>; constexpr inline InAddrT InAddr_Loopback = EncodeInAddr<127, 0, 0, 1>; enum class Protocol : s32 { IpProto_Ip = 0, IpProto_Icmp = 1, IpProto_Tcp = 6, IpProto_Udp = 17, IpProto_None = 59, IpProto_UdpLite = 136, IpProto_Raw = 255, IpProto_Max = 256, }; enum class Type : u32 { Sock_Default = 0, Sock_Stream = 1, Sock_Dgram = 2, Sock_Raw = 3, Sock_SeqPacket = 5, Sock_NonBlock = 0x20000000, }; enum class Family : u8 { Af_Unspec = 0, Pf_Unspec = Af_Unspec, Af_Inet = 2, Pf_Inet = Af_Inet, Af_Route = 17, Pf_Route = Af_Route, Af_Link = 18, Pf_Link = Af_Link, Af_Inet6 = 28, Pf_Inet6 = Af_Inet6, Af_Max = 42, Pf_Max = Af_Max }; enum class MsgFlag : s32 { Msg_None = (0 << 0), Msg_Oob = (1 << 0), Msg_Peek = (1 << 1), Msg_DontRoute = (1 << 2), /* ... */ Msg_Trunc = (1 << 4), Msg_CTrunc = (1 << 5), Msg_WaitAll = (1 << 6), Msg_DontWait = (1 << 7), /* ... */ }; enum class FcntlCommand : u32 { F_GetFl = 3, F_SetFl = 4, }; enum class FcntlFlag : u32 { None = (0 << 0), O_NonBlock = (1 << 11), }; enum class ShutdownMethod : u32 { Shut_Rd = 0, Shut_Wr = 1, Shut_RdWr = 2, }; struct HostEnt { char *h_name; char **h_aliases; Family h_addrtype; int h_length; char **h_addr_list; }; struct InAddr { InAddrT s_addr; }; enum class AddrInfoFlag : u32 { Ai_None = (0 << 0), Ai_Passive = (1 << 0), Ai_CanonName = (1 << 1), Ai_NumericHost = (1 << 2), Ai_NumericServ = (1 << 3), Ai_AddrConfig = (1 << 10), }; struct SockAddr { u8 sa_len; Family sa_family; char sa_data[14]; }; struct SockAddrIn { u8 sin_len; Family sin_family; InPortT sin_port; InAddr sin_addr; u8 sin_zero[8]; }; static_assert(sizeof(SockAddr) == sizeof(SockAddrIn)); struct AddrInfo { AddrInfoFlag ai_flags; Family ai_family; Type ai_socktype; Protocol ai_protocol; SockLenT ai_addrlen; SockAddr *ai_addr; char *ai_canonname; AddrInfo *ai_next; }; struct TimeVal { long tv_sec; long tv_usec; }; struct Linger { int l_onoff; int l_linger; }; #define AMS_SOCKET_IMPL_DEFINE_ENUM_OPERATORS(__ENUM__) \ constexpr inline __ENUM__ operator | (__ENUM__ lhs, __ENUM__ rhs) { return static_cast<__ENUM__>(static_cast<std::underlying_type_t<__ENUM__>>(lhs) | static_cast<std::underlying_type_t<__ENUM__>>(rhs)); } \ constexpr inline __ENUM__ operator |=(__ENUM__ &lhs, __ENUM__ rhs) { return lhs = lhs | rhs; } \ constexpr inline __ENUM__ operator & (__ENUM__ lhs, __ENUM__ rhs) { return static_cast<__ENUM__>(static_cast<std::underlying_type_t<__ENUM__>>(lhs) & static_cast<std::underlying_type_t<__ENUM__>>(rhs)); } \ constexpr inline __ENUM__ operator &=(__ENUM__ &lhs, __ENUM__ rhs) { return lhs = lhs & rhs; } \ constexpr inline __ENUM__ operator ^ (__ENUM__ lhs, __ENUM__ rhs) { return static_cast<__ENUM__>(static_cast<std::underlying_type_t<__ENUM__>>(lhs) ^ static_cast<std::underlying_type_t<__ENUM__>>(rhs)); } \ constexpr inline __ENUM__ operator ^=(__ENUM__ &lhs, __ENUM__ rhs) { return lhs = lhs ^ rhs; } \ constexpr inline __ENUM__ operator ~ (__ENUM__ e) { return static_cast<__ENUM__>(~static_cast<std::underlying_type_t<__ENUM__>>(e)); } AMS_SOCKET_IMPL_DEFINE_ENUM_OPERATORS(Type) AMS_SOCKET_IMPL_DEFINE_ENUM_OPERATORS(AddrInfoFlag) AMS_SOCKET_IMPL_DEFINE_ENUM_OPERATORS(MsgFlag) AMS_SOCKET_IMPL_DEFINE_ENUM_OPERATORS(FcntlFlag) #undef AMS_SOCKET_IMPL_DEFINE_ENUM_OPERATORS }
5,849
C++
.h
150
31.966667
215
0.526409
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
7,581
socket_system_config.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/socket/socket_system_config.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/socket/socket_config.hpp> namespace ams::socket { class SystemConfigDefault : public Config { public: static constexpr size_t DefaultTcpInitialSendBufferSize = 32_KB; static constexpr size_t DefaultTcpInitialReceiveBufferSize = 64_KB; static constexpr size_t DefaultTcpAutoSendBufferSizeMax = 256_KB; static constexpr size_t DefaultTcpAutoReceiveBufferSizeMax = 256_KB; static constexpr size_t DefaultUdpSendBufferSize = 9_KB; static constexpr size_t DefaultUdpReceiveBufferSize = 42240; static constexpr auto DefaultSocketBufferEfficiency = 2; static constexpr auto DefaultConcurrency = 8; static constexpr size_t DefaultAllocatorPoolSize = 128_KB; static constexpr size_t PerTcpSocketWorstCaseMemoryPoolSize = [] { constexpr size_t WorstCaseTcpSendBufferSize = AlignMss(std::max(DefaultTcpInitialSendBufferSize, DefaultTcpAutoSendBufferSizeMax)); constexpr size_t WorstCaseTcpReceiveBufferSize = AlignMss(std::max(DefaultTcpInitialReceiveBufferSize, DefaultTcpAutoReceiveBufferSizeMax)); return util::AlignUp(WorstCaseTcpSendBufferSize * DefaultSocketBufferEfficiency + WorstCaseTcpReceiveBufferSize * DefaultSocketBufferEfficiency, os::MemoryPageSize); }(); static constexpr size_t PerUdpSocketWorstCaseMemoryPoolSize = [] { constexpr size_t WorstCaseUdpSendBufferSize = AlignMss(DefaultUdpSendBufferSize); constexpr size_t WorstCaseUdpReceiveBufferSize = AlignMss(DefaultUdpReceiveBufferSize); return util::AlignUp(WorstCaseUdpSendBufferSize * DefaultSocketBufferEfficiency + WorstCaseUdpReceiveBufferSize * DefaultSocketBufferEfficiency, os::MemoryPageSize); }(); public: constexpr SystemConfigDefault(void *mp, size_t mp_sz, size_t ap, int c=DefaultConcurrency) : Config(mp, mp_sz, ap, DefaultTcpInitialSendBufferSize, DefaultTcpInitialReceiveBufferSize, DefaultTcpAutoSendBufferSizeMax, DefaultTcpAutoReceiveBufferSizeMax, DefaultUdpSendBufferSize, DefaultUdpReceiveBufferSize, DefaultSocketBufferEfficiency, c) { /* Mark as system. */ m_system = true; } }; class SystemConfigLightDefault : public Config { public: static constexpr size_t DefaultTcpInitialSendBufferSize = 16_KB; static constexpr size_t DefaultTcpInitialReceiveBufferSize = 16_KB; static constexpr size_t DefaultTcpAutoSendBufferSizeMax = 0_KB; static constexpr size_t DefaultTcpAutoReceiveBufferSizeMax = 0_KB; static constexpr size_t DefaultUdpSendBufferSize = 9_KB; static constexpr size_t DefaultUdpReceiveBufferSize = 42240; static constexpr auto DefaultSocketBufferEfficiency = 2; static constexpr auto DefaultConcurrency = 2; static constexpr size_t DefaultAllocatorPoolSize = 64_KB; static constexpr size_t PerTcpSocketWorstCaseMemoryPoolSize = [] { constexpr size_t WorstCaseTcpSendBufferSize = AlignMss(std::max(DefaultTcpInitialSendBufferSize, DefaultTcpAutoSendBufferSizeMax)); constexpr size_t WorstCaseTcpReceiveBufferSize = AlignMss(std::max(DefaultTcpInitialReceiveBufferSize, DefaultTcpAutoReceiveBufferSizeMax)); return util::AlignUp(WorstCaseTcpSendBufferSize * DefaultSocketBufferEfficiency + WorstCaseTcpReceiveBufferSize * DefaultSocketBufferEfficiency, os::MemoryPageSize); }(); static constexpr size_t PerUdpSocketWorstCaseMemoryPoolSize = [] { constexpr size_t WorstCaseUdpSendBufferSize = AlignMss(DefaultUdpSendBufferSize); constexpr size_t WorstCaseUdpReceiveBufferSize = AlignMss(DefaultUdpReceiveBufferSize); return util::AlignUp(WorstCaseUdpSendBufferSize * DefaultSocketBufferEfficiency + WorstCaseUdpReceiveBufferSize * DefaultSocketBufferEfficiency, os::MemoryPageSize); }(); public: constexpr SystemConfigLightDefault(void *mp, size_t mp_sz, size_t ap, int c=DefaultConcurrency) : Config(mp, mp_sz, ap, DefaultTcpInitialSendBufferSize, DefaultTcpInitialReceiveBufferSize, DefaultTcpAutoSendBufferSizeMax, DefaultTcpAutoReceiveBufferSizeMax, DefaultUdpSendBufferSize, DefaultUdpReceiveBufferSize, DefaultSocketBufferEfficiency, c) { /* Mark as system. */ m_system = true; } }; }
5,659
C++
.h
86
53.802326
181
0.684589
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
7,582
socket_api.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/socket/socket_api.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/socket/socket_types.hpp> #include <stratosphere/socket/socket_options.hpp> #include <stratosphere/socket/socket_errno.hpp> #include <stratosphere/socket/socket_config.hpp> namespace ams::socket { Errno GetLastError(); void SetLastError(Errno err); u32 InetHtonl(u32 host); u16 InetHtons(u16 host); u32 InetNtohl(u32 net); u16 InetNtohs(u16 net); Result Initialize(const Config &config); Result Finalize(); Result InitializeAllocatorForInternal(void *buffer, size_t size); ssize_t RecvFrom(s32 desc, void *buffer, size_t buffer_size, MsgFlag flags, SockAddr *out_address, SockLenT *out_addr_len); ssize_t Recv(s32 desc, void *buffer, size_t buffer_size, MsgFlag flags); ssize_t SendTo(s32 desc, const void *buffer, size_t buffer_size, MsgFlag flags, const SockAddr *address, SockLenT len); ssize_t Send(s32 desc, const void *buffer, size_t buffer_size, MsgFlag flags); s32 Shutdown(s32 desc, ShutdownMethod how); s32 Socket(Family domain, Type type, Protocol protocol); s32 SocketExempt(Family domain, Type type, Protocol protocol); s32 Accept(s32 desc, SockAddr *out_address, SockLenT *out_addr_len); s32 Bind(s32 desc, const SockAddr *address, SockLenT len); s32 Connect(s32 desc, const SockAddr *address, SockLenT len); s32 GetSockName(s32 desc, SockAddr *out_address, SockLenT *out_addr_len); s32 SetSockOpt(s32 desc, Level level, Option option_name, const void *option_value, SockLenT option_size); s32 Listen(s32 desc, s32 backlog); s32 Close(s32 desc); }
2,263
C++
.h
46
45.543478
127
0.748296
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
7,583
socket_config.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/socket/socket_config.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/os.hpp> #include <stratosphere/socket/socket_constants.hpp> namespace ams::socket { constexpr ALWAYS_INLINE size_t AlignMss(size_t size) { return util::DivideUp(size, static_cast<size_t>(1500)) * static_cast<size_t>(1500); } class Config { private: u32 m_version; protected: bool m_system; bool m_smbp; void *m_memory_pool; size_t m_memory_pool_size; size_t m_allocator_pool_size; size_t m_tcp_initial_send_buffer_size; size_t m_tcp_initial_receive_buffer_size; size_t m_tcp_auto_send_buffer_size_max; size_t m_tcp_auto_receive_buffer_size_max; size_t m_udp_send_buffer_size; size_t m_udp_receive_buffer_size; int m_sb_efficiency; int m_concurrency_count_max; public: constexpr Config(void *mp, size_t mp_sz, size_t ap, size_t is, size_t ir, size_t as, size_t ar, size_t us, size_t ur, int sbe, int c) : m_version(LibraryVersion), m_system(false), m_smbp(false), m_memory_pool(mp), m_memory_pool_size(mp_sz), m_allocator_pool_size(ap), m_tcp_initial_send_buffer_size(is), m_tcp_initial_receive_buffer_size(ir), m_tcp_auto_send_buffer_size_max(as), m_tcp_auto_receive_buffer_size_max(ar), m_udp_send_buffer_size(us), m_udp_receive_buffer_size(ur), m_sb_efficiency(sbe), m_concurrency_count_max(c) { /* ... */ } constexpr u32 GetVersion() const { return m_version; } constexpr bool IsSystemClient() const { return m_system; } constexpr bool IsSmbpClient() const { return m_smbp; } constexpr void *GetMemoryPool() const { return m_memory_pool; } constexpr size_t GetMemoryPoolSize() const { return m_memory_pool_size; } constexpr size_t GetAllocatorPoolSize() const { return m_allocator_pool_size; } constexpr size_t GetTcpInitialSendBufferSize() const { return m_tcp_initial_send_buffer_size; } constexpr size_t GetTcpInitialReceiveBufferSize() const { return m_tcp_initial_receive_buffer_size; } constexpr size_t GetTcpAutoSendBufferSizeMax() const { return m_tcp_auto_send_buffer_size_max; } constexpr size_t GetTcpAutoReceiveBufferSizeMax() const { return m_tcp_auto_receive_buffer_size_max; } constexpr size_t GetUdpSendBufferSize() const { return m_udp_send_buffer_size; } constexpr size_t GetUdpReceiveBufferSize() const { return m_udp_receive_buffer_size; } constexpr int GetSocketBufferEfficiency() const { return m_sb_efficiency; } constexpr int GetConcurrencyCountMax() const { return m_concurrency_count_max; } constexpr void SetTcpInitialSendBufferSize(size_t size) { m_tcp_initial_send_buffer_size = size; } constexpr void SetTcpInitialReceiveBufferSize(size_t size) { m_tcp_initial_receive_buffer_size = size; } constexpr void SetTcpAutoSendBufferSizeMax(size_t size) { m_tcp_auto_send_buffer_size_max = size; } constexpr void SetTcpAutoReceiveBufferSizeMax(size_t size) { m_tcp_auto_receive_buffer_size_max = size; } constexpr void SetUdpSendBufferSize(size_t size) { m_udp_send_buffer_size = size; } constexpr void SetUdpReceiveBufferSize(size_t size) { m_udp_receive_buffer_size = size; } constexpr void SetSocketBufferEfficiency(int sb) { AMS_ABORT_UNLESS(1 <= sb && sb <= 8); m_sb_efficiency = sb; } constexpr void SetConcurrencyCountMax(int c) { m_concurrency_count_max = c; } }; }
4,582
C++
.h
83
44.542169
145
0.638326
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
7,584
socket_options.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/socket/socket_options.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> namespace ams::socket { enum class Level : s32 { Sol_Ip = 0, Sol_Icmp = 1, Sol_Tcp = 6, Sol_Udp = 17, Sol_UdpLite = 136, Sol_Socket = 0xFFFF, }; enum class Option : u32 { /* ==================================== */ So_Debug = (1 << 0), So_AcceptConn = (1 << 1), So_ReuseAddr = (1 << 2), So_KeepAlive = (1 << 3), So_DontRoute = (1 << 4), So_Broadcast = (1 << 5), So_UseLoopback = (1 << 6), So_Linger = (1 << 7), So_OobInline = (1 << 8), So_ReusePort = (1 << 9), So_SndBuf = (1 << 12) | 0x01, So_RcvBuf = (1 << 12) | 0x02, So_SndLoWat = (1 << 12) | 0x03, So_RcvLoWat = (1 << 12) | 0x04, So_SndTimeo = (1 << 12) | 0x05, So_RcvTimeo = (1 << 12) | 0x06, So_Error = (1 << 12) | 0x07, So_Type = (1 << 12) | 0x08, So_Label = (1 << 12) | 0x09, So_PeerLabel = (1 << 12) | 0x10, So_ListenQLimit = (1 << 12) | 0x11, So_ListenQLen = (1 << 12) | 0x12, So_ListenIncQLen = (1 << 12) | 0x13, So_SetFib = (1 << 12) | 0x14, So_User_Cookie = (1 << 12) | 0x15, So_Protocol = (1 << 12) | 0x16, So_Nn_Shutdown_Exempt = (1 << 16), So_Vendor = (1u << 31), So_Nn_Linger = So_Vendor | 0x01, /* ==================================== */ /* ==================================== */ Ip_Options = 1, Ip_HdrIncl = 2, Ip_Tos = 3, Ip_Ttl = 4, Ip_RecvOpts = 5, Ip_Multicast_If = 9, Ip_Multicast_Ttl = 10, Ip_Multicast_Loop = 11, Ip_Add_Membership = 12, Ip_Drop_Membership = 13, Ip_Multicast_Vif = 14, Ip_Rsvp_On = 15, Ip_Rsvp_Off = 16, Ip_Rsvp_Vif_On = 17, Ip_Rsvp_Vif_Off = 18, Ip_PortRange = 19, Ip_Faith = 22, Ip_OnesBcast = 23, Ip_BindAny = 24, Ip_RecvTtl = 65, Ip_MinTtl = 66, Ip_DontFrag = 67, Ip_RecvTos = 68, Ip_Add_Source_Membership = 70, Ip_Drop_Source_Membership = 71, Ip_Block_Source = 72, Ip_Unblock_Source = 73, /* ==================================== */ /* ==================================== */ Tcp_NoDelay = (1 << 0), Tcp_MaxSeg = (1 << 1), Tcp_NoPush = (1 << 2), Tcp_NoOpt = (1 << 3), Tcp_Md5Sig = (1 << 4), Tcp_Info = (1 << 5), Tcp_Congestion = (1 << 6), Tcp_KeepInit = (1 << 7), Tcp_KeepIdle = (1 << 8), Tcp_KeepIntvl = (1 << 9), Tcp_KeepCnt = (1 << 10), Tcp_Vendor = So_Vendor, /* ==================================== */ }; }
4,133
C++
.h
103
32.495146
76
0.389345
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
7,585
socket_constants.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/socket/socket_constants.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> namespace ams::socket { constexpr inline s32 InvalidSocket = -1; constexpr inline s32 SocketError = -1; constexpr inline u32 MaxSocketsPerClient = 0x80; constexpr inline auto DefaultTcpAutoBufferSizeMax = 192_KB; constexpr inline auto MinTransferMemorySize = (2 * DefaultTcpAutoBufferSizeMax + 128_KB); constexpr inline auto MinSocketAllocatorSize = 128_KB; constexpr inline auto MinSocketMemoryPoolSize = MinSocketAllocatorSize + MinTransferMemorySize; constexpr inline auto MinMemHeapAllocatorSize = 16_KB; constexpr inline auto MinimumSharedMbufPoolReservation = 4_KB; constexpr inline size_t MemoryPoolAlignment = 4_KB; constexpr inline auto ConcurrencyLimitMax = 14; /* TODO: Does this need to be 1 for sockets to work on lower firmware versions? */ /* Is this value actually used/checked by bsdsockets sysmodule? */ constexpr inline auto LibraryVersion = 7; }
1,658
C++
.h
33
46.878788
108
0.741497
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
7,587
socket_platform_types_translation.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/socket/impl/socket_platform_types_translation.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/socket/socket_types.hpp> #include <stratosphere/socket/socket_options.hpp> #include <stratosphere/socket/socket_constants.hpp> #include <stratosphere/socket/socket_errno.hpp> namespace ams::socket::impl { #if defined(ATMOSPHERE_OS_WINDOWS) class PosixWinSockConverter { private: struct SocketData { SOCKET winsock; bool exempt; bool shutdown; constexpr SocketData() : winsock(static_cast<SOCKET>(INVALID_SOCKET)), exempt(), shutdown() { /* ... */ } }; private: os::SdkMutex m_mutex{}; SocketData m_data[MaxSocketsPerClient]{}; private: static constexpr int GetInitialIndex(SOCKET winsock) { /* The lower 2 bits of a winsock are always zero; Nintendo uses the upper bits as a hashmap index into m_data. */ return (winsock >> 2) % MaxSocketsPerClient; } public: constexpr PosixWinSockConverter() = default; s32 AcquirePosixHandle(SOCKET winsock, bool exempt = false); s32 GetShutdown(bool &shutdown, s32 posix); s32 GetSocketExempt(bool &exempt, s32 posix); SOCKET PosixToWinsockSocket(s32 posix); void ReleaseAllPosixHandles(); void ReleasePosixHandle(s32 posix); s32 SetShutdown(s32 posix, bool shutdown); s32 SetSocketExempt(s32 posix, bool exempt); s32 WinsockToPosixSocket(SOCKET winsock); }; s32 MapProtocolValue(Protocol protocol); Protocol MapProtocolValue(s32 protocol); s32 MapTypeValue(Type type); Type MapTypeValue(s32 type); s8 MapFamilyValue(Family family); Family MapFamilyValue(s8 family); s32 MapMsgFlagValue(MsgFlag flag); MsgFlag MapMsgFlagValue(s32 flag); u32 MapAddrInfoFlagValue(AddrInfoFlag flag); AddrInfoFlag MapAddrInfoFlagValue(u32 flag); u32 MapShutdownMethodValue(ShutdownMethod how); ShutdownMethod MapShutdownMethodValue(u32 how); u32 MapFcntlFlagValue(FcntlFlag flag); FcntlFlag MapFcntlFlagValue(u32 flag); s32 MapLevelValue(Level level); Level MapLevelValue(s32 level); s32 MapOptionValue(Level level, Option option); Option MapOptionValue(s32 level, s32 option); s32 MapErrnoValue(Errno error); Errno MapErrnoValue(s32 error); #endif #define AMS_SOCKET_IMPL_DECLARE_CONVERSION(AMS, PLATFORM) \ void CopyToPlatform(PLATFORM *dst, const AMS *src); \ void CopyFromPlatform(AMS *dst, const PLATFORM *src); AMS_SOCKET_IMPL_DECLARE_CONVERSION(SockAddrIn, sockaddr_in); AMS_SOCKET_IMPL_DECLARE_CONVERSION(TimeVal, timeval); AMS_SOCKET_IMPL_DECLARE_CONVERSION(Linger, linger); #undef AMS_SOCKET_IMPL_DECLARE_CONVERSION }
3,513
C++
.h
80
36.85
129
0.699766
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
7,588
nsd_types.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/nsd/nsd_types.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> namespace ams::nsd { struct EnvironmentIdentifier { static constexpr size_t Size = 8; char value[Size]; constexpr friend bool operator==(const EnvironmentIdentifier &lhs, const EnvironmentIdentifier &rhs) { return util::Strncmp(lhs.value, rhs.value, Size) == 0; } constexpr friend bool operator!=(const EnvironmentIdentifier &lhs, const EnvironmentIdentifier &rhs) { return !(lhs == rhs); } }; constexpr inline const EnvironmentIdentifier EnvironmentIdentifierOfProductDevice = {"lp1"}; constexpr inline const EnvironmentIdentifier EnvironmentIdentifierOfNotProductDevice = {"dd1"}; }
1,353
C++
.h
31
39.16129
110
0.728723
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
7,589
nsd_device.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/nsd/impl/device/nsd_device.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/nsd/nsd_types.hpp> namespace ams::nsd::impl::device { const EnvironmentIdentifier &GetEnvironmentIdentifierFromSettings(); }
826
C++
.h
21
37.333333
76
0.76808
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
7,590
hos_stratosphere_api.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/hos/hos_stratosphere_api.hpp
/* * 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/>. */ #pragma once #include <stratosphere/hos/hos_types.hpp> namespace ams::hos { void InitializeForStratosphere(); void InitializeForStratosphereDebug(hos::Version debug_version); }
824
C++
.h
21
37
76
0.765957
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
7,591
hos_types.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/hos/hos_types.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> namespace ams::hos { enum Version : u32 { Version_Min = ::ams::TargetFirmware_Min, Version_1_0_0 = ::ams::TargetFirmware_1_0_0, Version_2_0_0 = ::ams::TargetFirmware_2_0_0, Version_2_1_0 = ::ams::TargetFirmware_2_1_0, Version_2_2_0 = ::ams::TargetFirmware_2_2_0, Version_2_3_0 = ::ams::TargetFirmware_2_3_0, Version_3_0_0 = ::ams::TargetFirmware_3_0_0, Version_3_0_1 = ::ams::TargetFirmware_3_0_1, Version_3_0_2 = ::ams::TargetFirmware_3_0_2, Version_4_0_0 = ::ams::TargetFirmware_4_0_0, Version_4_0_1 = ::ams::TargetFirmware_4_0_1, Version_4_1_0 = ::ams::TargetFirmware_4_1_0, Version_5_0_0 = ::ams::TargetFirmware_5_0_0, Version_5_0_1 = ::ams::TargetFirmware_5_0_1, Version_5_0_2 = ::ams::TargetFirmware_5_0_2, Version_5_1_0 = ::ams::TargetFirmware_5_1_0, Version_6_0_0 = ::ams::TargetFirmware_6_0_0, Version_6_0_1 = ::ams::TargetFirmware_6_0_1, Version_6_1_0 = ::ams::TargetFirmware_6_1_0, Version_6_2_0 = ::ams::TargetFirmware_6_2_0, Version_7_0_0 = ::ams::TargetFirmware_7_0_0, Version_7_0_1 = ::ams::TargetFirmware_7_0_1, Version_8_0_0 = ::ams::TargetFirmware_8_0_0, Version_8_0_1 = ::ams::TargetFirmware_8_0_1, Version_8_1_0 = ::ams::TargetFirmware_8_1_0, Version_8_1_1 = ::ams::TargetFirmware_8_1_1, Version_9_0_0 = ::ams::TargetFirmware_9_0_0, Version_9_0_1 = ::ams::TargetFirmware_9_0_1, Version_9_1_0 = ::ams::TargetFirmware_9_1_0, Version_9_2_0 = ::ams::TargetFirmware_9_2_0, Version_10_0_0 = ::ams::TargetFirmware_10_0_0, Version_10_0_1 = ::ams::TargetFirmware_10_0_1, Version_10_0_2 = ::ams::TargetFirmware_10_0_2, Version_10_0_3 = ::ams::TargetFirmware_10_0_3, Version_10_0_4 = ::ams::TargetFirmware_10_0_4, Version_10_1_0 = ::ams::TargetFirmware_10_1_0, Version_10_2_0 = ::ams::TargetFirmware_10_2_0, Version_11_0_0 = ::ams::TargetFirmware_11_0_0, Version_11_0_1 = ::ams::TargetFirmware_11_0_1, Version_12_0_0 = ::ams::TargetFirmware_12_0_0, Version_12_0_1 = ::ams::TargetFirmware_12_0_1, Version_12_0_2 = ::ams::TargetFirmware_12_0_2, Version_12_0_3 = ::ams::TargetFirmware_12_0_3, Version_12_1_0 = ::ams::TargetFirmware_12_1_0, Version_13_0_0 = ::ams::TargetFirmware_13_0_0, Version_13_1_0 = ::ams::TargetFirmware_13_1_0, Version_13_2_0 = ::ams::TargetFirmware_13_2_0, Version_13_2_1 = ::ams::TargetFirmware_13_2_1, Version_14_0_0 = ::ams::TargetFirmware_14_0_0, Version_14_1_0 = ::ams::TargetFirmware_14_1_0, Version_14_1_1 = ::ams::TargetFirmware_14_1_1, Version_14_1_2 = ::ams::TargetFirmware_14_1_2, Version_15_0_0 = ::ams::TargetFirmware_15_0_0, Version_15_0_1 = ::ams::TargetFirmware_15_0_1, Version_16_0_0 = ::ams::TargetFirmware_16_0_0, Version_16_0_1 = ::ams::TargetFirmware_16_0_1, Version_16_0_2 = ::ams::TargetFirmware_16_0_2, Version_16_0_3 = ::ams::TargetFirmware_16_0_3, Version_16_1_0 = ::ams::TargetFirmware_16_1_0, Version_17_0_0 = ::ams::TargetFirmware_17_0_0, Version_17_0_1 = ::ams::TargetFirmware_17_0_1, Version_18_0_0 = ::ams::TargetFirmware_18_0_0, Version_18_1_0 = ::ams::TargetFirmware_18_1_0, Version_19_0_0 = ::ams::TargetFirmware_19_0_0, Version_Current = ::ams::TargetFirmware_Current, Version_Max = ::ams::TargetFirmware_Max, }; }
4,395
C++
.h
87
43.114943
76
0.600093
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
7,592
hos_version_api.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/hos/hos_version_api.hpp
/* * 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/>. */ #pragma once #include <stratosphere/hos/hos_types.hpp> namespace ams::hos { ::ams::hos::Version GetVersion(); }
755
C++
.h
20
35.65
76
0.752394
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
7,593
fssrv_memory_resource_from_exp_heap.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/fssrv/fssrv_memory_resource_from_exp_heap.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/os.hpp> #include <stratosphere/lmem/lmem_exp_heap.hpp> namespace ams::fssrv { /* ACCURATE_TO_VERSION: Unknown */ class MemoryResourceFromExpHeap : public ams::MemoryResource { private: lmem::HeapHandle m_heap_handle; public: constexpr explicit MemoryResourceFromExpHeap(lmem::HeapHandle handle) : m_heap_handle(handle) { /* ... */ } protected: virtual void *AllocateImpl(size_t size, size_t align) override { return lmem::AllocateFromExpHeap(m_heap_handle, size, static_cast<s32>(align)); } virtual void DeallocateImpl(void *p, size_t size, size_t align) override { AMS_UNUSED(size, align); return lmem::FreeToExpHeap(m_heap_handle, p); } virtual bool IsEqualImpl(const MemoryResource &rhs) const override { AMS_UNUSED(rhs); return false; } }; /* ACCURATE_TO_VERSION: Unknown */ class PeakCheckableMemoryResourceFromExpHeap : public ams::MemoryResource { private: lmem::HeapHandle m_heap_handle; os::SdkMutex m_mutex; size_t m_peak_free_size; size_t m_current_free_size; public: constexpr explicit PeakCheckableMemoryResourceFromExpHeap(size_t heap_size) : m_heap_handle(nullptr), m_mutex(), m_peak_free_size(heap_size), m_current_free_size(heap_size) { /* ... */ } void SetHeapHandle(lmem::HeapHandle handle) { m_heap_handle = handle; } size_t GetPeakFreeSize() const { return m_peak_free_size; } size_t GetCurrentFreeSize() const { return m_current_free_size; } void ClearPeak() { m_peak_free_size = m_current_free_size; } std::scoped_lock<os::SdkMutex> GetScopedLock() { return std::scoped_lock(m_mutex); } void OnAllocate(void *p, size_t size); void OnDeallocate(void *p, size_t size); protected: virtual void *AllocateImpl(size_t size, size_t align) override; virtual void DeallocateImpl(void *p, size_t size, size_t align) override; virtual bool IsEqualImpl(const MemoryResource &rhs) const override { AMS_UNUSED(rhs); return false; } }; }
3,078
C++
.h
68
36.147059
198
0.634667
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
7,594
fssrv_file_system_proxy_server_session_resource_manager.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/fssrv/fssrv_file_system_proxy_server_session_resource_manager.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> namespace ams::fssrv { enum class FileSystemProxyServerSessionType : s32 { Any = 0, Realtime = 1, Background = 2, Other = 3, }; constexpr inline auto FileSystemProxyServerActiveSessionCount = 5; }
930
C++
.h
26
32.384615
76
0.717778
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
7,595
fssrv_file_system_proxy_api.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/fssrv/fssrv_file_system_proxy_api.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> namespace ams::fssrv::fscreator { struct FileSystemCreatorInterfaces; } namespace ams::fssrv { class BaseStorageServiceImpl; class BaseFileSystemServiceImpl; class NcaFileSystemServiceImpl; class SaveDataFileSystemServiceImpl; class AccessFailureManagementServiceImpl; class TimeServiceImpl; class StatusReportServiceImpl; class ProgramRegistryServiceImpl; class AccessLogServiceImpl; class DebugConfigurationServiceImpl; /* ACCURATE_TO_VERSION: Unknown */ struct FileSystemProxyConfiguration { fscreator::FileSystemCreatorInterfaces *m_fs_creator_interfaces; BaseStorageServiceImpl *m_base_storage_service_impl; BaseFileSystemServiceImpl *m_base_file_system_service_impl; NcaFileSystemServiceImpl *m_nca_file_system_service_impl; SaveDataFileSystemServiceImpl *m_save_data_file_system_service_impl; AccessFailureManagementServiceImpl *m_access_failure_management_service_impl; TimeServiceImpl *m_time_service_impl; StatusReportServiceImpl *m_status_report_service_impl; ProgramRegistryServiceImpl *m_program_registry_service_impl; AccessLogServiceImpl *m_access_log_service_impl; DebugConfigurationServiceImpl *m_debug_configuration_service_impl; }; struct InternalProgramIdRangeForSpeedEmulation { u64 program_id_value_min; u64 program_id_value_max; }; } namespace ams::fssrv { void InitializeForFileSystemProxy(const FileSystemProxyConfiguration &config); void InitializeFileSystemProxyServer(int threads); }
2,271
C++
.h
54
37.314815
85
0.773243
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
7,596
fssrv_memory_resource_from_standard_allocator.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/fssrv/fssrv_memory_resource_from_standard_allocator.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/os.hpp> namespace ams::mem { class StandardAllocator; } namespace ams::fssrv { /* ACCURATE_TO_VERSION: Unknown */ class MemoryResourceFromStandardAllocator : public ams::MemoryResource { private: mem::StandardAllocator *m_allocator; os::SdkMutex m_mutex; size_t m_peak_free_size; size_t m_current_free_size; size_t m_peak_allocated_size; public: explicit MemoryResourceFromStandardAllocator(mem::StandardAllocator *allocator); constexpr virtual ~MemoryResourceFromStandardAllocator() = default; public: size_t GetPeakFreeSize() const { return m_peak_free_size; } size_t GetCurrentFreeSize() const { return m_current_free_size; } size_t GetPeakAllocatedSize() const { return m_peak_allocated_size; } void ClearPeak(); protected: virtual void *AllocateImpl(size_t size, size_t align) override; virtual void DeallocateImpl(void *p, size_t size, size_t align) override; virtual bool IsEqualImpl(const MemoryResource &rhs) const override { AMS_UNUSED(rhs); return false; } }; }
1,933
C++
.h
47
34.170213
92
0.678191
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
7,597
fssrv_interface_adapters.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/fssrv/fssrv_interface_adapters.hpp
/* * 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/>. */ #pragma once #include <stratosphere/fssrv/interface_adapters/fssrv_storage_interface_adapter.hpp> #include <stratosphere/fssrv/interface_adapters/fssrv_filesystem_interface_adapter.hpp>
821
C++
.h
18
43.833333
87
0.779577
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
7,598
fssrv_file_system_proxy_impl.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/fssrv/fssrv_file_system_proxy_impl.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/fssrv/sf/fssrv_sf_i_file_system_proxy.hpp> #include <stratosphere/fssrv/sf/fssrv_sf_i_program_registry.hpp> #include <stratosphere/fssrv/sf/fssrv_sf_i_file_system_proxy_for_loader.hpp> namespace ams::fssrv { namespace impl { class FileSystemProxyCoreImpl; } class NcaFileSystemService; class SaveDataFileSystemService; /* ACCURATE_TO_VERSION: Unknown */ class FileSystemProxyImpl { NON_COPYABLE(FileSystemProxyImpl); NON_MOVEABLE(FileSystemProxyImpl); private: impl::FileSystemProxyCoreImpl *m_impl; std::shared_ptr<NcaFileSystemService> m_nca_service; std::shared_ptr<SaveDataFileSystemService> m_save_data_service; u64 m_process_id; public: FileSystemProxyImpl(); ~FileSystemProxyImpl(); /* TODO */ public: /* fsp-srv */ Result OpenFileSystem(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out, const fssrv::sf::FspPath &path, u32 type); Result SetCurrentProcess(const ams::sf::ClientProcessId &client_pid); Result OpenDataFileSystemByCurrentProcess(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out); Result OpenFileSystemWithPatch(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out, ncm::ProgramId program_id, u32 type); Result OpenFileSystemWithIdObsolete(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out, const fssrv::sf::FspPath &path, u64 program_id, u32 type); Result OpenDataFileSystemByProgramId(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out, ncm::ProgramId program_id); Result OpenFileSystemWithId(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out, const fssrv::sf::FspPath &path, fs::ContentAttributes attr, u64 program_id, u32 type); Result OpenBisFileSystem(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out, const fssrv::sf::FspPath &path, u32 id); Result OpenBisStorage(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IStorage>> out, u32 id); Result InvalidateBisCache(); Result OpenHostFileSystem(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out, const fssrv::sf::FspPath &path); Result OpenSdCardFileSystem(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out); Result FormatSdCardFileSystem(); Result DeleteSaveDataFileSystem(u64 save_data_id); Result CreateSaveDataFileSystem(const fs::SaveDataAttribute &attribute, const fs::SaveDataCreationInfo &creation_info, const fs::SaveDataMetaInfo &meta_info); Result CreateSaveDataFileSystemBySystemSaveDataId(const fs::SaveDataAttribute &attribute, const fs::SaveDataCreationInfo &creation_info); Result RegisterSaveDataFileSystemAtomicDeletion(const ams::sf::InBuffer &save_data_ids); Result DeleteSaveDataFileSystemBySaveDataSpaceId(u8 indexer_space_id, u64 save_data_id); Result FormatSdCardDryRun(); Result IsExFatSupported(ams::sf::Out<bool> out); Result DeleteSaveDataFileSystemBySaveDataAttribute(u8 space_id, const fs::SaveDataAttribute &attribute); Result OpenGameCardStorage(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IStorage>> out, u32 handle, u32 partition); Result OpenGameCardFileSystem(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out, u32 handle, u32 partition); Result ExtendSaveDataFileSystem(u8 space_id, u64 save_data_id, s64 available_size, s64 journal_size); Result DeleteCacheStorage(u16 index); Result GetCacheStorageSize(ams::sf::Out<s64> out_size, ams::sf::Out<s64> out_journal_size, u16 index); Result CreateSaveDataFileSystemWithHashSalt(const fs::SaveDataAttribute &attribute, const fs::SaveDataCreationInfo &creation_info, const fs::SaveDataMetaInfo &meta_info, const fs::HashSalt &salt); Result OpenHostFileSystemWithOption(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out, const fssrv::sf::FspPath &path, u32 option); Result OpenSaveDataFileSystem(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out, u8 space_id, const fs::SaveDataAttribute &attribute); Result OpenSaveDataFileSystemBySystemSaveDataId(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out, u8 space_id, const fs::SaveDataAttribute &attribute); Result OpenReadOnlySaveDataFileSystem(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out, u8 space_id, const fs::SaveDataAttribute &attribute); Result ReadSaveDataFileSystemExtraDataBySaveDataSpaceId(const ams::sf::OutBuffer &buffer, u8 space_id, u64 save_data_id); Result ReadSaveDataFileSystemExtraData(const ams::sf::OutBuffer &buffer, u64 save_data_id); Result WriteSaveDataFileSystemExtraData(u64 save_data_id, u8 space_id, const ams::sf::InBuffer &buffer); /* ... */ Result OpenImageDirectoryFileSystem(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out, u32 id); /* ... */ Result OpenContentStorageFileSystem(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out, u32 id); /* ... */ Result OpenDataStorageByCurrentProcess(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IStorage>> out); Result OpenDataStorageByProgramId(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IStorage>> out, ncm::ProgramId program_id); Result OpenDataStorageByDataId(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IStorage>> out, ncm::DataId data_id, u8 storage_id); Result OpenPatchDataStorageByCurrentProcess(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IStorage>> out); Result OpenDataFileSystemWithProgramIndex(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out, u8 index); Result OpenDataStorageWithProgramIndex(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IStorage>> out, u8 index); Result OpenDataStorageByPathObsolete(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IStorage>> out, const fssrv::sf::FspPath &path, u32 type); Result OpenDataStorageByPath(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IStorage>> out, const fssrv::sf::FspPath &path, fs::ContentAttributes attr, u32 type); Result OpenDeviceOperator(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IDeviceOperator>> out); Result OpenSdCardDetectionEventNotifier(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IEventNotifier>> out); Result OpenGameCardDetectionEventNotifier(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IEventNotifier>> out); Result OpenSystemDataUpdateEventNotifier(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IEventNotifier>> out); Result NotifySystemDataUpdateEvent(); /* ... */ Result SetCurrentPosixTime(s64 posix_time); /* ... */ Result GetRightsId(ams::sf::Out<fs::RightsId> out, ncm::ProgramId program_id, ncm::StorageId storage_id); Result RegisterExternalKey(const fs::RightsId &rights_id, const spl::AccessKey &access_key); Result UnregisterAllExternalKey(); Result GetProgramId(ams::sf::Out<ncm::ProgramId> out, const fssrv::sf::FspPath &path, fs::ContentAttributes attr); Result GetRightsIdByPath(ams::sf::Out<fs::RightsId> out, const fssrv::sf::FspPath &path); Result GetRightsIdAndKeyGenerationByPathObsolete(ams::sf::Out<fs::RightsId> out, ams::sf::Out<u8> out_key_generation, const fssrv::sf::FspPath &path); Result GetRightsIdAndKeyGenerationByPath(ams::sf::Out<fs::RightsId> out, ams::sf::Out<u8> out_key_generation, const fssrv::sf::FspPath &path, fs::ContentAttributes attr); Result SetCurrentPosixTimeWithTimeDifference(s64 posix_time, s32 time_difference); Result GetFreeSpaceSizeForSaveData(ams::sf::Out<s64> out, u8 space_id); Result VerifySaveDataFileSystemBySaveDataSpaceId(); Result CorruptSaveDataFileSystemBySaveDataSpaceId(); Result QuerySaveDataInternalStorageTotalSize(); Result GetSaveDataCommitId(); Result UnregisterExternalKey(const fs::RightsId &rights_id); Result SetSdCardEncryptionSeed(const fs::EncryptionSeed &seed); Result SetSdCardAccessibility(bool accessible); Result IsSdCardAccessible(ams::sf::Out<bool> out); Result IsSignedSystemPartitionOnSdCardValid(ams::sf::Out<bool> out); Result OpenAccessFailureDetectionEventNotifier(); /* ... */ Result GetAndClearErrorInfo(ams::sf::Out<fs::FileSystemProxyErrorInfo> out); Result RegisterProgramIndexMapInfo(const ams::sf::InBuffer &buffer, s32 count); Result SetBisRootForHost(u32 id, const fssrv::sf::FspPath &path); Result SetSaveDataSize(s64 size, s64 journal_size); Result SetSaveDataRootPath(const fssrv::sf::FspPath &path); Result DisableAutoSaveDataCreation(); Result SetGlobalAccessLogMode(u32 mode); Result GetGlobalAccessLogMode(ams::sf::Out<u32> out); Result OutputAccessLogToSdCard(const ams::sf::InBuffer &buf); Result RegisterUpdatePartition(); Result OpenRegisteredUpdatePartition(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out); Result GetAndClearMemoryReportInfo(ams::sf::Out<fs::MemoryReportInfo> out); /* ... */ Result GetProgramIndexForAccessLog(ams::sf::Out<u32> out_idx, ams::sf::Out<u32> out_count); Result GetFsStackUsage(ams::sf::Out<u32> out, u32 type); Result UnsetSaveDataRootPath(); Result OutputMultiProgramTagAccessLog(); Result FlushAccessLogOnSdCard(); Result OutputApplicationInfoAccessLog(); Result RegisterDebugConfiguration(u32 key, s64 value); Result UnregisterDebugConfiguration(u32 key); Result OverrideSaveDataTransferTokenSignVerificationKey(const ams::sf::InBuffer &buf); Result CorruptSaveDataFileSystemByOffset(u8 space_id, u64 save_data_id, s64 offset); /* ... */ public: /* fsp-ldr */ Result OpenCodeFileSystemDeprecated(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out_fs, const fssrv::sf::Path &path, ncm::ProgramId program_id); Result 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); Result 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); Result 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); Result IsArchivedProgram(ams::sf::Out<bool> out, u64 process_id); }; static_assert(sf::IsIFileSystemProxy<FileSystemProxyImpl>); static_assert(sf::IsIFileSystemProxyForLoader<FileSystemProxyImpl>); /* ACCURATE_TO_VERSION: Unknown */ class InvalidFileSystemProxyImplForLoader { public: Result OpenCodeFileSystemDeprecated(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out_fs, const fssrv::sf::Path &path, ncm::ProgramId program_id) { AMS_UNUSED(out_fs, path, program_id); R_THROW(fs::ResultPortAcceptableCountLimited()); } Result 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_UNUSED(out_fs, out_verif, path, program_id); R_THROW(fs::ResultPortAcceptableCountLimited()); } Result 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_UNUSED(out_fs, out_verif, path, attr, program_id); R_THROW(fs::ResultPortAcceptableCountLimited()); } Result 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_UNUSED(out_fs, out_verif, path, attr, program_id); R_THROW(fs::ResultPortAcceptableCountLimited()); } Result IsArchivedProgram(ams::sf::Out<bool> out, u64 process_id) { AMS_UNUSED(out, process_id); R_THROW(fs::ResultPortAcceptableCountLimited()); } Result SetCurrentProcess(const ams::sf::ClientProcessId &client_pid) { AMS_UNUSED(client_pid); R_THROW(fs::ResultPortAcceptableCountLimited()); } }; static_assert(sf::IsIFileSystemProxyForLoader<FileSystemProxyImpl>); }
14,317
C++
.h
180
68.338889
253
0.692133
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
7,599
fssrv_i_file_system_creator.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/fssrv/fssrv_i_file_system_creator.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/fs/impl/fs_newable.hpp> namespace ams::fs { class IStorage; enum class BisPartitionId; class Path; namespace fsa { class IFileSystem; } } namespace ams::fssystem { class NcaReader; class NcaFsHeaderReader; class IAsynchronousAccessSplitter; namespace save { /* TODO */ } } namespace ams::fssrv::fscreator { /* ACCURATE_TO_VERSION: Unknown */ class IRomFileSystemCreator { public: virtual ~IRomFileSystemCreator() { /* ... */ } virtual Result Create(std::shared_ptr<fs::fsa::IFileSystem> *out, std::shared_ptr<fs::IStorage> storage) = 0; }; /* ACCURATE_TO_VERSION: Unknown */ class IPartitionFileSystemCreator { public: virtual ~IPartitionFileSystemCreator() { /* ... */ } virtual Result Create(std::shared_ptr<fs::fsa::IFileSystem> *out, std::shared_ptr<fs::IStorage> storage) = 0; }; /* ACCURATE_TO_VERSION: Unknown */ class IStorageOnNcaCreator { public: virtual ~IStorageOnNcaCreator() { /* ... */ } virtual Result 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) = 0; virtual Result 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) = 0; virtual Result CreateNcaReader(std::shared_ptr<fssystem::NcaReader> *out, std::shared_ptr<fs::IStorage> storage) = 0; }; /* ACCURATE_TO_VERSION: Unknown */ class ILocalFileSystemCreator { public: virtual Result Create(std::shared_ptr<fs::fsa::IFileSystem> *out, const fs::Path &path, bool case_sensitive, bool ensure_root, Result on_path_not_found) = 0; public: Result Create(std::shared_ptr<fs::fsa::IFileSystem> *out, const fs::Path &path, bool case_sensitive) { R_RETURN(this->Create(out, path, case_sensitive, false, ResultSuccess())); } }; /* ACCURATE_TO_VERSION: Unknown */ class ISubDirectoryFileSystemCreator { public: virtual Result Create(std::shared_ptr<fs::fsa::IFileSystem> *out, std::shared_ptr<fs::fsa::IFileSystem> base_fs, const fs::Path &path) = 0; }; /* ACCURATE_TO_VERSION: Unknown */ struct FileSystemCreatorInterfaces { ILocalFileSystemCreator *local_fs_creator; ISubDirectoryFileSystemCreator *subdir_fs_creator; /* TODO: These don't exist any more, and should be refactored out. */ IRomFileSystemCreator *rom_fs_creator; IPartitionFileSystemCreator *partition_fs_creator; IStorageOnNcaCreator *storage_on_nca_creator; /* TODO: More creators. */ }; static_assert(util::is_pod<FileSystemCreatorInterfaces>::value); }
3,811
C++
.h
81
40.716049
327
0.688511
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
7,600
fssrv_program_registry_impl.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/fssrv/fssrv_program_registry_impl.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/fssrv/sf/fssrv_sf_i_program_registry.hpp> namespace ams::fssrv { class ProgramRegistryServiceImpl; namespace impl { class ProgramInfo; } /* ACCURATE_TO_VERSION: Unknown */ class ProgramRegistryImpl { NON_COPYABLE(ProgramRegistryImpl); NON_MOVEABLE(ProgramRegistryImpl); private: u64 m_process_id; public: ProgramRegistryImpl(); ~ProgramRegistryImpl(); public: static void Initialize(ProgramRegistryServiceImpl *service); public: Result 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); Result UnregisterProgram(u64 process_id); Result SetCurrentProcess(const ams::sf::ClientProcessId &client_pid); Result SetEnabledProgramVerification(bool en); }; static_assert(sf::IsIProgramRegistry<ProgramRegistryImpl>); /* ACCURATE_TO_VERSION: Unknown */ class InvalidProgramRegistryImpl { public: Result 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) { AMS_UNUSED(process_id, program_id, storage_id, data, data_size, desc, desc_size); R_THROW(fs::ResultPortAcceptableCountLimited()); } Result UnregisterProgram(u64 process_id) { AMS_UNUSED(process_id); R_THROW(fs::ResultPortAcceptableCountLimited()); } Result SetCurrentProcess(const ams::sf::ClientProcessId &client_pid) { AMS_UNUSED(client_pid); R_THROW(fs::ResultPortAcceptableCountLimited()); } Result SetEnabledProgramVerification(bool en) { AMS_UNUSED(en); R_THROW(fs::ResultPortAcceptableCountLimited()); } }; static_assert(sf::IsIProgramRegistry<InvalidProgramRegistryImpl>); }
2,773
C++
.h
63
35.825397
175
0.670248
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
7,601
fssrv_program_registry_service.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/fssrv/fssrv_program_registry_service.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/fssystem/fssystem_pimpl.hpp> namespace ams::fssrv { namespace impl { class ProgramInfo; class ProgramRegistryManager; class ProgramIndexMapInfoManager; } /* ACCURATE_TO_VERSION: Unknown */ class ProgramRegistryServiceImpl { public: struct Configuration { /* ... */ }; private: Configuration m_config; fssystem::Pimpl<impl::ProgramRegistryManager, 0x40> m_registry_manager; fssystem::Pimpl<impl::ProgramIndexMapInfoManager, 0x50> m_index_map_info_manager; public: ProgramRegistryServiceImpl(const Configuration &cfg) : m_config(cfg) { /* ... */ } Result RegisterProgramInfo(u64 process_id, u64 program_id, u8 storage_id, const void *data, s64 data_size, const void *desc, s64 desc_size); Result UnregisterProgramInfo(u64 process_id); Result ResetProgramIndexMapInfo(const fs::ProgramIndexMapInfo *infos, int count); Result GetProgramInfo(std::shared_ptr<impl::ProgramInfo> *out, u64 process_id); Result GetProgramInfoByProgramId(std::shared_ptr<impl::ProgramInfo> *out, u64 program_id); size_t GetProgramIndexMapInfoCount(); util::optional<fs::ProgramIndexMapInfo> GetProgramIndexMapInfo(const ncm::ProgramId &program_id); ncm::ProgramId GetProgramIdByIndex(const ncm::ProgramId &program_id, u8 index); }; }
2,164
C++
.h
46
40.021739
152
0.696251
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
7,602
fssrv_nca_crypto_configuration.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/fssrv/fssrv_nca_crypto_configuration.hpp
/* * 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/>. */ #pragma once #include <stratosphere/fssystem/fssystem_nca_file_system_driver.hpp> namespace ams::fssrv { const ::ams::fssystem::NcaCryptoConfiguration *GetDefaultNcaCryptoConfiguration(bool prod); }
841
C++
.h
20
40
95
0.771394
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
7,603
fssrv_nca_file_system_service_impl.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/fssrv/fssrv_nca_file_system_service_impl.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/fssystem/fssystem_pimpl.hpp> #include <stratosphere/fssrv/fssrv_file_system_proxy_api.hpp> namespace ams::fssrv { class BaseFileSystemServiceImpl; class ProgramRegistryServiceImpl; class AccessFailureManagementServiceImpl; namespace fscreator { class LocalFileSystemCreator; class TargetManagerFileSystemCreator; class PartitionFileSystemCreator; class IRomFileSystemCreator; class StorageOnNcaCreator; class SubDirectoryFileSystemCreator; class EncryptedFileSystemCreator; class INspRootFileSystemCreator; } namespace impl { class UpdatePartitionPath; class ExternalKeyManager; class LocationResolverSet; class SystemDataUpdateEventManager; } /* ACCURATE_TO_VERSION: Unknown */ class NcaFileSystemServiceImpl { public: struct Configuration { BaseFileSystemServiceImpl *base_fs_service; fscreator::LocalFileSystemCreator *local_fs_creator; fscreator::TargetManagerFileSystemCreator *tm_fs_creator; fscreator::PartitionFileSystemCreator *partition_fs_creator; fscreator::IRomFileSystemCreator *rom_fs_creator; fscreator::StorageOnNcaCreator *storage_on_nca_creator; fscreator::SubDirectoryFileSystemCreator *subdir_fs_creator; fscreator::EncryptedFileSystemCreator *encrypted_fs_creator; fscreator::INspRootFileSystemCreator *nsp_root_fs_creator; ProgramRegistryServiceImpl *program_registry_service; AccessFailureManagementServiceImpl *access_failure_management_service; InternalProgramIdRangeForSpeedEmulation program_id_range_for_speed_emulation; }; private: struct MountInfo { bool is_game_card; u32 gc_handle; bool is_host_fs; bool can_mount_nca; }; private: Configuration m_config; fssystem::Pimpl<impl::UpdatePartitionPath, 0x350> m_update_partition_path; fssystem::Pimpl<impl::ExternalKeyManager, 0x50> m_external_key_manager; fssystem::Pimpl<impl::UpdatePartitionPath, 0xA8> m_location_resolver_set; fssystem::Pimpl<impl::SystemDataUpdateEventManager, 0x48> m_system_data_update_event_manager; fs::EncryptionSeed m_encryption_seed; int m_romfs_remount_for_data_corruption_count; int m_romfs_unrecoverable_data_corruption_by_remount_count; int m_romfs_recovered_by_invalidate_cache_count; os::SdkMutex m_romfs_count_mutex; public: NcaFileSystemServiceImpl(const Configuration &cfg) : m_config(cfg) { /* ... */ } }; }
3,533
C++
.h
78
36.230769
105
0.689315
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
7,604
fssrv_impl_program_index_map_info_manager.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/fssrv/impl/fssrv_impl_program_index_map_info_manager.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/ncm/ncm_ids.hpp> #include <stratosphere/fs/impl/fs_newable.hpp> #include <stratosphere/fs/fs_program_index_map_info.hpp> #include <stratosphere/fssystem/fssystem_pimpl.hpp> namespace ams::fssrv::impl { /* ACCURATE_TO_VERSION: 13.4.0.0 */ struct ProgramIndexMapInfoEntry : public ::ams::util::IntrusiveListBaseNode<ProgramIndexMapInfoEntry>, public ::ams::fs::impl::Newable { ncm::ProgramId program_id; ncm::ProgramId base_program_id; u8 program_index; }; /* ACCURATE_TO_VERSION: 13.4.0.0 */ class ProgramIndexMapInfoManager { NON_COPYABLE(ProgramIndexMapInfoManager); NON_MOVEABLE(ProgramIndexMapInfoManager); private: using ProgramIndexMapInfoList = util::IntrusiveListBaseTraits<ProgramIndexMapInfoEntry>::ListType; private: ProgramIndexMapInfoList m_list; mutable os::SdkMutex m_mutex; public: constexpr ProgramIndexMapInfoManager() : m_list(), m_mutex() { /* ... */ } void Clear() { /* Acquire exclusive access to the map. */ std::scoped_lock lk(m_mutex); /* Actually clear. */ this->ClearImpl(); } size_t GetProgramCount() const { /* Acquire exclusive access to the map. */ std::scoped_lock lk(m_mutex); /* Get the size. */ return m_list.size(); } util::optional<fs::ProgramIndexMapInfo> Get(const ncm::ProgramId &program_id) const { /* Acquire exclusive access to the map. */ std::scoped_lock lk(m_mutex); /* Get the entry from the map. */ return this->GetImpl([&] (const ProgramIndexMapInfoEntry &entry) { return entry.program_id == program_id; }); } ncm::ProgramId GetProgramId(const ncm::ProgramId &program_id, u8 program_index) const { /* Acquire exclusive access to the map. */ std::scoped_lock lk(m_mutex); /* Get the program info for the desired program id. */ const auto base_info = this->GetImpl([&] (const ProgramIndexMapInfoEntry &entry) { return entry.program_id == program_id; }); /* Check that an entry exists for the program id. */ if (!base_info.has_value()) { return ncm::InvalidProgramId; } /* Get a program info which matches the same base program with the desired index. */ const auto target_info = this->GetImpl([&] (const ProgramIndexMapInfoEntry &entry) { return entry.base_program_id == base_info->base_program_id && entry.program_index == program_index; }); /* Return the desired program id. */ if (target_info.has_value()) { return target_info->program_id; } else { return ncm::InvalidProgramId; } } Result Reset(const fs::ProgramIndexMapInfo *infos, int count) { /* Acquire exclusive access to the map. */ std::scoped_lock lk(m_mutex); /* Clear the map, and ensure we remain clear if we fail after this point. */ this->ClearImpl(); ON_RESULT_FAILURE { this->ClearImpl(); }; /* Add each info to the list. */ for (int i = 0; i < count; ++i) { /* Allocate new entry. */ auto *entry = new ProgramIndexMapInfoEntry; R_UNLESS(entry != nullptr, fs::ResultAllocationMemoryFailedNew()); /* Copy over the info. */ entry->program_id = infos[i].program_id; entry->base_program_id = infos[i].base_program_id; entry->program_index = infos[i].program_index; /* Add to the list. */ m_list.push_back(*entry); } /* We successfully imported the map. */ R_SUCCEED(); } private: void ClearImpl() { /* Delete all entries. */ while (!m_list.empty()) { /* Get the first entry. */ ProgramIndexMapInfoEntry *front = std::addressof(*m_list.begin()); /* Erase it from the list. */ m_list.erase(m_list.iterator_to(*front)); /* Delete the entry. */ delete front; } } template<typename F> util::optional<fs::ProgramIndexMapInfo> GetImpl(F f) const { /* Try to find an entry matching the predicate. */ util::optional<fs::ProgramIndexMapInfo> match = util::nullopt; for (const auto &entry : m_list) { /* If the predicate matches, we want to return the relevant info. */ if (f(entry)) { match.emplace(); match->program_id = entry.program_id; match->base_program_id = entry.base_program_id; match->program_index = entry.program_index; break; } } return match; } }; } AMS_FSSYSTEM_ENABLE_PIMPL(::ams::fssrv::impl::ProgramIndexMapInfoManager)
6,337
C++
.h
133
33.834586
140
0.543732
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
7,605
fssrv_file_system_proxy_service_object.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/fssrv/impl/fssrv_file_system_proxy_service_object.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/fssrv/sf/fssrv_sf_i_file_system_proxy.hpp> #include <stratosphere/fssrv/sf/fssrv_sf_i_program_registry.hpp> #include <stratosphere/fssrv/sf/fssrv_sf_i_file_system_proxy_for_loader.hpp> #include <stratosphere/fssrv/fssrv_file_system_proxy_impl.hpp> namespace ams::fssrv::impl { /* ACCURATE_TO_VERSION: 13.4.0.0 */ ams::sf::EmplacedRef<fssrv::sf::IFileSystemProxy, fssrv::FileSystemProxyImpl> GetFileSystemProxyServiceObject(); ams::sf::SharedPointer<fssrv::sf::IProgramRegistry> GetProgramRegistryServiceObject(); ams::sf::SharedPointer<fssrv::sf::IProgramRegistry> GetInvalidProgramRegistryServiceObject(); ams::sf::SharedPointer<fssrv::sf::IFileSystemProxyForLoader> GetFileSystemProxyForLoaderServiceObject(); ams::sf::SharedPointer<fssrv::sf::IFileSystemProxyForLoader> GetInvalidFileSystemProxyForLoaderServiceObject(); }
1,549
C++
.h
29
50.931034
116
0.783498
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
7,606
fssrv_access_control_bits.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/fssrv/impl/fssrv_access_control_bits.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/ncm/ncm_ids.hpp> #include <stratosphere/fs/impl/fs_newable.hpp> #include <stratosphere/fssrv/impl/fssrv_access_control_bits.hpp> namespace ams::fssrv::impl { /* ACCURATE_TO_VERSION: 13.4.0.0 */ #define AMS_FSSRV_FOR_EACH_ACCESS_CONTROL_CAPABILITY(HANDLER, _NS_) \ HANDLER(CanAbandonAccessFailure, _NS_::AccessFailureResolution) \ HANDLER(CanChallengeCardExistence, _NS_::GameCard) \ HANDLER(CanControlMmcPatrol, _NS_::None) \ HANDLER(CanCorruptSaveData, _NS_::Debug, _NS_::CorruptSaveData) \ HANDLER(CanCorruptSystemSaveData, _NS_::CorruptSaveData, _NS_::SaveDataManagement, _NS_::SaveDataBackUp) \ HANDLER(CanCreateOthersSystemSaveData, _NS_::SaveDataBackUp) \ HANDLER(CanCreateOwnSaveData, _NS_::CreateOwnSaveData) \ HANDLER(CanCreateSaveData, _NS_::CreateSaveData, _NS_::SaveDataBackUp) \ HANDLER(CanCreateSaveDataWithHashSalt, _NS_::None) \ HANDLER(CanCreateSystemSaveData, _NS_::SaveDataBackUp, _NS_::SystemSaveData) \ HANDLER(CanDebugSaveData, _NS_::Debug, _NS_::SaveDataForDebug) \ HANDLER(CanDeleteOwnSaveData, _NS_::CreateOwnSaveData) \ HANDLER(CanDeleteSaveData, _NS_::SaveDataManagement, _NS_::SaveDataBackUp) \ HANDLER(CanDeleteSystemSaveData, _NS_::SystemSaveDataManagement, _NS_::SaveDataBackUp, _NS_::SystemSaveData) \ HANDLER(CanEraseMmc, _NS_::BisAllRaw) \ HANDLER(CanExtendOthersSystemSaveData, _NS_::SaveDataBackUp) \ HANDLER(CanExtendOwnSaveData, _NS_::CreateOwnSaveData) \ HANDLER(CanExtendSaveData, _NS_::CreateSaveData, _NS_::SaveDataBackUp) \ HANDLER(CanExtendSystemSaveData, _NS_::SaveDataBackUp, _NS_::SystemSaveData) \ HANDLER(CanFillBis, _NS_::Debug, _NS_::FillBis) \ HANDLER(CanFinalizeGameCardDriver, _NS_::GameCardPrivate) \ HANDLER(CanFindOwnSaveDataWithFilter, _NS_::CreateOwnSaveData) \ HANDLER(CanFormatSdCard, _NS_::FormatSdCard) \ HANDLER(CanGetAccessFailureDetectionEvent, _NS_::AccessFailureResolution) \ HANDLER(CanGetGameCardAsicInfo, _NS_::GameCardPrivate) \ HANDLER(CanGetGameCardDeviceCertificate, _NS_::GameCard) \ HANDLER(CanGetGameCardIdSet, _NS_::GameCard) \ HANDLER(CanGetRightsId, _NS_::GetRightsId) \ HANDLER(CanGetSaveDataCommitId, _NS_::SaveDataTransferVersion2, _NS_::SaveDataBackUp) \ HANDLER(CanInvalidateBisCache, _NS_::BisAllRaw) \ HANDLER(CanIsAccessFailureDetected, _NS_::AccessFailureResolution) \ HANDLER(CanListAccessibleSaveDataOwnerId, _NS_::SaveDataTransferVersion2, _NS_::SaveDataTransfer, _NS_::CreateSaveData) \ HANDLER(CanMountAllBaseFileSystemRead, _NS_::None) \ HANDLER(CanMountAllBaseFileSystemWrite, _NS_::None) \ HANDLER(CanMountApplicationPackageRead, _NS_::ContentManager, _NS_::ApplicationInfo) \ HANDLER(CanMountBisCalibrationFileRead, _NS_::BisAllRaw, _NS_::Calibration) \ HANDLER(CanMountBisCalibrationFileWrite, _NS_::BisAllRaw, _NS_::Calibration) \ HANDLER(CanMountBisSafeModeRead, _NS_::BisAllRaw) \ HANDLER(CanMountBisSafeModeWrite, _NS_::BisAllRaw) \ HANDLER(CanMountBisSystemProperEncryptionRead, _NS_::BisAllRaw) \ HANDLER(CanMountBisSystemProperEncryptionWrite, _NS_::BisAllRaw) \ HANDLER(CanMountBisSystemProperPartitionRead, _NS_::BisFileSystem, _NS_::BisAllRaw) \ HANDLER(CanMountBisSystemProperPartitionWrite, _NS_::BisFileSystem, _NS_::BisAllRaw) \ HANDLER(CanMountBisSystemRead, _NS_::BisFileSystem, _NS_::BisAllRaw) \ HANDLER(CanMountBisSystemWrite, _NS_::BisFileSystem, _NS_::BisAllRaw) \ HANDLER(CanMountBisUserRead, _NS_::BisFileSystem, _NS_::BisAllRaw) \ HANDLER(CanMountBisUserWrite, _NS_::BisFileSystem, _NS_::BisAllRaw) \ HANDLER(CanMountCloudBackupWorkStorageRead, _NS_::SaveDataTransferVersion2) \ HANDLER(CanMountCloudBackupWorkStorageWrite, _NS_::SaveDataTransferVersion2) \ HANDLER(CanMountContentControlRead, _NS_::ContentManager, _NS_::ApplicationInfo) \ HANDLER(CanMountContentDataRead, _NS_::ContentManager, _NS_::ApplicationInfo) \ HANDLER(CanMountContentManualRead, _NS_::ContentManager, _NS_::ApplicationInfo) \ HANDLER(CanMountContentMetaRead, _NS_::ContentManager, _NS_::ApplicationInfo) \ HANDLER(CanMountContentStorageRead, _NS_::ContentManager) \ HANDLER(CanMountContentStorageWrite, _NS_::ContentManager) \ HANDLER(CanMountCustomStorage0Read, _NS_::None) \ HANDLER(CanMountCustomStorage0Write, _NS_::None) \ HANDLER(CanMountDeviceSaveDataRead, _NS_::DeviceSaveData, _NS_::SaveDataBackUp) \ HANDLER(CanMountDeviceSaveDataWrite, _NS_::DeviceSaveData, _NS_::SaveDataBackUp) \ HANDLER(CanMountGameCardRead, _NS_::GameCard) \ HANDLER(CanMountHostRead, _NS_::Debug, _NS_::Host) \ HANDLER(CanMountHostWrite, _NS_::Debug, _NS_::Host) \ HANDLER(CanMountImageAndVideoStorageRead, _NS_::ImageManager) \ HANDLER(CanMountImageAndVideoStorageWrite, _NS_::ImageManager) \ HANDLER(CanMountLogoRead, _NS_::ContentManager, _NS_::ApplicationInfo) \ HANDLER(CanMountOthersSaveDataRead, _NS_::SaveDataBackUp) \ HANDLER(CanMountOthersSaveDataWrite, _NS_::SaveDataBackUp) \ HANDLER(CanMountOthersSystemSaveDataRead, _NS_::SaveDataBackUp) \ HANDLER(CanMountOthersSystemSaveDataWrite, _NS_::SaveDataBackUp) \ HANDLER(CanMountRegisteredUpdatePartitionRead, _NS_::SystemUpdate) \ HANDLER(CanMountSaveDataStorageRead, _NS_::None) \ HANDLER(CanMountSaveDataStorageWrite, _NS_::None) \ HANDLER(CanMountSdCardRead, _NS_::Debug, _NS_::SdCard) \ HANDLER(CanMountSdCardWrite, _NS_::Debug, _NS_::SdCard) \ HANDLER(CanMountSystemDataPrivateRead, _NS_::SystemData, _NS_::SystemSaveData) \ HANDLER(CanMountSystemSaveDataRead, _NS_::SaveDataBackUp, _NS_::SystemSaveData) \ HANDLER(CanMountSystemSaveDataWrite, _NS_::SaveDataBackUp, _NS_::SystemSaveData) \ HANDLER(CanMountTemporaryDirectoryRead, _NS_::Debug) \ HANDLER(CanMountTemporaryDirectoryWrite, _NS_::Debug) \ HANDLER(CanNotifySystemDataUpdateEvent, _NS_::SystemUpdate) \ HANDLER(CanOpenAccessFailureDetectionEventNotifier, _NS_::AccessFailureResolution) \ HANDLER(CanOpenBisPartitionBootConfigAndPackage2Part1Read, _NS_::SystemUpdate, _NS_::BisAllRaw) \ HANDLER(CanOpenBisPartitionBootConfigAndPackage2Part1Write, _NS_::SystemUpdate, _NS_::BisAllRaw) \ HANDLER(CanOpenBisPartitionBootConfigAndPackage2Part2Read, _NS_::SystemUpdate, _NS_::BisAllRaw) \ HANDLER(CanOpenBisPartitionBootConfigAndPackage2Part2Write, _NS_::SystemUpdate, _NS_::BisAllRaw) \ HANDLER(CanOpenBisPartitionBootConfigAndPackage2Part3Read, _NS_::SystemUpdate, _NS_::BisAllRaw) \ HANDLER(CanOpenBisPartitionBootConfigAndPackage2Part3Write, _NS_::SystemUpdate, _NS_::BisAllRaw) \ HANDLER(CanOpenBisPartitionBootConfigAndPackage2Part4Read, _NS_::SystemUpdate, _NS_::BisAllRaw) \ HANDLER(CanOpenBisPartitionBootConfigAndPackage2Part4Write, _NS_::SystemUpdate, _NS_::BisAllRaw) \ HANDLER(CanOpenBisPartitionBootConfigAndPackage2Part5Read, _NS_::SystemUpdate, _NS_::BisAllRaw) \ HANDLER(CanOpenBisPartitionBootConfigAndPackage2Part5Write, _NS_::SystemUpdate, _NS_::BisAllRaw) \ HANDLER(CanOpenBisPartitionBootConfigAndPackage2Part6Read, _NS_::SystemUpdate, _NS_::BisAllRaw) \ HANDLER(CanOpenBisPartitionBootConfigAndPackage2Part6Write, _NS_::SystemUpdate, _NS_::BisAllRaw) \ HANDLER(CanOpenBisPartitionBootPartition1RootRead, _NS_::SystemUpdate, _NS_::BisAllRaw, _NS_::BootModeControl) \ HANDLER(CanOpenBisPartitionBootPartition1RootWrite, _NS_::SystemUpdate, _NS_::BisAllRaw, _NS_::BootModeControl) \ HANDLER(CanOpenBisPartitionBootPartition2RootRead, _NS_::SystemUpdate, _NS_::BisAllRaw) \ HANDLER(CanOpenBisPartitionBootPartition2RootWrite, _NS_::SystemUpdate, _NS_::BisAllRaw) \ HANDLER(CanOpenBisPartitionCalibrationBinaryRead, _NS_::BisAllRaw, _NS_::Calibration) \ HANDLER(CanOpenBisPartitionCalibrationBinaryWrite, _NS_::BisAllRaw, _NS_::Calibration) \ HANDLER(CanOpenBisPartitionCalibrationFileRead, _NS_::BisAllRaw, _NS_::Calibration) \ HANDLER(CanOpenBisPartitionCalibrationFileWrite, _NS_::BisAllRaw, _NS_::Calibration) \ HANDLER(CanOpenBisPartitionSafeModeRead, _NS_::BisAllRaw) \ HANDLER(CanOpenBisPartitionSafeModeWrite, _NS_::BisAllRaw) \ HANDLER(CanOpenBisPartitionSystemProperEncryptionRead, _NS_::BisAllRaw) \ HANDLER(CanOpenBisPartitionSystemProperEncryptionWrite, _NS_::BisAllRaw) \ HANDLER(CanOpenBisPartitionSystemProperPartitionRead, _NS_::BisAllRaw) \ HANDLER(CanOpenBisPartitionSystemProperPartitionWrite, _NS_::BisAllRaw) \ HANDLER(CanOpenBisPartitionSystemRead, _NS_::BisAllRaw) \ HANDLER(CanOpenBisPartitionSystemWrite, _NS_::BisAllRaw) \ HANDLER(CanOpenBisPartitionUserDataRootRead, _NS_::BisAllRaw) \ HANDLER(CanOpenBisPartitionUserDataRootWrite, _NS_::BisAllRaw) \ HANDLER(CanOpenBisPartitionUserRead, _NS_::BisAllRaw) \ HANDLER(CanOpenBisPartitionUserWrite, _NS_::BisAllRaw) \ HANDLER(CanOpenBisWiper, _NS_::ContentManager) \ HANDLER(CanOpenDataStorageByPath, _NS_::None) \ HANDLER(CanOpenGameCardDetectionEventNotifier, _NS_::DeviceDetection, _NS_::GameCardRaw, _NS_::GameCard) \ HANDLER(CanOpenGameCardStorageRead, _NS_::GameCardRaw) \ HANDLER(CanOpenGameCardStorageWrite, _NS_::GameCardRaw) \ HANDLER(CanOpenOwnSaveDataTransferProhibiter, _NS_::CreateOwnSaveData) \ HANDLER(CanOpenSaveDataInfoReader, _NS_::SaveDataManagement, _NS_::SaveDataBackUp) \ HANDLER(CanOpenSaveDataInfoReaderForInternal, _NS_::SaveDataManagement) \ HANDLER(CanOpenSaveDataInfoReaderForSystem, _NS_::SystemSaveDataManagement, _NS_::SaveDataBackUp) \ HANDLER(CanOpenSaveDataInternalStorageRead, _NS_::None) \ HANDLER(CanOpenSaveDataInternalStorageWrite, _NS_::None) \ HANDLER(CanOpenSaveDataMetaFile, _NS_::SaveDataMeta) \ HANDLER(CanOpenSaveDataMover, _NS_::MoveCacheStorage) \ HANDLER(CanOpenSaveDataTransferManager, _NS_::SaveDataTransfer) \ HANDLER(CanOpenSaveDataTransferManagerForRepair, _NS_::SaveDataBackUp) \ HANDLER(CanOpenSaveDataTransferManagerForSaveDataRepair, _NS_::SaveDataTransferVersion2) \ HANDLER(CanOpenSaveDataTransferManagerForSaveDataRepairTool, _NS_::None) \ HANDLER(CanOpenSaveDataTransferManagerVersion2, _NS_::SaveDataTransferVersion2) \ HANDLER(CanOpenSaveDataTransferProhibiter, _NS_::SaveDataTransferVersion2, _NS_::CreateSaveData) \ HANDLER(CanOpenSdCardDetectionEventNotifier, _NS_::DeviceDetection, _NS_::SdCard) \ HANDLER(CanOpenSdCardStorageRead, _NS_::Debug, _NS_::SdCard) \ HANDLER(CanOpenSdCardStorageWrite, _NS_::Debug, _NS_::SdCard) \ HANDLER(CanOpenSystemDataUpdateEventNotifier, _NS_::SystemData, _NS_::SystemSaveData) \ HANDLER(CanOverrideSaveDataTransferTokenSignVerificationKey, _NS_::None) \ HANDLER(CanQuerySaveDataInternalStorageTotalSize, _NS_::SaveDataTransfer) \ HANDLER(CanReadOwnSaveDataFileSystemExtraData, _NS_::CreateOwnSaveData) \ HANDLER(CanReadSaveDataFileSystemExtraData, _NS_::SystemSaveDataManagement, _NS_::SaveDataManagement, _NS_::SaveDataBackUp) \ HANDLER(CanRegisterExternalKey, _NS_::RegisterExternalKey) \ HANDLER(CanRegisterProgramIndexMapInfo, _NS_::RegisterProgramIndexMapInfo) \ HANDLER(CanRegisterUpdatePartition, _NS_::RegisterUpdatePartition) \ HANDLER(CanResolveAccessFailure, _NS_::AccessFailureResolution) \ HANDLER(CanSetCurrentPosixTime, _NS_::SetTime) \ HANDLER(CanSetDebugConfiguration, _NS_::None) \ HANDLER(CanSetEncryptionSeed, _NS_::ContentManager) \ HANDLER(CanSetGlobalAccessLogMode, _NS_::SettingsControl) \ HANDLER(CanSetSdCardAccessibility, _NS_::SdCard) \ HANDLER(CanSetSpeedEmulationMode, _NS_::SettingsControl) \ HANDLER(CanSimulateDevice, _NS_::Debug) \ HANDLER(CanVerifySaveData, _NS_::SaveDataManagement, _NS_::SaveDataBackUp) \ HANDLER(CanWriteSaveDataFileSystemExtraDataAll, _NS_::None) \ HANDLER(CanWriteSaveDataFileSystemExtraDataCommitId, _NS_::SaveDataBackUp) \ HANDLER(CanWriteSaveDataFileSystemExtraDataFlags, _NS_::SaveDataTransferVersion2, _NS_::SystemSaveDataManagement, _NS_::SaveDataBackUp) \ HANDLER(CanWriteSaveDataFileSystemExtraDataTimeStamp, _NS_::SaveDataBackUp) /* ACCURATE_TO_VERSION: 13.4.0.0 */ class AccessControlBits { public: enum class Bits : u64 { None = 0, ApplicationInfo = UINT64_C(1) << 0, BootModeControl = UINT64_C(1) << 1, Calibration = UINT64_C(1) << 2, SystemSaveData = UINT64_C(1) << 3, GameCard = UINT64_C(1) << 4, SaveDataBackUp = UINT64_C(1) << 5, SaveDataManagement = UINT64_C(1) << 6, BisAllRaw = UINT64_C(1) << 7, GameCardRaw = UINT64_C(1) << 8, GameCardPrivate = UINT64_C(1) << 9, SetTime = UINT64_C(1) << 10, ContentManager = UINT64_C(1) << 11, ImageManager = UINT64_C(1) << 12, CreateSaveData = UINT64_C(1) << 13, SystemSaveDataManagement = UINT64_C(1) << 14, BisFileSystem = UINT64_C(1) << 15, SystemUpdate = UINT64_C(1) << 16, SaveDataMeta = UINT64_C(1) << 17, DeviceSaveData = UINT64_C(1) << 18, SettingsControl = UINT64_C(1) << 19, SystemData = UINT64_C(1) << 20, SdCard = UINT64_C(1) << 21, Host = UINT64_C(1) << 22, FillBis = UINT64_C(1) << 23, CorruptSaveData = UINT64_C(1) << 24, SaveDataForDebug = UINT64_C(1) << 25, FormatSdCard = UINT64_C(1) << 26, GetRightsId = UINT64_C(1) << 27, RegisterExternalKey = UINT64_C(1) << 28, RegisterUpdatePartition = UINT64_C(1) << 29, SaveDataTransfer = UINT64_C(1) << 30, DeviceDetection = UINT64_C(1) << 31, AccessFailureResolution = UINT64_C(1) << 32, SaveDataTransferVersion2 = UINT64_C(1) << 33, RegisterProgramIndexMapInfo = UINT64_C(1) << 34, CreateOwnSaveData = UINT64_C(1) << 35, MoveCacheStorage = UINT64_C(1) << 36, Debug = UINT64_C(1) << 62, FullPermission = UINT64_C(1) << 63 }; private: static constexpr u64 CombineBits(Bits b) { return util::ToUnderlying(b); } template<typename... Args> static constexpr u64 CombineBits(Bits b, Args... args) { return CombineBits(b) | CombineBits(args...); } private: const u64 m_value; public: constexpr AccessControlBits(u64 v) : m_value(v) { /* ... */ } constexpr u64 GetValue() const { return m_value; } #define DEFINE_ACCESS_GETTER(name, ...) \ constexpr bool name() const { constexpr u64 Mask = CombineBits(Bits::FullPermission, ## __VA_ARGS__); return (m_value & Mask); } AMS_FSSRV_FOR_EACH_ACCESS_CONTROL_CAPABILITY(DEFINE_ACCESS_GETTER, Bits) #undef DEFINE_ACCESS_GETTER }; }
29,056
C++
.h
243
109.646091
156
0.39032
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
7,607
fssrv_external_key_manager.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/fssrv/impl/fssrv_external_key_manager.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/ncm/ncm_ids.hpp> #include <stratosphere/fs/fs_rights_id.hpp> #include <stratosphere/fs/impl/fs_newable.hpp> #include <stratosphere/spl/spl_types.hpp> namespace ams::fssrv::impl { /* ACCURATE_TO_VERSION: 13.4.0.0 */ class ExternalKeyEntry : public util::IntrusiveListBaseNode<ExternalKeyEntry>, public ::ams::fs::impl::Newable { private: fs::RightsId m_rights_id; spl::AccessKey m_access_key; public: ExternalKeyEntry(const fs::RightsId &rights_id, const spl::AccessKey &access_key) : m_rights_id(rights_id), m_access_key(access_key) { /* ... */ } bool Contains(const fs::RightsId &rights_id) const { return crypto::IsSameBytes(std::addressof(m_rights_id), std::addressof(rights_id), sizeof(m_rights_id)); } bool Contains(const void *key, size_t key_size) const { AMS_ASSERT(key_size == sizeof(spl::AccessKey)); AMS_UNUSED(key_size); return crypto::IsSameBytes(std::addressof(m_access_key), key, sizeof(m_access_key)); } void CopyAccessKey(spl::AccessKey *out) const { AMS_ASSERT(out != nullptr); std::memcpy(out, std::addressof(m_access_key), sizeof(m_access_key)); } }; /* ACCURATE_TO_VERSION: 13.4.0.0 */ class ExternalKeyManager { NON_COPYABLE(ExternalKeyManager); NON_MOVEABLE(ExternalKeyManager); private: using ExternalKeyList = util::IntrusiveListBaseTraits<ExternalKeyEntry>::ListType; private: ExternalKeyList m_key_list; os::SdkMutex m_mutex; public: constexpr ExternalKeyManager() : m_key_list(), m_mutex() { /* ... */ } Result Register(const fs::RightsId &rights_id, const spl::AccessKey &access_key) { /* Acquire exclusive access to the key list */ std::scoped_lock lk(m_mutex); /* Try to find an existing entry. */ spl::AccessKey existing; if (R_SUCCEEDED(this->FindCore(std::addressof(existing), rights_id))) { /* Check the key matches what was previously registered. */ R_UNLESS(crypto::IsSameBytes(std::addressof(existing), std::addressof(access_key), sizeof(access_key)), fs::ResultNcaExternalKeyInconsistent()); } else { /* Make a new entry. */ auto *entry = new ExternalKeyEntry(rights_id, access_key); R_UNLESS(entry != nullptr, fs::ResultAllocationMemoryFailed()); /* Add the entry to our list. */ m_key_list.push_back(*entry); } R_SUCCEED(); } Result Unregister(const fs::RightsId &rights_id) { /* Acquire exclusive access to the key list */ std::scoped_lock lk(m_mutex); /* Find a matching entry. */ for (auto it = m_key_list.begin(); it != m_key_list.end(); ++it) { if (it->Contains(rights_id)) { auto *entry = std::addressof(*it); m_key_list.erase(it); delete entry; break; } } /* Always succeed. */ R_SUCCEED(); } Result UnregisterAll() { /* Acquire exclusive access to the key list */ std::scoped_lock lk(m_mutex); /* Remove all entries until our list is empty. */ while (!m_key_list.empty()) { auto *entry = std::addressof(*m_key_list.begin()); m_key_list.erase(m_key_list.iterator_to(*entry)); delete entry; } R_SUCCEED(); } bool IsAvailableAccessKey(const void *key, size_t key_size) { /* Acquire exclusive access to the key list */ std::scoped_lock lk(m_mutex); /* Check if any entry contains the key. */ for (const auto &entry : m_key_list) { if (entry.Contains(key, key_size)) { return true; } } return false; } Result Find(spl::AccessKey *out, const fs::RightsId &rights_id) { /* Acquire exclusive access to the key list */ std::scoped_lock lk(m_mutex); /* Try to find an entry with the desired rights id. */ R_RETURN(this->FindCore(out, rights_id)); } private: Result FindCore(spl::AccessKey *out, const fs::RightsId &rights_id) { for (const auto &entry : m_key_list) { if (entry.Contains(rights_id)) { entry.CopyAccessKey(out); R_SUCCEED(); } } R_THROW(fs::ResultNcaExternalKeyUnregistered()); } }; }
5,900
C++
.h
127
33
164
0.542007
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
7,608
fssrv_access_control.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/fssrv/impl/fssrv_access_control.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/ncm/ncm_ids.hpp> #include <stratosphere/fs/impl/fs_newable.hpp> #include <stratosphere/fssrv/impl/fssrv_access_control_bits.hpp> namespace ams::fssrv { bool IsDebugFlagEnabled(); void SetDebugFlagEnabled(bool en); } namespace ams::fssrv::impl { /* ACCURATE_TO_VERSION: 13.4.0.0 */ struct Accessibility { u8 value; constexpr bool CanRead() const { return value & (1 << 0); } constexpr bool CanWrite() const { return value & (1 << 1); } static constexpr Accessibility MakeAccessibility(bool read, bool write) { return { static_cast<u8>(read * (1 << 0) + write * (1 << 1)) }; } }; static_assert(std::is_trivial<Accessibility>::value); class ContentOwnerInfo : public util::IntrusiveListBaseNode<ContentOwnerInfo>, public ::ams::fs::impl::Newable { private: u64 m_id; public: ContentOwnerInfo(u64 id) : m_id(id) { /* ... */ } u64 GetId() const { return m_id; } }; class SaveDataOwnerInfo : public util::IntrusiveListBaseNode<SaveDataOwnerInfo>, public ::ams::fs::impl::Newable { private: u64 m_id; Accessibility m_accessibility; public: SaveDataOwnerInfo(u64 id, Accessibility access) : m_id(id), m_accessibility(access) { /* ... */ } u64 GetId() const { return m_id; } Accessibility GetAccessibility() const { return m_accessibility; } }; /* ACCURATE_TO_VERSION: 13.4.0.0 */ class AccessControl { public: enum class AccessibilityType : u32 { MountLogo, MountContentMeta, MountContentControl, MountContentManual, MountContentData, MountApplicationPackage, MountSaveDataStorage, MountContentStorage, MountImageAndVideoStorage, MountCloudBackupWorkStorage, MountCustomStorage, MountBisCalibrationFile, MountBisSafeMode, MountBisUser, MountBisSystem, MountBisSystemProperEncryption, MountBisSystemProperPartition, MountSdCard, MountGameCard, MountDeviceSaveData, MountSystemSaveData, MountOthersSaveData, MountOthersSystemSaveData, OpenBisPartitionBootPartition1Root, OpenBisPartitionBootPartition2Root, OpenBisPartitionUserDataRoot, OpenBisPartitionBootConfigAndPackage2Part1, OpenBisPartitionBootConfigAndPackage2Part2, OpenBisPartitionBootConfigAndPackage2Part3, OpenBisPartitionBootConfigAndPackage2Part4, OpenBisPartitionBootConfigAndPackage2Part5, OpenBisPartitionBootConfigAndPackage2Part6, OpenBisPartitionCalibrationBinary, OpenBisPartitionCalibrationFile, OpenBisPartitionSafeMode, OpenBisPartitionUser, OpenBisPartitionSystem, OpenBisPartitionSystemProperEncryption, OpenBisPartitionSystemProperPartition, OpenSdCardStorage, OpenGameCardStorage, MountSystemDataPrivate, MountHost, MountRegisteredUpdatePartition, MountSaveDataInternalStorage, MountTemporaryDirectory, MountAllBaseFileSystem, NotMount, Count, }; enum class OperationType : u32 { InvalidateBisCache, EraseMmc, GetGameCardDeviceCertificate, GetGameCardIdSet, FinalizeGameCardDriver, GetGameCardAsicInfo, CreateSaveData, DeleteSaveData, CreateSystemSaveData, CreateOthersSystemSaveData, DeleteSystemSaveData, OpenSaveDataInfoReader, OpenSaveDataInfoReaderForSystem, OpenSaveDataInfoReaderForInternal, OpenSaveDataMetaFile, SetCurrentPosixTime, ReadSaveDataFileSystemExtraData, SetGlobalAccessLogMode, SetSpeedEmulationMode, Debug, FillBis, CorruptSaveData, CorruptSystemSaveData, VerifySaveData, DebugSaveData, FormatSdCard, GetRightsId, RegisterExternalKey, SetEncryptionSeed, WriteSaveDataFileSystemExtraDataTimeStamp, WriteSaveDataFileSystemExtraDataFlags, WriteSaveDataFileSystemExtraDataCommitId, WriteSaveDataFileSystemExtraDataAll, ExtendSaveData, ExtendSystemSaveData, ExtendOthersSystemSaveData, RegisterUpdatePartition, OpenSaveDataTransferManager, OpenSaveDataTransferManagerVersion2, OpenSaveDataTransferManagerForSaveDataRepair, OpenSaveDataTransferManagerForSaveDataRepairTool, OpenSaveDataTransferProhibiter, OpenSaveDataMover, OpenBisWiper, ListAccessibleSaveDataOwnerId, ControlMmcPatrol, OverrideSaveDataTransferTokenSignVerificationKey, OpenSdCardDetectionEventNotifier, OpenGameCardDetectionEventNotifier, OpenSystemDataUpdateEventNotifier, NotifySystemDataUpdateEvent, OpenAccessFailureDetectionEventNotifier, GetAccessFailureDetectionEvent, IsAccessFailureDetected, ResolveAccessFailure, AbandonAccessFailure, QuerySaveDataInternalStorageTotalSize, GetSaveDataCommitId, SetSdCardAccessibility, SimulateDevice, CreateSaveDataWithHashSalt, RegisterProgramIndexMapInfo, ChallengeCardExistence, CreateOwnSaveData, DeleteOwnSaveData, ReadOwnSaveDataFileSystemExtraData, ExtendOwnSaveData, OpenOwnSaveDataTransferProhibiter, FindOwnSaveDataWithFilter, OpenSaveDataTransferManagerForRepair, SetDebugConfiguration, OpenDataStorageByPath, Count, }; AMS_PRAGMA_BEGIN_PACK(4) struct AccessControlDataHeader { u8 version; u8 reserved[3]; u64 flag_bits; u32 content_owner_infos_offset; u32 content_owner_infos_size; u32 save_data_owner_infos_offset; u32 save_data_owner_infos_size; }; struct AccessControlDescriptor { u8 version; u8 content_owner_id_count; u8 save_data_owner_id_count; u8 reserved; u64 flag_bits; u64 content_owner_id_min; u64 content_owner_id_max; u64 save_data_owner_id_min; u64 save_data_owner_id_max; /* ... */ }; AMS_PRAGMA_END_PACK() static_assert(util::is_pod<AccessControlDataHeader>::value); static_assert(util::is_pod<AccessControlDescriptor>::value); static constexpr u64 AllFlagBitsMask = ~static_cast<u64>(0); static constexpr u64 DebugFlagDisableMask = AllFlagBitsMask & ~util::ToUnderlying(AccessControlBits::Bits::Debug); private: using ContentOwnerInfoList = util::IntrusiveListBaseTraits<ContentOwnerInfo>::ListType; using SaveDataOwnerInfoList = util::IntrusiveListBaseTraits<SaveDataOwnerInfo>::ListType; private: util::optional<AccessControlBits> m_flag_bits; ContentOwnerInfoList m_content_owner_infos; SaveDataOwnerInfoList m_save_data_owner_infos; public: AccessControl(const void *data, s64 data_size, const void *desc, s64 desc_size); AccessControl(const void *data, s64 data_size, const void *desc, s64 desc_size, u64 flag_mask); ~AccessControl(); public: bool HasContentOwnerId(u64 owner_id) const; Accessibility GetAccessibilitySaveDataOwnedBy(u64 owner_id) const; void ListContentOwnerId(s32 *out_count, u64 *out_owner_ids, s32 offset, s32 count) const; void ListSaveDataOwnedId(s32 *out_count, ncm::ApplicationId *out_owner_ids, s32 offset, s32 count) const; Accessibility GetAccessibilityFor(AccessibilityType type) const; bool CanCall(OperationType type) const; public: u64 GetRawFlagBits() const { return m_flag_bits.value().GetValue(); } }; }
9,974
C++
.h
231
29.554113
126
0.603539
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
7,609
fssrv_sf_i_file_system_proxy.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/fssrv/sf/fssrv_sf_i_file_system_proxy.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/sf.hpp> #include <stratosphere/fssrv/sf/fssrv_sf_ifilesystem.hpp> #include <stratosphere/fssrv/sf/fssrv_sf_istorage.hpp> #include <stratosphere/fssrv/sf/fssrv_sf_i_device_operator.hpp> #include <stratosphere/fssrv/sf/fssrv_sf_i_event_notifier.hpp> #include <stratosphere/fs/fs_error_info.hpp> #include <stratosphere/fs/fs_memory_report_info.hpp> /* ACCURATE_TO_VERSION: 13.4.0.0 */ #define AMS_FSSRV_I_FILE_SYSTEM_PROXY_INTERFACE_INFO(C, H) \ AMS_SF_METHOD_INFO(C, H, 0, Result, OpenFileSystem, (ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out, const fssrv::sf::FspPath &path, u32 type), (out, path, type), hos::Version_Min, hos::Version_1_0_0) \ AMS_SF_METHOD_INFO(C, H, 1, Result, SetCurrentProcess, (const ams::sf::ClientProcessId &client_pid), (client_pid)) \ AMS_SF_METHOD_INFO(C, H, 2, Result, OpenDataFileSystemByCurrentProcess, (ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out), (out)) \ AMS_SF_METHOD_INFO(C, H, 7, Result, OpenFileSystemWithPatch, (ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out, ncm::ProgramId program_id, u32 type), (out, program_id, type), hos::Version_2_0_0) \ AMS_SF_METHOD_INFO(C, H, 8, Result, OpenFileSystemWithIdObsolete, (ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out, const fssrv::sf::FspPath &path, u64 program_id, u32 type), (out, path, program_id, type), hos::Version_2_0_0) \ AMS_SF_METHOD_INFO(C, H, 9, Result, OpenDataFileSystemByProgramId, (ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out, ncm::ProgramId program_id), (out, program_id), hos::Version_3_0_0) \ AMS_SF_METHOD_INFO(C, H, 8, Result, OpenFileSystemWithId, (ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out, const fssrv::sf::FspPath &path, fs::ContentAttributes attr, u64 program_id, u32 type), (out, path, attr, program_id, type), hos::Version_16_0_0) \ AMS_SF_METHOD_INFO(C, H, 11, Result, OpenBisFileSystem, (ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out, const fssrv::sf::FspPath &path, u32 id), (out, path, id)) \ AMS_SF_METHOD_INFO(C, H, 12, Result, OpenBisStorage, (ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IStorage>> out, u32 id), (out, id)) \ AMS_SF_METHOD_INFO(C, H, 13, Result, InvalidateBisCache, (), ()) \ AMS_SF_METHOD_INFO(C, H, 17, Result, OpenHostFileSystem, (ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out, const fssrv::sf::FspPath &path), (out, path)) \ AMS_SF_METHOD_INFO(C, H, 18, Result, OpenSdCardFileSystem, (ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out), (out)) \ AMS_SF_METHOD_INFO(C, H, 19, Result, FormatSdCardFileSystem, (), (), hos::Version_2_0_0) \ AMS_SF_METHOD_INFO(C, H, 21, Result, DeleteSaveDataFileSystem, (u64 save_data_id), (save_data_id)) \ AMS_SF_METHOD_INFO(C, H, 22, Result, CreateSaveDataFileSystem, (const fs::SaveDataAttribute &attribute, const fs::SaveDataCreationInfo &creation_info, const fs::SaveDataMetaInfo &meta_info), (attribute, creation_info, meta_info)) \ AMS_SF_METHOD_INFO(C, H, 23, Result, CreateSaveDataFileSystemBySystemSaveDataId, (const fs::SaveDataAttribute &attribute, const fs::SaveDataCreationInfo &creation_info), (attribute, creation_info)) \ AMS_SF_METHOD_INFO(C, H, 24, Result, RegisterSaveDataFileSystemAtomicDeletion, (const ams::sf::InBuffer &save_data_ids), (save_data_ids)) \ AMS_SF_METHOD_INFO(C, H, 25, Result, DeleteSaveDataFileSystemBySaveDataSpaceId, (u8 indexer_space_id, u64 save_data_id), (indexer_space_id, save_data_id), hos::Version_2_0_0) \ AMS_SF_METHOD_INFO(C, H, 26, Result, FormatSdCardDryRun, (), (), hos::Version_2_0_0) \ AMS_SF_METHOD_INFO(C, H, 27, Result, IsExFatSupported, (ams::sf::Out<bool> out), (out), hos::Version_2_0_0) \ AMS_SF_METHOD_INFO(C, H, 28, Result, DeleteSaveDataFileSystemBySaveDataAttribute, (u8 space_id, const fs::SaveDataAttribute &attribute), (space_id, attribute), hos::Version_4_0_0) \ AMS_SF_METHOD_INFO(C, H, 30, Result, OpenGameCardStorage, (ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IStorage>> out, u32 handle, u32 partition), (out, handle, partition)) \ AMS_SF_METHOD_INFO(C, H, 31, Result, OpenGameCardFileSystem, (ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out, u32 handle, u32 partition), (out, handle, partition)) \ AMS_SF_METHOD_INFO(C, H, 32, Result, ExtendSaveDataFileSystem, (u8 space_id, u64 save_data_id, s64 available_size, s64 journal_size), (space_id, save_data_id, available_size, journal_size), hos::Version_3_0_0) \ AMS_SF_METHOD_INFO(C, H, 33, Result, DeleteCacheStorage, (u16 index), (index), hos::Version_5_0_0) \ AMS_SF_METHOD_INFO(C, H, 34, Result, GetCacheStorageSize, (ams::sf::Out<s64> out_size, ams::sf::Out<s64> out_journal_size, u16 index), (out_size, out_journal_size, index), hos::Version_5_0_0) \ AMS_SF_METHOD_INFO(C, H, 35, Result, CreateSaveDataFileSystemWithHashSalt, (const fs::SaveDataAttribute &attribute, const fs::SaveDataCreationInfo &creation_info, const fs::SaveDataMetaInfo &meta_info, const fs::HashSalt &salt), (attribute, creation_info, meta_info, salt), hos::Version_6_0_0) \ AMS_SF_METHOD_INFO(C, H, 36, Result, OpenHostFileSystemWithOption, (ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out, const fssrv::sf::FspPath &path, u32 option), (out, path, option), hos::Version_9_0_0) \ AMS_SF_METHOD_INFO(C, H, 51, Result, OpenSaveDataFileSystem, (ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out, u8 space_id, const fs::SaveDataAttribute &attribute), (out, space_id, attribute)) \ AMS_SF_METHOD_INFO(C, H, 52, Result, OpenSaveDataFileSystemBySystemSaveDataId, (ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out, u8 space_id, const fs::SaveDataAttribute &attribute), (out, space_id, attribute)) \ AMS_SF_METHOD_INFO(C, H, 53, Result, OpenReadOnlySaveDataFileSystem, (ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out, u8 space_id, const fs::SaveDataAttribute &attribute), (out, space_id, attribute), hos::Version_2_0_0) \ AMS_SF_METHOD_INFO(C, H, 57, Result, ReadSaveDataFileSystemExtraDataBySaveDataSpaceId, (const ams::sf::OutBuffer &buffer, u8 space_id, u64 save_data_id), (buffer, space_id, save_data_id), hos::Version_3_0_0) \ AMS_SF_METHOD_INFO(C, H, 58, Result, ReadSaveDataFileSystemExtraData, (const ams::sf::OutBuffer &buffer, u64 save_data_id), (buffer, save_data_id)) \ AMS_SF_METHOD_INFO(C, H, 59, Result, WriteSaveDataFileSystemExtraData, (u64 save_data_id, u8 space_id, const ams::sf::InBuffer &buffer), (save_data_id, space_id, buffer), hos::Version_2_0_0) \ /* AMS_SF_METHOD_INFO(C, H, 60, Result, OpenSaveDataInfoReader, (), ()) */ \ /* AMS_SF_METHOD_INFO(C, H, 61, Result, OpenSaveDataInfoReaderBySaveDataSpaceId, (), ()) */ \ /* AMS_SF_METHOD_INFO(C, H, 62, Result, OpenSaveDataInfoReaderOnlyCacheStorage, (), (), hos::Version_5_0_0) */ \ /* AMS_SF_METHOD_INFO(C, H, 64, Result, OpenSaveDataInternalStorageFileSystem, (), (), hos::Version_5_0_0) */ \ /* AMS_SF_METHOD_INFO(C, H, 65, Result, UpdateSaveDataMacForDebug, (), (), hos::Version_5_0_0) */ \ /* AMS_SF_METHOD_INFO(C, H, 66, Result, WriteSaveDataFileSystemExtraDataWithMask, (), (), hos::Version_5_0_0) */ \ /* AMS_SF_METHOD_INFO(C, H, 67, Result, FindSaveDataWithFilter, (), (), hos::Version_6_0_0) */ \ /* AMS_SF_METHOD_INFO(C, H, 68, Result, OpenSaveDataInfoReaderWithFilter, (), (), hos::Version_6_0_0) */ \ /* AMS_SF_METHOD_INFO(C, H, 69, Result, ReadSaveDataFileSystemExtraDataBySaveDataAttribute, (), (), hos::Version_8_0_0) */ \ /* AMS_SF_METHOD_INFO(C, H, 70, Result, WriteSaveDataFileSystemExtraDataWithMaskBySaveDataAttribute, (), (), hos::Version_8_0_0) */ \ /* AMS_SF_METHOD_INFO(C, H, 71, Result, ReadSaveDataFileSystemExtraDataWithMaskBySaveDataAttribute, (), (), hos::Version_10_0_0) */ \ /* AMS_SF_METHOD_INFO(C, H, 80, Result, OpenSaveDataMetaFile, (), ()) */ \ /* AMS_SF_METHOD_INFO(C, H, 81, Result, OpenSaveDataTransferManager, (), (), hos::Version_4_0_0) */ \ /* AMS_SF_METHOD_INFO(C, H, 82, Result, OpenSaveDataTransferManagerVersion2, (), (), hos::Version_5_0_0) */ \ /* AMS_SF_METHOD_INFO(C, H, 83, Result, OpenSaveDataTransferProhibiter, (), (), hos::Version_6_0_0) */ \ /* AMS_SF_METHOD_INFO(C, H, 84, Result, ListAccessibleSaveDataOwnerId, (), (), hos::Version_6_0_0) */ \ /* AMS_SF_METHOD_INFO(C, H, 85, Result, OpenSaveDataTransferManagerForSaveDataRepair, (), (), hos::Version_9_0_0) */ \ /* AMS_SF_METHOD_INFO(C, H, 86, Result, OpenSaveDataMover, (), (), hos::Version_10_0_0) */ \ /* AMS_SF_METHOD_INFO(C, H, 87, Result, OpenSaveDataTransferManagerForRepair, (), (), hos::Version_11_0_0) */ \ AMS_SF_METHOD_INFO(C, H, 100, Result, OpenImageDirectoryFileSystem, (ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out, u32 id), (out, id)) \ /* AMS_SF_METHOD_INFO(C, H, 101, Result, OpenBaseFileSystem, (), (), hos::Version_11_0_0) */ \ /* AMS_SF_METHOD_INFO(C, H, 102, Result, FormatBaseFileSystem, (), (), hos::Version_12_0_0) */ \ AMS_SF_METHOD_INFO(C, H, 110, Result, OpenContentStorageFileSystem, (ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out, u32 id), (out, id)) \ /* AMS_SF_METHOD_INFO(C, H, 120, Result, OpenCloudBackupWorkStorageFileSystem, (), (), hos::Version_6_0_0, hos::Version_9_2_0) */ \ /* AMS_SF_METHOD_INFO(C, H, 130, Result, OpenCustomStorageFileSystem, (), (), hos::Version_7_0_0) */ \ AMS_SF_METHOD_INFO(C, H, 200, Result, OpenDataStorageByCurrentProcess, (ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IStorage>> out), (out)) \ AMS_SF_METHOD_INFO(C, H, 201, Result, OpenDataStorageByProgramId, (ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IStorage>> out, ncm::ProgramId program_id), (out, program_id), hos::Version_3_0_0) \ AMS_SF_METHOD_INFO(C, H, 202, Result, OpenDataStorageByDataId, (ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IStorage>> out, ncm::DataId data_id, u8 storage_id), (out, data_id, storage_id)) \ AMS_SF_METHOD_INFO(C, H, 203, Result, OpenPatchDataStorageByCurrentProcess, (ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IStorage>> out), (out)) \ AMS_SF_METHOD_INFO(C, H, 204, Result, OpenDataFileSystemWithProgramIndex, (ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out, u8 index), (out, index), hos::Version_7_0_0) \ AMS_SF_METHOD_INFO(C, H, 205, Result, OpenDataStorageWithProgramIndex, (ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IStorage>> out, u8 index), (out, index), hos::Version_7_0_0) \ AMS_SF_METHOD_INFO(C, H, 206, Result, OpenDataStorageByPathObsolete, (ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IStorage>> out, const fssrv::sf::FspPath &path, u32 type), (out, path, type), hos::Version_13_0_0, hos::Version_15_0_1) \ AMS_SF_METHOD_INFO(C, H, 206, Result, OpenDataStorageByPath, (ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IStorage>> out, const fssrv::sf::FspPath &path, fs::ContentAttributes attr, u32 type), (out, path, attr, type), hos::Version_16_0_0) \ AMS_SF_METHOD_INFO(C, H, 400, Result, OpenDeviceOperator, (ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IDeviceOperator>> out), (out)) \ AMS_SF_METHOD_INFO(C, H, 500, Result, OpenSdCardDetectionEventNotifier, (ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IEventNotifier>> out), (out)) \ AMS_SF_METHOD_INFO(C, H, 501, Result, OpenGameCardDetectionEventNotifier, (ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IEventNotifier>> out), (out)) \ AMS_SF_METHOD_INFO(C, H, 510, Result, OpenSystemDataUpdateEventNotifier, (ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IEventNotifier>> out), (out), hos::Version_5_0_0) \ AMS_SF_METHOD_INFO(C, H, 511, Result, NotifySystemDataUpdateEvent, (), (), hos::Version_5_0_0) \ /* AMS_SF_METHOD_INFO(C, H, 520, Result, SimulateDeviceDetectionEvent, (), (), hos::Version_6_0_0) */ \ AMS_SF_METHOD_INFO(C, H, 600, Result, SetCurrentPosixTime, (s64 posix_time), (posix_time), hos::Version_Min, hos::Version_3_0_2) \ /* AMS_SF_METHOD_INFO(C, H, 601, Result, QuerySaveDataTotalSize, (), ()) */ \ /* AMS_SF_METHOD_INFO(C, H, 602, Result, VerifySaveDataFileSystem, (), ()) */ \ /* AMS_SF_METHOD_INFO(C, H, 603, Result, CorruptSaveDataFileSystem, (), ()) */ \ /* AMS_SF_METHOD_INFO(C, H, 604, Result, CreatePaddingFile, (), ()) */ \ /* AMS_SF_METHOD_INFO(C, H, 605, Result, DeleteAllPaddingFiles, (), ()) */ \ AMS_SF_METHOD_INFO(C, H, 606, Result, GetRightsId, (ams::sf::Out<fs::RightsId> out, ncm::ProgramId program_id, ncm::StorageId storage_id), (out, program_id, storage_id), hos::Version_2_0_0) \ AMS_SF_METHOD_INFO(C, H, 607, Result, RegisterExternalKey, (const fs::RightsId &rights_id, const spl::AccessKey &access_key), (rights_id, access_key), hos::Version_2_0_0) \ AMS_SF_METHOD_INFO(C, H, 608, Result, UnregisterAllExternalKey, (), (), hos::Version_2_0_0) \ AMS_SF_METHOD_INFO(C, H, 609, Result, GetRightsIdByPath, (ams::sf::Out<fs::RightsId> out, const fssrv::sf::FspPath &path), (out, path), hos::Version_2_0_0, hos::Version_15_0_1) \ AMS_SF_METHOD_INFO(C, H, 610, Result, GetRightsIdAndKeyGenerationByPathObsolete, (ams::sf::Out<fs::RightsId> out, ams::sf::Out<u8> out_key_generation, const fssrv::sf::FspPath &path), (out, out_key_generation, path), hos::Version_3_0_0) \ AMS_SF_METHOD_INFO(C, H, 610, Result, GetRightsIdAndKeyGenerationByPath, (ams::sf::Out<fs::RightsId> out, ams::sf::Out<u8> out_key_generation, const fssrv::sf::FspPath &path, fs::ContentAttributes attr), (out, out_key_generation, path, attr), hos::Version_16_0_0) \ AMS_SF_METHOD_INFO(C, H, 611, Result, SetCurrentPosixTimeWithTimeDifference, (s64 posix_time, s32 time_difference), (posix_time, time_difference), hos::Version_4_0_0) \ AMS_SF_METHOD_INFO(C, H, 612, Result, GetFreeSpaceSizeForSaveData, (ams::sf::Out<s64> out, u8 space_id), (out, space_id), hos::Version_4_0_0) \ AMS_SF_METHOD_INFO(C, H, 613, Result, VerifySaveDataFileSystemBySaveDataSpaceId, (), (), hos::Version_4_0_0) \ AMS_SF_METHOD_INFO(C, H, 614, Result, CorruptSaveDataFileSystemBySaveDataSpaceId, (), (), hos::Version_4_0_0) \ AMS_SF_METHOD_INFO(C, H, 615, Result, QuerySaveDataInternalStorageTotalSize, (), (), hos::Version_5_0_0) \ AMS_SF_METHOD_INFO(C, H, 616, Result, GetSaveDataCommitId, (), (), hos::Version_6_0_0) \ AMS_SF_METHOD_INFO(C, H, 617, Result, UnregisterExternalKey, (const fs::RightsId &rights_id), (rights_id), hos::Version_7_0_0) \ AMS_SF_METHOD_INFO(C, H, 618, Result, GetProgramId, (ams::sf::Out<ncm::ProgramId> out, const fssrv::sf::FspPath &path, fs::ContentAttributes attr), (out, path, attr), hos::Version_17_0_0) \ AMS_SF_METHOD_INFO(C, H, 620, Result, SetSdCardEncryptionSeed, (const fs::EncryptionSeed &seed), (seed), hos::Version_2_0_0) \ AMS_SF_METHOD_INFO(C, H, 630, Result, SetSdCardAccessibility, (bool accessible), (accessible), hos::Version_4_0_0) \ AMS_SF_METHOD_INFO(C, H, 631, Result, IsSdCardAccessible, (ams::sf::Out<bool> out), (out), hos::Version_4_0_0) \ AMS_SF_METHOD_INFO(C, H, 640, Result, IsSignedSystemPartitionOnSdCardValid, (ams::sf::Out<bool> out), (out), hos::Version_4_0_0, hos::Version_7_0_1) \ AMS_SF_METHOD_INFO(C, H, 700, Result, OpenAccessFailureDetectionEventNotifier, (), (), hos::Version_5_0_0) \ /* AMS_SF_METHOD_INFO(C, H, 701, Result, GetAccessFailureDetectionEvent, (), (), hos::Version_5_0_0) */ \ /* AMS_SF_METHOD_INFO(C, H, 702, Result, IsAccessFailureDetected, (), (), hos::Version_5_0_0) */ \ /* AMS_SF_METHOD_INFO(C, H, 710, Result, ResolveAccessFailure, (), (), hos::Version_5_0_0) */ \ /* AMS_SF_METHOD_INFO(C, H, 720, Result, AbandonAccessFailure, (), (), hos::Version_5_0_0) */ \ AMS_SF_METHOD_INFO(C, H, 800, Result, GetAndClearErrorInfo, (ams::sf::Out<fs::FileSystemProxyErrorInfo> out), (out), hos::Version_2_0_0) \ AMS_SF_METHOD_INFO(C, H, 810, Result, RegisterProgramIndexMapInfo, (const ams::sf::InBuffer &buffer, s32 count), (buffer, count), hos::Version_7_0_0) \ AMS_SF_METHOD_INFO(C, H, 1000, Result, SetBisRootForHost, (u32 id, const fssrv::sf::FspPath &path), (id, path), hos::Version_Min, hos::Version_9_2_0) \ AMS_SF_METHOD_INFO(C, H, 1001, Result, SetSaveDataSize, (s64 size, s64 journal_size), (size, journal_size)) \ AMS_SF_METHOD_INFO(C, H, 1002, Result, SetSaveDataRootPath, (const fssrv::sf::FspPath &path), (path)) \ AMS_SF_METHOD_INFO(C, H, 1003, Result, DisableAutoSaveDataCreation, (), ()) \ AMS_SF_METHOD_INFO(C, H, 1004, Result, SetGlobalAccessLogMode, (u32 mode), (mode)) \ AMS_SF_METHOD_INFO(C, H, 1005, Result, GetGlobalAccessLogMode, (ams::sf::Out<u32> out), (out)) \ AMS_SF_METHOD_INFO(C, H, 1006, Result, OutputAccessLogToSdCard, (const ams::sf::InBuffer &buf), (buf)) \ AMS_SF_METHOD_INFO(C, H, 1007, Result, RegisterUpdatePartition, (), (), hos::Version_4_0_0) \ AMS_SF_METHOD_INFO(C, H, 1008, Result, OpenRegisteredUpdatePartition, (ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out), (out), hos::Version_4_0_0) \ AMS_SF_METHOD_INFO(C, H, 1009, Result, GetAndClearMemoryReportInfo, (ams::sf::Out<fs::MemoryReportInfo> out), (out), hos::Version_4_0_0) \ /* AMS_SF_METHOD_INFO(C, H, 1010, Result, SetDataStorageRedirectTarget, (), (), hos::Version_5_1_0, hos::Version_6_2_0) */ \ AMS_SF_METHOD_INFO(C, H, 1011, Result, GetProgramIndexForAccessLog, (ams::sf::Out<u32> out_idx, ams::sf::Out<u32> out_count), (out_idx, out_count), hos::Version_7_0_0) \ AMS_SF_METHOD_INFO(C, H, 1012, Result, GetFsStackUsage, (ams::sf::Out<u32> out, u32 type), (out, type), hos::Version_9_0_0) \ AMS_SF_METHOD_INFO(C, H, 1013, Result, UnsetSaveDataRootPath, (), (), hos::Version_9_0_0) \ AMS_SF_METHOD_INFO(C, H, 1014, Result, OutputMultiProgramTagAccessLog, (), (), hos::Version_10_0_0, hos::Version_10_2_0) \ AMS_SF_METHOD_INFO(C, H, 1016, Result, FlushAccessLogOnSdCard, (), (), hos::Version_11_0_0) \ AMS_SF_METHOD_INFO(C, H, 1017, Result, OutputApplicationInfoAccessLog, (), (), hos::Version_11_0_0) \ AMS_SF_METHOD_INFO(C, H, 1018, Result, RegisterDebugConfiguration, (u32 key, s64 value), (key, value), hos::Version_13_0_0) \ AMS_SF_METHOD_INFO(C, H, 1019, Result, UnregisterDebugConfiguration, (u32 key), (key), hos::Version_13_0_0) \ AMS_SF_METHOD_INFO(C, H, 1100, Result, OverrideSaveDataTransferTokenSignVerificationKey, (const ams::sf::InBuffer &buf), (buf), hos::Version_4_0_0) \ AMS_SF_METHOD_INFO(C, H, 1110, Result, CorruptSaveDataFileSystemByOffset, (u8 space_id, u64 save_data_id, s64 offset), (space_id, save_data_id, offset), hos::Version_6_0_0) \ /* AMS_SF_METHOD_INFO(C, H, 1200, Result, OpenMultiCommitManager, (), (), hos::Version_6_0_0) */ \ /* AMS_SF_METHOD_INFO(C, H, 1300, Result, OpenBisWiper, (), (), hos::Version_10_0_0) */ AMS_SF_DEFINE_INTERFACE(ams::fssrv::sf, IFileSystemProxy, AMS_FSSRV_I_FILE_SYSTEM_PROXY_INTERFACE_INFO, 0x7DF34ED2)
46,953
C++
.h
154
301.188312
359
0.288288
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
7,610
fssrv_sf_i_event_notifier.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/fssrv/sf/fssrv_sf_i_event_notifier.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/sf.hpp> /* ACCURATE_TO_VERSION: 13.4.0.0 */ #define AMS_FSSRV_I_EVENT_NOTIFIER_INTERFACE_INFO(C, H) \ AMS_SF_METHOD_INFO(C, H, 0, Result, GetEventHandle, (ams::sf::OutCopyHandle out), (out)) AMS_SF_DEFINE_INTERFACE(ams::fssrv::sf, IEventNotifier, AMS_FSSRV_I_EVENT_NOTIFIER_INTERFACE_INFO, 0xA7E3A62C)
1,002
C++
.h
22
43.636364
110
0.752556
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
7,611
fssrv_sf_idirectory.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/fssrv/sf/fssrv_sf_idirectory.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/sf.hpp> #include <stratosphere/fs/fs_directory.hpp> /* ACCURATE_TO_VERSION: 13.4.0.0 */ #define AMS_FSSRV_I_DIRECTORY_INTERFACE_INFO(C, H) \ AMS_SF_METHOD_INFO(C, H, 0, Result, Read, (ams::sf::Out<s64> out, const ams::sf::OutBuffer &out_entries), (out, out_entries)) \ AMS_SF_METHOD_INFO(C, H, 1, Result, GetEntryCount, (ams::sf::Out<s64> out), (out)) AMS_SF_DEFINE_INTERFACE(ams::fssrv::sf, IDirectory, AMS_FSSRV_I_DIRECTORY_INTERFACE_INFO, 0xB4953DB6)
1,294
C++
.h
24
51.916667
140
0.658517
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
7,612
fssrv_sf_i_device_operator.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/fssrv/sf/fssrv_sf_i_device_operator.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/sf.hpp> #include <stratosphere/fs/fs_error_info.hpp> #include <stratosphere/fs/fs_game_card.hpp> /* TODO */ /* ACCURATE_TO_VERSION: 13.4.0.0 */ #define AMS_FSSRV_I_DEVICE_OPERATOR_INTERFACE_INFO(C, H) \ AMS_SF_METHOD_INFO(C, H, 0, Result, IsSdCardInserted, (ams::sf::Out<bool> out), (out)) \ AMS_SF_METHOD_INFO(C, H, 1, Result, GetSdCardSpeedMode, (ams::sf::Out<s64> out), (out)) \ AMS_SF_METHOD_INFO(C, H, 2, Result, GetSdCardCid, (ams::sf::OutBuffer out, s64 size), (out, size)) \ AMS_SF_METHOD_INFO(C, H, 3, Result, GetSdCardUserAreaSize, (ams::sf::Out<s64> out), (out)) \ AMS_SF_METHOD_INFO(C, H, 4, Result, GetSdCardProtectedAreaSize, (ams::sf::Out<s64> out), (out)) \ AMS_SF_METHOD_INFO(C, H, 5, Result, GetAndClearSdCardErrorInfo, (ams::sf::Out<fs::StorageErrorInfo> out_sei, ams::sf::Out<s64> out_size, ams::sf::OutBuffer out_buf, s64 size), (out_sei, out_size, out_buf, size)) \ AMS_SF_METHOD_INFO(C, H, 100, Result, GetMmcCid, (ams::sf::OutBuffer out, s64 size), (out, size)) \ AMS_SF_METHOD_INFO(C, H, 101, Result, GetMmcSpeedMode, (ams::sf::Out<s64> out), (out)) \ AMS_SF_METHOD_INFO(C, H, 112, Result, GetMmcPatrolCount, (ams::sf::Out<u32> out), (out)) \ AMS_SF_METHOD_INFO(C, H, 113, Result, GetAndClearMmcErrorInfo, (ams::sf::Out<fs::StorageErrorInfo> out_sei, ams::sf::Out<s64> out_size, ams::sf::OutBuffer out_buf, s64 size), (out_sei, out_size, out_buf, size)) \ AMS_SF_METHOD_INFO(C, H, 114, Result, GetMmcExtendedCsd, (ams::sf::OutBuffer out, s64 size), (out, size)) \ AMS_SF_METHOD_INFO(C, H, 200, Result, IsGameCardInserted, (ams::sf::Out<bool> out), (out)) \ AMS_SF_METHOD_INFO(C, H, 202, Result, GetGameCardHandle, (ams::sf::Out<u32> out), (out)) \ AMS_SF_METHOD_INFO(C, H, 208, Result, GetGameCardIdSet, (ams::sf::OutBuffer out, s64 size), (out, size)) \ AMS_SF_METHOD_INFO(C, H, 217, Result, GetGameCardErrorReportInfo, (ams::sf::Out<fs::GameCardErrorReportInfo> out), (out)) \ AMS_SF_METHOD_INFO(C, H, 218, Result, GetGameCardDeviceId, (ams::sf::OutBuffer out, s64 size), (out, size)) AMS_SF_DEFINE_INTERFACE(ams::fssrv::sf, IDeviceOperator, AMS_FSSRV_I_DEVICE_OPERATOR_INTERFACE_INFO, 0x1484E21C)
4,507
C++
.h
40
109.675
219
0.443897
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
7,613
fssrv_sf_i_program_registry.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/fssrv/sf/fssrv_sf_i_program_registry.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/sf.hpp> #include <stratosphere/fs/fs_code.hpp> #include <stratosphere/fssrv/sf/fssrv_sf_ifilesystem.hpp> /* ACCURATE_TO_VERSION: 13.4.0.0 */ #define AMS_FSSRV_I_PROGRAM_REGISTRY_INTERFACE_INFO(C, H) \ AMS_SF_METHOD_INFO(C, H, 0, Result, 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), (process_id, program_id, storage_id, data, data_size, desc, desc_size)) \ AMS_SF_METHOD_INFO(C, H, 1, Result, UnregisterProgram, (u64 process_id), (process_id)) \ AMS_SF_METHOD_INFO(C, H, 2, Result, SetCurrentProcess, (const ams::sf::ClientProcessId &client_pid), (client_pid)) \ AMS_SF_METHOD_INFO(C, H, 256, Result, SetEnabledProgramVerification, (bool en), (en)) AMS_SF_DEFINE_INTERFACE(ams::fssrv::sf, IProgramRegistry, AMS_FSSRV_I_PROGRAM_REGISTRY_INTERFACE_INFO, 0xDA73738C)
2,325
C++
.h
27
83.888889
287
0.504139
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
7,614
fssrv_sf_ifilesystem.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/fssrv/sf/fssrv_sf_ifilesystem.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/sf.hpp> #include <stratosphere/fs/fs_filesystem.hpp> #include <stratosphere/fs/fs_filesystem_for_debug.hpp> #include <stratosphere/fssrv/sf/fssrv_sf_path.hpp> #include <stratosphere/fssrv/sf/fssrv_sf_ifile.hpp> #include <stratosphere/fssrv/sf/fssrv_sf_idirectory.hpp> /* ACCURATE_TO_VERSION: 13.4.0.0 */ #define AMS_FSSRV_I_FILESYSTEM_INTERFACE_INFO(C, H) \ AMS_SF_METHOD_INFO(C, H, 0, Result, CreateFile, (const ams::fssrv::sf::Path &path, s64 size, s32 option), (path, size, option)) \ AMS_SF_METHOD_INFO(C, H, 1, Result, DeleteFile, (const ams::fssrv::sf::Path &path), (path)) \ AMS_SF_METHOD_INFO(C, H, 2, Result, CreateDirectory, (const ams::fssrv::sf::Path &path), (path)) \ AMS_SF_METHOD_INFO(C, H, 3, Result, DeleteDirectory, (const ams::fssrv::sf::Path &path), (path)) \ AMS_SF_METHOD_INFO(C, H, 4, Result, DeleteDirectoryRecursively, (const ams::fssrv::sf::Path &path), (path)) \ AMS_SF_METHOD_INFO(C, H, 5, Result, RenameFile, (const ams::fssrv::sf::Path &old_path, const ams::fssrv::sf::Path &new_path), (old_path, new_path)) \ AMS_SF_METHOD_INFO(C, H, 6, Result, RenameDirectory, (const ams::fssrv::sf::Path &old_path, const ams::fssrv::sf::Path &new_path), (old_path, new_path)) \ AMS_SF_METHOD_INFO(C, H, 7, Result, GetEntryType, (ams::sf::Out<u32> out, const ams::fssrv::sf::Path &path), (out, path)) \ AMS_SF_METHOD_INFO(C, H, 8, Result, OpenFile, (ams::sf::Out<ams::sf::SharedPointer<ams::fssrv::sf::IFile>> out, const ams::fssrv::sf::Path &path, u32 mode), (out, path, mode)) \ AMS_SF_METHOD_INFO(C, H, 9, Result, OpenDirectory, (ams::sf::Out<ams::sf::SharedPointer<ams::fssrv::sf::IDirectory>> out, const ams::fssrv::sf::Path &path, u32 mode), (out, path, mode)) \ AMS_SF_METHOD_INFO(C, H, 10, Result, Commit, (), ()) \ AMS_SF_METHOD_INFO(C, H, 11, Result, GetFreeSpaceSize, (ams::sf::Out<s64> out, const ams::fssrv::sf::Path &path), (out, path)) \ AMS_SF_METHOD_INFO(C, H, 12, Result, GetTotalSpaceSize, (ams::sf::Out<s64> out, const ams::fssrv::sf::Path &path), (out, path)) \ AMS_SF_METHOD_INFO(C, H, 13, Result, CleanDirectoryRecursively, (const ams::fssrv::sf::Path &path), (path), hos::Version_3_0_0) \ AMS_SF_METHOD_INFO(C, H, 14, Result, GetFileTimeStampRaw, (ams::sf::Out<ams::fs::FileTimeStampRaw> out, const ams::fssrv::sf::Path &path), (out, path), hos::Version_3_0_0) \ AMS_SF_METHOD_INFO(C, H, 15, Result, QueryEntry, (const ams::sf::OutNonSecureBuffer &out_buf, const ams::sf::InNonSecureBuffer &in_buf, s32 query_id, const ams::fssrv::sf::Path &path), (out_buf, in_buf, query_id, path), hos::Version_4_0_0) AMS_SF_DEFINE_INTERFACE(ams::fssrv::sf, IFileSystem, AMS_FSSRV_I_FILESYSTEM_INTERFACE_INFO, 0xD4EA59E7)
5,538
C++
.h
42
128.952381
261
0.425555
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
7,615
fssrv_sf_istorage.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/fssrv/sf/fssrv_sf_istorage.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/sf.hpp> #include <stratosphere/fs/fs_file.hpp> #include <stratosphere/fs/fs_query_range.hpp> /* ACCURATE_TO_VERSION: 13.4.0.0 */ #define AMS_FSSRV_I_STORAGE_INTERFACE_INFO(C, H) \ AMS_SF_METHOD_INFO(C, H, 0, Result, Read, (s64 offset, const ams::sf::OutNonSecureBuffer &buffer, s64 size), (offset, buffer, size)) \ AMS_SF_METHOD_INFO(C, H, 1, Result, Write, (s64 offset, const ams::sf::InNonSecureBuffer &buffer, s64 size), (offset, buffer, size)) \ AMS_SF_METHOD_INFO(C, H, 2, Result, Flush, (), ()) \ AMS_SF_METHOD_INFO(C, H, 3, Result, SetSize, (s64 size), (size)) \ AMS_SF_METHOD_INFO(C, H, 4, Result, GetSize, (ams::sf::Out<s64> out), (out)) \ AMS_SF_METHOD_INFO(C, H, 5, Result, OperateRange, (ams::sf::Out<ams::fs::StorageQueryRangeInfo> out, s32 op_id, s64 offset, s64 size), (out, op_id, offset, size), hos::Version_4_0_0) AMS_SF_DEFINE_INTERFACE(ams::fssrv::sf, IStorage, AMS_FSSRV_I_STORAGE_INTERFACE_INFO, 0xC4D2CAEB)
2,244
C++
.h
29
75
188
0.521916
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
7,616
fssrv_sf_path.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/fssrv/sf/fssrv_sf_path.hpp
/* * 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/>. */ #pragma once #include <stratosphere/fs/fs_common.hpp> #include <stratosphere/fs/fs_directory.hpp> #include <stratosphere/sf/sf_buffer_tags.hpp> namespace ams::fssrv::sf { /* ACCURATE_TO_VERSION: 13.4.0.0 */ struct Path : public ams::sf::LargeData { char str[fs::EntryNameLengthMax + 1]; static constexpr Path Encode(const char *p) { Path path = {}; for (size_t i = 0; i < sizeof(path) - 1; i++) { path.str[i] = p[i]; if (p[i] == '\x00') { break; } } return path; } static constexpr size_t GetPathLength(const Path &path) { size_t len = 0; for (size_t i = 0; i < sizeof(path) - 1 && path.str[i] != '\x00'; i++) { len++; } return len; } }; static_assert(util::is_pod<Path>::value); #if defined(ATMOSPHERE_OS_HORIZON) static_assert(sizeof(Path) == FS_MAX_PATH); #endif using FspPath = Path; }
1,684
C++
.h
47
29.021277
84
0.607362
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
7,617
fssrv_sf_ifile.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/fssrv/sf/fssrv_sf_ifile.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/sf.hpp> #include <stratosphere/fs/fs_file.hpp> #include <stratosphere/fs/fs_query_range.hpp> /* ACCURATE_TO_VERSION: 13.4.0.0 */ #define AMS_FSSRV_I_FILE_INTERFACE_INFO(C, H) \ AMS_SF_METHOD_INFO(C, H, 0, Result, Read, (ams::sf::Out<s64> out, s64 offset, const ams::sf::OutNonSecureBuffer &buffer, s64 size, ams::fs::ReadOption option), (out, offset, buffer, size, option)) \ AMS_SF_METHOD_INFO(C, H, 1, Result, Write, (s64 offset, const ams::sf::InNonSecureBuffer &buffer, s64 size, ams::fs::WriteOption option), (offset, buffer, size, option)) \ AMS_SF_METHOD_INFO(C, H, 2, Result, Flush, (), ()) \ AMS_SF_METHOD_INFO(C, H, 3, Result, SetSize, (s64 size), (size)) \ AMS_SF_METHOD_INFO(C, H, 4, Result, GetSize, (ams::sf::Out<s64> out), (out)) \ AMS_SF_METHOD_INFO(C, H, 5, Result, OperateRange, (ams::sf::Out<ams::fs::FileQueryRangeInfo> out, s32 op_id, s64 offset, s64 size), (out, op_id, offset, size), hos::Version_4_0_0) \ AMS_SF_METHOD_INFO(C, H, 6, Result, OperateRangeWithBuffer, (const ams::sf::OutNonSecureBuffer &out_buf, const ams::sf::InNonSecureBuffer &in_buf, s32 op_id, s64 offset, s64 size), (out_buf, in_buf, op_id, offset, size), hos::Version_12_0_0) AMS_SF_DEFINE_INTERFACE(ams::fssrv::sf, IFile, AMS_FSSRV_I_FILE_INTERFACE_INFO, 0xF3716DA1)
2,892
C++
.h
30
93.933333
246
0.485664
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
7,618
fssrv_sf_i_file_system_proxy_for_loader.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/fssrv/sf/fssrv_sf_i_file_system_proxy_for_loader.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/sf.hpp> #include <stratosphere/fssrv/sf/fssrv_sf_ifilesystem.hpp> #include <stratosphere/fs/fs_code_verification_data.hpp> #include <stratosphere/fs/fs_content_attributes.hpp> /* ACCURATE_TO_VERSION: 17.5.0.0 */ #define AMS_FSSRV_I_FILE_SYSTEM_PROXY_FOR_LOADER_INTERFACE_INFO(C, H) \ AMS_SF_METHOD_INFO(C, H, 0, Result, OpenCodeFileSystemDeprecated, (ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFileSystem>> out_fs, const fssrv::sf::Path &path, ncm::ProgramId program_id), (out_fs, path, program_id), hos::Version_Min, hos::Version_9_2_0) \ AMS_SF_METHOD_INFO(C, H, 0, Result, 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), (out_fs, out_verif, path, program_id), hos::Version_10_0_0, hos::Version_15_0_1) \ AMS_SF_METHOD_INFO(C, H, 0, Result, 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), (out_fs, out_verif, path, attr, program_id), hos::Version_16_0_0, hos::Version_16_1_0) \ AMS_SF_METHOD_INFO(C, H, 0, Result, 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), (out_fs, out_verif, path, attr, program_id), hos::Version_17_0_0) \ AMS_SF_METHOD_INFO(C, H, 1, Result, IsArchivedProgram, (ams::sf::Out<bool> out, u64 process_id), (out, process_id)) \ AMS_SF_METHOD_INFO(C, H, 2, Result, SetCurrentProcess, (const ams::sf::ClientProcessId &client_pid), (client_pid), hos::Version_4_0_0) AMS_SF_DEFINE_INTERFACE(ams::fssrv::sf, IFileSystemProxyForLoader, AMS_FSSRV_I_FILE_SYSTEM_PROXY_FOR_LOADER_INTERFACE_INFO, 0xDC92EE15)
3,575
C++
.h
30
116.833333
364
0.544454
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
7,619
fssrv_storage_interface_adapter.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/fssrv/interface_adapters/fssrv_storage_interface_adapter.hpp
/* * 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/>. */ #pragma once #include <stratosphere/fs/fs_common.hpp> #include <stratosphere/fs/fs_query_range.hpp> #include <stratosphere/fssystem/fssystem_utility.hpp> #include <stratosphere/fssrv/sf/fssrv_sf_istorage.hpp> namespace ams::fs { class IStorage; } namespace ams::fssrv::impl { /* ACCURATE_TO_VERSION: 13.4.0.0 */ class StorageInterfaceAdapter { NON_COPYABLE(StorageInterfaceAdapter); private: std::shared_ptr<fs::IStorage> m_base_storage; public: explicit StorageInterfaceAdapter(std::shared_ptr<fs::IStorage> &&storage) : m_base_storage(std::move(storage)) { /* ... */ } public: /* Command API. */ Result Read(s64 offset, const ams::sf::OutNonSecureBuffer &buffer, s64 size); Result Write(s64 offset, const ams::sf::InNonSecureBuffer &buffer, s64 size); Result Flush(); Result SetSize(s64 size); Result GetSize(ams::sf::Out<s64> out); Result OperateRange(ams::sf::Out<fs::StorageQueryRangeInfo> out, s32 op_id, s64 offset, s64 size); }; static_assert(fssrv::sf::IsIStorage<StorageInterfaceAdapter>); #if defined(ATMOSPHERE_OS_HORIZON) class RemoteStorage { NON_COPYABLE(RemoteStorage); NON_MOVEABLE(RemoteStorage); private: ::FsStorage m_base_storage; public: RemoteStorage(::FsStorage &s) : m_base_storage(s) { /* ... */} virtual ~RemoteStorage() { fsStorageClose(std::addressof(m_base_storage)); } public: Result Read(s64 offset, const ams::sf::OutNonSecureBuffer &buffer, s64 size) { R_RETURN(fsStorageRead(std::addressof(m_base_storage), offset, buffer.GetPointer(), size)); } Result Write(s64 offset, const ams::sf::InNonSecureBuffer &buffer, s64 size) { R_RETURN(fsStorageWrite(std::addressof(m_base_storage), offset, buffer.GetPointer(), size)); } Result Flush(){ R_RETURN(fsStorageFlush(std::addressof(m_base_storage))); } Result SetSize(s64 size) { R_RETURN(fsStorageSetSize(std::addressof(m_base_storage), size)); } Result GetSize(ams::sf::Out<s64> out) { R_RETURN(fsStorageGetSize(std::addressof(m_base_storage), out.GetPointer())); } Result OperateRange(ams::sf::Out<fs::StorageQueryRangeInfo> out, s32 op_id, s64 offset, s64 size) { static_assert(sizeof(::FsRangeInfo) == sizeof(fs::StorageQueryRangeInfo)); R_RETURN(fsStorageOperateRange(std::addressof(m_base_storage), static_cast<::FsOperationId>(op_id), offset, size, reinterpret_cast<::FsRangeInfo *>(out.GetPointer()))); } }; static_assert(fssrv::sf::IsIStorage<RemoteStorage>); #endif }
3,517
C++
.h
74
39.243243
184
0.65102
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
7,620
fssrv_filesystem_interface_adapter.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/fssrv/interface_adapters/fssrv_filesystem_interface_adapter.hpp
/* * 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/>. */ #pragma once #include <stratosphere/fs/fs_common.hpp> #include <stratosphere/fs/fs_file.hpp> #include <stratosphere/fs/fs_directory.hpp> #include <stratosphere/fs/fs_filesystem.hpp> #include <stratosphere/fs/fs_query_range.hpp> #include <stratosphere/fssystem/fssystem_utility.hpp> #include <stratosphere/fssrv/sf/fssrv_sf_path.hpp> #include <stratosphere/fssrv/sf/fssrv_sf_ifile.hpp> #include <stratosphere/fssrv/sf/fssrv_sf_idirectory.hpp> #include <stratosphere/fssrv/sf/fssrv_sf_ifilesystem.hpp> namespace ams::fs::fsa { class IFile; class IDirectory; class IFileSystem; } namespace ams::fssrv::impl { class FileSystemInterfaceAdapter; /* ACCURATE_TO_VERSION: 13.4.0.0 */ class FileInterfaceAdapter { NON_COPYABLE(FileInterfaceAdapter); NON_MOVEABLE(FileInterfaceAdapter); private: ams::sf::SharedPointer<FileSystemInterfaceAdapter> m_parent_filesystem; std::unique_ptr<fs::fsa::IFile> m_base_file; bool m_allow_all_operations; public: FileInterfaceAdapter(std::unique_ptr<fs::fsa::IFile> &&file, FileSystemInterfaceAdapter *parent, bool allow_all); private: void InvalidateCache(); public: /* Command API. */ Result Read(ams::sf::Out<s64> out, s64 offset, const ams::sf::OutNonSecureBuffer &buffer, s64 size, fs::ReadOption option); Result Write(s64 offset, const ams::sf::InNonSecureBuffer &buffer, s64 size, fs::WriteOption option); Result Flush(); Result SetSize(s64 size); Result GetSize(ams::sf::Out<s64> out); Result OperateRange(ams::sf::Out<fs::FileQueryRangeInfo> out, s32 op_id, s64 offset, s64 size); Result OperateRangeWithBuffer(const ams::sf::OutNonSecureBuffer &out_buf, const ams::sf::InNonSecureBuffer &in_buf, s32 op_id, s64 offset, s64 size); }; static_assert(fssrv::sf::IsIFile<FileInterfaceAdapter>); /* ACCURATE_TO_VERSION: 13.4.0.0 */ class DirectoryInterfaceAdapter { NON_COPYABLE(DirectoryInterfaceAdapter); NON_MOVEABLE(DirectoryInterfaceAdapter); private: ams::sf::SharedPointer<FileSystemInterfaceAdapter> m_parent_filesystem; std::unique_ptr<fs::fsa::IDirectory> m_base_dir; bool m_allow_all_operations; public: DirectoryInterfaceAdapter(std::unique_ptr<fs::fsa::IDirectory> &&dir, FileSystemInterfaceAdapter *parent, bool allow_all); public: /* Command API */ Result Read(ams::sf::Out<s64> out, const ams::sf::OutBuffer &out_entries); Result GetEntryCount(ams::sf::Out<s64> out); }; static_assert(fssrv::sf::IsIDirectory<DirectoryInterfaceAdapter>); /* ACCURATE_TO_VERSION: 13.4.0.0 */ class FileSystemInterfaceAdapter : public ams::sf::ISharedObject { NON_COPYABLE(FileSystemInterfaceAdapter); NON_MOVEABLE(FileSystemInterfaceAdapter); private: std::shared_ptr<fs::fsa::IFileSystem> m_base_fs; fs::PathFlags m_path_flags; bool m_allow_all_operations; bool m_is_mitm_interface; public: FileSystemInterfaceAdapter(std::shared_ptr<fs::fsa::IFileSystem> &&fs, const fs::PathFlags &flags, bool allow_all, bool is_mitm_interface = false) : m_base_fs(std::move(fs)), m_path_flags(flags), m_allow_all_operations(allow_all), m_is_mitm_interface(is_mitm_interface) { /* ... */ } FileSystemInterfaceAdapter(std::shared_ptr<fs::fsa::IFileSystem> &&fs, bool allow_all, bool is_mitm_interface = false) : m_base_fs(std::move(fs)), m_path_flags(), m_allow_all_operations(allow_all), m_is_mitm_interface(is_mitm_interface) { /* ... */ } private: Result SetUpPath(fs::Path *out, const fssrv::sf::Path &sf_path); public: /* Command API. */ Result CreateFile(const fssrv::sf::Path &path, s64 size, s32 option); Result DeleteFile(const fssrv::sf::Path &path); Result CreateDirectory(const fssrv::sf::Path &path); Result DeleteDirectory(const fssrv::sf::Path &path); Result DeleteDirectoryRecursively(const fssrv::sf::Path &path); Result RenameFile(const fssrv::sf::Path &old_path, const fssrv::sf::Path &new_path); Result RenameDirectory(const fssrv::sf::Path &old_path, const fssrv::sf::Path &new_path); Result GetEntryType(ams::sf::Out<u32> out, const fssrv::sf::Path &path); Result OpenFile(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFile>> out, const fssrv::sf::Path &path, u32 mode); Result OpenDirectory(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IDirectory>> out, const fssrv::sf::Path &path, u32 mode); Result Commit(); Result GetFreeSpaceSize(ams::sf::Out<s64> out, const fssrv::sf::Path &path); Result GetTotalSpaceSize(ams::sf::Out<s64> out, const fssrv::sf::Path &path); Result CleanDirectoryRecursively(const fssrv::sf::Path &path); Result GetFileTimeStampRaw(ams::sf::Out<fs::FileTimeStampRaw> out, const fssrv::sf::Path &path); Result QueryEntry(const ams::sf::OutNonSecureBuffer &out_buf, const ams::sf::InNonSecureBuffer &in_buf, s32 query_id, const fssrv::sf::Path &path); }; #if defined(ATMOSPHERE_OS_HORIZON) class RemoteFile { NON_COPYABLE(RemoteFile); NON_MOVEABLE(RemoteFile); private: ::FsFile m_base_file; public: RemoteFile(::FsFile &s) : m_base_file(s) { /* ... */} virtual ~RemoteFile() { fsFileClose(std::addressof(m_base_file)); } public: Result Read(ams::sf::Out<s64> out, s64 offset, const ams::sf::OutNonSecureBuffer &buffer, s64 size, fs::ReadOption option) { R_RETURN(fsFileRead(std::addressof(m_base_file), offset, buffer.GetPointer(), size, option._value, reinterpret_cast<u64 *>(out.GetPointer()))); } Result Write(s64 offset, const ams::sf::InNonSecureBuffer &buffer, s64 size, fs::WriteOption option) { R_RETURN(fsFileWrite(std::addressof(m_base_file), offset, buffer.GetPointer(), size, option._value)); } Result Flush(){ R_RETURN(fsFileFlush(std::addressof(m_base_file))); } Result SetSize(s64 size) { R_RETURN(fsFileSetSize(std::addressof(m_base_file), size)); } Result GetSize(ams::sf::Out<s64> out) { R_RETURN(fsFileGetSize(std::addressof(m_base_file), out.GetPointer())); } Result OperateRange(ams::sf::Out<fs::FileQueryRangeInfo> out, s32 op_id, s64 offset, s64 size) { static_assert(sizeof(::FsRangeInfo) == sizeof(fs::FileQueryRangeInfo)); R_RETURN(fsFileOperateRange(std::addressof(m_base_file), static_cast<::FsOperationId>(op_id), offset, size, reinterpret_cast<::FsRangeInfo *>(out.GetPointer()))); } Result OperateRangeWithBuffer(const ams::sf::OutNonSecureBuffer &out_buf, const ams::sf::InNonSecureBuffer &in_buf, s32 op_id, s64 offset, s64 size) { AMS_UNUSED(out_buf, in_buf, op_id, offset, size); AMS_ABORT("TODO"); } }; static_assert(fssrv::sf::IsIFile<RemoteFile>); class RemoteDirectory { NON_COPYABLE(RemoteDirectory); NON_MOVEABLE(RemoteDirectory); private: ::FsDir m_base_dir; public: RemoteDirectory(::FsDir &s) : m_base_dir(s) { /* ... */} virtual ~RemoteDirectory() { fsDirClose(std::addressof(m_base_dir)); } public: Result Read(ams::sf::Out<s64> out, const ams::sf::OutBuffer &out_entries) { static_assert(sizeof(::FsDirectoryEntry) == sizeof(fs::DirectoryEntry)); R_RETURN(fsDirRead(std::addressof(m_base_dir), out.GetPointer(), out_entries.GetSize() / sizeof(fs::DirectoryEntry), reinterpret_cast<::FsDirectoryEntry *>(out_entries.GetPointer()))); } Result GetEntryCount(ams::sf::Out<s64> out) { R_RETURN(fsDirGetEntryCount(std::addressof(m_base_dir), out.GetPointer())); } }; static_assert(fssrv::sf::IsIDirectory<RemoteDirectory>); class RemoteFileSystem { NON_COPYABLE(RemoteFileSystem); NON_MOVEABLE(RemoteFileSystem); private: ::FsFileSystem m_base_fs; public: RemoteFileSystem(::FsFileSystem &s) : m_base_fs(s) { /* ... */} virtual ~RemoteFileSystem() { fsFsClose(std::addressof(m_base_fs)); } public: /* Command API. */ Result CreateFile(const fssrv::sf::Path &path, s64 size, s32 option) { R_RETURN(fsFsCreateFile(std::addressof(m_base_fs), path.str, size, option)); } Result DeleteFile(const fssrv::sf::Path &path) { R_RETURN(fsFsDeleteFile(std::addressof(m_base_fs), path.str)); } Result CreateDirectory(const fssrv::sf::Path &path) { R_RETURN(fsFsCreateDirectory(std::addressof(m_base_fs), path.str)); } Result DeleteDirectory(const fssrv::sf::Path &path) { R_RETURN(fsFsDeleteDirectory(std::addressof(m_base_fs), path.str)); } Result DeleteDirectoryRecursively(const fssrv::sf::Path &path) { R_RETURN(fsFsDeleteDirectoryRecursively(std::addressof(m_base_fs), path.str)); } Result RenameFile(const fssrv::sf::Path &old_path, const fssrv::sf::Path &new_path) { R_RETURN(fsFsRenameFile(std::addressof(m_base_fs), old_path.str, new_path.str)); } Result RenameDirectory(const fssrv::sf::Path &old_path, const fssrv::sf::Path &new_path) { R_RETURN(fsFsRenameDirectory(std::addressof(m_base_fs), old_path.str, new_path.str)); } Result GetEntryType(ams::sf::Out<u32> out, const fssrv::sf::Path &path) { static_assert(sizeof(::FsDirEntryType) == sizeof(u32)); R_RETURN(fsFsGetEntryType(std::addressof(m_base_fs), path.str, reinterpret_cast<::FsDirEntryType *>(out.GetPointer()))); } Result Commit() { R_RETURN(fsFsCommit(std::addressof(m_base_fs))); } Result GetFreeSpaceSize(ams::sf::Out<s64> out, const fssrv::sf::Path &path) { R_RETURN(fsFsGetFreeSpace(std::addressof(m_base_fs), path.str, out.GetPointer())); } Result GetTotalSpaceSize(ams::sf::Out<s64> out, const fssrv::sf::Path &path) { R_RETURN(fsFsGetTotalSpace(std::addressof(m_base_fs), path.str, out.GetPointer())); } Result CleanDirectoryRecursively(const fssrv::sf::Path &path) { R_RETURN(fsFsCleanDirectoryRecursively(std::addressof(m_base_fs), path.str)); } Result GetFileTimeStampRaw(ams::sf::Out<fs::FileTimeStampRaw> out, const fssrv::sf::Path &path) { static_assert(sizeof(fs::FileTimeStampRaw) == sizeof(::FsTimeStampRaw)); R_RETURN(fsFsGetFileTimeStampRaw(std::addressof(m_base_fs), path.str, reinterpret_cast<::FsTimeStampRaw *>(out.GetPointer()))); } Result QueryEntry(const ams::sf::OutNonSecureBuffer &out_buf, const ams::sf::InNonSecureBuffer &in_buf, s32 query_id, const fssrv::sf::Path &path) { R_RETURN(fsFsQueryEntry(std::addressof(m_base_fs), out_buf.GetPointer(), out_buf.GetSize(), in_buf.GetPointer(), in_buf.GetSize(), path.str, static_cast<FsFileSystemQueryId>(query_id))); } Result OpenFile(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IFile>> out, const fssrv::sf::Path &path, u32 mode); Result OpenDirectory(ams::sf::Out<ams::sf::SharedPointer<fssrv::sf::IDirectory>> out, const fssrv::sf::Path &path, u32 mode); }; static_assert(fssrv::sf::IsIFileSystem<RemoteFileSystem>); #endif }
12,892
C++
.h
226
46.323009
202
0.632137
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
7,621
fssrv_storage_on_nca_creator.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/fssrv/fscreator/fssrv_storage_on_nca_creator.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/fssrv/fssrv_i_file_system_creator.hpp> #include <stratosphere/fs/fs_i_buffer_manager.hpp> #include <stratosphere/fssystem/fssystem_i_hash_256_generator.hpp> namespace ams::fssystem { struct NcaCryptoConfiguration; struct NcaCompressionConfiguration; } namespace ams::fssrv::fscreator { class StorageOnNcaCreator : public IStorageOnNcaCreator { NON_COPYABLE(StorageOnNcaCreator); NON_MOVEABLE(StorageOnNcaCreator); private: MemoryResource *m_allocator; const fssystem::NcaCryptoConfiguration &m_nca_crypto_cfg; const fssystem::NcaCompressionConfiguration &m_nca_compression_cfg; fs::IBufferManager * const m_buffer_manager; fssystem::IHash256GeneratorFactorySelector * const m_hash_generator_factory_selector; public: explicit StorageOnNcaCreator(MemoryResource *mr, const fssystem::NcaCryptoConfiguration &cfg, const fssystem::NcaCompressionConfiguration &c_cfg, fs::IBufferManager *bm, fssystem::IHash256GeneratorFactorySelector *hgfs) : m_allocator(mr), m_nca_crypto_cfg(cfg), m_nca_compression_cfg(c_cfg), m_buffer_manager(bm), m_hash_generator_factory_selector(hgfs) { /* ... */ } virtual Result 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) override; virtual Result 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) override; virtual Result CreateNcaReader(std::shared_ptr<fssystem::NcaReader> *out, std::shared_ptr<fs::IStorage> storage) override; #if !defined(ATMOSPHERE_BOARD_NINTENDO_NX) Result 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); Result 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); Result 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); #endif }; }
3,668
C++
.h
50
66.46
337
0.740371
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
7,622
fssrv_local_file_system_creator.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/fssrv/fscreator/fssrv_local_file_system_creator.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/fssrv/fssrv_i_file_system_creator.hpp> namespace ams::fssrv::fscreator { /* ACCURATE_TO_VERSION: 13.4.0.0 */ class LocalFileSystemCreator final : public ILocalFileSystemCreator { NON_COPYABLE(LocalFileSystemCreator); NON_MOVEABLE(LocalFileSystemCreator); private: bool m_is_development; public: explicit LocalFileSystemCreator(bool dev) : m_is_development(dev) { /* ... */ } virtual Result Create(std::shared_ptr<fs::fsa::IFileSystem> *out, const fs::Path &path, bool case_sensitive, bool ensure_root, Result on_path_not_found) override; }; }
1,321
C++
.h
30
39.766667
174
0.722611
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
7,623
fssrv_subdirectory_file_system_creator.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/fssrv/fscreator/fssrv_subdirectory_file_system_creator.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/fssrv/fssrv_i_file_system_creator.hpp> namespace ams::fssrv::fscreator { /* ACCURATE_TO_VERSION: 13.4.0.0 */ class SubDirectoryFileSystemCreator final : public ISubDirectoryFileSystemCreator { NON_COPYABLE(SubDirectoryFileSystemCreator); NON_MOVEABLE(SubDirectoryFileSystemCreator); public: explicit SubDirectoryFileSystemCreator() { /* ... */ } virtual Result Create(std::shared_ptr<fs::fsa::IFileSystem> *out, std::shared_ptr<fs::fsa::IFileSystem> base_fs, const fs::Path &path) override; }; }
1,254
C++
.h
28
41
156
0.735679
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
7,624
fssrv_partition_file_system_creator.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/fssrv/fscreator/fssrv_partition_file_system_creator.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/fssrv/fssrv_i_file_system_creator.hpp> namespace ams::fssrv::fscreator { /* ACCURATE_TO_VERSION: Unknown */ class PartitionFileSystemCreator : public IPartitionFileSystemCreator { NON_COPYABLE(PartitionFileSystemCreator); NON_MOVEABLE(PartitionFileSystemCreator); public: PartitionFileSystemCreator() { /* ... */ } virtual Result Create(std::shared_ptr<fs::fsa::IFileSystem> *out, std::shared_ptr<fs::IStorage> storage) override; }; }
1,193
C++
.h
28
38.821429
126
0.734711
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
7,625
fssrv_rom_file_system_creator.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/fssrv/fscreator/fssrv_rom_file_system_creator.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/fssrv/fssrv_i_file_system_creator.hpp> namespace ams::fssrv::fscreator { /* ACCURATE_TO_VERSION: Unknown */ class RomFileSystemCreator : public IRomFileSystemCreator { NON_COPYABLE(RomFileSystemCreator); NON_MOVEABLE(RomFileSystemCreator); private: MemoryResource *m_allocator; public: explicit RomFileSystemCreator(MemoryResource *mr) : m_allocator(mr) { /* ... */ } virtual Result Create(std::shared_ptr<fs::fsa::IFileSystem> *out, std::shared_ptr<fs::IStorage> storage) override; }; }
1,266
C++
.h
30
37.933333
126
0.722403
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
7,626
regulator_session_api.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/regulator/regulator_session_api.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/regulator/regulator_types.hpp> namespace ams::regulator { struct RegulatorSession { void *_session; }; Result OpenSession(RegulatorSession *out, DeviceCode device_code); void CloseSession(RegulatorSession *session); bool GetVoltageEnabled(RegulatorSession *session); Result SetVoltageEnabled(RegulatorSession *session, bool enabled); Result SetVoltageValue(RegulatorSession *session, u32 micro_volts); }
1,140
C++
.h
28
37.714286
76
0.766727
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
7,627
regulator_api.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/regulator/regulator_api.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/regulator/regulator_types.hpp> namespace ams::regulator { void Initialize(); void Finalize(); }
801
C++
.h
22
34.272727
76
0.757732
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
7,628
regulator_types.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/regulator/regulator_types.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> namespace ams::regulator { /* ... */ }
717
C++
.h
20
33.8
76
0.744957
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
7,629
dmnt_cheat_types.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/dmnt/dmnt_cheat_types.hpp
/* * 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/>. */ #pragma once #include <stratosphere/os.hpp> #include <stratosphere/ncm/ncm_ids.hpp> #include <stratosphere/sf/sf_buffer_tags.hpp> namespace ams::dmnt::cheat { struct CheatProcessMetadata { struct MemoryRegionExtents { u64 base; u64 size; }; os::ProcessId process_id; ncm::ProgramId program_id; MemoryRegionExtents main_nso_extents; MemoryRegionExtents heap_extents; MemoryRegionExtents alias_extents; MemoryRegionExtents aslr_extents; u8 main_nso_module_id[0x20]; }; static_assert(util::is_pod<CheatProcessMetadata>::value && sizeof(CheatProcessMetadata) == 0x70, "CheatProcessMetadata definition!"); struct CheatDefinition : sf::LargeData, sf::PrefersMapAliasTransferMode { char readable_name[0x40]; uint32_t num_opcodes; uint32_t opcodes[0x100]; }; struct CheatEntry : sf::LargeData, sf::PrefersMapAliasTransferMode { bool enabled; uint32_t cheat_id; CheatDefinition definition; }; static_assert(util::is_pod<CheatDefinition>::value, "CheatDefinition"); static_assert(util::is_pod<CheatEntry>::value, "CheatEntry"); struct FrozenAddressValue { u64 value; u8 width; }; struct FrozenAddressEntry { u64 address; FrozenAddressValue value; }; }
2,016
C++
.h
55
31.054545
137
0.702051
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
7,630
powctl_select_devices.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/powctl/powctl_select_devices.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/powctl/powctl_types.hpp> #if defined(ATMOSPHERE_BOARD_NINTENDO_NX) #include <stratosphere/powctl/powctl_devices.board.nintendo_nx.hpp> #else /* Error? */ #endif
864
C++
.h
23
35.565217
76
0.760714
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
7,631
powctl_devices.board.nintendo_nx.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/powctl/powctl_devices.board.nintendo_nx.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/i2c.hpp> #include <stratosphere/powctl/powctl_types.hpp> namespace ams::powctl { /* Fuel Gauge. */ constexpr inline const DeviceCode DeviceCode_Max17050 = i2c::DeviceCode_Max17050; /* Charger. */ constexpr inline const DeviceCode DeviceCode_Bq24193 = i2c::DeviceCode_Bq24193; }
993
C++
.h
25
37.36
85
0.757261
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
7,632
powctl_charger_api.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/powctl/powctl_charger_api.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> #include <stratosphere/powctl/powctl_types.hpp> #include <stratosphere/powctl/powctl_session_api.hpp> namespace ams::powctl { /* Charger API. */ Result GetChargerChargeCurrentState(ChargeCurrentState *out, Session &session); Result SetChargerChargeCurrentState(Session &session, ChargeCurrentState state); Result GetChargerFastChargeCurrentLimit(int *out_ma, Session &session); Result SetChargerFastChargeCurrentLimit(Session &session, int ma); Result GetChargerChargeVoltageLimit(int *out_mv, Session &session); Result SetChargerChargeVoltageLimit(Session &session, int mv); Result SetChargerChargerConfiguration(Session &session, ChargerConfiguration cfg); Result IsChargerHiZEnabled(bool *out, Session &session); Result SetChargerHiZEnabled(Session &session, bool en); Result GetChargerInputCurrentLimit(int *out_ma, Session &session); Result SetChargerInputCurrentLimit(Session &session, int ma); Result SetChargerInputVoltageLimit(Session &session, int mv); Result SetChargerBoostModeCurrentLimit(Session &session, int ma); Result GetChargerChargerStatus(ChargerStatus *out, Session &session); Result IsChargerWatchdogTimerEnabled(bool *out, Session &session); Result SetChargerWatchdogTimerEnabled(Session &session, bool en); Result SetChargerWatchdogTimerTimeout(Session &session, TimeSpan timeout); Result ResetChargerWatchdogTimer(Session &session); Result GetChargerBatteryCompensation(int *out_mo, Session &session); Result SetChargerBatteryCompensation(Session &session, int mo); Result GetChargerVoltageClamp(int *out_mv, Session &session); Result SetChargerVoltageClamp(Session &session, int mv); }
2,391
C++
.h
44
50.590909
86
0.78988
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
7,633
powctl_types.hpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/include/stratosphere/powctl/powctl_types.hpp
/* * 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/>. */ #pragma once #include <vapours.hpp> namespace ams::powctl { /* Charger types. */ enum ChargerStatus { ChargerStatus_Charging = 1, ChargerStatus_NotCharging = 3, ChargerStatus_ChargeTerminationDone = 4, }; enum ChargerConfiguration { ChargerConfiguration_ChargeDisable = 1, ChargerConfiguration_ChargeBattery = 2, ChargerConfiguration_Otg = 3, }; enum ChargeCurrentState { ChargeCurrentState_Unknown = 0x0, ChargeCurrentState_NotCharging = 0x1, ChargeCurrentState_ChargingForce20Percent = 0x2, ChargeCurrentState_Charging = 0x3, }; enum class BatteryTemperatureLevel { TooLow = 0, Low = 1, Medium = 2, High = 3, TooHigh = 4, }; enum class PowerState { FullAwake = 0, MinimumAwake = 1, SleepCharge = 2, SleepDischarge = 3, ShutdownChargeMain = 4, }; }
1,704
C++
.h
50
28.58
76
0.635094
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