id
int64 0
755k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
65
| repo_stars
int64 100
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 9
values | repo_extraction_date
stringclasses 92
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6,523
|
lmem_impl_exp_heap.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/lmem/impl/lmem_impl_exp_heap.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "lmem_impl_exp_heap.hpp"
namespace ams::lmem::impl {
namespace {
constexpr u16 FreeBlockMagic = 0x4652; /* FR */
constexpr u16 UsedBlockMagic = 0x5544; /* UD */
constexpr u16 DefaultGroupId = 0x00;
constexpr u16 MaxGroupId = 0xFF;
constexpr size_t MinimumAlignment = 4;
constexpr size_t MaximumPaddingalignment = 0x80;
constexpr AllocationMode DefaultAllocationMode = AllocationMode_FirstFit;
constexpr size_t MinimumFreeBlockSize = 4;
struct MemoryRegion {
void *start;
void *end;
};
inline bool IsValidHeapHandle(HeapHandle handle) {
return handle->magic == ExpHeapMagic;
}
[[maybe_unused]] inline ExpHeapHead *GetExpHeapHead(HeapHead *heap_head) {
return std::addressof(heap_head->impl_head.exp_heap_head);
}
[[maybe_unused]] inline const ExpHeapHead *GetExpHeapHead(const HeapHead *heap_head) {
return std::addressof(heap_head->impl_head.exp_heap_head);
}
[[maybe_unused]] inline HeapHead *GetHeapHead(ExpHeapHead *exp_heap_head) {
return util::GetParentPointer<&HeapHead::impl_head>(util::GetParentPointer<&ImplementationHeapHead::exp_heap_head>(exp_heap_head));
}
[[maybe_unused]] inline const HeapHead *GetHeapHead(const ExpHeapHead *exp_heap_head) {
return util::GetParentPointer<&HeapHead::impl_head>(util::GetParentPointer<&ImplementationHeapHead::exp_heap_head>(exp_heap_head));
}
inline void *GetExpHeapMemoryStart(ExpHeapHead *exp_heap_head) {
return reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(exp_heap_head) + sizeof(ImplementationHeapHead));
}
inline void *GetMemoryBlockStart(ExpHeapMemoryBlockHead *head) {
return reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(head) + sizeof(*head));
}
inline const void *GetMemoryBlockStart(const ExpHeapMemoryBlockHead *head) {
return reinterpret_cast<const void *>(reinterpret_cast<uintptr_t>(head) + sizeof(*head));
}
inline void *GetMemoryBlockEnd(ExpHeapMemoryBlockHead *head) {
return reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(GetMemoryBlockStart(head)) + head->block_size);
}
inline const void *GetMemoryBlockEnd(const ExpHeapMemoryBlockHead *head) {
return reinterpret_cast<const void *>(reinterpret_cast<uintptr_t>(GetMemoryBlockStart(head)) + head->block_size);
}
inline ExpHeapMemoryBlockHead *GetHeadForMemoryBlock(const void *block) {
return reinterpret_cast<ExpHeapMemoryBlockHead *>(reinterpret_cast<uintptr_t>(block) - sizeof(ExpHeapMemoryBlockHead));
}
inline bool IsValidUsedMemoryBlock(const HeapHead *heap, const void *block) {
/* Block must fall within the heap range. */
if (heap != nullptr) {
if (block < heap->heap_start || heap->heap_end <= block) {
return false;
}
}
/* Block magic must be used. */
const ExpHeapMemoryBlockHead *head = GetHeadForMemoryBlock(block);
if (head->magic != UsedBlockMagic) {
return false;
}
/* End of block must remain within the heap range. */
if (heap != nullptr) {
if (reinterpret_cast<uintptr_t>(block) + head->block_size > reinterpret_cast<uintptr_t>(heap->heap_end)) {
return false;
}
}
return true;
}
inline u16 GetMemoryBlockAlignmentPadding(const ExpHeapMemoryBlockHead *block_head) {
return static_cast<u16>((block_head->attributes >> 8) & 0x7F);
}
inline void SetMemoryBlockAlignmentPadding(ExpHeapMemoryBlockHead *block_head, u16 padding) {
block_head->attributes &= ~static_cast<decltype(block_head->attributes)>(0x7F << 8);
block_head->attributes |= static_cast<decltype(block_head->attributes)>(padding & 0x7F) << 8;
}
inline u16 GetMemoryBlockGroupId(const ExpHeapMemoryBlockHead *block_head) {
return static_cast<u16>(block_head->attributes & 0xFF);
}
inline void SetMemoryBlockGroupId(ExpHeapMemoryBlockHead *block_head, u16 group_id) {
block_head->attributes &= ~static_cast<decltype(block_head->attributes)>(0xFF);
block_head->attributes |= static_cast<decltype(block_head->attributes)>(group_id & 0xFF);
}
inline AllocationDirection GetMemoryBlockAllocationDirection(const ExpHeapMemoryBlockHead *block_head) {
return static_cast<AllocationDirection>((block_head->attributes >> 15) & 1);
}
inline void SetMemoryBlockAllocationDirection(ExpHeapMemoryBlockHead *block_head, AllocationDirection dir) {
block_head->attributes &= ~static_cast<decltype(block_head->attributes)>(0x8000);
block_head->attributes |= static_cast<decltype(block_head->attributes)>(dir) << 15;
}
inline void GetMemoryBlockRegion(MemoryRegion *out, ExpHeapMemoryBlockHead *head) {
out->start = reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(head) - GetMemoryBlockAlignmentPadding(head));
out->end = GetMemoryBlockEnd(head);
}
inline AllocationMode GetAllocationModeImpl(const ExpHeapHead *head) {
return static_cast<AllocationMode>(head->mode);
}
inline void SetAllocationModeImpl(ExpHeapHead *head, AllocationMode mode) {
head->mode = mode;
}
inline ExpHeapMemoryBlockHead *InitializeMemoryBlock(const MemoryRegion ®ion, u16 magic) {
/* Construct the block. */
ExpHeapMemoryBlockHead *block = std::construct_at(reinterpret_cast<ExpHeapMemoryBlockHead *>(region.start));
/* Initialize all members. */
block->magic = magic;
block->attributes = 0;
block->block_size = GetPointerDifference(GetMemoryBlockStart(block), region.end);
return block;
}
inline ExpHeapMemoryBlockHead *InitializeFreeMemoryBlock(const MemoryRegion ®ion) {
return InitializeMemoryBlock(region, FreeBlockMagic);
}
inline ExpHeapMemoryBlockHead *InitializeUsedMemoryBlock(const MemoryRegion ®ion) {
return InitializeMemoryBlock(region, UsedBlockMagic);
}
HeapHead *InitializeExpHeap(void *start, void *end, u32 option) {
HeapHead *heap_head = reinterpret_cast<HeapHead *>(start);
ExpHeapHead *exp_heap_head = GetExpHeapHead(heap_head);
/* Initialize the parent heap. */
InitializeHeapHead(heap_head, ExpHeapMagic, GetExpHeapMemoryStart(exp_heap_head), end, option);
/* Call exp heap member constructors. */
std::construct_at(std::addressof(exp_heap_head->free_list));
std::construct_at(std::addressof(exp_heap_head->used_list));
/* Set exp heap fields. */
exp_heap_head->group_id = DefaultGroupId;
exp_heap_head->use_alignment_margins = false;
SetAllocationModeImpl(exp_heap_head, DefaultAllocationMode);
/* Initialize memory block. */
{
MemoryRegion region{ .start = heap_head->heap_start, .end = heap_head->heap_end, };
exp_heap_head->free_list.push_back(*InitializeFreeMemoryBlock(region));
}
return heap_head;
}
bool CoalesceFreedRegion(ExpHeapHead *head, const MemoryRegion *region) {
auto prev_free_block_it = head->free_list.end();
MemoryRegion free_region = *region;
/* Locate the block. */
for (auto it = head->free_list.begin(); it != head->free_list.end(); it++) {
ExpHeapMemoryBlockHead *cur_free_block = std::addressof(*it);
if (cur_free_block < region->start) {
prev_free_block_it = it;
continue;
}
/* Coalesce block after, if possible. */
if (cur_free_block == region->end) {
free_region.end = GetMemoryBlockEnd(cur_free_block);
it = head->free_list.erase(it);
/* Fill the memory with a pattern, for debug. */
FillUnallocatedMemory(GetHeapHead(head), cur_free_block, sizeof(ExpHeapMemoryBlockHead));
}
break;
}
/* We'll want to insert after the previous free block. */
auto insertion_it = head->free_list.begin();
if (prev_free_block_it != head->free_list.end()) {
/* There's a previous free block, so we want to insert as the next iterator. */
if (GetMemoryBlockEnd(std::addressof(*prev_free_block_it)) == region->start) {
/* We can coalesce, so do so. */
free_region.start = std::addressof(*prev_free_block_it);
insertion_it = head->free_list.erase(prev_free_block_it);
} else {
/* We can't coalesce, so just select the next iterator. */
insertion_it = (++prev_free_block_it);
}
}
/* Ensure region is big enough for a block. */
/* NOTE: Nintendo does not check against minimum block size here, only header size. */
/* We will check against minimum block size, to avoid the creation of zero-size blocks. */
if (GetPointerDifference(free_region.start, free_region.end) < sizeof(ExpHeapMemoryBlockHead) + MinimumFreeBlockSize) {
return false;
}
/* Fill the memory with a pattern, for debug. */
FillFreedMemory(GetHeapHead(head), free_region.start, GetPointerDifference(free_region.start, free_region.end));
/* Insert the new memory block. */
head->free_list.insert(insertion_it, *InitializeFreeMemoryBlock(free_region));
return true;
}
void *ConvertFreeBlockToUsedBlock(ExpHeapHead *head, ExpHeapMemoryBlockHead *block_head, void *block, size_t size, AllocationDirection direction) {
/* Calculate freed memory regions. */
MemoryRegion free_region_front;
GetMemoryBlockRegion(std::addressof(free_region_front), block_head);
MemoryRegion free_region_back{ .start = reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(block) + size), .end = free_region_front.end, };
/* Adjust end of head region. */
free_region_front.end = reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(block) - sizeof(ExpHeapMemoryBlockHead));
/* Remove the old block. */
auto old_block_it = head->free_list.erase(head->free_list.iterator_to(*block_head));
/* If the front margins are big enough (and we're allowed to do so), make a new block. */
if ((GetPointerDifference(free_region_front.start, free_region_front.end) < sizeof(ExpHeapMemoryBlockHead) + MinimumFreeBlockSize) ||
(direction == AllocationDirection_Front && !head->use_alignment_margins && GetPointerDifference(free_region_front.start, free_region_front.end) < MaximumPaddingalignment)) {
/* There isn't enough space for a new block, or else we're not allowed to make one. */
free_region_front.end = free_region_front.start;
} else {
/* Make a new block! */
head->free_list.insert(old_block_it, *InitializeFreeMemoryBlock(free_region_front));
}
/* If the back margins are big enough (and we're allowed to do so), make a new block. */
if ((GetPointerDifference(free_region_back.start, free_region_back.end) < sizeof(ExpHeapMemoryBlockHead) + MinimumFreeBlockSize) ||
(direction == AllocationDirection_Back && !head->use_alignment_margins && GetPointerDifference(free_region_back.start, free_region_back.end) < MaximumPaddingalignment)) {
/* There isn't enough space for a new block, or else we're not allowed to make one. */
free_region_back.end = free_region_back.start;
} else {
/* Make a new block! */
head->free_list.insert(old_block_it, *InitializeFreeMemoryBlock(free_region_back));
}
/* Fill the memory with a pattern, for debug. */
FillAllocatedMemory(GetHeapHead(head), free_region_front.end, GetPointerDifference(free_region_front.end, free_region_back.start));
{
/* Create the used block */
MemoryRegion used_region{ .start = reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(block) - sizeof(ExpHeapMemoryBlockHead)), .end = free_region_back.start };
ExpHeapMemoryBlockHead *used_block = InitializeUsedMemoryBlock(used_region);
/* Insert it into the used list. */
head->used_list.push_back(*used_block);
SetMemoryBlockAllocationDirection(used_block, direction);
SetMemoryBlockAlignmentPadding(used_block, static_cast<u16>(GetPointerDifference(free_region_front.end, used_block)));
SetMemoryBlockGroupId(used_block, head->group_id);
}
return block;
}
void *AllocateFromHead(HeapHead *heap, size_t size, s32 alignment) {
ExpHeapHead *exp_heap_head = GetExpHeapHead(heap);
const bool is_first_fit = GetAllocationModeImpl(exp_heap_head) == AllocationMode_FirstFit;
/* Choose a block. */
ExpHeapMemoryBlockHead *found_block_head = nullptr;
void *found_block = nullptr;
size_t best_size = std::numeric_limits<size_t>::max();
for (auto it = exp_heap_head->free_list.begin(); it != exp_heap_head->free_list.end(); it++) {
const uintptr_t absolute_block_start = reinterpret_cast<uintptr_t>(GetMemoryBlockStart(std::addressof(*it)));
const uintptr_t block_start = util::AlignUp(absolute_block_start, alignment);
const size_t block_offset = block_start - absolute_block_start;
if (it->block_size >= size + block_offset && best_size > it->block_size) {
found_block_head = std::addressof(*it);
found_block = reinterpret_cast<void *>(block_start);
best_size = it->block_size;
if (is_first_fit || best_size == size) {
break;
}
}
}
/* If we didn't find a block, return nullptr. */
if (found_block_head == nullptr) {
return nullptr;
}
return ConvertFreeBlockToUsedBlock(exp_heap_head, found_block_head, found_block, size, AllocationDirection_Front);
}
void *AllocateFromTail(HeapHead *heap, size_t size, s32 alignment) {
ExpHeapHead *exp_heap_head = GetExpHeapHead(heap);
const bool is_first_fit = GetAllocationModeImpl(exp_heap_head) == AllocationMode_FirstFit;
/* Choose a block. */
ExpHeapMemoryBlockHead *found_block_head = nullptr;
void *found_block = nullptr;
size_t best_size = std::numeric_limits<size_t>::max();
for (auto it = exp_heap_head->free_list.rbegin(); it != exp_heap_head->free_list.rend(); it++) {
const uintptr_t absolute_block_start = reinterpret_cast<uintptr_t>(GetMemoryBlockStart(std::addressof(*it)));
const uintptr_t block_start = util::AlignUp(absolute_block_start, alignment);
const size_t block_offset = block_start - absolute_block_start;
if (it->block_size >= size + block_offset && best_size > it->block_size) {
found_block_head = std::addressof(*it);
found_block = reinterpret_cast<void *>(block_start);
best_size = it->block_size;
if (is_first_fit || best_size == size) {
break;
}
}
}
/* If we didn't find a block, return nullptr. */
if (found_block_head == nullptr) {
return nullptr;
}
return ConvertFreeBlockToUsedBlock(exp_heap_head, found_block_head, found_block, size, AllocationDirection_Back);
}
}
HeapHandle CreateExpHeap(void *address, size_t size, u32 option) {
const uintptr_t uptr_end = util::AlignDown(reinterpret_cast<uintptr_t>(address) + size, MinimumAlignment);
const uintptr_t uptr_start = util::AlignUp(reinterpret_cast<uintptr_t>(address), MinimumAlignment);
if (uptr_start > uptr_end || GetPointerDifference(uptr_start, uptr_end) < sizeof(ExpHeapMemoryBlockHead) + MinimumFreeBlockSize) {
return nullptr;
}
return InitializeExpHeap(reinterpret_cast<void *>(uptr_start), reinterpret_cast<void *>(uptr_end), option);
}
void DestroyExpHeap(HeapHandle handle) {
AMS_ASSERT(IsValidHeapHandle(handle));
FinalizeHeap(handle);
}
MemoryRange AdjustExpHeap(HeapHandle handle) {
AMS_ASSERT(IsValidHeapHandle(handle));
HeapHead *heap_head = handle;
ExpHeapHead *exp_heap_head = GetExpHeapHead(heap_head);
/* If there's no free blocks, we can't do anything. */
if (exp_heap_head->free_list.empty()) {
return MakeMemoryRange(handle->heap_end, 0);
}
/* Get the memory block end, make sure it really is the last block. */
ExpHeapMemoryBlockHead *block = std::addressof(exp_heap_head->free_list.back());
void * const block_start = GetMemoryBlockStart(block);
const size_t block_size = block->block_size;
void * const block_end = reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(block_start) + block_size);
if (block_end != handle->heap_end) {
return MakeMemoryRange(handle->heap_end, 0);
}
/* Remove the memory block. */
exp_heap_head->free_list.pop_back();
const size_t freed_size = block_size + sizeof(ExpHeapMemoryBlockHead);
heap_head->heap_end = reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(heap_head->heap_end) - freed_size);
return MakeMemoryRange(heap_head->heap_end, freed_size);
}
void *AllocateFromExpHeap(HeapHandle handle, size_t size, s32 alignment) {
AMS_ASSERT(IsValidHeapHandle(handle));
/* Fix up alignments less than 4. */
if (alignment == 1 || alignment == 2) {
alignment = 4;
} else if (alignment == -1 || alignment == -2) {
alignment = -4;
}
/* Ensure the alignment is valid. */
const s32 abs_alignment = std::abs(alignment);
AMS_ASSERT((abs_alignment & (abs_alignment - 1)) == 0);
AMS_ASSERT(MinimumAlignment <= static_cast<size_t>(abs_alignment));
AMS_UNUSED(abs_alignment);
/* Fix size to be correctly aligned. */
if (size == 0) {
size = 1;
}
size = util::AlignUp(size, MinimumAlignment);
/* Allocate a memory block. */
void *allocated_memory = nullptr;
if (alignment >= 0) {
allocated_memory = AllocateFromHead(handle, size, alignment);
} else {
allocated_memory = AllocateFromTail(handle, size, -alignment);
}
return allocated_memory;
}
void FreeToExpHeap(HeapHandle handle, void *mem_block) {
/* Ensure this is actually a valid heap and a valid memory block we allocated. */
AMS_ASSERT(IsValidHeapHandle(handle));
AMS_ASSERT(IsValidUsedMemoryBlock(handle, mem_block));
/* TODO: Nintendo does not allow FreeToExpHeap(nullptr). Should we? */
/* Get block pointers. */
HeapHead *heap_head = handle;
ExpHeapHead *exp_heap_head = GetExpHeapHead(heap_head);
ExpHeapMemoryBlockHead *block = GetHeadForMemoryBlock(mem_block);
MemoryRegion region;
/* Erase the heap from the used list, and coalesce it with adjacent blocks. */
GetMemoryBlockRegion(std::addressof(region), block);
exp_heap_head->used_list.erase(exp_heap_head->used_list.iterator_to(*block));
/* Coalesce with adjacent blocks. */
const bool coalesced = CoalesceFreedRegion(exp_heap_head, std::addressof(region));
AMS_ASSERT(coalesced);
AMS_UNUSED(coalesced);
}
size_t ResizeExpHeapMemoryBlock(HeapHandle handle, void *mem_block, size_t size) {
/* Ensure this is actually a valid heap and a valid memory block we allocated. */
AMS_ASSERT(IsValidHeapHandle(handle));
AMS_ASSERT(IsValidUsedMemoryBlock(handle, mem_block));
ExpHeapHead *exp_heap_head = GetExpHeapHead(handle);
ExpHeapMemoryBlockHead *block_head = GetHeadForMemoryBlock(mem_block);
const size_t original_block_size = block_head->block_size;
/* It's possible that there's no actual resizing being done. */
size = util::AlignUp(size, MinimumAlignment);
if (size == original_block_size) {
return size;
}
/* We're resizing one way or the other. */
if (size > original_block_size) {
/* We want to try to make the block bigger. */
/* Find the free block after this one. */
void * const cur_block_end = GetMemoryBlockEnd(block_head);
ExpHeapMemoryBlockHead *next_block_head = nullptr;
for (auto it = exp_heap_head->free_list.begin(); it != exp_heap_head->free_list.end(); it++) {
if (std::addressof(*it) == cur_block_end) {
next_block_head = std::addressof(*it);
break;
}
}
/* If we can't get a big enough allocation using the next block, give up. */
if (next_block_head == nullptr || size > original_block_size + sizeof(ExpHeapMemoryBlockHead) + next_block_head->block_size) {
return 0;
}
/* Grow the block to encompass the next block. */
{
/* Get block region. */
MemoryRegion new_free_region;
GetMemoryBlockRegion(std::addressof(new_free_region), next_block_head);
/* Remove the next block from the free list. */
auto insertion_it = exp_heap_head->free_list.erase(exp_heap_head->free_list.iterator_to(*next_block_head));
/* Figure out the new block extents. */
void *old_start = new_free_region.start;
new_free_region.start = reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(mem_block) + size);
/* Only maintain the new free region as a memory block candidate if it can hold a header. */
/* NOTE: Nintendo does not check against minimum block size here, only header size. */
/* We will check against minimum block size, to avoid the creation of zero-size blocks. */
if (GetPointerDifference(new_free_region.start, new_free_region.end) < sizeof(ExpHeapMemoryBlockHead) + MinimumFreeBlockSize) {
new_free_region.start = new_free_region.end;
}
/* Adjust block sizes. */
block_head->block_size = GetPointerDifference(mem_block, new_free_region.start);
if (GetPointerDifference(new_free_region.start, new_free_region.end) >= sizeof(ExpHeapMemoryBlockHead) + MinimumFreeBlockSize) {
exp_heap_head->free_list.insert(insertion_it, *InitializeFreeMemoryBlock(new_free_region));
}
/* Fill the memory with a pattern, for debug. */
FillAllocatedMemory(GetHeapHead(exp_heap_head), old_start, GetPointerDifference(old_start, new_free_region.start));
}
} else {
/* We're shrinking the block. Nice and easy. */
MemoryRegion new_free_region{ .start = reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(mem_block)+ size), .end = GetMemoryBlockEnd(block_head) };
/* Try to free the new memory. */
block_head->block_size = size;
if (!CoalesceFreedRegion(exp_heap_head, std::addressof(new_free_region))) {
/* We didn't shrink the block successfully, so restore the size. */
block_head->block_size = original_block_size;
}
}
return block_head->block_size;
}
size_t GetExpHeapTotalFreeSize(HeapHandle handle) {
AMS_ASSERT(IsValidHeapHandle(handle));
size_t total_size = 0;
for (const auto &it : GetExpHeapHead(handle)->free_list) {
total_size += it.block_size;
}
return total_size;
}
size_t GetExpHeapAllocatableSize(HeapHandle handle, s32 alignment) {
AMS_ASSERT(IsValidHeapHandle(handle));
/* Ensure alignment is positive. */
alignment = std::abs(alignment);
size_t max_size = std::numeric_limits<size_t>::min();
size_t min_offset = std::numeric_limits<size_t>::max();
for (const auto &it : GetExpHeapHead(handle)->free_list) {
const uintptr_t absolute_block_start = reinterpret_cast<uintptr_t>(GetMemoryBlockStart(std::addressof(it)));
const uintptr_t block_start = util::AlignUp(absolute_block_start, alignment);
const uintptr_t block_end = reinterpret_cast<uintptr_t>(GetMemoryBlockEnd(std::addressof(it)));
if (block_start < block_end) {
const size_t block_size = GetPointerDifference(block_start, block_end);
const size_t offset = GetPointerDifference(absolute_block_start, block_start);
if (block_size > max_size || (block_size == max_size && offset < min_offset)) {
max_size = block_size;
min_offset = offset;
}
}
}
return max_size;
}
AllocationMode GetExpHeapAllocationMode(HeapHandle handle) {
AMS_ASSERT(IsValidHeapHandle(handle));
return GetAllocationModeImpl(GetExpHeapHead(handle));
}
AllocationMode SetExpHeapAllocationMode(HeapHandle handle, AllocationMode new_mode) {
AMS_ASSERT(IsValidHeapHandle(handle));
ExpHeapHead *exp_heap_head = GetExpHeapHead(handle);
const AllocationMode old_mode = GetAllocationModeImpl(exp_heap_head);
SetAllocationModeImpl(exp_heap_head, new_mode);
return old_mode;
}
u16 GetExpHeapGroupId(HeapHandle handle) {
AMS_ASSERT(IsValidHeapHandle(handle));
return GetExpHeapHead(handle)->group_id;
}
u16 SetExpHeapGroupId(HeapHandle handle, u16 group_id) {
AMS_ASSERT(IsValidHeapHandle(handle));
AMS_ASSERT(group_id <= MaxGroupId);
ExpHeapHead *exp_heap_head = GetExpHeapHead(handle);
const u16 old_group_id = exp_heap_head->group_id;
exp_heap_head->group_id = group_id;
return old_group_id;
}
void VisitExpHeapAllocatedBlocks(HeapHandle handle, HeapVisitor visitor, uintptr_t user_data) {
AMS_ASSERT(IsValidHeapHandle(handle));
for (auto &it : GetExpHeapHead(handle)->used_list) {
(*visitor)(GetMemoryBlockStart(std::addressof(it)), handle, user_data);
}
}
size_t GetExpHeapMemoryBlockSize(const void *memory_block) {
AMS_ASSERT(IsValidUsedMemoryBlock(nullptr, memory_block));
return GetHeadForMemoryBlock(memory_block)->block_size;
}
u16 GetExpHeapMemoryBlockGroupId(const void *memory_block) {
AMS_ASSERT(IsValidUsedMemoryBlock(nullptr, memory_block));
return GetMemoryBlockGroupId(GetHeadForMemoryBlock(memory_block));
}
AllocationDirection GetExpHeapMemoryBlockAllocationDirection(const void *memory_block) {
AMS_ASSERT(IsValidUsedMemoryBlock(nullptr, memory_block));
return GetMemoryBlockAllocationDirection(GetHeadForMemoryBlock(memory_block));
}
}
| 29,211
|
C++
|
.cpp
| 501
| 46.307385
| 189
| 0.624029
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,524
|
nim_network_install_manager_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/nim/nim_network_install_manager_api.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams::nim {
#if defined(ATMOSPHERE_OS_HORIZON)
namespace {
constinit bool g_initialized;
}
/* Management. */
void InitializeForNetworkInstallManager() {
AMS_ASSERT(!g_initialized);
R_ABORT_UNLESS(nimInitialize());
g_initialized = true;
}
void FinalizeForNetworkInstallManager() {
AMS_ASSERT(g_initialized);
nimExit();
g_initialized = false;
}
/* Service API. */
Result DestroySystemUpdateTask(const SystemUpdateTaskId &id) {
static_assert(sizeof(SystemUpdateTaskId) == sizeof(::NimSystemUpdateTaskId));
R_RETURN(nimDestroySystemUpdateTask(reinterpret_cast<const ::NimSystemUpdateTaskId *>(std::addressof(id))));
}
s32 ListSystemUpdateTask(SystemUpdateTaskId *out_list, size_t out_list_size) {
static_assert(sizeof(SystemUpdateTaskId) == sizeof(::NimSystemUpdateTaskId));
s32 count;
R_ABORT_UNLESS(nimListSystemUpdateTask(std::addressof(count), reinterpret_cast<::NimSystemUpdateTaskId *>(out_list), out_list_size));
return count;
}
#else
/* Management. */
void InitializeForNetworkInstallManager() {
AMS_ABORT("TODO: nim logic on non-libnx platform");
}
void FinalizeForNetworkInstallManager() {
AMS_ABORT("TODO: nim logic on non-libnx platform");
}
/* Service API. */
Result DestroySystemUpdateTask(const SystemUpdateTaskId &) {
AMS_ABORT("TODO: nim logic on non-libnx platform");
}
s32 ListSystemUpdateTask(SystemUpdateTaskId *, size_t) {
AMS_ABORT("TODO: nim logic on non-libnx platform");
}
#endif
}
| 2,326
|
C++
|
.cpp
| 60
| 33.366667
| 141
| 0.701155
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,525
|
mitm_pm_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/mitm/mitm_pm_api.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#if defined(ATMOSPHERE_OS_HORIZON)
#include "mitm_pm.os.horizon.h"
#endif
namespace ams::mitm::pm {
/* PM API. */
#if defined(ATMOSPHERE_OS_HORIZON)
void Initialize() {
R_ABORT_UNLESS(amsMitmPmInitialize());
}
void Finalize() {
amsMitmPmExit();
}
Result PrepareLaunchProgram(u64 *out, ncm::ProgramId program_id, const cfg::OverrideStatus &status, bool is_application) {
static_assert(sizeof(status) == sizeof(CfgOverrideStatus), "CfgOverrideStatus definition!");
R_RETURN(amsMitmPmPrepareLaunchProgram(out, program_id.value, reinterpret_cast<const CfgOverrideStatus *>(std::addressof(status)), is_application));
}
#endif
}
| 1,359
|
C++
|
.cpp
| 34
| 36.411765
| 156
| 0.731818
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,526
|
kvdb_archive.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/kvdb/kvdb_archive.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams::kvdb {
namespace {
/* Convenience definitions. */
constexpr u8 ArchiveHeaderMagic[4] = {'I', 'M', 'K', 'V'};
constexpr u8 ArchiveEntryMagic[4] = {'I', 'M', 'E', 'N'};
/* Archive types. */
struct ArchiveHeader {
u8 magic[sizeof(ArchiveHeaderMagic)];
u32 pad;
u32 entry_count;
Result Validate() const {
R_UNLESS(std::memcmp(this->magic, ArchiveHeaderMagic, sizeof(ArchiveHeaderMagic)) == 0, kvdb::ResultInvalidKeyValue());
R_SUCCEED();
}
static ArchiveHeader Make(size_t entry_count) {
ArchiveHeader header = {};
std::memcpy(header.magic, ArchiveHeaderMagic, sizeof(ArchiveHeaderMagic));
header.entry_count = static_cast<u32>(entry_count);
return header;
}
};
static_assert(sizeof(ArchiveHeader) == 0xC && util::is_pod<ArchiveHeader>::value, "ArchiveHeader definition!");
struct ArchiveEntryHeader {
u8 magic[sizeof(ArchiveEntryMagic)];
u32 key_size;
u32 value_size;
Result Validate() const {
R_UNLESS(std::memcmp(this->magic, ArchiveEntryMagic, sizeof(ArchiveEntryMagic)) == 0, kvdb::ResultInvalidKeyValue());
R_SUCCEED();
}
static ArchiveEntryHeader Make(size_t ksz, size_t vsz) {
ArchiveEntryHeader header = {};
std::memcpy(header.magic, ArchiveEntryMagic, sizeof(ArchiveEntryMagic));
header.key_size = ksz;
header.value_size = vsz;
return header;
}
};
static_assert(sizeof(ArchiveEntryHeader) == 0xC && util::is_pod<ArchiveEntryHeader>::value, "ArchiveEntryHeader definition!");
}
/* Reader functionality. */
Result ArchiveReader::Peek(void *dst, size_t size) {
/* Bounds check. */
R_UNLESS(m_offset + size <= m_buffer.GetSize(), kvdb::ResultInvalidKeyValue());
R_UNLESS(m_offset < m_offset + size, kvdb::ResultInvalidKeyValue());
std::memcpy(dst, m_buffer.Get() + m_offset, size);
R_SUCCEED();
}
Result ArchiveReader::Read(void *dst, size_t size) {
R_TRY(this->Peek(dst, size));
m_offset += size;
R_SUCCEED();
}
Result ArchiveReader::ReadEntryCount(size_t *out) {
/* This should only be called at the start of reading stream. */
AMS_ABORT_UNLESS(m_offset == 0);
/* Read and validate header. */
ArchiveHeader header;
R_TRY(this->Read(std::addressof(header), sizeof(header)));
R_TRY(header.Validate());
*out = header.entry_count;
R_SUCCEED();
}
Result ArchiveReader::GetEntrySize(size_t *out_key_size, size_t *out_value_size) {
/* This should only be called after ReadEntryCount. */
AMS_ABORT_UNLESS(m_offset != 0);
/* Peek the next entry header. */
ArchiveEntryHeader header;
R_TRY(this->Peek(std::addressof(header), sizeof(header)));
R_TRY(header.Validate());
*out_key_size = header.key_size;
*out_value_size = header.value_size;
R_SUCCEED();
}
Result ArchiveReader::ReadEntry(void *out_key, size_t key_size, void *out_value, size_t value_size) {
/* This should only be called after ReadEntryCount. */
AMS_ABORT_UNLESS(m_offset != 0);
/* Read the next entry header. */
ArchiveEntryHeader header;
R_TRY(this->Read(std::addressof(header), sizeof(header)));
R_TRY(header.Validate());
/* Key size and Value size must be correct. */
AMS_ABORT_UNLESS(key_size == header.key_size);
AMS_ABORT_UNLESS(value_size == header.value_size);
R_ABORT_UNLESS(this->Read(out_key, key_size));
R_ABORT_UNLESS(this->Read(out_value, value_size));
R_SUCCEED();
}
/* Writer functionality. */
Result ArchiveWriter::Write(const void *src, size_t size) {
/* Bounds check. */
R_UNLESS(m_offset + size <= m_buffer.GetSize(), kvdb::ResultInvalidKeyValue());
R_UNLESS(m_offset < m_offset + size, kvdb::ResultInvalidKeyValue());
std::memcpy(m_buffer.Get() + m_offset, src, size);
m_offset += size;
R_SUCCEED();
}
void ArchiveWriter::WriteHeader(size_t entry_count) {
/* This should only be called at start of write. */
AMS_ABORT_UNLESS(m_offset == 0);
ArchiveHeader header = ArchiveHeader::Make(entry_count);
R_ABORT_UNLESS(this->Write(std::addressof(header), sizeof(header)));
}
void ArchiveWriter::WriteEntry(const void *key, size_t key_size, const void *value, size_t value_size) {
/* This should only be called after writing header. */
AMS_ABORT_UNLESS(m_offset != 0);
ArchiveEntryHeader header = ArchiveEntryHeader::Make(key_size, value_size);
R_ABORT_UNLESS(this->Write(std::addressof(header), sizeof(header)));
R_ABORT_UNLESS(this->Write(key, key_size));
R_ABORT_UNLESS(this->Write(value, value_size));
}
/* Size helper functionality. */
ArchiveSizeHelper::ArchiveSizeHelper() : m_size(sizeof(ArchiveHeader)) {
/* ... */
}
void ArchiveSizeHelper::AddEntry(size_t key_size, size_t value_size) {
m_size += sizeof(ArchiveEntryHeader) + key_size + value_size;
}
}
| 6,165
|
C++
|
.cpp
| 135
| 36.955556
| 135
| 0.618103
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,527
|
kvdb_file_key_value_store.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/kvdb/kvdb_file_key_value_store.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams::kvdb {
/* Cache implementation. */
void *FileKeyValueStore::Cache::Allocate(size_t size) {
if (m_backing_buffer_size - m_backing_buffer_free_offset < size) {
return nullptr;
}
ON_SCOPE_EXIT { m_backing_buffer_free_offset += size; };
return m_backing_buffer + m_backing_buffer_free_offset;
}
Result FileKeyValueStore::Cache::Initialize(void *buffer, size_t buffer_size, size_t capacity) {
m_backing_buffer = static_cast<u8 *>(buffer);
m_backing_buffer_size = buffer_size;
m_backing_buffer_free_offset = 0;
m_entries = nullptr;
m_count = 0;
m_capacity = capacity;
/* If we have memory to work with, ensure it's at least enough for the cache entries. */
if (m_backing_buffer != nullptr) {
m_entries = static_cast<decltype(m_entries)>(this->Allocate(sizeof(*m_entries) * m_capacity));
R_UNLESS(m_entries != nullptr, kvdb::ResultBufferInsufficient());
}
R_SUCCEED();
}
void FileKeyValueStore::Cache::Invalidate() {
if (!this->HasEntries()) {
return;
}
/* Reset the allocation pool. */
m_backing_buffer_free_offset = 0;
m_count = 0;
m_entries = static_cast<decltype(m_entries)>(this->Allocate(sizeof(*m_entries) * m_capacity));
AMS_ABORT_UNLESS(m_entries != nullptr);
}
util::optional<size_t> FileKeyValueStore::Cache::TryGet(void *out_value, size_t max_out_size, const void *key, size_t key_size) {
if (!this->HasEntries()) {
return util::nullopt;
}
/* Try to find the entry. */
for (size_t i = 0; i < m_count; i++) {
const auto &entry = m_entries[i];
if (entry.key_size == key_size && std::memcmp(entry.key, key, key_size) == 0) {
/* If we don't have enough space, fail to read from cache. */
if (max_out_size < entry.value_size) {
return util::nullopt;
}
std::memcpy(out_value, entry.value, entry.value_size);
return entry.value_size;
}
}
return util::nullopt;
}
util::optional<size_t> FileKeyValueStore::Cache::TryGetSize(const void *key, size_t key_size) {
if (!this->HasEntries()) {
return util::nullopt;
}
/* Try to find the entry. */
for (size_t i = 0; i < m_count; i++) {
const auto &entry = m_entries[i];
if (entry.key_size == key_size && std::memcmp(entry.key, key, key_size) == 0) {
return entry.value_size;
}
}
return util::nullopt;
}
void FileKeyValueStore::Cache::Set(const void *key, size_t key_size, const void *value, size_t value_size) {
if (!this->HasEntries()) {
return;
}
/* Ensure key size is small enough. */
AMS_ABORT_UNLESS(key_size <= MaxKeySize);
/* If we're at capacity, invalidate the cache. */
if (m_count == m_capacity) {
this->Invalidate();
}
/* Allocate memory for the value. */
void *value_buf = this->Allocate(value_size);
if (value_buf == nullptr) {
/* We didn't have enough memory for the value. Invalidating might get us enough memory. */
this->Invalidate();
value_buf = this->Allocate(value_size);
if (value_buf == nullptr) {
/* If we still don't have enough memory, just fail to put the value in the cache. */
return;
}
}
auto &entry = m_entries[m_count++];
std::memcpy(entry.key, key, key_size);
entry.key_size = key_size;
entry.value = value_buf;
std::memcpy(entry.value, value, value_size);
entry.value_size = value_size;
}
bool FileKeyValueStore::Cache::Contains(const void *key, size_t key_size) {
return this->TryGetSize(key, key_size).has_value();
}
/* Store functionality. */
FileKeyValueStore::Path FileKeyValueStore::GetPath(const void *_key, size_t key_size) {
/* Format is "<dir>/<hex formatted key>.val" */
FileKeyValueStore::Path key_path(m_dir_path.Get());
key_path.Append('/');
/* Append hex formatted key. */
const u8 *key = static_cast<const u8 *>(_key);
for (size_t i = 0; i < key_size; i++) {
key_path.AppendFormat("%02x", key[i]);
}
/* Append extension. */
key_path.Append(FileExtension);
return key_path;
}
Result FileKeyValueStore::GetKey(size_t *out_size, void *_out_key, size_t max_out_size, const FileKeyValueStore::FileName &file_name) {
/* Validate that the filename can be converted to a key. */
/* TODO: Nintendo does not validate that the key is valid hex. Should we do this? */
const size_t file_name_len = file_name.GetLength();
const size_t key_name_len = file_name_len - FileExtensionLength;
R_UNLESS(file_name_len >= FileExtensionLength + 2, kvdb::ResultInvalidKeyValue());
R_UNLESS(file_name.EqualsPostfix(FileExtension), kvdb::ResultInvalidKeyValue());
R_UNLESS(util::IsAligned(key_name_len, 2), kvdb::ResultInvalidKeyValue());
/* Validate that we have space for the converted key. */
const size_t key_size = key_name_len / 2;
R_UNLESS(key_size <= max_out_size, kvdb::ResultBufferInsufficient());
/* Convert the hex key back. */
u8 *out_key = static_cast<u8 *>(_out_key);
for (size_t i = 0; i < key_size; i++) {
char substr[2 * sizeof(u8) + 1];
file_name.GetSubString(substr, sizeof(substr), 2 * i, sizeof(substr) - 1);
out_key[i] = static_cast<u8>(std::strtoul(substr, nullptr, 0x10));
}
*out_size = key_size;
R_SUCCEED();
}
Result FileKeyValueStore::Initialize(const char *dir) {
R_RETURN(this->InitializeWithCache(dir, nullptr, 0, 0));
}
Result FileKeyValueStore::InitializeWithCache(const char *dir, void *cache_buffer, size_t cache_buffer_size, size_t cache_capacity) {
/* Ensure that the passed path is a directory. */
fs::DirectoryEntryType entry_type;
R_TRY(fs::GetEntryType(std::addressof(entry_type), dir));
R_UNLESS(entry_type == fs::DirectoryEntryType_Directory, fs::ResultPathNotFound());
/* Set path. */
m_dir_path.Assign(dir);
/* Initialize our cache. */
R_TRY(m_cache.Initialize(cache_buffer, cache_buffer_size, cache_capacity));
R_SUCCEED();
}
Result FileKeyValueStore::Get(size_t *out_size, void *out_value, size_t max_out_size, const void *key, size_t key_size) {
std::scoped_lock lk(m_lock);
/* Ensure key size is small enough. */
R_UNLESS(key_size <= MaxKeySize, kvdb::ResultOutOfKeyResource());
/* Try to get from cache. */
{
auto size = m_cache.TryGet(out_value, max_out_size, key, key_size);
if (size) {
*out_size = *size;
R_SUCCEED();
}
}
/* Open the value file. */
fs::FileHandle file;
R_TRY_CATCH(fs::OpenFile(std::addressof(file), this->GetPath(key, key_size), fs::OpenMode_Read)) {
R_CONVERT(fs::ResultPathNotFound, kvdb::ResultKeyNotFound());
} R_END_TRY_CATCH;
ON_SCOPE_EXIT { fs::CloseFile(file); };
/* Get the value size. */
s64 file_size;
R_TRY(fs::GetFileSize(std::addressof(file_size), file));
/* Ensure there's enough space for the value. */
R_UNLESS(file_size <= static_cast<s64>(max_out_size), kvdb::ResultBufferInsufficient());
/* Read the value. */
const size_t value_size = static_cast<size_t>(file_size);
R_TRY(fs::ReadFile(file, 0, out_value, value_size));
*out_size = value_size;
/* Cache the newly read value. */
m_cache.Set(key, key_size, out_value, value_size);
R_SUCCEED();
}
Result FileKeyValueStore::GetSize(size_t *out_size, const void *key, size_t key_size) {
std::scoped_lock lk(m_lock);
/* Ensure key size is small enough. */
R_UNLESS(key_size <= MaxKeySize, kvdb::ResultOutOfKeyResource());
/* Try to get from cache. */
{
auto size = m_cache.TryGetSize(key, key_size);
if (size) {
*out_size = *size;
R_SUCCEED();
}
}
/* Open the value file. */
fs::FileHandle file;
R_TRY_CATCH(fs::OpenFile(std::addressof(file), this->GetPath(key, key_size), fs::OpenMode_Read)) {
R_CONVERT(fs::ResultPathNotFound, kvdb::ResultKeyNotFound());
} R_END_TRY_CATCH;
ON_SCOPE_EXIT { fs::CloseFile(file); };
/* Get the value size. */
s64 file_size;
R_TRY(fs::GetFileSize(std::addressof(file_size), file));
*out_size = static_cast<size_t>(file_size);
R_SUCCEED();
}
Result FileKeyValueStore::Set(const void *key, size_t key_size, const void *value, size_t value_size) {
std::scoped_lock lk(m_lock);
/* Ensure key size is small enough. */
R_UNLESS(key_size <= MaxKeySize, kvdb::ResultOutOfKeyResource());
/* When the cache contains the key being set, Nintendo invalidates the cache. */
if (m_cache.Contains(key, key_size)) {
m_cache.Invalidate();
}
/* Delete the file, if it exists. Don't check result, since it's okay if it's already deleted. */
auto key_path = this->GetPath(key, key_size);
fs::DeleteFile(key_path);
/* Create the new value file. */
R_TRY(fs::CreateFile(key_path, value_size));
/* Open the value file. */
fs::FileHandle file;
R_TRY(fs::OpenFile(std::addressof(file), key_path, fs::OpenMode_Write));
ON_SCOPE_EXIT { fs::CloseFile(file); };
/* Write the value file and flush. */
R_TRY(fs::WriteFile(file, 0, value, value_size, fs::WriteOption::Flush));
R_SUCCEED();
}
Result FileKeyValueStore::Remove(const void *key, size_t key_size) {
std::scoped_lock lk(m_lock);
/* Ensure key size is small enough. */
R_UNLESS(key_size <= MaxKeySize, kvdb::ResultOutOfKeyResource());
/* When the cache contains the key being set, Nintendo invalidates the cache. */
if (m_cache.Contains(key, key_size)) {
m_cache.Invalidate();
}
/* Remove the file. */
R_TRY_CATCH(fs::DeleteFile(this->GetPath(key, key_size))) {
R_CONVERT(fs::ResultPathNotFound, kvdb::ResultKeyNotFound())
} R_END_TRY_CATCH;
R_SUCCEED();
}
}
| 11,543
|
C++
|
.cpp
| 251
| 36.808765
| 139
| 0.594231
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,528
|
time_standard_network_system_clock.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/time/time_standard_network_system_clock.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams::time {
Result StandardNetworkSystemClock::GetCurrentTime(PosixTime *out) {
#if defined(ATMOSPHERE_OS_HORIZON)
static_assert(sizeof(*out) == sizeof(u64));
R_RETURN(::timeGetCurrentTime(::TimeType_NetworkSystemClock, reinterpret_cast<u64 *>(out)));
#else
AMS_UNUSED(out);
AMS_ABORT("TODO");
#endif
}
StandardNetworkSystemClock::time_point StandardNetworkSystemClock::now() {
PosixTime posix_time = {};
if (R_FAILED(GetCurrentTime(std::addressof(posix_time)))) {
posix_time.value = 0;
}
return time_point(duration(posix_time.value));
}
std::time_t StandardNetworkSystemClock::to_time_t(const StandardNetworkSystemClock::time_point &t) {
return static_cast<std::time_t>(std::chrono::duration_cast<std::chrono::seconds>(t.time_since_epoch()).count());
}
StandardNetworkSystemClock::time_point StandardNetworkSystemClock::from_time_t(std::time_t t) {
return time_point(duration(t));
}
/* TODO: Result StandardNetworkSystemClock::GetSystemClockContext(SystemClockContext *out); */
}
| 1,814
|
C++
|
.cpp
| 41
| 39
| 120
| 0.708215
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,529
|
time_calendar_time.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/time/time_calendar_time.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams::time {
bool CalendarTime::IsValid() const {
return time::IsValidDate(this->year, this->month, this->day);
}
CalendarTime &CalendarTime::operator+=(const TimeSpan &ts) {
*this = ToCalendarTimeInUtc(ToPosixTimeFromUtc(*this) + ts);
return *this;
}
CalendarTime &CalendarTime::operator-=(const TimeSpan &ts) {
*this = ToCalendarTimeInUtc(ToPosixTimeFromUtc(*this) - ts);
return *this;
}
CalendarTime operator+(const CalendarTime &lhs, const TimeSpan &rhs) {
return ToCalendarTimeInUtc(ToPosixTimeFromUtc(lhs) + rhs);
}
CalendarTime operator-(const CalendarTime &lhs, const TimeSpan &rhs) {
return ToCalendarTimeInUtc(ToPosixTimeFromUtc(lhs) - rhs);
}
TimeSpan operator-(const CalendarTime &lhs, const CalendarTime &rhs) {
return ToPosixTimeFromUtc(lhs) - ToPosixTimeFromUtc(rhs);
}
}
| 1,579
|
C++
|
.cpp
| 38
| 37.026316
| 76
| 0.718852
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,530
|
time_standard_steady_clock.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/time/time_standard_steady_clock.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams::time {
Result GetStandardSteadyClockCurrentTimePoint(SteadyClockTimePoint *out) {
#if defined(ATMOSPHERE_OS_HORIZON)
static_assert(sizeof(*out) == sizeof(::TimeSteadyClockTimePoint));
R_RETURN(::timeGetStandardSteadyClockTimePoint(reinterpret_cast<::TimeSteadyClockTimePoint *>(out)));
#else
AMS_UNUSED(out);
AMS_ABORT("TODO");
#endif
}
TimeSpan GetStandardSteadyClockInternalOffset() {
TimeSpanType offset;
#if defined(ATMOSPHERE_OS_HORIZON)
static_assert(sizeof(TimeSpanType) == sizeof(s64));
R_ABORT_UNLESS(::timeGetStandardSteadyClockInternalOffset(reinterpret_cast<s64 *>(std::addressof(offset))));
#else
AMS_UNUSED(offset);
AMS_ABORT("TODO");
#endif
return offset;
}
Result StandardSteadyClock::GetCurrentTimePoint(SteadyClockTimePoint *out) {
R_RETURN(GetStandardSteadyClockCurrentTimePoint(out));
}
StandardSteadyClock::time_point StandardSteadyClock::now() {
SteadyClockTimePoint steady_clock_time_point = {0, util::InvalidUuid};
if (R_FAILED(StandardSteadyClock::GetCurrentTimePoint(std::addressof(steady_clock_time_point)))) {
steady_clock_time_point.value = 0;
steady_clock_time_point.source_id = util::InvalidUuid;
}
return StandardSteadyClock::time_point(StandardSteadyClock::duration(steady_clock_time_point.value));
}
}
| 2,151
|
C++
|
.cpp
| 49
| 37.857143
| 116
| 0.711897
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,531
|
time_timezone_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/time/time_timezone_api.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams::time {
CalendarTime ToCalendarTimeInUtc(const PosixTime &posix_time) {
return impl::util::ToCalendarTimeInUtc(posix_time);
}
PosixTime ToPosixTimeFromUtc(const CalendarTime &calendar_time) {
return impl::util::ToPosixTimeFromUtc(calendar_time);
}
}
| 963
|
C++
|
.cpp
| 24
| 37.041667
| 76
| 0.751872
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,532
|
time_standard_user_system_clock.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/time/time_standard_user_system_clock.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams::time {
Result StandardUserSystemClock::GetCurrentTime(PosixTime *out) {
#if defined(ATMOSPHERE_OS_HORIZON)
static_assert(sizeof(*out) == sizeof(u64));
R_RETURN(::timeGetCurrentTime(::TimeType_UserSystemClock, reinterpret_cast<u64 *>(out)));
#else
AMS_UNUSED(out);
AMS_ABORT("TODO");
#endif
}
StandardUserSystemClock::time_point StandardUserSystemClock::now() {
PosixTime posix_time = {};
if (R_FAILED(GetCurrentTime(std::addressof(posix_time)))) {
posix_time.value = 0;
}
return time_point(duration(posix_time.value));
}
std::time_t StandardUserSystemClock::to_time_t(const StandardUserSystemClock::time_point &t) {
return static_cast<std::time_t>(std::chrono::duration_cast<std::chrono::seconds>(t.time_since_epoch()).count());
}
StandardUserSystemClock::time_point StandardUserSystemClock::from_time_t(std::time_t t) {
return time_point(duration(t));
}
/* TODO: Result StandardUserSystemClock::GetSystemClockContext(SystemClockContext *out); */
}
| 1,787
|
C++
|
.cpp
| 41
| 38.341463
| 120
| 0.703682
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,533
|
time_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/time/time_api.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#if defined(ATMOSPHERE_OS_HORIZON)
extern "C" {
extern TimeServiceType __nx_time_service_type;
}
#endif
namespace ams::time {
namespace {
enum InitializeMode {
InitializeMode_None,
InitializeMode_Normal,
InitializeMode_Menu,
InitializeMode_System,
InitializeMode_Repair,
InitializeMode_SystemUser,
};
constinit u32 g_initialize_count = 0;
constinit InitializeMode g_initialize_mode = InitializeMode_None;
constinit os::SdkMutex g_initialize_mutex;
Result InitializeImpl(InitializeMode mode) {
std::scoped_lock lk(g_initialize_mutex);
if (g_initialize_count > 0) {
AMS_ABORT_UNLESS(mode == g_initialize_mode);
g_initialize_count++;
R_SUCCEED();
}
#if defined(ATMOSPHERE_OS_HORIZON)
switch (mode) {
case InitializeMode_Normal: __nx_time_service_type = ::TimeServiceType_User; break;
case InitializeMode_Menu: __nx_time_service_type = ::TimeServiceType_Menu; break;
case InitializeMode_System: __nx_time_service_type = ::TimeServiceType_System; break;
case InitializeMode_Repair: __nx_time_service_type = ::TimeServiceType_Repair; break;
case InitializeMode_SystemUser: __nx_time_service_type = ::TimeServiceType_SystemUser; break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
R_TRY(::timeInitialize());
#else
// TODO: Real AMS_ABORT("TODO");
#endif
g_initialize_count++;
g_initialize_mode = mode;
R_SUCCEED();
}
}
Result Initialize() {
R_RETURN(InitializeImpl(InitializeMode_Normal));
}
Result InitializeForSystem() {
R_RETURN(InitializeImpl(InitializeMode_System));
}
Result InitializeForSystemUser() {
if (hos::GetVersion() >= hos::Version_9_0_0) {
R_RETURN(InitializeImpl(InitializeMode_SystemUser));
} else {
R_RETURN(InitializeImpl(InitializeMode_Normal));
}
}
Result Finalize() {
std::scoped_lock lk(g_initialize_mutex);
if (g_initialize_count > 0) {
if ((--g_initialize_count) == 0) {
#if defined(ATMOSPHERE_OS_HORIZON)
::timeExit();
#else
// TODO: Real AMS_ABORT("TODO");
#endif
g_initialize_mode = InitializeMode_None;
}
}
R_SUCCEED();
}
bool IsInitialized() {
std::scoped_lock lk(g_initialize_mutex);
return g_initialize_count > 0;
}
bool IsValidDate(int year, int month, int day) {
return impl::util::IsValidDate(year, month, day);
}
Result GetElapsedSecondsBetween(s64 *out, const SteadyClockTimePoint &from, const SteadyClockTimePoint &to) {
R_RETURN(impl::util::GetSpanBetween(out, from, to));
}
}
| 3,769
|
C++
|
.cpp
| 97
| 29.783505
| 113
| 0.608719
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,534
|
time_impl_util_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/time/impl/util/time_impl_util_api.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams::time::impl::util {
namespace {
constexpr inline const int DaysPerMonth[12] = {
31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};
static_assert(std::accumulate(std::begin(DaysPerMonth), std::end(DaysPerMonth), 0) == 365);
constexpr inline const std::array<int, 12> SumDaysPerMonth = [] {
std::array<int, 12> days = {};
for (size_t i = 1; i < days.size(); ++i) {
days[i] = days[i - 1] + DaysPerMonth[i - 1];
}
return days;
}();
static_assert(SumDaysPerMonth[ 0] == 0);
static_assert(SumDaysPerMonth[11] + DaysPerMonth[11] == 365);
constexpr bool IsLeapYearImpl(int year) {
if ((year % 400) == 0) {
return true;
} else if ((year % 100) == 0) {
return false;
} else if ((year % 4) == 0) {
return true;
} else {
return false;
}
}
constexpr int DateToDaysImpl(int year, int month, int day) {
/* Lightly validate input. */
AMS_ASSERT(year > 0);
AMS_ASSERT(month > 0);
AMS_ASSERT(day > 0);
/* Adjust months within range. */
year += month / 12;
month %= 12;
if (month == 0) {
month = 12;
}
AMS_ASSERT(1 <= month && month <= 12);
/* Calculate days. */
int res = (year - 1) * 365;
res += (year / 4) - (year / 100) + (year / 400);
res += SumDaysPerMonth[month - 1] + day;
/* Subtract leap day, if it hasn't happened yet. */
if (month < 3 && IsLeapYearImpl(year)) {
res -= 1;
}
/* Subtract the current day. */
res -= 1;
return res;
}
constexpr void DaysToDateImpl(int *out_year, int *out_month, int *out_day, int days) {
/* Lightly validate input. */
AMS_ASSERT(days > 0);
/* Declare unit conversion factors. */
constexpr int DaysPerYear = 365;
constexpr int DaysPerFourYears = DaysPerYear * 4 + 1;
constexpr int DaysPerCentury = DaysPerFourYears * 25 - 1;
constexpr int DaysPerFourCenturies = DaysPerCentury * 4 + 1;
/* Adjust date. */
days -= 59;
days += 365;
/* Determine various units. */
int four_centuries = days / DaysPerFourCenturies;
int four_centuries_rem = days % DaysPerFourCenturies;
if (four_centuries_rem < 0) {
four_centuries_rem += DaysPerFourCenturies;
--four_centuries;
}
int centuries = four_centuries_rem / DaysPerCentury;
int centuries_rem = four_centuries_rem % DaysPerCentury;
int four_years = centuries_rem / DaysPerFourYears;
int four_years_rem = centuries_rem % DaysPerFourYears;
int years = four_years_rem / DaysPerYear;
int years_rem = four_years_rem % DaysPerYear;
/* Adjust into range. */
int year = 400 * four_centuries + 100 * centuries + 4 * four_years + years;
int month = (5 * years_rem + 2) / 153;
int day = years_rem - (153 * month + 2) / 5 + 1;
/* Adjust in case we fell into a pathological case. */
if (years == 4 || centuries == 4) {
month = 11;
day = 29;
year -= 1;
}
/* Adjust month. */
if (month <= 9) {
month += 3;
} else {
month -= 9;
year += 1;
}
/* Set output. */
if (out_year) {
*out_year = year;
}
if (out_month) {
*out_month = month;
}
if (out_day) {
*out_day = day;
}
}
constexpr inline int EpochDays = DateToDaysImpl(1970, 1, 1);
static_assert([]() -> bool {
int year{}, month{}, day{};
DaysToDateImpl(std::addressof(year), std::addressof(month), std::addressof(day), EpochDays);
return year == 1970 && month == 1 && day == 1;
}());
}
Result GetSpanBetween(s64 *out, const SteadyClockTimePoint &from, const SteadyClockTimePoint &to) {
AMS_ASSERT(out != nullptr);
R_UNLESS(out != nullptr, time::ResultInvalidPointer());
R_UNLESS(from.source_id == to.source_id, time::ResultNotComparable());
R_UNLESS(ams::util::TrySubtractWithoutOverflow(out, to.value, from.value), time::ResultOverflowed());
R_SUCCEED();
}
bool IsValidDate(int year, int month, int day) {
return 1 <= year && 1 <= month && month <= 12 && 1 <= day && day <= GetDaysInMonth(year, month);
}
bool IsLeapYear(int year) {
AMS_ASSERT(year > 0);
return IsLeapYearImpl(year);
}
int GetDaysInMonth(int year, int month) {
/* Check pre-conditions. */
AMS_ASSERT(year > 0);
AMS_ASSERT(1 <= month && month <= 12);
if (month == 2 && IsLeapYear(year)) {
return DaysPerMonth[month - 1] + 1;
} else {
return DaysPerMonth[month - 1];
}
}
int DateToDays(int year, int month, int day) {
return DateToDaysImpl(year, month, day);
}
void DaysToDate(int *out_year, int *out_month, int *out_day, int days) {
DaysToDateImpl(out_year, out_month, out_day, days);
}
CalendarTime ToCalendarTimeInUtc(const PosixTime &posix_time) {
constexpr s64 SecondsPerDay = TimeSpan::FromDays(1).GetSeconds();
constexpr s64 SecondsPerHour = TimeSpan::FromHours(1).GetSeconds();
constexpr s64 SecondsPerMinute = TimeSpan::FromMinutes(1).GetSeconds();
/* Get year/month/day. */
int year, month, day;
DaysToDate(std::addressof(year), std::addressof(month), std::addressof(day), static_cast<int>(posix_time.value / SecondsPerDay) + EpochDays);
/* Handle negative posix times. */
s64 posix_abs = posix_time.value >= 0 ? posix_time.value : -1 * posix_time.value;
s64 posix_rem = posix_abs % SecondsPerDay;
if (posix_time.value < 0) {
posix_rem *= -1;
}
/* Adjust remainder if negative. */
if (posix_rem < 0) {
if ((--day) <= 0) {
if ((--month) <= 0) {
--year;
month = 12;
}
day = time::impl::util::GetDaysInMonth(year, month);
}
posix_rem += SecondsPerDay;
}
const int hour = posix_rem / SecondsPerHour;
posix_rem %= SecondsPerHour;
const int minute = posix_rem / SecondsPerMinute;
posix_rem %= SecondsPerMinute;
const int second = posix_rem;
return CalendarTime {
.year = static_cast<s16>(year),
.month = static_cast<s8>(month),
.day = static_cast<s8>(day),
.hour = static_cast<s8>(hour),
.minute = static_cast<s8>(minute),
.second = static_cast<s8>(second),
};
}
PosixTime ToPosixTimeFromUtc(const CalendarTime &calendar_time) {
/* Validate pre-conditions. */
AMS_ASSERT(IsValidDate(calendar_time.year, calendar_time.month, calendar_time.day));
AMS_ASSERT(0 <= calendar_time.hour && calendar_time.hour <= 23);
AMS_ASSERT(0 <= calendar_time.minute && calendar_time.minute <= 59);
AMS_ASSERT(0 <= calendar_time.second && calendar_time.second <= 59);
/* Extract/convert fields. */
const s64 days = static_cast<s64>(time::impl::util::DateToDays(calendar_time.year, calendar_time.month, calendar_time.day)) - EpochDays;
const s64 hours = calendar_time.hour;
const s64 minutes = calendar_time.minute;
const s64 seconds = calendar_time.second;
return PosixTime { .value = ((((days * 24) + hours) * 60) + minutes) * 60 + seconds };
}
}
| 8,953
|
C++
|
.cpp
| 207
| 32.434783
| 149
| 0.541283
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,535
|
gpio_remote_manager_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/gpio/gpio_remote_manager_impl.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "gpio_remote_manager_impl.hpp"
namespace ams::gpio {
#if defined(ATMOSPHERE_OS_HORIZON)
namespace {
struct GpioRemoteManagerTag;
using RemoteAllocator = ams::sf::ExpHeapStaticAllocator<3_KB, GpioRemoteManagerTag>;
using RemoteObjectFactory = ams::sf::ObjectFactory<typename RemoteAllocator::Policy>;
class StaticAllocatorInitializer {
public:
StaticAllocatorInitializer() {
RemoteAllocator::Initialize(lmem::CreateOption_None);
}
} g_static_allocator_initializer;
}
Result RemoteManagerImpl::OpenSession(ams::sf::Out<ams::sf::SharedPointer<gpio::sf::IPadSession>> out, gpio::GpioPadName pad_name) {
::GpioPadSession p;
R_TRY(::gpioOpenSession(std::addressof(p), static_cast<::GpioPadName>(static_cast<u32>(pad_name))));
out.SetValue(RemoteObjectFactory::CreateSharedEmplaced<gpio::sf::IPadSession, RemotePadSessionImpl>(p));
R_SUCCEED();
}
Result RemoteManagerImpl::OpenSession2(ams::sf::Out<ams::sf::SharedPointer<gpio::sf::IPadSession>> out, DeviceCode device_code, ddsf::AccessMode access_mode) {
::GpioPadSession p;
R_TRY(::gpioOpenSession2(std::addressof(p), device_code.GetInternalValue(), access_mode));
out.SetValue(RemoteObjectFactory::CreateSharedEmplaced<gpio::sf::IPadSession, RemotePadSessionImpl>(p));
R_SUCCEED();
}
#endif
}
| 2,126
|
C++
|
.cpp
| 44
| 42.227273
| 163
| 0.710907
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,536
|
gpio_client_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/gpio/gpio_client_api.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "gpio_remote_manager_impl.hpp"
namespace ams::gpio {
namespace {
constinit os::SdkMutex g_init_mutex;
constinit int g_initialize_count = 0;
ams::sf::SharedPointer<gpio::sf::IManager> g_manager;
#if defined(ATMOSPHERE_OS_HORIZON)
constinit bool g_remote = false;
ams::sf::UnmanagedServiceObject<gpio::sf::IManager, RemoteManagerImpl> g_remote_manager_impl;
#endif
gpio::sf::IPadSession *GetInterface(GpioPadSession *session) {
AMS_ASSERT(session->_session != nullptr);
return static_cast<gpio::sf::IPadSession *>(session->_session);
}
}
void Initialize() {
std::scoped_lock lk(g_init_mutex);
if ((g_initialize_count++) == 0) {
#if defined(ATMOSPHERE_OS_HORIZON)
R_ABORT_UNLESS(::gpioInitialize());
g_manager = g_remote_manager_impl.GetShared();
g_remote = true;
#else
AMS_ABORT("TODO");
#endif
}
}
void InitializeWith(ams::sf::SharedPointer<gpio::sf::IManager> manager) {
std::scoped_lock lk(g_init_mutex);
AMS_ABORT_UNLESS(g_initialize_count == 0);
g_manager = manager;
g_initialize_count = 1;
}
void Finalize() {
std::scoped_lock lk(g_init_mutex);
AMS_ASSERT(g_initialize_count > 0);
if ((--g_initialize_count) == 0) {
g_manager = nullptr;
#if defined(ATMOSPHERE_OS_HORIZON)
if (g_remote) {
::gpioExit();
}
#else
AMS_ABORT("TODO");
#endif
}
}
Result OpenSession(GpioPadSession *out_session, ams::DeviceCode device_code) {
/* Get the session. */
ams::sf::SharedPointer<gpio::sf::IPadSession> session;
{
if (hos::GetVersion() >= hos::Version_7_0_0) {
R_TRY(g_manager->OpenSession2(std::addressof(session), device_code, ddsf::AccessMode_ReadWrite));
} else {
R_TRY(g_manager->OpenSession(std::addressof(session), ConvertToGpioPadName(device_code)));
}
}
/* Set output. */
out_session->_session = session.Detach();
out_session->_event = nullptr;
/* We succeeded. */
R_SUCCEED();
}
void CloseSession(GpioPadSession *session) {
AMS_ASSERT(session != nullptr);
/* Unbind the interrupt, if it's still bound. */
if (session->_event != nullptr) {
gpio::UnbindInterrupt(session);
}
/* Close the session. */
ams::sf::ReleaseSharedObject(GetInterface(session));
session->_session = nullptr;
}
Result IsWakeEventActive(bool *out_is_active, ams::DeviceCode device_code) {
if (hos::GetVersion() >= hos::Version_7_0_0) {
R_TRY(g_manager->IsWakeEventActive2(out_is_active, device_code));
} else {
R_TRY(g_manager->IsWakeEventActive(out_is_active, ConvertToGpioPadName(device_code)));
}
R_SUCCEED();
}
Direction GetDirection(GpioPadSession *session) {
Direction out;
R_ABORT_UNLESS(GetInterface(session)->GetDirection(std::addressof(out)));
return out;
}
void SetDirection(GpioPadSession *session, Direction direction) {
R_ABORT_UNLESS(GetInterface(session)->SetDirection(direction));
}
GpioValue GetValue(GpioPadSession *session) {
GpioValue out;
R_ABORT_UNLESS(GetInterface(session)->GetValue(std::addressof(out)));
return out;
}
void SetValue(GpioPadSession *session, GpioValue value) {
R_ABORT_UNLESS(GetInterface(session)->SetValue(value));
}
InterruptMode GetInterruptMode(GpioPadSession *session) {
InterruptMode out;
R_ABORT_UNLESS(GetInterface(session)->GetInterruptMode(std::addressof(out)));
return out;
}
void SetInterruptMode(GpioPadSession *session, InterruptMode mode) {
R_ABORT_UNLESS(GetInterface(session)->SetInterruptMode(mode));
}
bool GetInterruptEnable(GpioPadSession *session) {
bool out;
R_ABORT_UNLESS(GetInterface(session)->GetInterruptEnable(std::addressof(out)));
return out;
}
void SetInterruptEnable(GpioPadSession *session, bool en) {
R_ABORT_UNLESS(GetInterface(session)->SetInterruptEnable(en));
}
InterruptStatus GetInterruptStatus(GpioPadSession *session) {
InterruptStatus out;
R_ABORT_UNLESS(GetInterface(session)->GetInterruptStatus(std::addressof(out)));
return out;
}
void ClearInterruptStatus(GpioPadSession *session) {
R_ABORT_UNLESS(GetInterface(session)->ClearInterruptStatus());
}
int GetDebounceTime(GpioPadSession *session) {
int out;
R_ABORT_UNLESS(GetInterface(session)->GetDebounceTime(std::addressof(out)));
return out;
}
void SetDebounceTime(GpioPadSession *session, int ms) {
R_ABORT_UNLESS(GetInterface(session)->SetDebounceTime(ms));
}
bool GetDebounceEnabled(GpioPadSession *session) {
bool out;
R_ABORT_UNLESS(GetInterface(session)->GetDebounceEnabled(std::addressof(out)));
return out;
}
void SetDebounceEnabled(GpioPadSession *session, bool en) {
R_ABORT_UNLESS(GetInterface(session)->SetDebounceEnabled(en));
}
Result BindInterrupt(os::SystemEventType *event, GpioPadSession *session) {
AMS_ASSERT(session->_event == nullptr);
ams::sf::NativeHandle handle;
R_TRY(GetInterface(session)->BindInterrupt(std::addressof(handle)));
os::AttachReadableHandleToSystemEvent(event, handle.GetOsHandle(), handle.IsManaged(), os::EventClearMode_ManualClear);
handle.Detach();
session->_event = event;
R_SUCCEED();
}
void UnbindInterrupt(GpioPadSession *session) {
AMS_ASSERT(session->_event != nullptr);
R_ABORT_UNLESS(GetInterface(session)->UnbindInterrupt());
os::DestroySystemEvent(session->_event);
session->_event = nullptr;
}
}
| 6,810
|
C++
|
.cpp
| 169
| 32.278107
| 127
| 0.644839
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,537
|
gpio_driver_service_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/gpio/driver/gpio_driver_service_api.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "impl/gpio_driver_core.hpp"
namespace ams::gpio::driver {
void RegisterDriver(IGpioDriver *driver) {
return impl::RegisterDriver(driver);
}
void UnregisterDriver(IGpioDriver *driver) {
return impl::UnregisterDriver(driver);
}
Result RegisterDeviceCode(DeviceCode device_code, Pad *pad) {
R_RETURN(impl::RegisterDeviceCode(device_code, pad));
}
bool UnregisterDeviceCode(DeviceCode device_code) {
return impl::UnregisterDeviceCode(device_code);
}
void RegisterInterruptHandler(ddsf::IEventHandler *handler) {
return impl::RegisterInterruptHandler(handler);
}
void UnregisterInterruptHandler(ddsf::IEventHandler *handler) {
return impl::UnregisterInterruptHandler(handler);
}
void SetInitialGpioConfig() {
#if defined(ATMOSPHERE_BOARD_NINTENDO_NX)
return board::SetInitialGpioConfig();
#endif
}
void SetInitialWakePinConfig() {
#if defined(ATMOSPHERE_BOARD_NINTENDO_NX)
return board::SetInitialWakePinConfig();
#endif
}
}
| 1,763
|
C++
|
.cpp
| 47
| 32.574468
| 76
| 0.72434
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,538
|
gpio_driver_client_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/gpio/driver/gpio_driver_client_api.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "impl/gpio_driver_core.hpp"
namespace ams::gpio::driver {
void Initialize() {
return impl::InitializeDrivers();
}
void Finalize() {
return impl::FinalizeDrivers();
}
}
| 877
|
C++
|
.cpp
| 25
| 32.04
| 76
| 0.730815
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,539
|
gpio_pad_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/gpio/driver/gpio_pad_api.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "impl/gpio_driver_core.hpp"
namespace ams::gpio::driver {
namespace {
Result OpenSessionImpl(GpioPadSession *out, Pad *pad, ddsf::AccessMode access_mode) {
/* Construct the session. */
auto *session = std::construct_at(std::addressof(impl::GetPadSessionImpl(*out)));
auto session_guard = SCOPE_GUARD { std::destroy_at(session); };
/* Open the session. */
R_TRY(session->Open(pad, access_mode));
session_guard.Cancel();
R_SUCCEED();
}
}
Result OpenSession(GpioPadSession *out, DeviceCode device_code, ddsf::AccessMode access_mode) {
/* Find the pad. */
Pad *pad = nullptr;
R_TRY(impl::FindPad(std::addressof(pad), device_code));
AMS_ASSERT(pad != nullptr);
/* Sanitize the access mode. */
if ((access_mode & ~(ddsf::AccessMode_ReadWrite)) != 0) {
access_mode = ddsf::AccessMode_None;
}
/* Try to open the session with the desired mode. */
R_TRY_CATCH(OpenSessionImpl(out, pad, access_mode)) {
R_CATCH(ddsf::ResultAccessModeDenied) {
/* Our current access mode was denied. Try adding the shared flag. */
R_TRY(OpenSessionImpl(out, pad, static_cast<ddsf::AccessMode>(access_mode | ddsf::AccessMode_Shared)));
}
} R_END_TRY_CATCH;
R_SUCCEED();
}
void CloseSession(GpioPadSession *session) {
AMS_ASSERT(session != nullptr);
std::destroy_at(std::addressof(impl::GetOpenPadSessionImpl(*session)));
}
Result SetDirection(GpioPadSession *session, gpio::Direction direction) {
/* Check that we have a valid session. */
AMS_ASSERT(session != nullptr);
auto &impl = impl::GetOpenPadSessionImpl(*session);
R_UNLESS(impl.IsOpen(), gpio::ResultNotOpen());
/* Check that we can perform the access. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Write), ddsf::ResultPermissionDenied());
/* Get the pad. */
auto &pad = impl.GetDevice().SafeCastTo<Pad>();
/* Perform the call. */
R_TRY(pad.GetDriver().SafeCastTo<IGpioDriver>().SetDirection(std::addressof(pad), direction));
R_SUCCEED();
}
Result GetDirection(gpio::Direction *out, GpioPadSession *session) {
/* Check that we have a valid session. */
AMS_ASSERT(session != nullptr);
auto &impl = impl::GetOpenPadSessionImpl(*session);
R_UNLESS(impl.IsOpen(), gpio::ResultNotOpen());
/* Check that we can perform the access. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Read), ddsf::ResultPermissionDenied());
/* Get the pad. */
auto &pad = impl.GetDevice().SafeCastTo<Pad>();
/* Perform the call. */
R_TRY(pad.GetDriver().SafeCastTo<IGpioDriver>().GetDirection(out, std::addressof(pad)));
R_SUCCEED();
}
Result SetValue(GpioPadSession *session, gpio::GpioValue value) {
/* Check that we have a valid session. */
AMS_ASSERT(session != nullptr);
auto &impl = impl::GetOpenPadSessionImpl(*session);
R_UNLESS(impl.IsOpen(), gpio::ResultNotOpen());
/* Check that we can perform the access. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Write), ddsf::ResultPermissionDenied());
/* Get the pad. */
auto &pad = impl.GetDevice().SafeCastTo<Pad>();
/* Perform the call. */
R_TRY(pad.GetDriver().SafeCastTo<IGpioDriver>().SetValue(std::addressof(pad), value));
R_SUCCEED();
}
Result GetValue(gpio::GpioValue *out, GpioPadSession *session) {
/* Check that we have a valid session. */
AMS_ASSERT(session != nullptr);
auto &impl = impl::GetOpenPadSessionImpl(*session);
R_UNLESS(impl.IsOpen(), gpio::ResultNotOpen());
/* Check that we can perform the access. */
R_UNLESS(impl.CheckAccess(ddsf::AccessMode_Read), ddsf::ResultPermissionDenied());
/* Get the pad. */
auto &pad = impl.GetDevice().SafeCastTo<Pad>();
/* Perform the call. */
R_TRY(pad.GetDriver().SafeCastTo<IGpioDriver>().GetValue(out, std::addressof(pad)));
R_SUCCEED();
}
}
| 4,940
|
C++
|
.cpp
| 104
| 39.509615
| 119
| 0.63731
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,540
|
gpio_pad.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/gpio/driver/gpio_pad.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "impl/gpio_driver_core.hpp"
namespace ams::gpio::driver {
bool Pad::IsAnySessionBoundToInterrupt() const {
/* Check to see if any session has an interrupt bound. */
bool bound = false;
this->ForEachSession([&](const ddsf::ISession &session) -> bool {
const auto &impl = session.SafeCastTo<impl::PadSessionImpl>();
if (impl.IsInterruptBound()) {
bound = true;
return false;
}
return true;
});
return bound;
}
void Pad::SignalInterruptBoundEvent() {
/* Signal relevant sessions. */
this->ForEachSession([&](ddsf::ISession &session) -> bool {
auto &impl = session.SafeCastTo<impl::PadSessionImpl>();
if (impl.IsInterruptBound()) {
impl.SignalInterruptBoundEvent();
}
return true;
});
}
}
| 1,576
|
C++
|
.cpp
| 42
| 30.97619
| 76
| 0.649215
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,541
|
gpio_pad_session_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/gpio/driver/impl/gpio_pad_session_impl.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams::gpio::driver::impl {
Result PadSessionImpl::Open(Pad *pad, ddsf::AccessMode access_mode) {
/* Check if the pad has any open sessions. */
const bool first_session = !pad->HasAnyOpenSession();
/* Open the session. */
R_TRY(ddsf::OpenSession(pad, this, access_mode));
auto pad_guard = SCOPE_GUARD { ddsf::CloseSession(this); };
/* If we're the first, we want to initialize the pad. */
if (first_session) {
R_TRY(pad->GetDriver().SafeCastTo<IGpioDriver>().InitializePad(pad));
}
/* We opened successfully. */
pad_guard.Cancel();
R_SUCCEED();
}
void PadSessionImpl::Close() {
/* If the session isn't open, nothing to do. */
if (!this->IsOpen()) {
return;
}
/* Unbind the interrupt, if it's bound. */
if (this->IsInterruptBound()) {
this->UnbindInterrupt();
}
/* Get the pad we're a session for. */
auto &pad = this->GetDevice().SafeCastTo<Pad>();
/* Close the session. */
ddsf::CloseSession(this);
/* If we were the last session on the pad, finalize the pad. */
if (!pad.HasAnyOpenSession()) {
pad.GetDriver().SafeCastTo<IGpioDriver>().FinalizePad(std::addressof(pad));
}
}
Result PadSessionImpl::BindInterrupt(os::SystemEventType *event) {
/* Acquire exclusive access to the relevant interrupt control mutex. */
auto &pad = this->GetDevice().SafeCastTo<Pad>();
auto &mutex = pad.GetDriver().SafeCastTo<IGpioDriver>().GetInterruptControlMutex(pad);
std::scoped_lock lk(mutex);
/* Check that we're not already bound. */
R_UNLESS(!this->IsInterruptBound(), gpio::ResultAlreadyBound());
R_UNLESS(!this->GetDevice().SafeCastTo<Pad>().IsAnySessionBoundToInterrupt(), gpio::ResultAlreadyBound());
/* Create the system event. */
R_TRY(os::CreateSystemEvent(event, os::EventClearMode_ManualClear, true));
auto ev_guard = SCOPE_GUARD { os::DestroySystemEvent(event); };
/* Attach the event to our holder. */
m_event_holder.AttachEvent(event);
auto hl_guard = SCOPE_GUARD { m_event_holder.DetachEvent(); };
/* Update interrupt needed. */
R_TRY(this->UpdateDriverInterruptEnabled());
/* We succeeded. */
hl_guard.Cancel();
ev_guard.Cancel();
R_SUCCEED();
}
void PadSessionImpl::UnbindInterrupt() {
/* Acquire exclusive access to the relevant interrupt control mutex. */
auto &pad = this->GetDevice().SafeCastTo<Pad>();
auto &mutex = pad.GetDriver().SafeCastTo<IGpioDriver>().GetInterruptControlMutex(pad);
std::scoped_lock lk(mutex);
/* If we're not bound, nothing to do. */
if (!this->IsInterruptBound()) {
return;
}
/* Detach and destroy the event */
os::DestroySystemEvent(m_event_holder.DetachEvent());
/* Update interrupt needed. */
R_ABORT_UNLESS(this->UpdateDriverInterruptEnabled());
}
Result PadSessionImpl::UpdateDriverInterruptEnabled() {
/* Check we have exclusive access to the relevant interrupt control mutex. */
auto &pad = this->GetDevice().SafeCastTo<Pad>();
auto &driver = pad.GetDriver().SafeCastTo<IGpioDriver>();
AMS_ASSERT(driver.GetInterruptControlMutex(pad).IsLockedByCurrentThread());
/* Set interrupt enabled. */
R_RETURN(driver.SetInterruptEnabled(std::addressof(pad), pad.IsInterruptRequiredForDriver()));
}
Result PadSessionImpl::GetInterruptEnabled(bool *out) const {
*out = this->GetDevice().SafeCastTo<Pad>().IsInterruptEnabled();
R_SUCCEED();
}
Result PadSessionImpl::SetInterruptEnabled(bool en) {
/* Acquire exclusive access to the relevant interrupt control mutex. */
auto &pad = this->GetDevice().SafeCastTo<Pad>();
auto &mutex = pad.GetDriver().SafeCastTo<IGpioDriver>().GetInterruptControlMutex(pad);
std::scoped_lock lk(mutex);
/* Set the interrupt enable. */
const bool prev = pad.IsInterruptEnabled();
pad.SetInterruptEnabled(en);
auto pad_guard = SCOPE_GUARD { pad.SetInterruptEnabled(prev); };
/* Update interrupt needed. */
R_TRY(this->UpdateDriverInterruptEnabled());
pad_guard.Cancel();
R_SUCCEED();
}
void PadSessionImpl::SignalInterruptBoundEvent() {
/* Check we have exclusive access to the relevant interrupt control mutex. */
auto &pad = this->GetDevice().SafeCastTo<Pad>();
auto &driver = pad.GetDriver().SafeCastTo<IGpioDriver>();
AMS_ASSERT(driver.GetInterruptControlMutex(pad).IsLockedByCurrentThread());
AMS_UNUSED(pad, driver);
if (auto *event = m_event_holder.GetSystemEvent(); event != nullptr) {
os::SignalSystemEvent(event);
}
}
}
| 5,670
|
C++
|
.cpp
| 121
| 39.016529
| 114
| 0.646675
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,542
|
gpio_driver_core.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/gpio/driver/impl/gpio_driver_core.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "gpio_driver_core.hpp"
namespace ams::gpio::driver::impl {
namespace {
os::ThreadType g_interrupt_thread;
constexpr inline size_t InterruptThreadStackSize = os::MemoryPageSize;
alignas(os::MemoryPageSize) u8 g_interrupt_thread_stack[InterruptThreadStackSize];
gpio::driver::IGpioDriver::List &GetGpioDriverList() {
AMS_FUNCTION_LOCAL_STATIC_CONSTINIT(gpio::driver::IGpioDriver::List, s_gpio_driver_list);
return s_gpio_driver_list;
}
ddsf::EventHandlerManager &GetInterruptHandlerManager() {
AMS_FUNCTION_LOCAL_STATIC(ddsf::EventHandlerManager, s_interrupt_handler_manager);
return s_interrupt_handler_manager;
}
ddsf::DeviceCodeEntryManager &GetDeviceCodeEntryManager() {
AMS_FUNCTION_LOCAL_STATIC(ddsf::DeviceCodeEntryManager, s_device_code_entry_manager, ddsf::GetDeviceCodeEntryHolderMemoryResource());
return s_device_code_entry_manager;
}
void InterruptThreadFunction(void *arg) {
AMS_UNUSED(arg);
GetInterruptHandlerManager().LoopAuto();
}
}
void InitializeDrivers() {
/* Ensure the event handler manager is initialized. */
GetInterruptHandlerManager().Initialize();
/* Initialize all registered drivers. */
for (auto &driver : GetGpioDriverList()) {
driver.SafeCastTo<IGpioDriver>().InitializeDriver();
}
/* Create the interrupt thread. */
R_ABORT_UNLESS(os::CreateThread(std::addressof(g_interrupt_thread), InterruptThreadFunction, nullptr, g_interrupt_thread_stack, InterruptThreadStackSize, AMS_GET_SYSTEM_THREAD_PRIORITY(gpio, InterruptHandler)));
os::SetThreadNamePointer(std::addressof(g_interrupt_thread), AMS_GET_SYSTEM_THREAD_NAME(gpio, InterruptHandler));
os::StartThread(std::addressof(g_interrupt_thread));
/* Wait for the interrupt thread to enter the loop. */
GetInterruptHandlerManager().WaitLoopEnter();
}
void FinalizeDrivers() {
/* Request the interrupt thread stop. */
GetInterruptHandlerManager().RequestStop();
os::WaitThread(std::addressof(g_interrupt_thread));
os::DestroyThread(std::addressof(g_interrupt_thread));
/* TODO: What else? */
AMS_ABORT();
}
void RegisterDriver(IGpioDriver *driver) {
AMS_ASSERT(driver != nullptr);
GetGpioDriverList().push_back(*driver);
}
void UnregisterDriver(IGpioDriver *driver) {
AMS_ASSERT(driver != nullptr);
if (driver->IsLinkedToList()) {
auto &list = GetGpioDriverList();
list.erase(list.iterator_to(*driver));
}
}
Result RegisterDeviceCode(DeviceCode device_code, Pad *pad) {
AMS_ASSERT(pad != nullptr);
R_TRY(GetDeviceCodeEntryManager().Add(device_code, pad));
R_SUCCEED();
}
bool UnregisterDeviceCode(DeviceCode device_code) {
return GetDeviceCodeEntryManager().Remove(device_code);
}
void RegisterInterruptHandler(ddsf::IEventHandler *handler) {
AMS_ASSERT(handler != nullptr);
GetInterruptHandlerManager().RegisterHandler(handler);
}
void UnregisterInterruptHandler(ddsf::IEventHandler *handler) {
AMS_ASSERT(handler != nullptr);
GetInterruptHandlerManager().UnregisterHandler(handler);
}
Result FindPad(Pad **out, DeviceCode device_code) {
/* Validate output. */
AMS_ASSERT(out != nullptr);
/* Find the device. */
ddsf::IDevice *device;
R_TRY(GetDeviceCodeEntryManager().FindDevice(std::addressof(device), device_code));
/* Set output. */
*out = device->SafeCastToPointer<Pad>();
R_SUCCEED();
}
Result FindPadByNumber(Pad **out, int pad_number) {
/* Validate output. */
AMS_ASSERT(out != nullptr);
/* Find the pad. */
bool found = false;
GetDeviceCodeEntryManager().ForEachEntry([&](ddsf::DeviceCodeEntry &entry) -> bool {
/* Convert the entry to a pad. */
auto &pad = entry.GetDevice().SafeCastTo<Pad>();
/* Check if the pad is the one we're looking for. */
if (pad.GetPadNumber() == pad_number) {
found = true;
*out = std::addressof(pad);
return false;
}
return true;
});
/* Check that we found the pad. */
R_UNLESS(found, ddsf::ResultDeviceCodeNotFound());
R_SUCCEED();
}
}
| 5,262
|
C++
|
.cpp
| 119
| 36.07563
| 219
| 0.657014
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,543
|
gpio_driver_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/gpio/driver/board/nintendo/nx/gpio_driver_api.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "impl/gpio_driver_impl.hpp"
#include "impl/gpio_initial_config.hpp"
#include "impl/gpio_tegra_pad.hpp"
namespace ams::gpio::driver::board::nintendo::nx {
namespace {
ams::gpio::driver::board::nintendo::nx::impl::DriverImpl *g_driver_impl = nullptr;
}
void Initialize(bool enable_interrupt_handlers) {
/* Check that we haven't previously initialized. */
AMS_ABORT_UNLESS(g_driver_impl == nullptr);
/* Get the device driver subsystem framework memory resource. */
auto *memory_resource = ddsf::GetMemoryResource();
/* Allocate a new driver. */
auto *driver_storage = static_cast<decltype(g_driver_impl)>(memory_resource->Allocate(sizeof(*g_driver_impl)));
AMS_ABORT_UNLESS(driver_storage != nullptr);
/* Construct the new driver. */
g_driver_impl = std::construct_at(driver_storage, impl::GpioRegistersPhysicalAddress, impl::GpioRegistersSize);
/* Register the driver. */
gpio::driver::RegisterDriver(g_driver_impl);
/* Register interrupt handlers, if we should. */
if (enable_interrupt_handlers) {
for (size_t i = 0; i < util::size(impl::InterruptNameTable); ++i) {
/* Allocate a handler. */
void *handler_storage = memory_resource->Allocate(sizeof(impl::InterruptEventHandler));
AMS_ABORT_UNLESS(handler_storage != nullptr);
/* Initialize the handler. */
auto *handler = std::construct_at(static_cast<impl::InterruptEventHandler *>(handler_storage));
handler->Initialize(g_driver_impl, impl::InterruptNameTable[i], static_cast<int>(i));
/* Register the handler. */
gpio::driver::RegisterInterruptHandler(handler);
}
}
/* Create and register all pads. */
for (const auto &entry : impl::PadMapCombinationList) {
/* Allocate a pad for our device. */
void *pad_storage = memory_resource->Allocate(sizeof(impl::TegraPad));
AMS_ABORT_UNLESS(pad_storage != nullptr);
/* Create a pad for our device. */
auto *pad = std::construct_at(static_cast<impl::TegraPad *>(pad_storage));
pad->SetParameters(entry.internal_number, impl::PadInfo{entry.wake_event});
/* Register the pad with our driver. */
g_driver_impl->RegisterDevice(pad);
/* Register the device code with our driver. */
R_ABORT_UNLESS(gpio::driver::RegisterDeviceCode(entry.device_code, pad));
}
}
void SetInitialGpioConfig() {
return impl::SetInitialGpioConfig();
}
void SetInitialWakePinConfig() {
return impl::SetInitialWakePinConfig();
}
}
| 3,449
|
C++
|
.cpp
| 69
| 41.782609
| 119
| 0.653377
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,544
|
gpio_driver_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/gpio/driver/board/nintendo/nx/impl/gpio_driver_impl.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "gpio_driver_impl.hpp"
#include "gpio_register_accessor.hpp"
namespace ams::gpio::driver::board::nintendo::nx::impl {
void InterruptEventHandler::Initialize(DriverImpl *drv, os::InterruptName intr, int ctlr) {
/* Set fields. */
m_driver = drv;
m_interrupt_name = intr;
m_controller_number = ctlr;
/* Initialize interrupt event. */
os::InitializeInterruptEvent(std::addressof(m_interrupt_event), intr, os::EventClearMode_ManualClear);
/* Initialize base. */
IEventHandler::Initialize(std::addressof(m_interrupt_event));
}
void InterruptEventHandler::HandleEvent() {
/* Lock the driver's interrupt mutex. */
std::scoped_lock lk(m_driver->m_interrupt_control_mutex);
/* Check each pad. */
bool found = false;
for (auto it = m_driver->m_interrupt_pad_list.begin(); !found && it != m_driver->m_interrupt_pad_list.end(); ++it) {
found = this->CheckAndHandleInterrupt(*it);
}
/* If we didn't find a pad, clear the interrupt event. */
if (!found) {
os::ClearInterruptEvent(std::addressof(m_interrupt_event));
}
}
bool InterruptEventHandler::CheckAndHandleInterrupt(TegraPad &pad) {
/* Get the pad's number. */
const InternalGpioPadNumber pad_number = static_cast<InternalGpioPadNumber>(pad.GetPadNumber());
/* Check if the pad matches our controller number. */
if (m_controller_number != ConvertInternalGpioPadNumberToController(pad_number)) {
return false;
}
/* Get the addresses of INT_STA, INT_ENB. */
const uintptr_t sta_address = GetGpioRegisterAddress(m_driver->m_gpio_virtual_address, GpioRegisterType_GPIO_INT_STA, pad_number);
const uintptr_t enb_address = GetGpioRegisterAddress(m_driver->m_gpio_virtual_address, GpioRegisterType_GPIO_INT_STA, pad_number);
const uintptr_t pad_index = ConvertInternalGpioPadNumberToBitIndex(pad_number);
/* Check if both STA and ENB are set. */
if (reg::Read(sta_address, 1u << pad_index) == 0 || reg::Read(enb_address, 1u << pad_index) == 0) {
return false;
}
/* The pad is signaled. First, clear the enb bit. */
SetMaskedBit(enb_address, pad_index, 0);
reg::Read(enb_address);
/* Disable the interrupt on the pad. */
pad.SetInterruptEnabled(false);
m_driver->RemoveInterruptPad(std::addressof(pad));
/* Clear the interrupt event. */
os::ClearInterruptEvent(std::addressof(m_interrupt_event));
/* Signal the pad's bound event. */
pad.SignalInterruptBoundEvent();
return true;
}
DriverImpl::DriverImpl(dd::PhysicalAddress reg_paddr, size_t size) : m_gpio_physical_address(reg_paddr), m_gpio_virtual_address(), m_suspend_handler(this), m_interrupt_pad_list(), m_interrupt_control_mutex() {
/* Get the corresponding virtual address for our physical address. */
m_gpio_virtual_address = dd::QueryIoMapping(reg_paddr, size);
AMS_ABORT_UNLESS(m_gpio_virtual_address != 0);
}
void DriverImpl::InitializeDriver() {
/* Initialize our suspend handler. */
m_suspend_handler.Initialize(m_gpio_virtual_address);
}
void DriverImpl::FinalizeDriver() {
/* ... */
}
Result DriverImpl::InitializePad(Pad *pad) {
/* Validate arguments. */
AMS_ASSERT(pad != nullptr);
/* Convert the pad to an internal number. */
const InternalGpioPadNumber pad_number = pad->GetPadNumber();
/* Configure the pad as GPIO by modifying the appropriate bit in CNF. */
const uintptr_t pad_address = GetGpioRegisterAddress(m_gpio_virtual_address, GpioRegisterType_GPIO_CNF, pad_number);
const uintptr_t pad_index = ConvertInternalGpioPadNumberToBitIndex(pad_number);
SetMaskedBit(pad_address, pad_index, 1);
/* Read the pad address to make sure our configuration takes. */
reg::Read(pad_address);
R_SUCCEED();
}
void DriverImpl::FinalizePad(Pad *pad) {
/* Validate arguments. */
AMS_ASSERT(pad != nullptr);
/* Nothing to do. */
AMS_UNUSED(pad);
}
Result DriverImpl::GetDirection(Direction *out, Pad *pad) const {
/* Validate arguments. */
AMS_ASSERT(out != nullptr);
AMS_ASSERT(pad != nullptr);
/* Convert the pad to an internal number. */
const InternalGpioPadNumber pad_number = pad->GetPadNumber();
/* Get the pad direction by reading the appropriate bit in OE */
const uintptr_t pad_address = GetGpioRegisterAddress(m_gpio_virtual_address, GpioRegisterType_GPIO_OE, pad_number);
const uintptr_t pad_index = ConvertInternalGpioPadNumberToBitIndex(pad_number);
if (reg::Read(pad_address, 1u << pad_index) != 0) {
*out = Direction_Output;
} else {
*out = Direction_Input;
}
R_SUCCEED();
}
Result DriverImpl::SetDirection(Pad *pad, Direction direction) {
/* Validate arguments. */
AMS_ASSERT(pad != nullptr);
/* Convert the pad to an internal number. */
const InternalGpioPadNumber pad_number = pad->GetPadNumber();
/* Configure the pad direction by modifying the appropriate bit in OE */
const uintptr_t pad_address = GetGpioRegisterAddress(m_gpio_virtual_address, GpioRegisterType_GPIO_OE, pad_number);
const uintptr_t pad_index = ConvertInternalGpioPadNumberToBitIndex(pad_number);
SetMaskedBit(pad_address, pad_index, direction);
/* Read the pad address to make sure our configuration takes. */
reg::Read(pad_address);
R_SUCCEED();
}
Result DriverImpl::GetValue(GpioValue *out, Pad *pad) const {
/* Validate arguments. */
AMS_ASSERT(out != nullptr);
AMS_ASSERT(pad != nullptr);
/* Convert the pad to an internal number. */
const InternalGpioPadNumber pad_number = pad->GetPadNumber();
/* Get the pad value by reading the appropriate bit in IN */
const uintptr_t pad_address = GetGpioRegisterAddress(m_gpio_virtual_address, GpioRegisterType_GPIO_IN, pad_number);
const uintptr_t pad_index = ConvertInternalGpioPadNumberToBitIndex(pad_number);
if (reg::Read(pad_address, 1u << pad_index) != 0) {
*out = GpioValue_High;
} else {
*out = GpioValue_Low;
}
R_SUCCEED();
}
Result DriverImpl::SetValue(Pad *pad, GpioValue value) {
/* Validate arguments. */
AMS_ASSERT(pad != nullptr);
/* Convert the pad to an internal number. */
const InternalGpioPadNumber pad_number = pad->GetPadNumber();
/* Configure the pad value by modifying the appropriate bit in IN */
const uintptr_t pad_address = GetGpioRegisterAddress(m_gpio_virtual_address, GpioRegisterType_GPIO_OUT, pad_number);
const uintptr_t pad_index = ConvertInternalGpioPadNumberToBitIndex(pad_number);
SetMaskedBit(pad_address, pad_index, value);
/* Read the pad address to make sure our configuration takes. */
reg::Read(pad_address);
R_SUCCEED();
}
Result DriverImpl::GetInterruptMode(InterruptMode *out, Pad *pad) const {
/* Validate arguments. */
AMS_ASSERT(out != nullptr);
AMS_ASSERT(pad != nullptr);
/* Convert the pad to an internal number. */
const InternalGpioPadNumber pad_number = pad->GetPadNumber();
/* Get the pad mode by reading the appropriate bits in INT_LVL */
const uintptr_t pad_address = GetGpioRegisterAddress(m_gpio_virtual_address, GpioRegisterType_GPIO_INT_LVL, pad_number);
const uintptr_t pad_index = ConvertInternalGpioPadNumberToBitIndex(pad_number);
switch ((reg::Read(pad_address) >> pad_index) & InternalInterruptMode_Mask) {
case InternalInterruptMode_LowLevel: *out = InterruptMode_LowLevel; break;
case InternalInterruptMode_HighLevel: *out = InterruptMode_HighLevel; break;
case InternalInterruptMode_RisingEdge: *out = InterruptMode_RisingEdge; break;
case InternalInterruptMode_FallingEdge: *out = InterruptMode_FallingEdge; break;
case InternalInterruptMode_AnyEdge: *out = InterruptMode_AnyEdge; break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
R_SUCCEED();
}
Result DriverImpl::SetInterruptMode(Pad *pad, InterruptMode mode) {
/* Validate arguments. */
AMS_ASSERT(pad != nullptr);
/* Convert the pad to an internal number. */
const InternalGpioPadNumber pad_number = pad->GetPadNumber();
/* Configure the pad mode by modifying the appropriate bits in INT_LVL */
const uintptr_t pad_address = GetGpioRegisterAddress(m_gpio_virtual_address, GpioRegisterType_GPIO_INT_LVL, pad_number);
const uintptr_t pad_index = ConvertInternalGpioPadNumberToBitIndex(pad_number);
switch (mode) {
case InterruptMode_LowLevel: reg::ReadWrite(pad_address, InternalInterruptMode_LowLevel << pad_index, InternalInterruptMode_Mask << pad_index); break;
case InterruptMode_HighLevel: reg::ReadWrite(pad_address, InternalInterruptMode_HighLevel << pad_index, InternalInterruptMode_Mask << pad_index); break;
case InterruptMode_RisingEdge: reg::ReadWrite(pad_address, InternalInterruptMode_RisingEdge << pad_index, InternalInterruptMode_Mask << pad_index); break;
case InterruptMode_FallingEdge: reg::ReadWrite(pad_address, InternalInterruptMode_FallingEdge << pad_index, InternalInterruptMode_Mask << pad_index); break;
case InterruptMode_AnyEdge: reg::ReadWrite(pad_address, InternalInterruptMode_AnyEdge << pad_index, InternalInterruptMode_Mask << pad_index); break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
/* Read the pad address to make sure our configuration takes. */
reg::Read(pad_address);
R_SUCCEED();
}
Result DriverImpl::SetInterruptEnabled(Pad *pad, bool en) {
/* TODO */
AMS_UNUSED(pad, en);
AMS_ABORT();
}
Result DriverImpl::GetInterruptStatus(InterruptStatus *out, Pad *pad) {
/* TODO */
AMS_UNUSED(out, pad);
AMS_ABORT();
}
Result DriverImpl::ClearInterruptStatus(Pad *pad) {
/* TODO */
AMS_UNUSED(pad);
AMS_ABORT();
}
Result DriverImpl::GetDebounceEnabled(bool *out, Pad *pad) const {
/* TODO */
AMS_UNUSED(out, pad);
AMS_ABORT();
}
Result DriverImpl::SetDebounceEnabled(Pad *pad, bool en) {
AMS_UNUSED(pad, en);
/* TODO */
AMS_ABORT();
}
Result DriverImpl::GetDebounceTime(s32 *out_ms, Pad *pad) const {
/* TODO */
AMS_UNUSED(out_ms, pad);
AMS_ABORT();
}
Result DriverImpl::SetDebounceTime(Pad *pad, s32 ms) {
/* TODO */
AMS_UNUSED(pad, ms);
AMS_ABORT();
}
Result DriverImpl::GetUnknown22(u32 *out) {
/* TODO */
AMS_UNUSED(out);
AMS_ABORT();
}
void DriverImpl::Unknown23() {
/* TODO */
AMS_ABORT();
}
Result DriverImpl::SetValueForSleepState(Pad *pad, GpioValue value) {
/* TODO */
AMS_UNUSED(pad, value);
AMS_ABORT();
}
Result DriverImpl::IsWakeEventActive(bool *out, Pad *pad) const {
/* TODO */
AMS_UNUSED(out, pad);
AMS_ABORT();
}
Result DriverImpl::SetWakeEventActiveFlagSetForDebug(Pad *pad, bool en) {
/* TODO */
AMS_UNUSED(pad, en);
AMS_ABORT();
}
Result DriverImpl::SetWakePinDebugMode(WakePinDebugMode mode) {
/* TODO */
AMS_UNUSED(mode);
AMS_ABORT();
}
Result DriverImpl::Suspend() {
/* TODO */
AMS_ABORT();
}
Result DriverImpl::SuspendLow() {
/* TODO */
AMS_ABORT();
}
Result DriverImpl::Resume() {
/* TODO */
AMS_ABORT();
}
Result DriverImpl::ResumeLow() {
/* TODO */
AMS_ABORT();
}
}
| 12,978
|
C++
|
.cpp
| 278
| 38.539568
| 213
| 0.645913
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,545
|
gpio_suspend_handler.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/gpio/driver/board/nintendo/nx/impl/gpio_suspend_handler.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "gpio_suspend_handler.hpp"
namespace ams::gpio::driver::board::nintendo::nx::impl {
void SuspendHandler::Initialize(uintptr_t gpio_vaddr) {
/* Set our gpio virtual address. */
m_gpio_virtual_address = gpio_vaddr;
/* Ensure that we can use the wec library. */
ams::wec::Initialize();
}
void SuspendHandler::SetValueForSleepState(TegraPad *pad, GpioValue value) {
/* TODO */
AMS_UNUSED(pad, value);
AMS_ABORT();
}
Result SuspendHandler::IsWakeEventActive(bool *out, TegraPad *pad) const {
/* TODO */
AMS_UNUSED(out, pad);
AMS_ABORT();
}
Result SuspendHandler::SetWakeEventActiveFlagSetForDebug(TegraPad *pad, bool en) {
/* TODO */
AMS_UNUSED(pad, en);
AMS_ABORT();
}
void SuspendHandler::SetWakePinDebugMode(WakePinDebugMode mode) {
/* TODO */
AMS_UNUSED(mode);
AMS_ABORT();
}
void SuspendHandler::Suspend() {
/* TODO */
AMS_ABORT();
}
void SuspendHandler::SuspendLow() {
/* TODO */
AMS_ABORT();
}
void SuspendHandler::Resume() {
/* TODO */
AMS_ABORT();
}
void SuspendHandler::ResumeLow() {
/* TODO */
AMS_ABORT();
}
}
| 1,965
|
C++
|
.cpp
| 61
| 26.459016
| 86
| 0.641649
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,546
|
gpio_initial_config.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/gpio/driver/board/nintendo/nx/impl/gpio_initial_config.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "gpio_driver_impl.hpp"
#include "gpio_initial_config.hpp"
#include "gpio_wake_pin_config.hpp"
namespace ams::gpio::driver::board::nintendo::nx::impl {
namespace {
spl::HardwareType GetHardwareType() {
/* Acquire access to spl: */
spl::Initialize();
ON_SCOPE_EXIT { spl::Finalize(); };
/* Get config. */
return ::ams::spl::GetHardwareType();
}
#include "gpio_initial_wake_pin_config_icosa.inc"
/* #include "gpio_initial_wake_pin_config_copper.inc" */
#include "gpio_initial_wake_pin_config_hoag.inc"
#include "gpio_initial_wake_pin_config_iowa.inc"
#include "gpio_initial_wake_pin_config_calcio.inc"
#include "gpio_initial_wake_pin_config_aula.inc"
#include "gpio_initial_config_icosa.inc"
/* #include "gpio_initial_config_copper.inc" */
#include "gpio_initial_config_hoag.inc"
#include "gpio_initial_config_iowa.inc"
#include "gpio_initial_config_calcio.inc"
#include "gpio_initial_config_aula.inc"
}
void SetInitialGpioConfig() {
/* Set wake event levels, wake event enables. */
const GpioInitialConfig *configs = nullptr;
size_t num_configs = 0;
/* Select the correct config. */
switch (GetHardwareType()) {
case spl::HardwareType::Icosa:
configs = InitialGpioConfigsIcosa;
num_configs = NumInitialGpioConfigsIcosa;
break;
case spl::HardwareType::Hoag:
configs = InitialGpioConfigsHoag;
num_configs = NumInitialGpioConfigsHoag;
break;
case spl::HardwareType::Iowa:
configs = InitialGpioConfigsIowa;
num_configs = NumInitialGpioConfigsIowa;
break;
case spl::HardwareType::Calcio:
configs = InitialGpioConfigsCalcio;
num_configs = NumInitialGpioConfigsCalcio;
break;
case spl::HardwareType::Aula:
configs = InitialGpioConfigsAula;
num_configs = NumInitialGpioConfigsAula;
break;
case spl::HardwareType::Copper:
AMS_UNREACHABLE_DEFAULT_CASE();
}
/* Check we can use our config. */
AMS_ABORT_UNLESS(configs != nullptr);
/* Apply the configs. */
{
/* Create a driver to use for the duration of our application. */
DriverImpl driver(GpioRegistersPhysicalAddress, GpioRegistersSize);
driver.InitializeDriver();
for (size_t i = 0; i < num_configs; ++i) {
/* Find the internal pad number for our device. */
bool found = false;
for (const auto &entry : PadMapCombinationList) {
if (entry.device_code == configs[i].device_code) {
/* We found an entry. */
found = true;
/* Create a pad for our device. */
TegraPad pad;
pad.SetParameters(entry.internal_number, PadInfo{entry.wake_event});
/* Initialize the pad. */
R_ABORT_UNLESS(driver.InitializePad(std::addressof(pad)));
/* Set the direction. */
R_ABORT_UNLESS(driver.SetDirection(std::addressof(pad), configs[i].direction));
/* If the direction is output, set the value. */
if (configs[i].direction == Direction_Output) {
R_ABORT_UNLESS(driver.SetValue(std::addressof(pad), configs[i].value));
}
/* Finalize the pad we made. */
driver.FinalizePad(std::addressof(pad));
break;
}
}
/* Ensure that we applied the config for the pad we wanted. */
AMS_ABORT_UNLESS(found);
}
/* Finalize the driver. */
driver.FinalizeDriver();
}
}
void SetInitialWakePinConfig() {
/* Ensure the wec driver is initialized. */
ams::wec::Initialize();
/* Set wake event levels, wake event enables. */
const WakePinConfig *configs = nullptr;
size_t num_configs = 0;
/* Select the correct config. */
switch (GetHardwareType()) {
case spl::HardwareType::Icosa:
configs = InitialWakePinConfigsIcosa;
num_configs = NumInitialWakePinConfigsIcosa;
break;
case spl::HardwareType::Hoag:
configs = InitialWakePinConfigsHoag;
num_configs = NumInitialWakePinConfigsHoag;
break;
case spl::HardwareType::Iowa:
configs = InitialWakePinConfigsIowa;
num_configs = NumInitialWakePinConfigsIowa;
break;
case spl::HardwareType::Calcio:
configs = InitialWakePinConfigsCalcio;
num_configs = NumInitialWakePinConfigsCalcio;
break;
case spl::HardwareType::Aula:
configs = InitialWakePinConfigsAula;
num_configs = NumInitialWakePinConfigsAula;
break;
case spl::HardwareType::Copper:
AMS_UNREACHABLE_DEFAULT_CASE();
}
/* Check we can use our config. */
AMS_ABORT_UNLESS(configs != nullptr);
/* Apply the config. */
for (size_t i = 0; i < num_configs; ++i) {
wec::SetWakeEventLevel(configs[i].wake_event, configs[i].level);
wec::SetWakeEventEnabled(configs[i].wake_event, configs[i].enable);
}
}
}
| 6,618
|
C++
|
.cpp
| 147
| 32.44898
| 103
| 0.565002
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,547
|
gpio_server_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/gpio/server/gpio_server_api.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "gpio_server_manager_impl.hpp"
namespace ams::gpio::server {
namespace {
ams::sf::UnmanagedServiceObject<gpio::sf::IManager, gpio::server::ManagerImpl> g_manager_impl;
}
ams::sf::SharedPointer<gpio::sf::IManager> GetServiceObject() {
return g_manager_impl.GetShared();
}
}
| 983
|
C++
|
.cpp
| 25
| 36.24
| 102
| 0.737395
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,548
|
gpio_server_manager_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/gpio/server/gpio_server_manager_impl.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "gpio_server_manager_impl.hpp"
namespace ams::gpio::server {
ManagerImpl::ManagerImpl() {
m_heap_handle = lmem::CreateExpHeap(m_heap_buffer, sizeof(m_heap_buffer), lmem::CreateOption_None);
m_pad_allocator.Attach(m_heap_handle);
}
ManagerImpl::~ManagerImpl() {
lmem::DestroyExpHeap(m_heap_handle);
}
Result ManagerImpl::OpenSessionForDev(ams::sf::Out<ams::sf::SharedPointer<gpio::sf::IPadSession>> out, s32 pad_descriptor) {
/* TODO */
AMS_UNUSED(out, pad_descriptor);
AMS_ABORT();
}
Result ManagerImpl::OpenSession(ams::sf::Out<ams::sf::SharedPointer<gpio::sf::IPadSession>> out, gpio::GpioPadName pad_name) {
R_RETURN(this->OpenSession2(out, ConvertToDeviceCode(pad_name), ddsf::AccessMode_ReadWrite));
}
Result ManagerImpl::OpenSessionForTest(ams::sf::Out<ams::sf::SharedPointer<gpio::sf::IPadSession>> out, gpio::GpioPadName pad_name) {
/* TODO */
AMS_UNUSED(out, pad_name);
AMS_ABORT();
}
Result ManagerImpl::IsWakeEventActive(ams::sf::Out<bool> out, gpio::GpioPadName pad_name) {
/* TODO */
AMS_UNUSED(out, pad_name);
AMS_ABORT();
}
Result ManagerImpl::GetWakeEventActiveFlagSet(ams::sf::Out<gpio::WakeBitFlag> out) {
/* TODO */
AMS_UNUSED(out);
AMS_ABORT();
}
Result ManagerImpl::SetWakeEventActiveFlagSetForDebug(gpio::GpioPadName pad_name, bool is_enabled) {
/* TODO */
AMS_UNUSED(pad_name, is_enabled);
AMS_ABORT();
}
Result ManagerImpl::SetWakePinDebugMode(s32 mode) {
/* TODO */
AMS_UNUSED(mode);
AMS_ABORT();
}
Result ManagerImpl::OpenSession2(ams::sf::Out<ams::sf::SharedPointer<gpio::sf::IPadSession>> out, DeviceCode device_code, ddsf::AccessMode access_mode) {
/* Allocate a session. */
auto session = Factory::CreateSharedEmplaced<gpio::sf::IPadSession, PadSessionImpl>(std::addressof(m_pad_allocator), this);
/* Open the session. */
R_TRY(session.GetImpl().OpenSession(device_code, access_mode));
/* We succeeded. */
*out = std::move(session);
R_SUCCEED();
}
Result ManagerImpl::IsWakeEventActive2(ams::sf::Out<bool> out, DeviceCode device_code) {
/* TODO */
AMS_UNUSED(out, device_code);
AMS_ABORT();
}
Result ManagerImpl::SetWakeEventActiveFlagSetForDebug2(DeviceCode device_code, bool is_enabled) {
/* TODO */
AMS_UNUSED(device_code, is_enabled);
AMS_ABORT();
}
Result ManagerImpl::SetRetryValues(u32 arg0, u32 arg1) {
/* TODO */
AMS_UNUSED(arg0, arg1);
AMS_ABORT();
}
}
| 3,390
|
C++
|
.cpp
| 83
| 34.554217
| 157
| 0.66231
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,549
|
init_libnx_shim.os.horizon.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/init/init_libnx_shim.os.horizon.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
extern "C" {
constinit u32 __nx_fs_num_sessions = 1;
constinit u32 __nx_applet_type = AppletType_None;
constinit bool __nx_fsdev_support_cwd = false;
extern int __system_argc;
extern char** __system_argv;
alignas(16) constinit u8 __nx_exception_stack[::ams::os::MemoryPageSize];
constinit u64 __nx_exception_stack_size = sizeof(__nx_exception_stack);
}
namespace ams {
namespace hos {
void InitializeForStratosphere();
}
namespace init {
void InitializeSystemModuleBeforeConstructors();
void InitializeSystemModule();
void FinalizeSystemModule();
void Startup();
}
void Main();
}
namespace {
constinit char *g_empty_argv = nullptr;
}
extern "C" void __libnx_exception_handler(ThreadExceptionDump *ctx) {
::ams::CrashHandler(ctx);
}
extern "C" void __libnx_initheap(void) {
/* Stratosphere system modules do not support newlib heap. */
}
extern "C" void __appInit(void) {
/* The very first thing all stratosphere code must do is initialize the os library. */
::ams::hos::InitializeForStratosphere();
/* Perform pre-C++ constructor init. */
::ams::init::InitializeSystemModuleBeforeConstructors();
}
extern "C" void __appExit(void) {
/* ... */
}
extern "C" void argvSetup(void) {
/* We don't use newlib argc/argv, so we can clear these. */
__system_argc = 0;
__system_argv = std::addressof(g_empty_argv);
}
extern "C" int main(int argc, char **argv) {
/* We don't use newlib argc/argv. */
AMS_UNUSED(argc, argv);
/* Perform remainder of logic with system module initialized. */
{
::ams::init::InitializeSystemModule();
ON_SCOPE_EXIT { ::ams::init::FinalizeSystemModule(); };
/* Perform miscellaneous startup. */
::ams::init::Startup();
/* Invoke ams main. */
::ams::Main();
}
}
extern "C" WEAK_SYMBOL void *__libnx_alloc(size_t) {
AMS_ABORT("__libnx_alloc was called");
}
extern "C" WEAK_SYMBOL void *__libnx_aligned_alloc(size_t, size_t) {
AMS_ABORT("__libnx_aligned_alloc was called");
}
extern "C" WEAK_SYMBOL void __libnx_free(void *) {
AMS_ABORT("__libnx_free was called");
}
| 2,886
|
C++
|
.cpp
| 82
| 31.04878
| 90
| 0.680014
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,550
|
init_malloc.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/init/init_malloc.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
/* NOTE: If AMS_INIT_USE_STANDARD_ALLOCATOR_FOR_MALLOC is defined, the relevant os primitives should be hooked up. */
#if defined(ATMOSPHERE_OS_HORIZON)
#define AMS_INIT_USE_STANDARD_ALLOCATOR_FOR_MALLOC
#elif defined(ATMOSPHERE_OS_WINDOWS)
//#define AMS_INIT_USE_STANDARD_ALLOCATOR_FOR_MALLOC
#elif defined(ATMOSPHERE_OS_LINUX)
//#define AMS_INIT_USE_STANDARD_ALLOCATOR_FOR_MALLOC
#elif defined(ATMOSPHERE_OS_MACOS)
//#define AMS_INIT_USE_STANDARD_ALLOCATOR_FOR_MALLOC
#else
#error "Unknown OS for enabling StandardAllocator backing impl for malloc"
#endif
namespace ams::init {
namespace {
#if defined(AMS_INIT_USE_STANDARD_ALLOCATOR_FOR_MALLOC)
constinit void *g_malloc_region_address = nullptr;
constinit size_t g_malloc_region_size = 0;
constinit util::TypedStorage<mem::StandardAllocator> g_malloc_allocator = {};
#endif
}
void InitializeAllocator(void *address, size_t size, bool cache_enabled) {
#if defined(AMS_INIT_USE_STANDARD_ALLOCATOR_FOR_MALLOC)
/* Check pre-conditions. */
AMS_ABORT_UNLESS(g_malloc_region_size == 0);
AMS_ABORT_UNLESS(size > 0);
/* Construct malloc allocator. */
util::ConstructAt(g_malloc_allocator);
/* Initialize allocator. */
util::GetReference(g_malloc_allocator).Initialize(address, size, cache_enabled);
/* Set malloc globals. */
g_malloc_region_address = address;
g_malloc_region_size = size;
#else
AMS_UNUSED(address, size, cache_enabled);
#endif
}
void InitializeAllocator(void *address, size_t size) {
return InitializeAllocator(address, size, false);
}
void InitializeDefaultAllocator() {
/* TODO: What should default heap size be? This uses virtual address space memory. */
return InitializeAllocator(nullptr, 128_MB, false);
}
mem::StandardAllocator *GetAllocator() {
#if defined(AMS_INIT_USE_STANDARD_ALLOCATOR_FOR_MALLOC)
/* Check pre-conditions. */
AMS_ASSERT(g_malloc_region_size > 0);
return util::GetPointer(g_malloc_allocator);
#else
return nullptr;
#endif
}
}
#if defined(AMS_INIT_USE_STANDARD_ALLOCATOR_FOR_MALLOC)
extern "C" void *malloc(size_t size) {
/* We require that an allocator region exists. */
if (::ams::init::g_malloc_region_size == 0) {
return nullptr;
}
/* Try to allocate. */
void *ptr = ::ams::util::GetReference(::ams::init::g_malloc_allocator).Allocate(size);
if (ptr == nullptr) {
errno = ENOMEM;
}
return ptr;
}
extern "C" void free(void *ptr) {
/* We require that an allocator region exists. */
if (::ams::init::g_malloc_region_size == 0) {
return;
}
if (ptr != nullptr) {
::ams::util::GetReference(::ams::init::g_malloc_allocator).Free(ptr);
}
}
extern "C" void *calloc(size_t num, size_t size) {
/* We require that an allocator region exists. */
if (::ams::init::g_malloc_region_size == 0) {
return nullptr;
}
/* Allocate the total needed space. */
const size_t total = num * size;
void *ptr = std::malloc(total);
/* Zero the memory if needed. */
if (ptr != nullptr) {
std::memset(ptr, 0, total);
} else {
errno = ENOMEM;
}
return ptr;
}
extern "C" void *realloc(void *ptr, size_t new_size) {
/* We require that an allocator region exists. */
if (::ams::init::g_malloc_region_size == 0) {
return nullptr;
}
/* Try to reallocate. */
void *r = ::ams::util::GetReference(::ams::init::g_malloc_allocator).Reallocate(ptr, new_size);
if (r == nullptr) {
errno = ENOMEM;
}
return r;
}
extern "C" void *aligned_alloc(size_t align, size_t size) {
/* We require that an allocator region exists. */
if (::ams::init::g_malloc_region_size == 0) {
return nullptr;
}
/* Try to allocate. */
void *ptr = ::ams::util::GetReference(::ams::init::g_malloc_allocator).Allocate(size, align);
if (ptr == nullptr) {
errno = ENOMEM;
}
return ptr;
}
extern "C" size_t malloc_usable_size(void *ptr) {
/* We require that an allocator region exists. */
if (::ams::init::g_malloc_region_size == 0) {
return 0;
}
/* Try to get the usable size. */
if (ptr == nullptr) {
errno = ENOMEM;
return 0;
}
return ::ams::util::GetReference(::ams::init::g_malloc_allocator).GetSizeOf(ptr);
}
#endif
| 5,226
|
C++
|
.cpp
| 144
| 30.861111
| 117
| 0.651881
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,551
|
init_system_module.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/init/init_system_module.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams::init {
WEAK_SYMBOL void InitializeSystemModuleBeforeConstructors() {
/* This should only be used in exceptional circumstances. */
}
WEAK_SYMBOL void InitializeSystemModule() {
/* TODO: What should we do here, if anything? */
/* Nintendo does nndiagStartup(); nn::diag::InitializeSystemProcessAbortObserver(); */
}
WEAK_SYMBOL void FinalizeSystemModule() {
/* Do nothing by default. */
}
WEAK_SYMBOL void Startup() {
/* TODO: What should we do here, if anything? */
/* Nintendo determines heap size and does init::InitializeAllocator, as relevant. */
}
}
| 1,317
|
C++
|
.cpp
| 32
| 37.0625
| 94
| 0.713281
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,552
|
init_operator_new.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/init/init_operator_new.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
WEAK_SYMBOL void *operator new(size_t size) {
return std::malloc(size);
}
WEAK_SYMBOL void *operator new(size_t size, const std::nothrow_t &) noexcept {
return std::malloc(size);
}
WEAK_SYMBOL void operator delete(void *p) noexcept {
return std::free(p);
}
WEAK_SYMBOL void operator delete(void *p, size_t) noexcept {
return std::free(p);
}
WEAK_SYMBOL void *operator new[](size_t size) {
return std::malloc(size);
}
WEAK_SYMBOL void *operator new[](size_t size, const std::nothrow_t &) noexcept {
return std::malloc(size);
}
WEAK_SYMBOL void operator delete[](void *p) noexcept {
return std::free(p);
}
WEAK_SYMBOL void operator delete[](void *p, size_t) noexcept {
return std::free(p);
}
| 1,393
|
C++
|
.cpp
| 40
| 32.475
| 80
| 0.729368
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,553
|
ro_ro_exception_info.os.horizon.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/ro/impl/ro_ro_exception_info.os.horizon.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams::ro::impl {
namespace {
bool SearchSegmentHead(uintptr_t *out, uintptr_t target, svc::MemoryState state) {
svc::MemoryInfo mem_info;
svc::PageInfo page_info;
bool success = false;
for (uintptr_t cur = target; cur <= target; cur = mem_info.base_address - 1) {
R_ABORT_UNLESS(svc::QueryMemory(std::addressof(mem_info), std::addressof(page_info), cur));
if (mem_info.state != state || mem_info.permission != svc::MemoryPermission_ReadExecute) {
break;
}
*out = mem_info.base_address;
success = true;
}
return success;
}
bool SearchSegmentTail(uintptr_t *out, uintptr_t target, svc::MemoryState state) {
svc::MemoryInfo mem_info;
svc::PageInfo page_info;
bool success = false;
for (uintptr_t cur = target; cur >= target; cur = mem_info.base_address + mem_info.size) {
R_ABORT_UNLESS(svc::QueryMemory(std::addressof(mem_info), std::addressof(page_info), cur));
if (mem_info.state != state) {
break;
}
*out = mem_info.base_address + mem_info.size - 1;
success = true;
}
return success;
}
bool QueryModule(uintptr_t *out_address, size_t *out_size, uintptr_t pc) {
/* Query the program counter. */
svc::MemoryInfo mem_info;
svc::PageInfo page_info;
R_ABORT_UNLESS(svc::QueryMemory(std::addressof(mem_info), std::addressof(page_info), pc));
/* Check memory info. */
if (mem_info.permission != svc::MemoryPermission_ReadExecute) {
return false;
}
if (mem_info.state != svc::MemoryState_Code && mem_info.state != svc::MemoryState_AliasCode) {
return false;
}
/* Find head/tail. */
uintptr_t head = 0, tail = 0;
AMS_ABORT_UNLESS(SearchSegmentHead(std::addressof(head), pc, mem_info.state));
AMS_ABORT_UNLESS(SearchSegmentTail(std::addressof(tail), pc, mem_info.state));
AMS_ABORT_UNLESS(SearchSegmentTail(std::addressof(tail), tail + 1, mem_info.state == svc::MemoryState_Code ? svc::MemoryState_CodeData : svc::MemoryState_AliasCodeData));
/* Set output. */
*out_address = head;
*out_size = tail + 1 - head;
return true;
}
}
bool GetExceptionInfo(ExceptionInfo *out, uintptr_t pc) {
/* Check pre-conditions. */
AMS_ASSERT(out != nullptr);
/* Find the module. */
if (!QueryModule(std::addressof(out->module_address), std::addressof(out->module_size), pc)) {
return false;
}
/* Validate the module. */
rocrt::ModuleHeaderLocation *loc = reinterpret_cast<rocrt::ModuleHeaderLocation *>(out->module_address);
rocrt::ModuleHeader *header = rocrt::GetModuleHeader(loc);
AMS_ABORT_UNLESS(header->signature == rocrt::ModuleHeaderVersion);
/* Set the exception info. */
out->info_offset = loc->header_offset + header->exception_info_start_offset;
out->info_size = header->exception_info_end_offset - header->exception_info_start_offset;
return true;
}
}
| 4,118
|
C++
|
.cpp
| 86
| 37.453488
| 182
| 0.599451
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,554
|
pgl_shell_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/pgl/pgl_shell_api.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "pgl_remote_event_observer.hpp"
namespace ams::pgl {
namespace {
struct PglEventObserverAllocator;
using RemoteAllocator = ams::sf::ExpHeapStaticAllocator<1_KB, PglEventObserverAllocator>;
using RemoteObjectFactory = ams::sf::ObjectFactory<typename RemoteAllocator::Policy>;
class StaticAllocatorInitializer {
public:
StaticAllocatorInitializer() {
RemoteAllocator::Initialize(lmem::CreateOption_None);
}
} g_static_allocator_initializer;
template<typename T, typename... Args>
T *AllocateFromStaticExpHeap(Args &&... args) {
T * const object = static_cast<T *>(RemoteAllocator::Allocate(sizeof(T)));
if (AMS_LIKELY(object != nullptr)) {
std::construct_at(object, std::forward<Args>(args)...);
}
return object;
}
template<typename T>
void FreeToStaticExpHeap(T *object) {
return RemoteAllocator::Deallocate(object, sizeof(T));
}
template<typename T, typename... Args> requires std::derived_from<T, impl::EventObserverInterface>
EventObserver::UniquePtr MakeUniqueFromStaticExpHeap(Args &&... args) {
return EventObserver::UniquePtr{AllocateFromStaticExpHeap<T>(std::forward<Args>(args)...)};
}
}
void EventObserver::Deleter::operator()(impl::EventObserverInterface *obj) {
FreeToStaticExpHeap(obj);
}
#if defined(ATMOSPHERE_OS_HORIZON)
Result Initialize() {
R_RETURN(::pglInitialize());
}
void Finalize() {
return pglExit();
}
Result LaunchProgram(os::ProcessId *out, const ncm::ProgramLocation &loc, u32 process_flags, u8 pgl_flags) {
static_assert(sizeof(*out) == sizeof(u64));
static_assert(sizeof(loc) == sizeof(::NcmProgramLocation));
R_RETURN(::pglLaunchProgram(reinterpret_cast<u64 *>(out), reinterpret_cast<const ::NcmProgramLocation *>(std::addressof(loc)), process_flags, pgl_flags));
}
Result TerminateProcess(os::ProcessId process_id) {
R_RETURN(::pglTerminateProcess(static_cast<u64>(process_id)));
}
Result LaunchProgramFromHost(os::ProcessId *out, const char *content_path, u32 process_flags) {
static_assert(sizeof(*out) == sizeof(u64));
R_RETURN(::pglLaunchProgramFromHost(reinterpret_cast<u64 *>(out), content_path, process_flags));
}
Result GetHostContentMetaInfo(pgl::ContentMetaInfo *out, const char *content_path) {
static_assert(sizeof(*out) == sizeof(::PglContentMetaInfo));
R_RETURN(::pglGetHostContentMetaInfo(reinterpret_cast<::PglContentMetaInfo *>(out), content_path));
}
Result GetApplicationProcessId(os::ProcessId *out) {
static_assert(sizeof(*out) == sizeof(u64));
R_RETURN(::pglGetApplicationProcessId(reinterpret_cast<u64 *>(out)));
}
Result BoostSystemMemoryResourceLimit(u64 size) {
R_RETURN(::pglBoostSystemMemoryResourceLimit(size));
}
Result IsProcessTracked(bool *out, os::ProcessId process_id) {
R_RETURN(::pglIsProcessTracked(out, static_cast<u64>(process_id)));
}
Result EnableApplicationCrashReport(bool enabled) {
R_RETURN(::pglEnableApplicationCrashReport(enabled));
}
Result IsApplicationCrashReportEnabled(bool *out) {
R_RETURN(::pglIsApplicationCrashReportEnabled(out));
}
Result EnableApplicationAllThreadDumpOnCrash(bool enabled) {
R_RETURN(::pglEnableApplicationAllThreadDumpOnCrash(enabled));
}
Result TriggerApplicationSnapShotDumper(const char *arg, SnapShotDumpType dump_type) {
R_RETURN(::pglTriggerApplicationSnapShotDumper(static_cast<::PglSnapShotDumpType>(dump_type), arg));
}
Result GetEventObserver(pgl::EventObserver *out) {
::PglEventObserver obs;
R_TRY(::pglGetEventObserver(std::addressof(obs)));
if (hos::GetVersion() >= hos::Version_12_0_0) {
auto observer_holder = MakeUniqueFromStaticExpHeap<impl::EventObserverByTipc<RemoteEventObserver>>(obs);
R_UNLESS(observer_holder != nullptr, pgl::ResultOutOfMemory());
*out = pgl::EventObserver(std::move(observer_holder));
} else {
auto remote_observer = RemoteObjectFactory::CreateSharedEmplaced<pgl::sf::IEventObserver, RemoteEventObserver>(obs);
R_UNLESS(remote_observer != nullptr, pgl::ResultOutOfMemory());
auto observer_holder = MakeUniqueFromStaticExpHeap<impl::EventObserverByCmif>(std::move(remote_observer));
R_UNLESS(observer_holder != nullptr, pgl::ResultOutOfMemory());
*out = pgl::EventObserver(std::move(observer_holder));
}
R_SUCCEED();
}
#else
Result Initialize() {
AMS_ABORT("TODO");
}
void Finalize() {
AMS_ABORT("TODO");
}
Result LaunchProgram(os::ProcessId *out, const ncm::ProgramLocation &loc, u32 process_flags, u8 pgl_flags) {
AMS_UNUSED(out, loc, process_flags, pgl_flags);
AMS_ABORT("TODO");
}
Result TerminateProcess(os::ProcessId process_id) {
AMS_UNUSED(process_id);
AMS_ABORT("TODO");
}
Result LaunchProgramFromHost(os::ProcessId *out, const char *content_path, u32 process_flags) {
AMS_UNUSED(out, content_path, process_flags);
AMS_ABORT("TODO");
}
Result GetHostContentMetaInfo(pgl::ContentMetaInfo *out, const char *content_path) {
AMS_UNUSED(out, content_path);
AMS_ABORT("TODO");
}
Result GetApplicationProcessId(os::ProcessId *out) {
AMS_UNUSED(out);
AMS_ABORT("TODO");
}
Result BoostSystemMemoryResourceLimit(u64 size) {
AMS_UNUSED(size);
AMS_ABORT("TODO");
}
Result IsProcessTracked(bool *out, os::ProcessId process_id) {
AMS_UNUSED(out, process_id);
AMS_ABORT("TODO");
}
Result EnableApplicationCrashReport(bool enabled) {
AMS_UNUSED(enabled);
AMS_ABORT("TODO");
}
Result IsApplicationCrashReportEnabled(bool *out) {
AMS_UNUSED(out);
AMS_ABORT("TODO");
}
Result EnableApplicationAllThreadDumpOnCrash(bool enabled) {
AMS_UNUSED(enabled);
AMS_ABORT("TODO");
}
Result TriggerApplicationSnapShotDumper(const char *arg, SnapShotDumpType dump_type) {
AMS_UNUSED(arg, dump_type);
AMS_ABORT("TODO");
}
Result GetEventObserver(pgl::EventObserver *out) {
AMS_UNUSED(out);
AMS_ABORT("TODO");
}
#endif
}
| 7,285
|
C++
|
.cpp
| 166
| 36.409639
| 162
| 0.672083
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,555
|
pgl_srv_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/pgl/srv/pgl_srv_api.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "pgl_srv_shell.hpp"
#include "pgl_srv_shell_event_observer.hpp"
#include "pgl_srv_tipc_utils.hpp"
namespace ams::pgl::srv {
namespace {
/* pgl. */
enum PortIndex {
PortIndex_Shell,
PortIndex_Count,
};
constexpr sm::ServiceName ShellServiceName = sm::ServiceName::Encode("pgl");
constexpr size_t ShellMaxSessions = 8; /* Official maximum is 6. */
using CmifServerManager = ams::sf::hipc::ServerManager<PortIndex_Count>;
constexpr size_t ObserverMaxSessions = 4;
using ShellPortMeta = ams::tipc::PortMeta<ShellMaxSessions + ObserverMaxSessions, pgl::tipc::IShellInterface, pgl::srv::ShellInterfaceTipc, ams::tipc::SingletonAllocator>;
using TipcServerManager = ams::tipc::ServerManager<ShellPortMeta>;
/* NOTE: Nintendo reserves only 0x2000 bytes for heap, which is used "mostly" to allocate shell event observers. */
/* However, we would like very much for homebrew sysmodules to be able to subscribe to events if they so choose */
/* And so we will use a larger heap (32 KB). Note that we reduce the heap size for tipc, where objects are */
/* allocated statically. */
/* We should have a smaller memory footprint than N in the end, regardless. */
struct CmifGlobals {
u8 heap_memory[32_KB];
lmem::HeapHandle heap_handle;
ams::sf::ExpHeapAllocator server_allocator;
ams::sf::UnmanagedServiceObject<pgl::sf::IShellInterface, pgl::srv::ShellInterfaceCmif> shell_interface{std::addressof(server_allocator)};
CmifServerManager server_manager;
};
struct TipcGlobals {
u8 heap_memory[24_KB];
lmem::HeapHandle heap_handle;
TipcServerManager server_manager;
ams::tipc::SlabAllocator<ams::tipc::ServiceObject<pgl::tipc::IEventObserver, pgl::srv::ShellEventObserverTipc>, ObserverMaxSessions> observer_allocator;
};
constinit union {
util::TypedStorage<CmifGlobals> cmif;
util::TypedStorage<TipcGlobals> tipc;
} g_globals;
ALWAYS_INLINE CmifGlobals &GetGlobalsForCmif() {
return GetReference(g_globals.cmif);
}
ALWAYS_INLINE TipcGlobals &GetGlobalsForTipc() {
return GetReference(g_globals.tipc);
}
ALWAYS_INLINE bool UseTipcServer() {
return hos::GetVersion() >= hos::Version_12_0_0;
}
ALWAYS_INLINE lmem::HeapHandle GetHeapHandle() {
if (UseTipcServer()) {
return GetGlobalsForTipc().heap_handle;
} else {
return GetGlobalsForCmif().heap_handle;
}
}
template<typename T>
ALWAYS_INLINE void InitializeHeapImpl(util::TypedStorage<T> &globals_storage) {
/* Construct the globals object. */
util::ConstructAt(globals_storage);
/* Get reference to the globals. */
auto &globals = GetReference(globals_storage);
/* Set the heap handle. */
globals.heap_handle = lmem::CreateExpHeap(globals.heap_memory, sizeof(globals.heap_memory), lmem::CreateOption_ThreadSafe);
/* If we should, setup the server allocator. */
if constexpr (requires (T &t) { t.server_allocator; }) {
globals.server_allocator.Attach(globals.heap_handle);
}
}
void RegisterServiceSession() {
/* Register "pgl" with the appropriate server manager. */
if (UseTipcServer()) {
/* Get the globals. */
auto &globals = GetGlobalsForTipc();
/* Initialize the server manager. */
globals.server_manager.Initialize();
/* Register the pgl service. */
globals.server_manager.RegisterPort(ShellServiceName, ShellMaxSessions);
} else {
/* Get the globals. */
auto &globals = GetGlobalsForCmif();
/* Register the shell server with the cmif server manager. */
R_ABORT_UNLESS(globals.server_manager.RegisterObjectForServer(globals.shell_interface.GetShared(), ShellServiceName, ShellMaxSessions));
}
}
void LoopProcessServer() {
/* Loop processing for the appropriate server manager. */
if (UseTipcServer()) {
GetGlobalsForTipc().server_manager.LoopAuto();
} else {
GetGlobalsForCmif().server_manager.LoopProcess();
}
}
}
void InitializeHeap() {
/* Initialize the heap (and construct the globals object) for the appropriate ipc protocol. */
if (UseTipcServer()) {
/* We're servicing via tipc. */
InitializeHeapImpl(g_globals.tipc);
} else {
/* We're servicing via cmif. */
InitializeHeapImpl(g_globals.cmif);
}
}
void *Allocate(size_t size) {
return lmem::AllocateFromExpHeap(GetHeapHandle(), size);
}
void Deallocate(void *p, size_t size) {
AMS_UNUSED(size);
return lmem::FreeToExpHeap(GetHeapHandle(), p);
}
void StartServer() {
/* Enable extra application threads, if we should. */
{
u8 enable_application_extra_thread;
const size_t sz = settings::fwdbg::GetSettingsItemValue(std::addressof(enable_application_extra_thread), sizeof(enable_application_extra_thread), "application_extra_thread", "enable_application_extra_thread");
if (sz == sizeof(enable_application_extra_thread) && enable_application_extra_thread != 0) {
/* NOTE: Nintendo does not check that this succeeds. */
pm::shell::BoostApplicationThreadResourceLimit();
}
}
/* Enable extra system threads, if we should. */
{
u8 enable_system_extra_thread;
const size_t sz = settings::fwdbg::GetSettingsItemValue(std::addressof(enable_system_extra_thread), sizeof(enable_system_extra_thread), "application_extra_thread", "enable_system_extra_thread");
if (sz == sizeof(enable_system_extra_thread) && enable_system_extra_thread != 0) {
/* NOTE: Nintendo does not check that this succeeds. */
pm::shell::BoostSystemThreadResourceLimit();
}
}
/* Register service session. */
RegisterServiceSession();
/* Start the Process Tracking thread. */
pgl::srv::InitializeProcessControlTask();
/* Loop process. */
LoopProcessServer();
}
Result AllocateShellEventObserverForTipc(os::NativeHandle *out) {
/* Get the shell event observer allocator. */
auto &allocator = GetGlobalsForTipc().observer_allocator;
/* Allocate an object. */
auto *object = allocator.Allocate();
R_UNLESS(object != nullptr, pgl::ResultOutOfMemory());
/* Set the object's deleter. */
object->SetDeleter(std::addressof(allocator));
/* Add the session to the server manager. */
/* NOTE: If this fails, the object will be leaked. */
/* TODO: Should we avoid leaking the object? Nintendo does not. */
R_TRY(GetGlobalsForTipc().server_manager.AddSession(out, object));
R_SUCCEED();
}
}
| 8,126
|
C++
|
.cpp
| 166
| 38.855422
| 221
| 0.628788
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,556
|
pgl_srv_shell.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/pgl/srv/pgl_srv_shell.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "pgl_srv_shell.hpp"
#include "pgl_srv_shell_event_observer.hpp"
namespace ams::pgl::srv {
namespace {
constexpr inline size_t ProcessDataCount = 0x20;
struct ProcessData {
os::ProcessId process_id;
u32 flags;
};
static_assert(util::is_pod<ProcessData>::value);
enum ProcessDataFlag : u32 {
ProcessDataFlag_None = 0,
ProcessDataFlag_DetailedCrashReportAllowed = (1 << 0),
ProcessDataFlag_DetailedCrashReportEnabled = (1 << 1),
ProcessDataFlag_HasLogOption = (1 << 2),
ProcessDataFlag_OutputAllLog = (1 << 3),
ProcessDataFlag_EnableCrashReportScreenShot = (1 << 4),
};
constinit bool g_is_production = true;
constinit bool g_enable_crash_report_screenshot = true;
constinit bool g_enable_jit_debug = false;
constexpr inline size_t ProcessControlTaskStackSize = 8_KB;
constinit os::ThreadType g_process_control_task_thread = {};
alignas(os::ThreadStackAlignment) constinit u8 g_process_control_task_stack[ProcessControlTaskStackSize];
constinit os::SdkMutex g_observer_list_mutex;
constinit util::IntrusiveListBaseTraits<ShellEventObserverHolder>::ListType g_observer_list;
constinit os::SdkMutex g_process_data_mutex;
constinit ProcessData g_process_data[ProcessDataCount] = {};
constinit os::ProcessId g_crashed_process_id = os::InvalidProcessId;
constinit os::ProcessId g_creport_process_id = os::InvalidProcessId;
constinit os::ProcessId g_ssd_process_id = os::InvalidProcessId;
ProcessData *FindProcessData(os::ProcessId process_id) {
for (auto &data : g_process_data) {
if (data.process_id == process_id) {
return std::addressof(data);
}
}
return nullptr;
}
u32 ConvertToProcessDataFlags(u8 pgl_flags) {
if ((pgl_flags & pgl::LaunchFlags_EnableDetailedCrashReport) == 0) {
/* If we shouldn't generate detailed crash reports, set no flags. */
return ProcessDataFlag_None;
} else {
/* We can and should generate detailed crash reports. */
u32 data_flags = ProcessDataFlag_DetailedCrashReportAllowed | ProcessDataFlag_DetailedCrashReportEnabled;
/* If we should enable crash report screenshots, check the correct flag. */
if (g_enable_crash_report_screenshot) {
const u32 test_flag = g_is_production ? pgl::LaunchFlags_EnableCrashReportScreenShotForProduction : pgl::LaunchFlags_EnableCrashReportScreenShotForDevelop;
if ((pgl_flags & test_flag) != 0) {
data_flags |= ProcessDataFlag_EnableCrashReportScreenShot;
}
}
return data_flags;
}
}
util::optional<os::ProcessId> GetRunningApplicationProcessId() {
os::ProcessId process_id;
if (R_SUCCEEDED(pm::shell::GetApplicationProcessIdForShell(std::addressof(process_id)))) {
return process_id;
} else {
return util::nullopt;
}
}
s32 ConvertDumpTypeToArgument(SnapShotDumpType dump_type) {
switch (dump_type) {
case SnapShotDumpType::None: return -1;
case SnapShotDumpType::Auto: return 0;
case SnapShotDumpType::Full: return 1;
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
bool GetSnapShotDumpOutputAllLog(os::ProcessId process_id) {
/* Check if we have an option set for the process. */
{
std::scoped_lock lk(g_process_data_mutex);
if (ProcessData *data = FindProcessData(process_id); data != nullptr) {
if ((data->flags & ProcessDataFlag_HasLogOption) != 0) {
return ((data->flags & ProcessDataFlag_OutputAllLog) != 0);
}
}
}
/* If we don't have an option for the process, fall back to settings. */
u8 log_option;
const size_t option_size = settings::fwdbg::GetSettingsItemValue(std::addressof(log_option), sizeof(log_option), "snap_shot_dump", "output_all_log");
return (option_size == sizeof(log_option) && log_option != 0);
}
size_t CreateSnapShotDumpArguments(char *dst, size_t dst_size, os::ProcessId process_id, SnapShotDumpType dump_type, const char *str_arg) {
const s32 dump_arg = ConvertDumpTypeToArgument(dump_type);
const s32 log_arg = GetSnapShotDumpOutputAllLog(process_id) ? 1 : 0;
if (str_arg != nullptr) {
return util::SNPrintf(dst, dst_size, "D %010llu \"%s\" -log %d -dump %d", static_cast<unsigned long long>(static_cast<u64>(process_id)), str_arg, log_arg, dump_arg);
} else {
return util::SNPrintf(dst, dst_size, "D %010llu -log %d -dump %d", static_cast<unsigned long long>(static_cast<u64>(process_id)), log_arg, dump_arg);
}
}
Result TriggerSnapShotDumper(os::ProcessId process_id, SnapShotDumpType dump_type, const char *arg) {
/* Create the arguments. */
char process_arguments[800];
const size_t arg_len = CreateSnapShotDumpArguments(process_arguments, sizeof(process_arguments), process_id, dump_type, arg);
/* Set the arguments. */
R_TRY(ldr::SetProgramArgument(ncm::SystemDebugAppletId::SnapShotDumper, process_arguments, arg_len + 1));
/* Launch the process. */
os::ProcessId ssd_process_id = os::InvalidProcessId;
R_TRY(pm::shell::LaunchProgram(std::addressof(ssd_process_id), ncm::ProgramLocation::Make(ncm::SystemDebugAppletId::SnapShotDumper, ncm::StorageId::BuiltInSystem), pm::LaunchFlags_None));
/* Set the globals. */
g_crashed_process_id = process_id;
g_ssd_process_id = ssd_process_id;
R_SUCCEED();
}
bool ShouldSnapShotAutoDump() {
bool dump;
const size_t sz = settings::fwdbg::GetSettingsItemValue(std::addressof(dump), sizeof(dump), "snap_shot_dump", "auto_dump");
return sz == sizeof(dump) && dump;
}
bool ShouldSnapShotFullDump() {
bool dump;
const size_t sz = settings::fwdbg::GetSettingsItemValue(std::addressof(dump), sizeof(dump), "snap_shot_dump", "full_dump");
return sz == sizeof(dump) && dump;
}
SnapShotDumpType GetSnapShotDumpType() {
if (ShouldSnapShotAutoDump()) {
if (ShouldSnapShotFullDump()) {
return SnapShotDumpType::Full;
} else {
return SnapShotDumpType::Auto;
}
} else {
return SnapShotDumpType::None;
}
}
void TriggerSnapShotDumper(os::ProcessId process_id) {
TriggerSnapShotDumper(process_id, GetSnapShotDumpType(), nullptr);
}
s32 GetCrashReportDetailedArgument(u32 data_flags) {
if (((data_flags & ProcessDataFlag_DetailedCrashReportAllowed) != 0) && ((data_flags & ProcessDataFlag_DetailedCrashReportEnabled) != 0)) {
return 1;
} else {
return 0;
}
}
s32 GetCrashReportScreenShotArgument(u32 data_flags) {
if (settings::system::GetErrorReportSharePermission() == settings::system::ErrorReportSharePermission_Granted) {
return ((data_flags & ProcessDataFlag_EnableCrashReportScreenShot) != 0) ? 1 : 0;
} else {
return 0;
}
}
void TriggerCrashReport(os::ProcessId process_id) {
/* If the program that crashed is creport, we should just terminate both processes and return. */
if (process_id == g_creport_process_id) {
TerminateProcess(g_crashed_process_id);
TerminateProcess(g_creport_process_id);
g_crashed_process_id = os::InvalidProcessId;
g_creport_process_id = os::InvalidProcessId;
return;
}
/* Get the data flags for the process. */
u32 data_flags;
{
std::scoped_lock lk(g_process_data_mutex);
if (auto *data = FindProcessData(process_id); data != nullptr) {
data_flags = data->flags;
} else {
data_flags = ProcessDataFlag_None;
}
}
/* Generate arguments. */
char arguments[0x40];
const size_t len = util::SNPrintf(arguments, sizeof(arguments), "%" PRId64 " %d %d %d", static_cast<s64>(static_cast<u64>(process_id)), GetCrashReportDetailedArgument(data_flags), GetCrashReportScreenShotArgument(data_flags), g_enable_jit_debug);
if (R_FAILED(ldr::SetProgramArgument(ncm::SystemProgramId::Creport, arguments, len + 1))) {
return;
}
/* Launch creport. */
os::ProcessId creport_process_id;
if (R_FAILED(pm::shell::LaunchProgram(std::addressof(creport_process_id), ncm::ProgramLocation::Make(ncm::SystemProgramId::Creport, ncm::StorageId::BuiltInSystem), pm::LaunchFlags_None))) {
return;
}
/* Set the globals. */
g_crashed_process_id = process_id;
g_creport_process_id = creport_process_id;
}
void HandleException(os::ProcessId process_id) {
if (g_enable_jit_debug) {
/* If jit debug is enabled, we want to try to launch snap shot dumper. */
ProcessData *data = nullptr;
{
std::scoped_lock lk(g_process_data_mutex);
data = FindProcessData(process_id);
}
/* If we're tracking the process, we can launch dumper. Otherwise we should just terminate. */
if (data != nullptr) {
TriggerSnapShotDumper(process_id);
} else {
TerminateProcess(process_id);
}
} else {
/* Otherwise, we want to launch creport. */
TriggerCrashReport(process_id);
}
}
void HandleExit(os::ProcessId process_id) {
std::scoped_lock lk(g_process_data_mutex);
if (auto *data = FindProcessData(process_id); data != nullptr) {
data->process_id = os::InvalidProcessId;
}
}
void OnProcessEvent(const pm::ProcessEventInfo &event_info) {
/* Determine if we're tracking the process. */
ProcessData *data = nullptr;
{
std::scoped_lock lk(g_process_data_mutex);
data = FindProcessData(event_info.process_id);
}
/* If we are, we're going to want to notify our listeners. */
if (data != nullptr) {
/* If we closed the process, note that. */
if (static_cast<pm::ProcessEvent>(event_info.event) == pm::ProcessEvent::Exited) {
HandleExit(event_info.process_id);
}
/* Notify all observers. */
std::scoped_lock lk(g_observer_list_mutex);
for (auto &observer : g_observer_list) {
observer.Notify(event_info);
}
}
/* If the process crashed, handle that. */
if (static_cast<pm::ProcessEvent>(event_info.event) == pm::ProcessEvent::Exception) {
HandleException(event_info.process_id);
}
}
void ProcessControlTask(void *) {
/* Get the process event event from pm. */
os::SystemEvent process_event;
R_ABORT_UNLESS(pm::shell::GetProcessEventEvent(std::addressof(process_event)));
while (true) {
/* Wait for an event to come in, and clear our signal. */
process_event.Wait();
process_event.Clear();
bool continue_getting_event = true;
while (continue_getting_event) {
/* Try to get an event info. */
pm::ProcessEventInfo event_info;
if (R_FAILED(pm::shell::GetProcessEventInfo(std::addressof(event_info)))) {
break;
}
/* Process the event. */
switch (static_cast<pm::ProcessEvent>(event_info.event)) {
case pm::ProcessEvent::None:
continue_getting_event = false;
break;
case pm::ProcessEvent::Exited:
{
/* If SnapShotDumper terminated, trigger a crash report. */
if (event_info.process_id == g_ssd_process_id && g_crashed_process_id != os::InvalidProcessId) {
TriggerCrashReport(g_crashed_process_id);
}
}
[[fallthrough]];
case pm::ProcessEvent::Started:
case pm::ProcessEvent::Exception:
case pm::ProcessEvent::DebugRunning:
case pm::ProcessEvent::DebugBreak:
OnProcessEvent(event_info);
break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
}
}
}
void InitializeProcessControlTask() {
/* Create the task thread. */
R_ABORT_UNLESS(os::CreateThread(std::addressof(g_process_control_task_thread), ProcessControlTask, nullptr, g_process_control_task_stack, sizeof(g_process_control_task_stack), AMS_GET_SYSTEM_THREAD_PRIORITY(pgl, ProcessControlTask)));
os::SetThreadNamePointer(std::addressof(g_process_control_task_thread), AMS_GET_SYSTEM_THREAD_NAME(pgl, ProcessControlTask));
/* Retrieve settings. */
settings::fwdbg::GetSettingsItemValue(std::addressof(g_enable_jit_debug), sizeof(g_enable_jit_debug), "jit_debug", "enable_jit_debug");
settings::fwdbg::GetSettingsItemValue(std::addressof(g_enable_crash_report_screenshot), sizeof(g_enable_crash_report_screenshot), "creport", "crash_screen_shot");
g_is_production = !settings::fwdbg::IsDebugModeEnabled();
/* Clear all process data. */
{
for (size_t i = 0; i < util::size(g_process_data); i++) {
g_process_data[i].process_id = os::InvalidProcessId;
}
}
/* Start the thread. */
os::StartThread(std::addressof(g_process_control_task_thread));
}
void RegisterShellEventObserver(ShellEventObserverHolder *holder) {
std::scoped_lock lk(g_observer_list_mutex);
g_observer_list.push_back(*holder);
}
void UnregisterShellEventObserver(ShellEventObserverHolder *holder) {
std::scoped_lock lk(g_observer_list_mutex);
for (auto &observer : g_observer_list) {
if (std::addressof(observer) == holder) {
g_observer_list.erase(g_observer_list.iterator_to(observer));
break;
}
}
}
Result LaunchProgram(os::ProcessId *out, const ncm::ProgramLocation &loc, u32 pm_flags, u8 pgl_flags) {
/* Convert the input flags to the internal format. */
const u32 data_flags = ConvertToProcessDataFlags(pgl_flags);
/* If jit debug is enabled, we want to be signaled on crash. */
if (g_enable_jit_debug) {
pm_flags |= pm::LaunchFlags_SignalOnException;
}
/* Launch the process. */
os::ProcessId process_id;
R_TRY(pm::shell::LaunchProgram(std::addressof(process_id), loc, pm_flags & pm::LaunchFlagsMask));
/* Create a ProcessData for the process. */
{
std::scoped_lock lk(g_process_data_mutex);
ProcessData *new_data = FindProcessData(os::InvalidProcessId);
AMS_ABORT_UNLESS(new_data != nullptr);
new_data->process_id = process_id;
new_data->flags = data_flags;
}
/* We succeeded. */
*out = process_id;
R_SUCCEED();
}
Result TerminateProcess(os::ProcessId process_id) {
/* Ask PM to terminate the process. */
R_RETURN(pm::shell::TerminateProcess(process_id));
}
Result GetApplicationProcessId(os::ProcessId *out) {
/* Get the application process id. */
auto application_process_id = GetRunningApplicationProcessId();
R_UNLESS(application_process_id, pgl::ResultApplicationNotRunning());
/* Return the id. */
*out = *application_process_id;
R_SUCCEED();
}
Result BoostSystemMemoryResourceLimit(u64 size) {
/* Ask PM to boost the limit. */
R_RETURN(pm::shell::BoostSystemMemoryResourceLimit(size));
}
bool IsProcessTracked(os::ProcessId process_id) {
/* Check whether a ProcessData exists for the process. */
std::scoped_lock lk(g_process_data_mutex);
return FindProcessData(process_id) != nullptr;
}
void EnableApplicationCrashReport(bool enabled) {
/* Get the application process id. */
auto application_process_id = GetRunningApplicationProcessId();
if (application_process_id) {
/* Find the data for the application process. */
std::scoped_lock lk(g_process_data_mutex);
ProcessData *data = FindProcessData(*application_process_id);
/* It's okay if we aren't tracking the process. */
if (data != nullptr) {
/* Set or clear the flag. */
if (enabled) {
data->flags |= ProcessDataFlag_DetailedCrashReportEnabled;
} else {
data->flags &= ~ProcessDataFlag_DetailedCrashReportEnabled;
}
}
}
}
bool IsApplicationCrashReportEnabled() {
/* Get the application process id. */
auto application_process_id = GetRunningApplicationProcessId();
if (!application_process_id) {
return false;
}
/* Find the data for the process. */
std::scoped_lock lk(g_process_data_mutex);
if (ProcessData *data = FindProcessData(*application_process_id); data != nullptr) {
return (data->flags & ProcessDataFlag_DetailedCrashReportEnabled) != 0;
} else {
return false;
}
}
void EnableApplicationAllThreadDumpOnCrash(bool enabled) {
/* Get the application process id. */
auto application_process_id = GetRunningApplicationProcessId();
if (application_process_id) {
/* Find the data for the application process. */
std::scoped_lock lk(g_process_data_mutex);
ProcessData *data = FindProcessData(*application_process_id);
/* It's okay if we aren't tracking the process. */
if (data != nullptr) {
/* Set or clear the flag. */
if (enabled) {
data->flags |= ProcessDataFlag_OutputAllLog;
} else {
data->flags &= ~ProcessDataFlag_OutputAllLog;
}
/* NOTE: Here Nintendo releases the lock, re-takes the lock, and re-finds the process data. */
/* This is unnecessary and less efficient, so we will not bother. */
/* Note that the flag bit has a meaningful value. */
data->flags |= ProcessDataFlag_HasLogOption;
}
}
}
Result TriggerApplicationSnapShotDumper(SnapShotDumpType dump_type, const char *arg) {
/* Try to get the application process id. */
os::ProcessId process_id;
R_TRY(pm::shell::GetApplicationProcessIdForShell(std::addressof(process_id)));
/* Launch the snapshot dumper, clearing the global tracker process id. */
ON_SCOPE_EXIT { g_ssd_process_id = os::InvalidProcessId; };
R_RETURN(TriggerSnapShotDumper(process_id, dump_type, arg));
}
}
| 21,427
|
C++
|
.cpp
| 423
| 37.612293
| 258
| 0.579511
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,557
|
pgl_srv_shell_interface.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/pgl/srv/pgl_srv_shell_interface.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "pgl_srv_shell.hpp"
#include "pgl_srv_shell_event_observer.hpp"
#include "pgl_srv_shell_host_utils.hpp"
#include "pgl_srv_tipc_utils.hpp"
namespace ams::pgl::srv {
Result ShellInterfaceCommon::LaunchProgramImpl(os::ProcessId *out, const ncm::ProgramLocation &loc, u32 pm_flags, u8 pgl_flags) {
R_RETURN(pgl::srv::LaunchProgram(out, loc, pm_flags, pgl_flags));
}
Result ShellInterfaceCommon::TerminateProcessImpl(os::ProcessId process_id) {
R_RETURN(pgl::srv::TerminateProcess(process_id));
}
Result ShellInterfaceCommon::LaunchProgramFromHostImpl(os::ProcessId *out, const void *content_path, size_t content_path_size, u32 pm_flags) {
AMS_UNUSED(content_path_size);
R_RETURN(pgl::srv::LaunchProgramFromHost(out, static_cast<const char *>(content_path), pm_flags));
}
Result ShellInterfaceCommon::GetHostContentMetaInfoImpl(pgl::ContentMetaInfo *out, const void *content_path, size_t content_path_size) {
AMS_UNUSED(content_path_size);
R_RETURN(pgl::srv::GetHostContentMetaInfo(out, static_cast<const char *>(content_path)));
}
Result ShellInterfaceCommon::GetApplicationProcessIdImpl(os::ProcessId *out) {
R_RETURN(pgl::srv::GetApplicationProcessId(out));
}
Result ShellInterfaceCommon::BoostSystemMemoryResourceLimitImpl(u64 size) {
R_RETURN(pgl::srv::BoostSystemMemoryResourceLimit(size));
}
Result ShellInterfaceCommon::IsProcessTrackedImpl(bool *out, os::ProcessId process_id) {
*out = pgl::srv::IsProcessTracked(process_id);
R_SUCCEED();
}
Result ShellInterfaceCommon::EnableApplicationCrashReportImpl(bool enabled) {
pgl::srv::EnableApplicationCrashReport(enabled);
R_SUCCEED();
}
Result ShellInterfaceCommon::IsApplicationCrashReportEnabledImpl(bool *out) {
*out = pgl::srv::IsApplicationCrashReportEnabled();
R_SUCCEED();
}
Result ShellInterfaceCommon::EnableApplicationAllThreadDumpOnCrashImpl(bool enabled) {
pgl::srv::EnableApplicationAllThreadDumpOnCrash(enabled);
R_SUCCEED();
}
Result ShellInterfaceCommon::TriggerApplicationSnapShotDumperImpl(SnapShotDumpType dump_type, const void *arg, size_t arg_size) {
AMS_UNUSED(arg_size);
R_RETURN(pgl::srv::TriggerApplicationSnapShotDumper(dump_type, static_cast<const char *>(arg)));
}
Result ShellInterfaceCmif::LaunchProgram(ams::sf::Out<os::ProcessId> out, const ncm::ProgramLocation &loc, u32 pm_flags, u8 pgl_flags) {
R_RETURN(this->LaunchProgramImpl(out.GetPointer(), loc, pm_flags, pgl_flags));
}
Result ShellInterfaceCmif::TerminateProcess(os::ProcessId process_id) {
R_RETURN(this->TerminateProcessImpl(process_id));
}
Result ShellInterfaceCmif::LaunchProgramFromHost(ams::sf::Out<os::ProcessId> out, const ams::sf::InBuffer &content_path, u32 pm_flags) {
R_RETURN(this->LaunchProgramFromHostImpl(out.GetPointer(), content_path.GetPointer(), content_path.GetSize(), pm_flags));
}
Result ShellInterfaceCmif::GetHostContentMetaInfo(ams::sf::Out<pgl::ContentMetaInfo> out, const ams::sf::InBuffer &content_path) {
R_RETURN(this->GetHostContentMetaInfoImpl(out.GetPointer(), content_path.GetPointer(), content_path.GetSize()));
}
Result ShellInterfaceCmif::GetApplicationProcessId(ams::sf::Out<os::ProcessId> out) {
R_RETURN(this->GetApplicationProcessIdImpl(out.GetPointer()));
}
Result ShellInterfaceCmif::BoostSystemMemoryResourceLimit(u64 size) {
R_RETURN(this->BoostSystemMemoryResourceLimitImpl(size));
}
Result ShellInterfaceCmif::IsProcessTracked(ams::sf::Out<bool> out, os::ProcessId process_id) {
R_RETURN(this->IsProcessTrackedImpl(out.GetPointer(), process_id));
}
Result ShellInterfaceCmif::EnableApplicationCrashReport(bool enabled) {
R_RETURN(this->EnableApplicationCrashReportImpl(enabled));
}
Result ShellInterfaceCmif::IsApplicationCrashReportEnabled(ams::sf::Out<bool> out) {
R_RETURN(this->IsApplicationCrashReportEnabledImpl(out.GetPointer()));
}
Result ShellInterfaceCmif::EnableApplicationAllThreadDumpOnCrash(bool enabled) {
R_RETURN(this->EnableApplicationAllThreadDumpOnCrashImpl(enabled));
}
Result ShellInterfaceCmif::TriggerApplicationSnapShotDumper(SnapShotDumpType dump_type, const ams::sf::InBuffer &arg) {
R_RETURN(this->TriggerApplicationSnapShotDumperImpl(dump_type, arg.GetPointer(), arg.GetSize()));
}
Result ShellInterfaceCmif::GetShellEventObserver(ams::sf::Out<ams::sf::SharedPointer<pgl::sf::IEventObserver>> out) {
/* Allocate a new interface. */
auto session = ObjectFactory::CreateSharedEmplaced<pgl::sf::IEventObserver, ShellEventObserverCmif>(m_allocator);
R_UNLESS(session != nullptr, pgl::ResultOutOfMemory());
*out = std::move(session);
R_SUCCEED();
}
Result ShellInterfaceCmif::Command21NotImplemented(ams::sf::Out<u64> out, u32 in, const ams::sf::InBuffer &buf1, const ams::sf::InBuffer &buf2) {
AMS_UNUSED(out, in, buf1, buf2);
R_THROW(pgl::ResultNotImplemented());
}
Result ShellInterfaceTipc::LaunchProgram(ams::tipc::Out<os::ProcessId> out, const ncm::ProgramLocation loc, u32 pm_flags, u8 pgl_flags) {
R_RETURN(this->LaunchProgramImpl(out.GetPointer(), loc, pm_flags, pgl_flags));
}
Result ShellInterfaceTipc::TerminateProcess(os::ProcessId process_id) {
R_RETURN(this->TerminateProcessImpl(process_id));
}
Result ShellInterfaceTipc::LaunchProgramFromHost(ams::tipc::Out<os::ProcessId> out, const ams::tipc::InBuffer content_path, u32 pm_flags) {
R_RETURN(this->LaunchProgramFromHostImpl(out.GetPointer(), content_path.GetPointer(), content_path.GetSize(), pm_flags));
}
Result ShellInterfaceTipc::GetHostContentMetaInfo(ams::tipc::Out<pgl::ContentMetaInfo> out, const ams::tipc::InBuffer content_path) {
R_RETURN(this->GetHostContentMetaInfoImpl(out.GetPointer(), content_path.GetPointer(), content_path.GetSize()));
}
Result ShellInterfaceTipc::GetApplicationProcessId(ams::tipc::Out<os::ProcessId> out) {
R_RETURN(this->GetApplicationProcessIdImpl(out.GetPointer()));
}
Result ShellInterfaceTipc::BoostSystemMemoryResourceLimit(u64 size) {
R_RETURN(this->BoostSystemMemoryResourceLimitImpl(size));
}
Result ShellInterfaceTipc::IsProcessTracked(ams::tipc::Out<bool> out, os::ProcessId process_id) {
R_RETURN(this->IsProcessTrackedImpl(out.GetPointer(), process_id));
}
Result ShellInterfaceTipc::EnableApplicationCrashReport(bool enabled) {
R_RETURN(this->EnableApplicationCrashReportImpl(enabled));
}
Result ShellInterfaceTipc::IsApplicationCrashReportEnabled(ams::tipc::Out<bool> out) {
R_RETURN(this->IsApplicationCrashReportEnabledImpl(out.GetPointer()));
}
Result ShellInterfaceTipc::EnableApplicationAllThreadDumpOnCrash(bool enabled) {
R_RETURN(this->EnableApplicationAllThreadDumpOnCrashImpl(enabled));
}
Result ShellInterfaceTipc::GetShellEventObserver(ams::tipc::OutMoveHandle out) {
R_RETURN(pgl::srv::AllocateShellEventObserverForTipc(out.GetPointer()));
}
}
| 7,957
|
C++
|
.cpp
| 139
| 51.151079
| 149
| 0.736889
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,558
|
pgl_srv_shell_event_observer.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/pgl/srv/pgl_srv_shell_event_observer.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "pgl_srv_shell_event_observer.hpp"
#include "pgl_srv_shell.hpp"
namespace ams::pgl::srv {
ShellEventObserverImpl::ShellEventObserverImpl() : m_message_queue(m_queue_buffer, QueueCapacity), m_event(os::EventClearMode_AutoClear, true) {
m_heap_handle = lmem::CreateUnitHeap(m_event_info_data, sizeof(m_event_info_data), sizeof(m_event_info_data[0]), lmem::CreateOption_ThreadSafe, 8, GetPointer(m_heap_head));
RegisterShellEventObserver(util::ConstructAt(m_holder, this));
}
ShellEventObserverImpl::~ShellEventObserverImpl() {
UnregisterShellEventObserver(GetPointer(m_holder));
util::DestroyAt(m_holder);
}
Result ShellEventObserverImpl::PopEventInfo(pm::ProcessEventInfo *out) {
/* Receive an info from the queue. */
uintptr_t info_address;
R_UNLESS(m_message_queue.TryReceive(std::addressof(info_address)), pgl::ResultNotAvailable());
pm::ProcessEventInfo *info = reinterpret_cast<pm::ProcessEventInfo *>(info_address);
/* Set the output. */
*out = *info;
/* Free the received info. */
lmem::FreeToUnitHeap(m_heap_handle, info);
R_SUCCEED();
}
void ShellEventObserverImpl::Notify(const pm::ProcessEventInfo &info) {
/* Allocate a new info. */
auto allocated = reinterpret_cast<pm::ProcessEventInfo *>(lmem::AllocateFromUnitHeap(m_heap_handle));
if (!allocated) {
return;
}
/* Set it to the notification. */
*allocated = info;
/* Try to send it. */
if (!m_message_queue.TrySend(reinterpret_cast<uintptr_t>(allocated))) {
lmem::FreeToUnitHeap(m_heap_handle, allocated);
return;
}
/* Notify that we have a new info available. */
m_event.Signal();
}
Result ShellEventObserverCmif::GetProcessEventHandle(ams::sf::OutCopyHandle out) {
out.SetValue(this->GetEvent().GetReadableHandle(), false);
R_SUCCEED();
}
Result ShellEventObserverCmif::GetProcessEventInfo(ams::sf::Out<pm::ProcessEventInfo> out) {
R_RETURN(this->PopEventInfo(out.GetPointer()));
}
Result ShellEventObserverTipc::GetProcessEventHandle(ams::tipc::OutCopyHandle out) {
out.SetValue(this->GetEvent().GetReadableHandle());
R_SUCCEED();
}
Result ShellEventObserverTipc::GetProcessEventInfo(ams::tipc::Out<pm::ProcessEventInfo> out) {
R_RETURN(this->PopEventInfo(out.GetPointer()));
}
}
| 3,175
|
C++
|
.cpp
| 69
| 39.637681
| 180
| 0.688572
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,559
|
pgl_srv_shell_host_utils.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/pgl/srv/pgl_srv_shell_host_utils.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "pgl_srv_shell_host_utils.hpp"
#include "pgl_srv_shell.hpp"
namespace ams::pgl::srv {
namespace {
constexpr inline char HostPackageMountName[] = "HostPackageRead";
static_assert(sizeof(HostPackageMountName) - 1 <= fs::MountNameLengthMax);
struct CaseInsensitiveCharTraits : public std::char_traits<char> {
static constexpr char to_upper(char c) {
return std::toupper(static_cast<unsigned char>(c));
}
static constexpr bool eq(char c1, char c2) {
return to_upper(c1) == to_upper(c2);
}
static constexpr bool lt(char c1, char c2) {
return to_upper(c1) < to_upper(c2);
}
static constexpr int compare(const char *s1, const char *s2, size_t n) {
while ( n-- != 0 ) {
if ( to_upper(*s1) < to_upper(*s2) ) return -1;
if ( to_upper(*s1) > to_upper(*s2) ) return 1;
++s1; ++s2;
}
return 0;
}
static constexpr const char *find(const char *s, int n, char a) {
auto const ua (to_upper(a));
while ( n-- != 0 )
{
if (to_upper(*s) == ua)
return s;
s++;
}
return nullptr;
}
};
using PathView = util::basic_string_view<char, CaseInsensitiveCharTraits>;
enum class ExtensionType {
None = 0,
Nsp = 1,
Nspd = 2,
};
bool HasSuffix(const char *str, const char *suffix) {
const size_t suffix_len = std::strlen(suffix);
const size_t str_len = std::strlen(str);
if (suffix_len > str_len) {
return false;
}
return (PathView(str).substr(str_len - suffix_len) == PathView(suffix));
}
class HostPackageReader {
NON_COPYABLE(HostPackageReader);
NON_MOVEABLE(HostPackageReader);
private:
char m_content_path[fs::EntryNameLengthMax] = {};
ExtensionType m_extension_type = ExtensionType::None;
char m_mount_name[fs::MountNameLengthMax] = {};
bool m_is_mounted = false;
ncm::AutoBuffer m_content_meta_buffer;
ncm::ProgramId m_program_id = ncm::InvalidProgramId;
u32 m_program_version = 0;
ncm::ContentMetaType m_content_meta_type = static_cast<ncm::ContentMetaType>(0);
u8 m_program_index = 0;
public:
HostPackageReader() : m_content_meta_buffer() { /* ... */ }
~HostPackageReader() {
if (m_is_mounted) {
fs::Unmount(m_mount_name);
}
}
Result Initialize(const char *package, const char *mount) {
/* Copy in the content path. */
R_UNLESS(strlen(package) <= sizeof(m_content_path) - 1, pgl::ResultBufferNotEnough());
std::strcpy(m_content_path, package);
/* Set the extension type. */
R_TRY(this->SetExtensionType());
/* Copy in mount name. */
R_UNLESS(strlen(mount) <= sizeof(m_mount_name) - 1, pgl::ResultBufferNotEnough());
std::strcpy(m_mount_name, mount);
/* Mount the package. */
R_TRY(fs::MountApplicationPackage(m_mount_name, m_content_path));
m_is_mounted = true;
/* Set the content meta buffer. */
R_TRY(this->SetContentMetaBuffer());
/* Ensure we have a content meta buffer. */
R_UNLESS(m_content_meta_buffer.Get() != nullptr, pgl::ResultContentMetaNotFound());
R_SUCCEED();
}
Result ReadProgramInfo() {
/* First, read the program index. */
R_TRY(this->GetProgramIndex(std::addressof(m_program_index)));
/* Next, create a key for the rest of the fields. */
const auto key = ncm::PackagedContentMetaReader(m_content_meta_buffer.Get(), m_content_meta_buffer.GetSize()).GetKey();
/* Set fields. */
m_program_id = {key.id};
m_program_version = key.version;
m_content_meta_type = key.type;
R_SUCCEED();
}
Result GetContentPath(lr::Path *out, ncm::ContentType type, util::optional<u8> index) const {
switch (m_extension_type) {
case ExtensionType::Nsp: R_RETURN(this->GetContentPathInNsp(out, type, index));
case ExtensionType::Nspd: R_RETURN(this->GetContentPathInNspd(out, type, index));
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
ncm::ProgramId GetProgramId() const {
return m_program_id;
}
u32 GetProgramVersion() const {
return m_program_version;
}
ncm::ContentMetaType GetContentMetaType() const {
return m_content_meta_type;
}
u8 GetProgramIndex() const {
return m_program_index;
}
private:
Result GetContentPathInNsp(lr::Path *out, ncm::ContentType type, util::optional<u8> index) const {
/* Create a reader. */
auto reader = ncm::PackagedContentMetaReader(m_content_meta_buffer.Get(), m_content_meta_buffer.GetSize());
/* Get the content info. */
const ncm::PackagedContentInfo *content_info = nullptr;
if (index) {
content_info = reader.GetContentInfo(type, *index);
} else {
content_info = reader.GetContentInfo(type);
}
R_UNLESS(content_info != nullptr, pgl::ResultApplicationContentNotFound());
/* Get the content id string. */
ncm::ContentIdString id_str;
ncm::GetStringFromContentId(id_str.data, sizeof(id_str.data), content_info->GetId());
/* Get the file name. */
char file_name[ncm::ContentIdStringLength + 5];
const size_t len = util::SNPrintf(file_name, sizeof(file_name), "%s.nca", id_str.data);
R_UNLESS(len + 1 == sizeof(file_name), pgl::ResultBufferNotEnough());
/* Ensure we have the content. */
bool has_content;
R_TRY(this->SearchContent(std::addressof(has_content), out, file_name, fs::OpenDirectoryMode_File));
R_UNLESS(has_content, pgl::ResultApplicationContentNotFound());
R_SUCCEED();
}
Result GetContentPathInNspd(lr::Path *out, ncm::ContentType type, util::optional<u8> index) const {
AMS_UNUSED(index);
/* Get the content name. */
const char *content_name = nullptr;
switch (type) {
case ncm::ContentType::Program: content_name = "program"; break;
case ncm::ContentType::Control: content_name = "control"; break;
case ncm::ContentType::HtmlDocument: content_name = "htmlDocument"; break;
case ncm::ContentType::LegalInformation: content_name = "legalInformation"; break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
/* Get the file name. */
/* NSPD does not support indexed content, so we always use 0 as the index. */
char file_name[0x20];
const size_t len = util::SNPrintf(file_name, sizeof(file_name), "%s%d.ncd", content_name, 0);
R_UNLESS(len + 1 <= sizeof(file_name), pgl::ResultBufferNotEnough());
/* Ensure we have the content. */
bool has_content;
R_TRY(this->SearchContent(std::addressof(has_content), out, file_name, fs::OpenDirectoryMode_Directory));
R_UNLESS(has_content, pgl::ResultApplicationContentNotFound());
R_SUCCEED();
}
Result GetProgramIndex(u8 *out) {
/* Nspd programs do not have indices. */
if (m_extension_type == ExtensionType::Nspd) {
*out = 0;
R_SUCCEED();
}
/* Create a reader. */
auto reader = ncm::PackagedContentMetaReader(m_content_meta_buffer.Get(), m_content_meta_buffer.GetSize());
/* Get the program content info. */
auto program_content_info = reader.GetContentInfo(ncm::ContentType::Program);
R_UNLESS(program_content_info, pgl::ResultApplicationContentNotFound());
/* Return the index. */
*out = program_content_info->GetIdOffset();
R_SUCCEED();
}
Result SetExtensionType() {
/* First, clear the suffix if the path is a program ncd. */
if (HasSuffix(m_content_path, "program0.ncd/")) {
m_content_path[strnlen(m_content_path, sizeof(m_content_path)) - std::strlen("program0.ncd/")] = 0;
}
if (HasSuffix(m_content_path, ".nsp")) {
m_extension_type = ExtensionType::Nsp;
R_SUCCEED();
} else if (HasSuffix(m_content_path, ".nspd") || HasSuffix(m_content_path, ".nspd/")) {
m_extension_type = ExtensionType::Nspd;
R_SUCCEED();
} else {
R_THROW(fs::ResultPathNotFound());
}
}
Result SetContentMetaBuffer() {
constexpr const char ContentMetaFileExtension[] = ".cnmt.nca";
constexpr const char ContentMetaDirectoryExtension[] = "meta0.ncd";
/* Find the Content meta path. */
bool has_content = false;
lr::Path meta_path;
switch (m_extension_type) {
case ExtensionType::Nsp: R_TRY(this->SearchContent(std::addressof(has_content), std::addressof(meta_path), ContentMetaFileExtension, fs::OpenDirectoryMode_File)); break;
case ExtensionType::Nspd: R_TRY(this->SearchContent(std::addressof(has_content), std::addressof(meta_path), ContentMetaDirectoryExtension, fs::OpenDirectoryMode_Directory)); break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
R_UNLESS(has_content, pgl::ResultContentMetaNotFound());
/* Read the content meta buffer. */
R_RETURN(ncm::TryReadContentMetaPath(std::addressof(m_content_meta_buffer), meta_path.str, ncm::ReadContentMetaPathWithoutExtendedDataOrDigest));
}
Result SearchContent(bool *out, lr::Path *out_path, const char *extension, fs::OpenDirectoryMode mode) const {
/* Generate the root directory path. */
char root_dir[sizeof(m_mount_name) + 2];
util::SNPrintf(root_dir, sizeof(root_dir), "%s:/", m_mount_name);
/* Open the root directory. */
fs::DirectoryHandle dir;
R_TRY(fs::OpenDirectory(std::addressof(dir), root_dir, mode));
ON_SCOPE_EXIT { fs::CloseDirectory(dir); };
/* Iterate over directory entries. */
while (true) {
fs::DirectoryEntry entry;
s64 count;
R_TRY(fs::ReadDirectory(std::addressof(count), std::addressof(entry), dir, 1));
if (count == 0) {
break;
}
/* Check if we match the suffix. */
if (HasSuffix(entry.name, extension)) {
*out = true;
if (out_path) {
const size_t len = util::SNPrintf(out_path->str, sizeof(out_path->str), "%s/%s", m_content_path, entry.name);
R_UNLESS(len + 1 < sizeof(out_path->str), pgl::ResultBufferNotEnough());
if (entry.type == fs::DirectoryEntryType_Directory) {
out_path->str[len] = '/';
out_path->str[len + 1] = 0;
}
}
R_SUCCEED();
}
}
/* We didn't find a match. */
*out = false;
R_SUCCEED();
}
};
}
Result LaunchProgramFromHost(os::ProcessId *out, const char *package_path, u32 pm_flags) {
/* Read the package. */
HostPackageReader reader;
R_TRY(reader.Initialize(package_path, HostPackageMountName));
/* Read the program info. */
R_TRY(reader.ReadProgramInfo());
/* Open a host location resolver. */
lr::LocationResolver host_resolver;
R_TRY(lr::OpenLocationResolver(std::addressof(host_resolver), ncm::StorageId::Host));
/* Get the content path. */
lr::Path content_path;
R_TRY(reader.GetContentPath(std::addressof(content_path), ncm::ContentType::Program, reader.GetProgramIndex()));
/* Erase the program redirection. */
R_TRY(host_resolver.EraseProgramRedirection(reader.GetProgramId()));
/* Redirect the program path to point to the new path. */
host_resolver.RedirectProgramPath(content_path, reader.GetProgramId());
/* Launch the program. */
R_RETURN(pgl::srv::LaunchProgram(out, ncm::ProgramLocation::Make(reader.GetProgramId(), ncm::StorageId::Host), pm_flags, pgl::LaunchFlags_None));
}
Result GetHostContentMetaInfo(pgl::ContentMetaInfo *out, const char *package_path) {
/* Read the package. */
HostPackageReader reader;
R_TRY(reader.Initialize(package_path, HostPackageMountName));
/* Read the program info. */
R_TRY(reader.ReadProgramInfo());
/* Get the content meta info. */
*out = {
.id = reader.GetProgramId().value,
.version = reader.GetProgramVersion(),
.content_type = ncm::ContentType::Program,
.id_offset = reader.GetProgramIndex(),
};
R_SUCCEED();
}
}
| 16,204
|
C++
|
.cpp
| 296
| 37.236486
| 205
| 0.508992
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,560
|
usb_device.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/usb/usb_device.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "usb_remote_ds_root_session.hpp"
#include "usb_remote_ds_service.hpp"
#include "impl/usb_util.hpp"
namespace ams::usb {
Result DsClient::Initialize(ComplexId complex_id) {
/* Clear interfaces. */
for (size_t i = 0; i < util::size(m_interfaces); ++i) {
m_interfaces[i] = nullptr;
}
/* Initialize heap. */
m_heap_handle = lmem::CreateExpHeap(m_heap_buffer, sizeof(m_heap_buffer), lmem::CreateOption_None);
R_UNLESS(m_heap_handle != nullptr, usb::ResultMemAllocFailure());
/* Attach our allocator. */
m_allocator.Attach(m_heap_handle);
/* Connect to usb:ds. */
/* NOTE: Here, Nintendo does m_domain.InitializeByDomain<...>(...); m_domain.SetSessionCount(1); */
{
#if defined(ATMOSPHERE_OS_HORIZON)
os::NativeHandle h;
R_TRY(sm::GetServiceHandle(std::addressof(h), sm::ServiceName::Encode("usb:ds")));
::Service srv;
::serviceCreate(&srv, h);
R_ABORT_UNLESS(serviceConvertToDomain(std::addressof(srv)));
using Allocator = decltype(m_allocator);
using ObjectFactory = sf::ObjectFactory<Allocator::Policy>;
if (hos::GetVersion() >= hos::Version_11_0_0) {
m_root_session = ObjectFactory::CreateSharedEmplaced<ds::IDsRootSession, RemoteDsRootSession>(std::addressof(m_allocator), srv, std::addressof(m_allocator));
R_TRY(m_root_session->GetService(std::addressof(m_ds_service)));
} else {
m_ds_service = ObjectFactory::CreateSharedEmplaced<ds::IDsService, RemoteDsService>(std::addressof(m_allocator), srv, std::addressof(m_allocator));
}
#else
AMS_ABORT("TODO");
#endif
}
/* Bind the client process. */
R_TRY(m_ds_service->Bind(complex_id, sf::CopyHandle(dd::GetCurrentProcessHandle(), false)));
/* Get the state change event. */
sf::NativeHandle event_handle;
R_TRY(m_ds_service->GetStateChangeEvent(std::addressof(event_handle)));
/* Attach the state change event handle to our event. */
os::AttachReadableHandleToSystemEvent(std::addressof(m_state_change_event), event_handle.GetOsHandle(), event_handle.IsManaged(), os::EventClearMode_ManualClear);
event_handle.Detach();
/* Mark ourselves as initialized. */
m_is_initialized = true;
R_SUCCEED();
}
Result DsClient::Finalize() {
/* Create a scoped reference. */
impl::ScopedRefCount scoped_ref(m_reference_count);
/* Check that we're initialized. */
R_UNLESS(m_is_initialized, usb::ResultNotInitialized());
/* Disable and finalize all interfaces. */
R_TRY(this->DisableDevice());
for (size_t i = 0; i < util::size(m_interfaces); ++i) {
if (m_interfaces[i] != nullptr) {
R_TRY(m_interfaces[i]->Finalize());
}
}
/* Check our reference count .*/
R_UNLESS(m_reference_count <= 1, usb::ResultResourceBusy());
/* Finalize members. */
m_is_initialized = false;
os::DestroySystemEvent(std::addressof(m_state_change_event));
lmem::DestroyExpHeap(m_heap_handle);
m_heap_handle = nullptr;
/* Destroy interface objects. */
m_ds_service = nullptr;
m_root_session = nullptr;
R_SUCCEED();
}
bool DsClient::IsInitialized() {
return m_is_initialized;
}
Result DsClient::EnableDevice() {
/* Create a scoped reference. */
impl::ScopedRefCount scoped_ref(m_reference_count);
/* Check that we're initialized. */
R_UNLESS(m_is_initialized, usb::ResultNotInitialized());
/* Enable all interfaces. */
if (hos::GetVersion() < hos::Version_11_0_0) {
for (size_t i = 0; i < util::size(m_interfaces); ++i) {
if (m_interfaces[i] != nullptr) {
R_TRY(m_interfaces[i]->Enable());
}
}
}
/* Enable the device. */
R_TRY(m_ds_service->Enable());
/* Mark disabled. */
m_is_enabled = true;
R_SUCCEED();
}
Result DsClient::DisableDevice() {
/* Create a scoped reference. */
impl::ScopedRefCount scoped_ref(m_reference_count);
/* Check that we're initialized. */
R_UNLESS(m_is_initialized, usb::ResultNotInitialized());
/* Disable the device. */
R_TRY(m_ds_service->Disable());
/* Disable all interfaces. */
if (hos::GetVersion() < hos::Version_11_0_0) {
for (size_t i = 0; i < util::size(m_interfaces); ++i) {
if (m_interfaces[i] != nullptr) {
R_TRY(m_interfaces[i]->Disable());
}
}
}
/* Mark disabled. */
m_is_enabled = false;
R_SUCCEED();
}
os::SystemEventType *DsClient::GetStateChangeEvent() {
/* Create a scoped reference. */
impl::ScopedRefCount scoped_ref(m_reference_count);
return m_is_initialized ? std::addressof(m_state_change_event) : nullptr;
}
Result DsClient::GetState(UsbState *out) {
/* Create a scoped reference. */
impl::ScopedRefCount scoped_ref(m_reference_count);
/* Check that we're initialized. */
R_UNLESS(m_is_initialized, usb::ResultNotInitialized());
/* Check that we have a service. */
AMS_ABORT_UNLESS(m_ds_service != nullptr);
R_RETURN(m_ds_service->GetState(out));
}
Result DsClient::ClearDeviceData() {
R_RETURN(m_ds_service->ClearDeviceData());
}
Result DsClient::AddUsbStringDescriptor(u8 *out_index, UsbStringDescriptor *desc) {
R_RETURN(m_ds_service->AddUsbStringDescriptor(out_index, sf::InBuffer(reinterpret_cast<const u8 *>(desc), sizeof(*desc))));
}
Result DsClient::DeleteUsbStringDescriptor(u8 index) {
R_RETURN(m_ds_service->DeleteUsbStringDescriptor(index));
}
Result DsClient::SetUsbDeviceDescriptor(UsbDeviceDescriptor *desc, UsbDeviceSpeed speed) {
R_RETURN(m_ds_service->SetUsbDeviceDescriptor(sf::InBuffer(reinterpret_cast<const u8 *>(desc), sizeof(*desc)), speed));
}
Result DsClient::SetBinaryObjectStore(u8 *data, int size) {
R_RETURN(m_ds_service->SetBinaryObjectStore(sf::InBuffer(reinterpret_cast<const u8 *>(data), size)));
}
Result DsClient::AddInterface(DsInterface *intf, sf::SharedPointer<ds::IDsInterface> *out_srv, uint8_t bInterfaceNumber) {
/* Create a scoped reference. */
impl::ScopedRefCount scoped_ref(m_reference_count);
/* Check that we're initialized. */
R_UNLESS(m_is_initialized, usb::ResultNotInitialized());
/* Check that we have a service. */
AMS_ABORT_UNLESS(m_ds_service != nullptr);
/* Register the interface. */
R_TRY(m_ds_service->RegisterInterface(out_srv, bInterfaceNumber));
/* Set interface. */
m_interfaces[bInterfaceNumber] = intf;
R_SUCCEED();
}
Result DsClient::DeleteInterface(uint8_t bInterfaceNumber) {
/* Create a scoped reference. */
impl::ScopedRefCount scoped_ref(m_reference_count);
/* Check that we're initialized. */
R_UNLESS(m_is_initialized, usb::ResultNotInitialized());
/* Check that we have the interface. */
R_UNLESS(m_interfaces[bInterfaceNumber] != nullptr, usb::ResultOperationDenied());
/* Clear the interface. */
m_interfaces[bInterfaceNumber] = nullptr;
R_SUCCEED();
}
Result DsInterface::Initialize(DsClient *client, u8 bInterfaceNumber) {
/* Check that we haven't already initialized. */
R_UNLESS(!m_is_initialized, usb::ResultAlreadyInitialized());
/* Set our client. */
m_client = client;
/* Clear all endpoints. */
for (size_t i = 0; i < util::size(m_endpoints); ++i) {
m_endpoints[i] = nullptr;
}
/* Set our interface number. */
R_UNLESS(bInterfaceNumber < util::size(m_client->m_interfaces), usb::ResultInvalidParameter());
m_interface_num = bInterfaceNumber;
/* Add the interface. */
R_TRY(m_client->AddInterface(this, std::addressof(m_interface), m_interface_num));
/* Ensure we cleanup if we fail after this. */
auto intf_guard = SCOPE_GUARD { m_client->DeleteInterface(m_interface_num); m_interface = nullptr; };
/* Get events. */
sf::NativeHandle setup_event_handle;
sf::NativeHandle ctrl_in_event_handle;
sf::NativeHandle ctrl_out_event_handle;
R_TRY(m_interface->GetSetupEvent(std::addressof(setup_event_handle)));
R_TRY(m_interface->GetCtrlInCompletionEvent(std::addressof(ctrl_in_event_handle)));
R_TRY(m_interface->GetCtrlOutCompletionEvent(std::addressof(ctrl_out_event_handle)));
/* Attach events. */
os::AttachReadableHandleToSystemEvent(std::addressof(m_setup_event), setup_event_handle.GetOsHandle(), setup_event_handle.IsManaged(), os::EventClearMode_ManualClear);
os::AttachReadableHandleToSystemEvent(std::addressof(m_ctrl_in_completion_event), ctrl_in_event_handle.GetOsHandle(), ctrl_in_event_handle.IsManaged(), os::EventClearMode_ManualClear);
os::AttachReadableHandleToSystemEvent(std::addressof(m_ctrl_out_completion_event), ctrl_out_event_handle.GetOsHandle(), ctrl_out_event_handle.IsManaged(), os::EventClearMode_ManualClear);
setup_event_handle.Detach();
ctrl_in_event_handle.Detach();
ctrl_out_event_handle.Detach();
/* Increment our client's reference count. */
++m_client->m_reference_count;
/* Set ourselves as initialized. */
m_is_initialized = true;
intf_guard.Cancel();
R_SUCCEED();
}
Result DsInterface::Finalize() {
/* Validate that we have a service. */
AMS_ABORT_UNLESS(m_interface != nullptr);
/* We must be disabled. */
R_UNLESS(!m_client->m_is_enabled, usb::ResultResourceBusy());
/* Finalize all endpoints. */
for (size_t i = 0; i < util::size(m_endpoints); ++i) {
if (m_endpoints[i] != nullptr) {
R_TRY(m_endpoints[i]->Finalize());
}
}
/* Create a scoped reference. */
impl::ScopedRefCount scoped_ref(m_reference_count);
/* Check that we're initialized. */
R_UNLESS(m_is_initialized, usb::ResultNotInitialized());
/* Check our reference count .*/
R_UNLESS(m_reference_count <= 1, usb::ResultResourceBusy());
/* Finalize members. */
m_is_initialized = false;
os::DestroySystemEvent(std::addressof(m_setup_event));
os::DestroySystemEvent(std::addressof(m_ctrl_in_completion_event));
os::DestroySystemEvent(std::addressof(m_ctrl_out_completion_event));
/* Delete ourselves from our cleint. */
m_client->DeleteInterface(m_interface_num);
/* Destroy our service. */
m_interface = nullptr;
/* Close our reference to our client. */
--m_client->m_reference_count;
m_client = nullptr;
R_SUCCEED();
}
Result DsInterface::AppendConfigurationData(UsbDeviceSpeed speed, void *data, u32 size) {
R_RETURN(m_interface->AppendConfigurationData(m_interface_num, speed, sf::InBuffer(data, size)));
}
bool DsInterface::IsInitialized() {
return m_is_initialized;
}
os::SystemEventType *DsInterface::GetSetupEvent() {
/* Create a scoped reference. */
impl::ScopedRefCount scoped_ref(m_reference_count);
return m_is_initialized ? std::addressof(m_setup_event) : nullptr;
}
Result DsInterface::GetSetupPacket(UsbCtrlRequest *out) {
/* Create a scoped reference. */
impl::ScopedRefCount scoped_ref(m_reference_count);
/* Check that we're initialized. */
R_UNLESS(m_is_initialized, usb::ResultNotInitialized());
/* Check that we have a service. */
AMS_ABORT_UNLESS(m_interface != nullptr);
R_RETURN(m_interface->GetSetupPacket(sf::OutBuffer(out, sizeof(*out))));
}
Result DsInterface::Enable() {
/* Create a scoped reference. */
impl::ScopedRefCount scoped_ref(m_reference_count);
/* Check that we're initialized. */
R_UNLESS(m_is_initialized, usb::ResultNotInitialized());
/* If we're already enabled, nothing to do. */
R_SUCCEED_IF(m_client->m_is_enabled);
/* Check that we have a service. */
AMS_ABORT_UNLESS(m_interface != nullptr);
/* Perform the enable. */
R_TRY(m_interface->Enable());
R_SUCCEED();
}
Result DsInterface::Disable() {
/* Create a scoped reference. */
impl::ScopedRefCount scoped_ref(m_reference_count);
/* Check that we're initialized. */
R_UNLESS(m_is_initialized, usb::ResultNotInitialized());
/* If we're already disabled, nothing to do. */
R_SUCCEED_IF(!m_client->m_is_enabled);
/* Check that we have a service. */
AMS_ABORT_UNLESS(m_interface != nullptr);
/* Perform the disable. */
R_TRY(m_interface->Disable());
R_SUCCEED();
}
Result DsInterface::AddEndpoint(DsEndpoint *ep, u8 bEndpointAddress, sf::SharedPointer<ds::IDsEndpoint> *out) {
/* Create a scoped reference. */
impl::ScopedRefCount scoped_ref(m_reference_count);
/* Check that we're initialized. */
R_UNLESS(m_is_initialized, usb::ResultNotInitialized());
/* Check that we're not already enabled. */
R_UNLESS(!m_client->m_is_enabled, usb::ResultOperationDenied());
/* Check that we have a service. */
AMS_ABORT_UNLESS(m_interface != nullptr);
/* Register the endpoint. */
R_TRY(m_interface->RegisterEndpoint(bEndpointAddress, out));
/* Set the endpoint. */
m_endpoints[impl::GetEndpointIndex(bEndpointAddress)] = ep;
R_SUCCEED();
}
Result DsInterface::DeleteEndpoint(u8 bEndpointAddress) {
/* Create a scoped reference. */
impl::ScopedRefCount scoped_ref(m_reference_count);
/* Check that we're initialized. */
R_UNLESS(m_is_initialized, usb::ResultNotInitialized());
/* Check that we're disabled and have the endpoint. */
const auto index = impl::GetEndpointIndex(bEndpointAddress);
R_UNLESS(!m_client->m_is_enabled, usb::ResultOperationDenied());
R_UNLESS(m_endpoints[index] != nullptr, usb::ResultOperationDenied());
/* Clear the endpoint. */
m_endpoints[index] = nullptr;
R_SUCCEED();
}
Result DsInterface::CtrlIn(u32 *out_transferred, void *dst, u32 size) {
/* Create a scoped reference. */
impl::ScopedRefCount scoped_ref(m_reference_count);
/* Check that we're initialized. */
R_UNLESS(m_is_initialized, usb::ResultNotInitialized());
/* Check that we're enabled. */
R_UNLESS(m_client->m_is_enabled, usb::ResultOperationDenied());
/* Check that the data is aligned. */
R_UNLESS(usb::IsDmaAligned(reinterpret_cast<u64>(dst)), usb::ResultAlignmentError());
/* If we should, flush cache. */
if (size != 0) {
dd::FlushDataCache(dst, size);
}
/* Check that we have a service. */
AMS_ABORT_UNLESS(m_interface != nullptr);
/* Perform the transfer. */
u32 urb_id;
R_TRY(m_interface->CtrlInAsync(std::addressof(urb_id), reinterpret_cast<u64>(dst), size));
/* Wait for control to finish. */
os::WaitSystemEvent(std::addressof(m_ctrl_in_completion_event));
os::ClearSystemEvent(std::addressof(m_ctrl_in_completion_event));
/* Get the urb report. */
R_ABORT_UNLESS(m_interface->GetCtrlInUrbReport(std::addressof(m_report)));
/* Check the report is for our urb. */
R_UNLESS(m_report.count == 1, usb::ResultInternalStateError());
R_UNLESS(m_report.reports[0].id == urb_id, usb::ResultInternalStateError());
/* Set output bytes. */
if (out_transferred != nullptr) {
*out_transferred = m_report.reports[0].transferred_size;
}
/* Handle the report. */
switch (m_report.reports[0].status) {
case UrbStatus_Cancelled:
R_THROW(usb::ResultInterrupted());
case UrbStatus_Failed:
R_THROW(usb::ResultTransactionError());
case UrbStatus_Finished:
R_SUCCEED();
default:
R_THROW(usb::ResultInternalStateError());
}
}
Result DsInterface::CtrlOut(u32 *out_transferred, void *dst, u32 size) {
/* Create a scoped reference. */
impl::ScopedRefCount scoped_ref(m_reference_count);
/* Check that we're initialized. */
R_UNLESS(m_is_initialized, usb::ResultNotInitialized());
/* Check that we're enabled. */
R_UNLESS(m_client->m_is_enabled, usb::ResultOperationDenied());
/* Check that the data is aligned. */
R_UNLESS(usb::IsDmaAligned(reinterpret_cast<u64>(dst)), usb::ResultAlignmentError());
/* If we should, invalidate cache. */
if (size != 0) {
dd::InvalidateDataCache(dst, size);
}
/* Check that we have a service. */
AMS_ABORT_UNLESS(m_interface != nullptr);
/* Perform the transfer. */
u32 urb_id;
R_TRY(m_interface->CtrlOutAsync(std::addressof(urb_id), reinterpret_cast<u64>(dst), size));
/* Wait for control to finish. */
os::WaitSystemEvent(std::addressof(m_ctrl_out_completion_event));
os::ClearSystemEvent(std::addressof(m_ctrl_out_completion_event));
/* Ensure that cache remains consistent. */
ON_SCOPE_EXIT {
if (size != 0) {
dd::InvalidateDataCache(dst, size);
}
};
/* Get the urb report. */
R_ABORT_UNLESS(m_interface->GetCtrlOutUrbReport(std::addressof(m_report)));
/* Check the report is for our urb. */
R_UNLESS(m_report.count == 1, usb::ResultInternalStateError());
R_UNLESS(m_report.reports[0].id == urb_id, usb::ResultInternalStateError());
/* Set output bytes. */
if (out_transferred != nullptr) {
*out_transferred = m_report.reports[0].transferred_size;
}
/* Handle the report. */
switch (m_report.reports[0].status) {
case UrbStatus_Cancelled:
R_THROW(usb::ResultInterrupted());
case UrbStatus_Failed:
R_THROW(usb::ResultTransactionError());
case UrbStatus_Finished:
R_SUCCEED();
default:
R_THROW(usb::ResultInternalStateError());
}
}
Result DsInterface::CtrlRead(u32 *out_transferred, void *dst, u32 size) {
/* Create a scoped reference. */
impl::ScopedRefCount scoped_ref(m_reference_count);
/* Check that we're initialized. */
R_UNLESS(m_is_initialized, usb::ResultNotInitialized());
/* Do the data transfer. */
Result result = this->CtrlOut(out_transferred, dst, size);
/* Do the status transfer. */
if (R_SUCCEEDED(result)) {
result = this->CtrlIn(nullptr, nullptr, 0);
}
/* If we fail, stall. */
if (R_FAILED(result)) {
result = this->CtrlStall();
}
R_RETURN(result);
}
Result DsInterface::CtrlWrite(u32 *out_transferred, void *dst, u32 size) {
/* Create a scoped reference. */
impl::ScopedRefCount scoped_ref(m_reference_count);
/* Check that we're initialized. */
R_UNLESS(m_is_initialized, usb::ResultNotInitialized());
/* Do the data transfer. */
Result result = this->CtrlIn(out_transferred, dst, size);
/* Do the status transfer. */
if (R_SUCCEEDED(result)) {
result = this->CtrlOut(nullptr, nullptr, 0);
}
/* If we failed, stall. */
if (R_FAILED(result)) {
result = this->CtrlStall();
}
R_RETURN(result);
}
Result DsInterface::CtrlDone() {
/* Create a scoped reference. */
impl::ScopedRefCount scoped_ref(m_reference_count);
/* Check that we're initialized. */
R_UNLESS(m_is_initialized, usb::ResultNotInitialized());
/* Do the status transfer. */
Result result = this->CtrlIn(nullptr, nullptr, 0);
/* If we failed, stall. */
if (R_FAILED(result)) {
result = this->CtrlStall();
}
R_RETURN(result);
}
Result DsInterface::CtrlStall() {
/* Create a scoped reference. */
impl::ScopedRefCount scoped_ref(m_reference_count);
/* Check that we're initialized. */
R_UNLESS(m_is_initialized, usb::ResultNotInitialized());
/* Check that we're enabled. */
R_UNLESS(m_client->m_is_enabled, usb::ResultOperationDenied());
/* Check that we have a service. */
AMS_ABORT_UNLESS(m_interface != nullptr);
R_RETURN(m_interface->CtrlStall());
}
Result DsEndpoint::Initialize(DsInterface *interface, u8 bEndpointAddress) {
/* Check that the interface is valid. */
AMS_ABORT_UNLESS(interface != nullptr);
/* Check that we're not already initialized. */
R_UNLESS(!m_is_initialized, usb::ResultAlreadyInitialized());
/* Set our interface. */
m_interface = interface;
/* Add the endpoint. */
R_TRY(m_interface->AddEndpoint(this, bEndpointAddress, std::addressof(m_endpoint)));
/* Set our address. */
m_address = bEndpointAddress;
/* Ensure we clean up if we fail after this. */
auto ep_guard = SCOPE_GUARD { m_interface->DeleteEndpoint(m_address); m_endpoint = nullptr; };
/* Get completion event. */
sf::NativeHandle event_handle;
R_TRY(m_endpoint->GetCompletionEvent(std::addressof(event_handle)));
/* Increment our interface's reference count. */
++m_interface->m_reference_count;
++m_interface->m_client->m_reference_count;
/* Attach our event. */
os::AttachReadableHandleToSystemEvent(std::addressof(m_completion_event), event_handle.GetOsHandle(), event_handle.IsManaged(), os::EventClearMode_ManualClear);
event_handle.Detach();
/* Mark initialized. */
m_is_initialized = true;
ep_guard.Cancel();
R_SUCCEED();
}
Result DsEndpoint::Finalize() {
/* Create a scoped reference. */
impl::ScopedRefCount scoped_ref(m_reference_count);
/* Check that we're initialized. */
R_UNLESS(m_is_initialized, usb::ResultNotInitialized());
/* Cancel any pending transactions. */
m_endpoint->Cancel();
/* Wait for us to be at one reference count. */
while (m_reference_count > 1) {
os::SleepThread(TimeSpan::FromMilliSeconds(25));
}
/* Destroy our event. */
os::DestroySystemEvent(std::addressof(m_completion_event));
/* Decrement our interface's reference count. */
--m_interface->m_reference_count;
--m_interface->m_client->m_reference_count;
/* Delete ourselves. */
R_TRY(m_interface->DeleteEndpoint(m_address));
/* Clear ourselves. */
m_interface = nullptr;
m_endpoint = nullptr;
/* Mark uninitialized. */
m_is_initialized = false;
R_SUCCEED();
}
bool DsEndpoint::IsInitialized() {
return m_is_initialized;
}
Result DsEndpoint::PostBuffer(u32 *out_transferred, void *buf, u32 size) {
/* Create a scoped reference. */
impl::ScopedRefCount scoped_ref(m_reference_count);
/* Check that we're initialized. */
R_UNLESS(m_is_initialized, usb::ResultNotInitialized());
/* Post buffer. */
u32 urb_id;
R_TRY(this->PostBufferAsync(std::addressof(urb_id), buf, size));
/* Wait for completion. */
os::WaitSystemEvent(std::addressof(m_completion_event));
os::ClearSystemEvent(std::addressof(m_completion_event));
/* Get URB report. */
UrbReport report;
AMS_ABORT_UNLESS(m_endpoint != nullptr);
R_ABORT_UNLESS(m_endpoint->GetUrbReport(std::addressof(report)));
/* Check the report is for our urb. */
R_UNLESS(report.count == 1, usb::ResultInternalStateError());
R_UNLESS(report.reports[0].id == urb_id, usb::ResultInternalStateError());
/* Set output bytes. */
if (out_transferred != nullptr) {
*out_transferred = report.reports[0].transferred_size;
}
/* Handle the report. */
switch (report.reports[0].status) {
case UrbStatus_Cancelled:
R_THROW(usb::ResultInterrupted());
case UrbStatus_Failed:
R_THROW(usb::ResultTransactionError());
case UrbStatus_Finished:
R_SUCCEED();
default:
R_THROW(usb::ResultInternalStateError());
}
}
Result DsEndpoint::PostBufferAsync(u32 *out_urb_id, void *buf, u32 size) {
/* Create a scoped reference. */
impl::ScopedRefCount scoped_ref(m_reference_count);
/* Check that we're initialized. */
R_UNLESS(m_is_initialized, usb::ResultNotInitialized());
/* Check that the buffer is DMA aligned. */
R_UNLESS(usb::IsDmaAligned(reinterpret_cast<u64>(buf)), usb::ResultAlignmentError());
/* Check that we have a service. */
AMS_ABORT_UNLESS(m_endpoint != nullptr);
/* Post */
u32 urb_id = 0;
R_TRY(m_endpoint->PostBufferAsync(std::addressof(urb_id), reinterpret_cast<u64>(buf), size));
*out_urb_id = urb_id;
R_SUCCEED();
}
os::SystemEventType *DsEndpoint::GetCompletionEvent() {
/* Create a scoped reference. */
impl::ScopedRefCount scoped_ref(m_reference_count);
return m_is_initialized ? std::addressof(m_completion_event) : nullptr;
}
Result DsEndpoint::GetUrbReport(UrbReport *out) {
/* Create a scoped reference. */
impl::ScopedRefCount scoped_ref(m_reference_count);
/* Check that we're initialized. */
R_UNLESS(m_is_initialized, usb::ResultNotInitialized());
/* Check that we have a service. */
AMS_ABORT_UNLESS(m_endpoint != nullptr);
R_RETURN(m_endpoint->GetUrbReport(out));
}
Result DsEndpoint::Cancel() {
/* Create a scoped reference. */
impl::ScopedRefCount scoped_ref(m_reference_count);
/* Check that we're initialized. */
R_UNLESS(m_is_initialized, usb::ResultNotInitialized());
/* Check that we have a service. */
AMS_ABORT_UNLESS(m_endpoint != nullptr);
R_RETURN(m_endpoint->Cancel());
}
Result DsEndpoint::SetZeroLengthTransfer(bool zlt) {
/* Create a scoped reference. */
impl::ScopedRefCount scoped_ref(m_reference_count);
/* Check that we're initialized. */
R_UNLESS(m_is_initialized, usb::ResultNotInitialized());
/* Check that we have a service. */
AMS_ABORT_UNLESS(m_endpoint != nullptr);
R_RETURN(m_endpoint->SetZlt(zlt));
}
}
| 28,390
|
C++
|
.cpp
| 608
| 37.46875
| 195
| 0.615376
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,561
|
usb_remote_ds_service.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/usb/usb_remote_ds_service.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "usb_remote_ds_service.hpp"
#include "usb_remote_ds_interface.hpp"
namespace ams::usb {
#if defined(ATMOSPHERE_OS_HORIZON)
Result RemoteDsService::Bind(usb::ComplexId complex_id, sf::CopyHandle &&process_h) {
if (hos::GetVersion() >= hos::Version_11_0_0) {
serviceAssumeDomain(std::addressof(m_srv));
R_TRY(serviceDispatchIn(std::addressof(m_srv), 0, complex_id,
.in_num_handles = 1,
.in_handles = { process_h.GetOsHandle() }
));
} else {
serviceAssumeDomain(std::addressof(m_srv));
R_TRY(serviceDispatchIn(std::addressof(m_srv), 0, complex_id));
serviceAssumeDomain(std::addressof(m_srv));
R_TRY(serviceDispatch(std::addressof(m_srv), 1,
.in_num_handles = 1,
.in_handles = { process_h.GetOsHandle() })
);
}
R_SUCCEED();
}
Result RemoteDsService::RegisterInterface(sf::Out<sf::SharedPointer<usb::ds::IDsInterface>> out, u8 bInterfaceNumber) {
Service srv;
serviceAssumeDomain(std::addressof(m_srv));
R_TRY(serviceDispatchIn(std::addressof(m_srv), (hos::GetVersion() >= hos::Version_11_0_0 ? 1 : 2), bInterfaceNumber,
.out_num_objects = 1,
.out_objects = std::addressof(srv),
));
*out = ObjectFactory::CreateSharedEmplaced<ds::IDsInterface, RemoteDsInterface>(m_allocator, srv, m_allocator);
R_SUCCEED();
}
Result RemoteDsService::GetStateChangeEvent(sf::OutCopyHandle out) {
serviceAssumeDomain(std::addressof(m_srv));
os::NativeHandle event_handle;
R_TRY((serviceDispatch(std::addressof(m_srv), hos::GetVersion() >= hos::Version_11_0_0 ? 2 : 3,
.out_handle_attrs = { SfOutHandleAttr_HipcCopy },
.out_handles = std::addressof(event_handle),
)));
out.SetValue(event_handle, true);
R_SUCCEED();
}
Result RemoteDsService::GetState(sf::Out<usb::UsbState> out) {
serviceAssumeDomain(std::addressof(m_srv));
R_RETURN(serviceDispatchOut(std::addressof(m_srv), hos::GetVersion() >= hos::Version_11_0_0 ? 3 : 4, *out));
}
Result RemoteDsService::ClearDeviceData() {
serviceAssumeDomain(std::addressof(m_srv));
R_RETURN(serviceDispatch(std::addressof(m_srv), hos::GetVersion() >= hos::Version_11_0_0 ? 4 : 5));
}
Result RemoteDsService::AddUsbStringDescriptor(sf::Out<u8> out, const sf::InBuffer &desc) {
serviceAssumeDomain(std::addressof(m_srv));
return serviceDispatchOut(std::addressof(m_srv), hos::GetVersion() >= hos::Version_11_0_0 ? 5 : 6, *out,
.buffer_attrs = { SfBufferAttr_HipcMapAlias | SfBufferAttr_In },
.buffers = { { desc.GetPointer(), desc.GetSize() } },
);
}
Result RemoteDsService::DeleteUsbStringDescriptor(u8 index) {
serviceAssumeDomain(std::addressof(m_srv));
R_RETURN(serviceDispatchIn(std::addressof(m_srv), hos::GetVersion() >= hos::Version_11_0_0 ? 6 : 7, index));
}
Result RemoteDsService::SetUsbDeviceDescriptor(const sf::InBuffer &desc, usb::UsbDeviceSpeed speed) {
serviceAssumeDomain(std::addressof(m_srv));
return serviceDispatchIn(std::addressof(m_srv), hos::GetVersion() >= hos::Version_11_0_0 ? 7 : 8, speed,
.buffer_attrs = { SfBufferAttr_HipcMapAlias | SfBufferAttr_In },
.buffers = { { desc.GetPointer(), desc.GetSize() } },
);
}
Result RemoteDsService::SetBinaryObjectStore(const sf::InBuffer &bos) {
serviceAssumeDomain(std::addressof(m_srv));
return serviceDispatch(std::addressof(m_srv), hos::GetVersion() >= hos::Version_11_0_0 ? 8 : 9,
.buffer_attrs = { SfBufferAttr_HipcMapAlias | SfBufferAttr_In },
.buffers = { { bos.GetPointer(), bos.GetSize() } },
);
}
Result RemoteDsService::Enable() {
serviceAssumeDomain(std::addressof(m_srv));
R_RETURN(serviceDispatch(std::addressof(m_srv), hos::GetVersion() >= hos::Version_11_0_0 ? 9 : 10));
}
Result RemoteDsService::Disable() {
serviceAssumeDomain(std::addressof(m_srv));
R_RETURN(serviceDispatch(std::addressof(m_srv), hos::GetVersion() >= hos::Version_11_0_0 ? 10 : 11));
}
#endif
}
| 5,021
|
C++
|
.cpp
| 101
| 41.881188
| 124
| 0.644286
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,562
|
usb_remote_ds_endpoint.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/usb/usb_remote_ds_endpoint.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "usb_remote_ds_endpoint.hpp"
namespace ams::usb {
#if defined(ATMOSPHERE_OS_HORIZON)
Result RemoteDsEndpoint::PostBufferAsync(sf::Out<u32> out_urb_id, u64 address, u32 size) {
const struct {
u32 size;
u64 address;
} in = { size, address };
serviceAssumeDomain(std::addressof(m_srv));
R_RETURN(serviceDispatchInOut(std::addressof(m_srv), 0, in, *out_urb_id));
}
Result RemoteDsEndpoint::Cancel() {
serviceAssumeDomain(std::addressof(m_srv));
R_RETURN(serviceDispatch(std::addressof(m_srv), 1));
}
Result RemoteDsEndpoint::GetCompletionEvent(sf::OutCopyHandle out) {
serviceAssumeDomain(std::addressof(m_srv));
os::NativeHandle event_handle;
R_TRY((serviceDispatch(std::addressof(m_srv), 2,
.out_handle_attrs = { SfOutHandleAttr_HipcCopy },
.out_handles = std::addressof(event_handle),
)));
out.SetValue(event_handle, true);
R_SUCCEED();
}
Result RemoteDsEndpoint::GetUrbReport(sf::Out<usb::UrbReport> out) {
serviceAssumeDomain(std::addressof(m_srv));
R_RETURN(serviceDispatchOut(std::addressof(m_srv), 3, *out));
}
Result RemoteDsEndpoint::Stall() {
serviceAssumeDomain(std::addressof(m_srv));
R_RETURN(serviceDispatch(std::addressof(m_srv), 4));
}
Result RemoteDsEndpoint::SetZlt(bool zlt) {
const u8 in = zlt ? 1 : 0;
serviceAssumeDomain(std::addressof(m_srv));
R_RETURN(serviceDispatchIn(std::addressof(m_srv), 5, in));
}
#endif
}
| 2,274
|
C++
|
.cpp
| 56
| 34.571429
| 94
| 0.675431
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,563
|
usb_remote_ds_root_session.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/usb/usb_remote_ds_root_session.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "usb_remote_ds_root_session.hpp"
#include "usb_remote_ds_service.hpp"
namespace ams::usb {
#if defined(ATMOSPHERE_OS_HORIZON)
Result RemoteDsRootSession::GetService(sf::Out<sf::SharedPointer<usb::ds::IDsService>> out) {
Service srv;
serviceAssumeDomain(std::addressof(m_srv));
R_TRY(serviceDispatch(std::addressof(m_srv), 0, .out_num_objects = 1, .out_objects = std::addressof(srv)));
*out = ObjectFactory::CreateSharedEmplaced<ds::IDsService, RemoteDsService>(m_allocator, srv, m_allocator);
R_SUCCEED();
}
#endif
}
| 1,251
|
C++
|
.cpp
| 29
| 39.517241
| 115
| 0.728618
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,564
|
usb_remote_ds_interface.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/usb/usb_remote_ds_interface.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "usb_remote_ds_interface.hpp"
#include "usb_remote_ds_endpoint.hpp"
namespace ams::usb {
#if defined(ATMOSPHERE_OS_HORIZON)
Result RemoteDsInterface::RegisterEndpoint(u8 endpoint_address, sf::Out<sf::SharedPointer<usb::ds::IDsEndpoint>> out) {
Service srv;
serviceAssumeDomain(std::addressof(m_srv));
R_TRY(serviceDispatchIn(std::addressof(m_srv), 0, endpoint_address,
.out_num_objects = 1,
.out_objects = std::addressof(srv),
));
*out = ObjectFactory::CreateSharedEmplaced<ds::IDsEndpoint, RemoteDsEndpoint>(m_allocator, srv);
R_SUCCEED();
}
Result RemoteDsInterface::GetSetupEvent(sf::OutCopyHandle out) {
serviceAssumeDomain(std::addressof(m_srv));
os::NativeHandle event_handle;
R_TRY((serviceDispatch(std::addressof(m_srv), 1,
.out_handle_attrs = { SfOutHandleAttr_HipcCopy },
.out_handles = std::addressof(event_handle),
)));
out.SetValue(event_handle, true);
R_SUCCEED();
}
Result RemoteDsInterface::GetSetupPacket(const sf::OutBuffer &out) {
serviceAssumeDomain(std::addressof(m_srv));
return serviceDispatch(std::addressof(m_srv), 2,
.buffer_attrs = { SfBufferAttr_HipcMapAlias | SfBufferAttr_Out },
.buffers = { { out.GetPointer(), out.GetSize() } },
);
}
Result RemoteDsInterface::CtrlInAsync(sf::Out<u32> out_urb_id, u64 address, u32 size) {
const struct {
u32 size;
u64 address;
} in = { size, address };
serviceAssumeDomain(std::addressof(m_srv));
R_RETURN(serviceDispatchInOut(std::addressof(m_srv), hos::GetVersion() >= hos::Version_11_0_0 ? 3 : 5, in, *out_urb_id));
}
Result RemoteDsInterface::CtrlOutAsync(sf::Out<u32> out_urb_id, u64 address, u32 size) {
const struct {
u32 size;
u64 address;
} in = { size, address };
serviceAssumeDomain(std::addressof(m_srv));
R_RETURN(serviceDispatchInOut(std::addressof(m_srv), hos::GetVersion() >= hos::Version_11_0_0 ? 4 : 6, in, *out_urb_id));
}
Result RemoteDsInterface::GetCtrlInCompletionEvent(sf::OutCopyHandle out) {
serviceAssumeDomain(std::addressof(m_srv));
os::NativeHandle event_handle;
R_TRY((serviceDispatch(std::addressof(m_srv), hos::GetVersion() >= hos::Version_11_0_0 ? 5 : 7,
.out_handle_attrs = { SfOutHandleAttr_HipcCopy },
.out_handles = std::addressof(event_handle),
)));
out.SetValue(event_handle, true);
R_SUCCEED();
}
Result RemoteDsInterface::GetCtrlInUrbReport(sf::Out<usb::UrbReport> out) {
serviceAssumeDomain(std::addressof(m_srv));
R_RETURN(serviceDispatchOut(std::addressof(m_srv), hos::GetVersion() >= hos::Version_11_0_0 ? 6 : 8, *out));
}
Result RemoteDsInterface::GetCtrlOutCompletionEvent(sf::OutCopyHandle out) {
serviceAssumeDomain(std::addressof(m_srv));
os::NativeHandle event_handle;
R_TRY((serviceDispatch(std::addressof(m_srv), hos::GetVersion() >= hos::Version_11_0_0 ? 7 : 9,
.out_handle_attrs = { SfOutHandleAttr_HipcCopy },
.out_handles = std::addressof(event_handle),
)));
out.SetValue(event_handle, true);
R_SUCCEED();
}
Result RemoteDsInterface::GetCtrlOutUrbReport(sf::Out<usb::UrbReport> out) {
serviceAssumeDomain(std::addressof(m_srv));
R_RETURN(serviceDispatchOut(std::addressof(m_srv), hos::GetVersion() >= hos::Version_11_0_0 ? 8 : 10, *out));
}
Result RemoteDsInterface::CtrlStall() {
serviceAssumeDomain(std::addressof(m_srv));
R_RETURN(serviceDispatch(std::addressof(m_srv), hos::GetVersion() >= hos::Version_11_0_0 ? 9 : 11));
}
Result RemoteDsInterface::AppendConfigurationData(u8 bInterfaceNumber, usb::UsbDeviceSpeed device_speed, const sf::InBuffer &data) {
if (hos::GetVersion() >= hos::Version_11_0_0) {
serviceAssumeDomain(std::addressof(m_srv));
return serviceDispatchIn(std::addressof(m_srv), 10, device_speed,
.buffer_attrs = { SfBufferAttr_HipcMapAlias | SfBufferAttr_In },
.buffers = { { data.GetPointer(), data.GetSize() } },
);
} else {
const struct {
u8 bInterfaceNumber;
usb::UsbDeviceSpeed device_speed;
} in = { bInterfaceNumber, device_speed };
serviceAssumeDomain(std::addressof(m_srv));
return serviceDispatchIn(std::addressof(m_srv), 12, in,
.buffer_attrs = { SfBufferAttr_HipcMapAlias | SfBufferAttr_In },
.buffers = { { data.GetPointer(), data.GetSize() } },
);
}
}
Result RemoteDsInterface::Enable() {
R_SUCCEED_IF(hos::GetVersion() >= hos::Version_11_0_0);
serviceAssumeDomain(std::addressof(m_srv));
R_RETURN(serviceDispatch(std::addressof(m_srv), 3));
}
Result RemoteDsInterface::Disable() {
R_SUCCEED_IF(hos::GetVersion() >= hos::Version_11_0_0);
serviceAssumeDomain(std::addressof(m_srv));
R_RETURN(serviceDispatch(std::addressof(m_srv), 3));
}
#endif
}
| 5,984
|
C++
|
.cpp
| 126
| 39.222222
| 136
| 0.640014
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,565
|
err_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/err/err_api.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "impl/err_string_util.hpp"
namespace ams::err {
namespace impl {
namespace {
constexpr int ErrorCodeCategoryPlatformPrefixForResultModule = 2000;
ALWAYS_INLINE ErrorCode ConvertResultToErrorCode(const Result &result) {
return {
.category = static_cast<ErrorCodeCategory>(ErrorCodeCategoryPlatformPrefixForResultModule + result.GetModule()),
.number = static_cast<ErrorCodeNumber>(result.GetDescription()),
};
}
[[maybe_unused]] ALWAYS_INLINE Result ConvertErrorCodeToResult(const ErrorCode &error_code) {
const auto result_value = ::ams::result::impl::ResultTraits::MakeValue(error_code.category - ErrorCodeCategoryPlatformPrefixForResultModule, error_code.number);
return ::ams::result::impl::MakeResult(result_value);
}
}
}
ErrorCode ConvertResultToErrorCode(const Result &result) {
AMS_ASSERT(R_FAILED(result));
return ::ams::err::impl::ConvertResultToErrorCode(result);
}
void GetErrorCodeString(char *dst, size_t dst_size, ErrorCode error_code) {
AMS_ASSERT(dst != nullptr);
AMS_ASSERT(dst_size >= static_cast<size_t>(ErrorCode::StringLengthMax));
AMS_ASSERT(error_code.IsValid());
return ::ams::err::impl::MakeErrorCodeString(dst, dst_size, error_code);
}
}
| 2,103
|
C++
|
.cpp
| 44
| 40.454545
| 176
| 0.68915
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,566
|
err_string_util.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/err/impl/err_string_util.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "err_string_util.hpp"
namespace ams::err::impl {
void MakeErrorCodeString(char *dst, size_t dst_size, ErrorCode error_code) {
const auto len = util::TSNPrintf(dst, dst_size, "%04d-%04d", error_code.category, error_code.number);
AMS_ASSERT(static_cast<size_t>(len) < dst_size);
AMS_UNUSED(len);
}
}
| 1,005
|
C++
|
.cpp
| 24
| 38.833333
| 109
| 0.728016
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,567
|
ldr_pm_api.os.horizon.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/ldr/ldr_pm_api.os.horizon.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "ldr_ams.os.horizon.h"
namespace ams::ldr::pm {
/* Information API. */
Result CreateProcess(os::NativeHandle *out, PinId pin_id, u32 flags, Handle reslimit) {
R_RETURN(ldrPmCreateProcess(pin_id.value, flags, reslimit, out));
}
Result GetProgramInfo(ProgramInfo *out, const ncm::ProgramLocation &loc) {
static_assert(sizeof(*out) == sizeof(LoaderProgramInfo));
R_RETURN(ldrPmGetProgramInfo(reinterpret_cast<const NcmProgramLocation *>(std::addressof(loc)), reinterpret_cast<LoaderProgramInfo *>(out)));
}
Result PinProgram(PinId *out, const ncm::ProgramLocation &loc) {
static_assert(sizeof(*out) == sizeof(u64), "PinId definition!");
R_RETURN(ldrPmPinProgram(reinterpret_cast<const NcmProgramLocation *>(std::addressof(loc)), reinterpret_cast<u64 *>(out)));
}
Result UnpinProgram(PinId pin_id) {
R_RETURN(ldrPmUnpinProgram(pin_id.value));
}
Result HasLaunchedBootProgram(bool *out, ncm::ProgramId program_id) {
R_RETURN(ldrPmAtmosphereHasLaunchedBootProgram(out, static_cast<u64>(program_id)));
}
Result AtmosphereGetProgramInfo(ProgramInfo *out, cfg::OverrideStatus *out_status, const ncm::ProgramLocation &loc) {
static_assert(sizeof(*out_status) == sizeof(CfgOverrideStatus), "CfgOverrideStatus definition!");
static_assert(sizeof(*out) == sizeof(LoaderProgramInfo));
R_RETURN(ldrPmAtmosphereGetProgramInfo(reinterpret_cast<LoaderProgramInfo *>(out), reinterpret_cast<CfgOverrideStatus *>(out_status), reinterpret_cast<const NcmProgramLocation *>(std::addressof(loc))));
}
Result SetEnabledProgramVerification(bool enabled) {
R_RETURN(ldrPmSetEnabledProgramVerification(enabled));
}
Result AtmospherePinProgram(PinId *out, const ncm::ProgramLocation &loc, const cfg::OverrideStatus &status) {
static_assert(sizeof(*out) == sizeof(u64), "PinId definition!");
static_assert(sizeof(status) == sizeof(CfgOverrideStatus), "CfgOverrideStatus definition!");
R_RETURN(ldrPmAtmospherePinProgram(reinterpret_cast<u64 *>(out), reinterpret_cast<const NcmProgramLocation *>(std::addressof(loc)), reinterpret_cast<const CfgOverrideStatus *>(std::addressof(status))));
}
}
| 2,923
|
C++
|
.cpp
| 50
| 53.38
| 210
| 0.734893
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,568
|
ldr_shell_api.os.horizon.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/ldr/ldr_shell_api.os.horizon.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams::ldr {
Result InitializeForShell() {
R_RETURN(::ldrShellInitialize());
}
Result FinalizeForShell() {
::ldrShellExit();
R_SUCCEED();
}
Result SetProgramArgument(ncm::ProgramId program_id, const void *arg, size_t size) {
R_RETURN(::ldrShellSetProgramArguments(static_cast<u64>(program_id), arg, size));
}
Result FlushArguments() {
R_RETURN(::ldrShellFlushArguments());
}
}
| 1,126
|
C++
|
.cpp
| 31
| 32.354839
| 89
| 0.711662
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,569
|
settings_region.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/settings/settings_region.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "impl/settings_region_impl.hpp"
namespace ams::settings::system {
void GetRegionCode(RegionCode *out) {
AMS_ABORT_UNLESS(out != nullptr);
s32 value = 0;
R_ABORT_UNLESS(settings::impl::GetRegionCode(std::addressof(value)));
*out = static_cast<RegionCode>(value);
}
}
| 981
|
C++
|
.cpp
| 25
| 35.96
| 77
| 0.728227
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,570
|
settings_firmware_version.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/settings/settings_firmware_version.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "impl/settings_firmware_version_impl.hpp"
namespace ams::settings::system {
void GetFirmwareVersion(FirmwareVersion *out) {
R_ABORT_UNLESS(settings::impl::GetFirmwareVersion(out));
}
}
| 876
|
C++
|
.cpp
| 22
| 37.318182
| 76
| 0.755582
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,571
|
settings_serial_number.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/settings/settings_serial_number.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "impl/settings_serial_number_impl.hpp"
namespace ams::settings::factory {
Result GetSerialNumber(SerialNumber *out) {
R_TRY_CATCH(settings::impl::GetSerialNumber(out)) {
/* It's not a fatal error if the calib filesystem is corrupted. */
R_CATCH_RETHROW(settings::ResultCalibrationDataFileSystemCorrupted)
R_CATCH_RETHROW(settings::ResultCalibrationDataCrcError)
} R_END_TRY_CATCH_WITH_ABORT_UNLESS;
R_SUCCEED();
}
}
namespace ams::settings::system {
void GetSerialNumber(SerialNumber *out) {
R_ABORT_UNLESS(settings::impl::GetSerialNumber(out));
}
}
| 1,313
|
C++
|
.cpp
| 32
| 36.75
| 79
| 0.72763
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,572
|
settings_product_model.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/settings/settings_product_model.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "impl/settings_product_model_impl.hpp"
namespace ams::settings::system {
ProductModel GetProductModel() {
s32 model = 0;
R_ABORT_UNLESS(settings::impl::GetProductModel(std::addressof(model)));
return static_cast<ProductModel>(model);
}
}
| 945
|
C++
|
.cpp
| 24
| 36.333333
| 79
| 0.740741
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,573
|
settings_error_report.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/settings/settings_error_report.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "impl/settings_error_report_impl.hpp"
namespace ams::settings::system {
ErrorReportSharePermission GetErrorReportSharePermission() {
s32 perm = 0;
R_ABORT_UNLESS(settings::impl::GetErrorReportSharePermission(std::addressof(perm)));
return static_cast<ErrorReportSharePermission>(perm);
}
}
| 997
|
C++
|
.cpp
| 24
| 38.5
| 92
| 0.754639
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,574
|
settings_platform_region.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/settings/settings_platform_region.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "impl/settings_platform_region_impl.hpp"
namespace ams::settings::system {
PlatformRegion GetPlatformRegion() {
if (hos::GetVersion() >= hos::Version_9_0_0) {
s32 region = 0;
R_ABORT_UNLESS(settings::impl::GetPlatformRegion(std::addressof(region)));
return static_cast<PlatformRegion>(region);
} else {
return PlatformRegion_Global;
}
}
}
| 1,094
|
C++
|
.cpp
| 28
| 34.607143
| 86
| 0.706491
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,575
|
settings_fwdbg_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/settings/settings_fwdbg_api.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams::settings::fwdbg {
#if defined(ATMOSPHERE_OS_HORIZON)
bool IsDebugModeEnabled() {
bool value = false;
R_ABORT_UNLESS(::setsysGetDebugModeFlag(std::addressof(value)));
return value;
}
size_t WEAK_SYMBOL GetSettingsItemValueSize(const char *name, const char *key) {
u64 size = 0;
R_ABORT_UNLESS(setsysGetSettingsItemValueSize(name, key, &size));
return size;
}
size_t WEAK_SYMBOL GetSettingsItemValue(void *dst, size_t dst_size, const char *name, const char *key) {
u64 size = 0;
R_ABORT_UNLESS(setsysGetSettingsItemValue(name, key, dst, dst_size, &size));
return size;
}
#else
bool IsDebugModeEnabled() {
AMS_ABORT("TODO");
}
size_t WEAK_SYMBOL GetSettingsItemValueSize(const char *name, const char *key) {
AMS_UNUSED(name, key);
AMS_ABORT("TODO");
}
size_t WEAK_SYMBOL GetSettingsItemValue(void *dst, size_t dst_size, const char *name, const char *key) {
AMS_UNUSED(dst, dst_size, name, key);
AMS_ABORT("TODO");
}
#endif
}
| 1,779
|
C++
|
.cpp
| 47
| 32.744681
| 108
| 0.686957
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,576
|
settings_configuration_id.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/settings/settings_configuration_id.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "impl/settings_configuration_id_impl.hpp"
namespace ams::settings::factory {
void GetConfigurationId1(ConfigurationId1 *out) {
R_ABORT_UNLESS(settings::impl::GetConfigurationId1(out));
}
}
| 880
|
C++
|
.cpp
| 22
| 37.5
| 76
| 0.756725
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,577
|
settings_key_value_store.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/settings/impl/settings_key_value_store.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "settings_key_value_store.hpp"
#include "settings_spl.hpp"
#include "settings_system_data.hpp"
namespace ams::settings::impl {
namespace {
constexpr fs::SystemSaveDataId SystemSaveDataId = 0x8000000000000051;
constexpr u32 SystemSaveDataFlags = fs::SaveDataFlags_KeepAfterRefurbishment | fs::SaveDataFlags_KeepAfterResettingSystemSaveData;
constexpr s64 SystemSaveDataSize = 544_KB;
constexpr s64 SystemSaveDataJournalSize = 544_KB;
constexpr inline const char FwdbgSystemDataMountName[] = "FwdbgSettingsD";
constexpr inline const char PfCfgSystemDataMountName[] = "PfcfgSettingsD";
constexpr inline const char SystemSaveDataMountName[] = "FwdbgSettingsS";
constexpr inline const char SettingsNameSeparator = '!';
/* Type forward declarations. */
class MapKey;
struct MapValue;
template<typename T>
class Allocator;
using Map = std::map<MapKey, MapValue, std::less<MapKey>, Allocator<std::pair<const MapKey, MapValue>>>;
/* Function forward declarations. */
void FreeMapValueToHeap(const MapValue &value);
void *AllocateFromHeap(size_t size);
void FreeToHeap(void *block, size_t size);
lmem::HeapHandle &GetHeapHandle();
Result GetKeyValueStoreMap(Map **out);
Result GetKeyValueStoreMap(Map **out, bool force_load);
Result GetKeyValueStoreMapForciblyForDebug(Map **out);
Result LoadKeyValueStoreMap(Map *out);
Result LoadKeyValueStoreMap(Map *out, SplHardwareType hardware_type);
template<typename T>
Result LoadKeyValueStoreMapCurrent(Map *out, T &data);
template<typename T>
Result LoadKeyValueStoreMapDefault(Map *out, T &data);
template<typename T, typename F>
Result LoadKeyValueStoreMapEntries(Map *out, T &data, F load);
template<typename T, typename F>
Result LoadKeyValueStoreMapEntry(Map *out, T &data, s64 &offset, F load);
Result LoadKeyValueStoreMapForDebug(Map *out, SystemSaveData *system_save_data, SystemSaveData *fwdbg_system_data, SystemSaveData *pfcfg_system_data);
template<typename T>
Result ReadData(T &data, s64 &offset, void *buffer, size_t size);
template<typename T>
Result ReadDataToHeap(T &data, s64 &offset, void **buffer, size_t size);
template<typename T>
Result ReadAllBytes(T *data, u64 *out_count, char * const out_buffer, size_t out_buffer_size);
template<typename T>
Result SaveKeyValueStoreMapCurrent(T &data, const Map &map);
struct SystemDataTag {
struct Fwdbg{};
struct PfCfg{};
};
class MapKey {
public:
static constexpr size_t MaxKeySize = sizeof(SettingsName) + sizeof(SettingsItemKey);
private:
char *m_chars;
size_t m_count;
public:
MapKey(const char * const chars) : m_chars(nullptr), m_count(0) {
AMS_ASSERT(chars != nullptr);
this->Assign(chars, util::Strnlen(chars, MaxKeySize));
}
MapKey(const char * const chars, s32 count) : m_chars(nullptr), m_count(0) {
AMS_ASSERT(chars != nullptr);
AMS_ASSERT(count >= 0);
this->Assign(chars, count);
}
MapKey(MapKey &&other) : m_chars(nullptr), m_count(0) {
std::swap(m_chars, other.m_chars);
std::swap(m_count, other.m_count);
}
MapKey(const MapKey &other) : m_chars(nullptr), m_count(0) {
this->Assign(other.GetString(), other.GetCount());
}
~MapKey() {
this->Reset();
}
MapKey &Append(char c) {
const char chars[2] = { c, 0 };
return this->Append(chars, 1);
}
MapKey &Append(const char * const chars, s32 count) {
AMS_ASSERT(chars != nullptr);
AMS_ASSERT(count >= 0);
/* Allocate the new key. */
const size_t new_count = m_count + count;
char *new_heap = static_cast<char *>(AllocateFromHeap(new_count));
/* Copy the existing string to the new heap. */
std::memcpy(new_heap, this->GetString(), this->GetCount());
/* Copy the string to append to the new heap. */
std::memcpy(new_heap + this->GetCount(), chars, count);
/* Null-terminate the new string. */
new_heap[new_count - 1] = '\x00';
/* Reset and update the key. */
this->Reset();
m_count = new_count;
m_chars = new_heap;
return *this;
}
MapKey &Assign(const char * const chars, s32 count) {
AMS_ASSERT(chars != nullptr);
AMS_ASSERT(count >= 0);
/* Reset the key. */
this->Reset();
/* Update the count and allocate the buffer. */
m_count = count + 1;
m_chars = static_cast<char *>(AllocateFromHeap(m_count));
/* Copy the characters to the buffer. */
std::memcpy(m_chars, chars, count);
m_chars[count] = '\x00';
return *this;
}
size_t Find(const MapKey &other) const {
return std::search(this->GetString(), this->GetString() + this->GetCount(), other.GetString(), other.GetString() + other.GetCount()) - this->GetString();
}
s32 GetCount() const {
return static_cast<s32>(m_count) - 1;
}
const char *GetString() const {
return m_chars;
}
private:
void Reset() {
if (m_chars != nullptr) {
FreeToHeap(m_chars, m_count);
m_chars = nullptr;
m_count = 0;
}
}
};
inline bool operator<(const MapKey &lhs, const MapKey &rhs) {
return std::strncmp(lhs.GetString(), rhs.GetString(), std::max(lhs.GetCount(), rhs.GetCount())) < 0;
}
MapKey MakeMapKey(const SettingsName &name, const SettingsItemKey &item_key) {
/* Create a map key. */
MapKey key(name.value, util::Strnlen(name.value, util::size(name.value)));
/* Append the settings name separator followed by the item key. */
key.Append(SettingsNameSeparator);
key.Append(item_key.value, util::Strnlen(item_key.value, util::size(item_key.value)));
/* Output the map key. */
return key;
}
struct MapValue {
public:
u8 type;
size_t current_value_size;
size_t default_value_size;
void *current_value;
void *default_value;
};
static_assert(sizeof(MapValue) == 0x28);
template<typename T>
class Allocator {
public:
using value_type = T;
using size_type = size_t;
using difference_type = ptrdiff_t;
public:
Allocator() noexcept = default;
~Allocator() noexcept = default;
Allocator(const Allocator &) noexcept = default;
Allocator(Allocator &&) noexcept = default;
T *allocate(size_t n) noexcept {
return static_cast<T *>(AllocateFromHeap(sizeof(T) * n));
}
void deallocate(T *p, size_t n) noexcept {
FreeToHeap(p, sizeof(T) * n);
}
private:
Allocator &operator=(const Allocator &) noexcept = default;
Allocator &operator=(Allocator &&) noexcept = default;
};
template<class T, class U>
constexpr inline bool operator==(const Allocator<T> &, const Allocator<U> &) {
return true;
}
constexpr inline size_t MapKeyBufferSize = MapKey::MaxKeySize * 2;
constexpr inline size_t MapEntryBufferSize = 0x40 + sizeof(Map::value_type);
constexpr inline size_t HeapMemorySize = 512_KB;
constinit os::SdkMutex g_key_value_store_mutex;
void ClearKeyValueStoreMap(Map &map) {
/* Free all values to the heap. */
for (const auto &kv_pair : map) {
FreeMapValueToHeap(kv_pair.second);
}
/* Clear the map. */
map.clear();
}
bool CompareValue(const void *lhs, size_t lhs_size, const void *rhs, size_t rhs_size) {
/* Check if both buffers are the same. */
if (lhs == rhs) {
return true;
}
/* If the value sizes don't match, return false. */
if (lhs_size != rhs_size) {
return false;
}
/* If the value sizes are 0, they are considered to match. */
if (lhs_size == 0) {
return true;
}
/* Compare the two values if they are non-null. */
return lhs != nullptr && rhs != nullptr && std::memcmp(lhs, rhs, lhs_size) == 0;
}
void FreeMapValueToHeap(const MapValue &map_value) {
/* Free the current value. */
if (map_value.current_value != nullptr && map_value.current_value != map_value.default_value) {
FreeToHeap(map_value.current_value, map_value.current_value_size);
}
/* Free the default value. */
if (map_value.default_value != nullptr) {
FreeToHeap(map_value.default_value, map_value.default_value_size);
}
}
void FreeToHeap(void *block, size_t size) {
AMS_UNUSED(size);
lmem::FreeToExpHeap(GetHeapHandle(), block);
}
void *AllocateFromHeap(size_t size) {
return lmem::AllocateFromExpHeap(GetHeapHandle(), size);
}
size_t GetHeapAllocatableSize() {
return lmem::GetExpHeapAllocatableSize(GetHeapHandle(), sizeof(void *));
}
lmem::HeapHandle &GetHeapHandle() {
AMS_FUNCTION_LOCAL_STATIC_CONSTINIT(u8, s_heap_memory[HeapMemorySize]);
AMS_FUNCTION_LOCAL_STATIC(lmem::HeapHandle, s_heap_handle, lmem::CreateExpHeap(s_heap_memory, sizeof(s_heap_memory), lmem::CreateOption_ThreadSafe));
return s_heap_handle;
}
Result GetKeyValueStoreMap(Map **out) {
/* Check preconditions. */
AMS_ASSERT(out != nullptr);
/* Get the map. */
R_RETURN(GetKeyValueStoreMap(out, false));
}
Result GetKeyValueStoreMap(Map **out, bool force_load) {
/* Check preconditions. */
AMS_ASSERT(out != nullptr);
/* Declare static instance variables. */
AMS_FUNCTION_LOCAL_STATIC(Map, s_map);
AMS_FUNCTION_LOCAL_STATIC_CONSTINIT(bool, s_is_map_loaded, false);
/* Get pointer to the map. */
Map * const map = std::addressof(s_map);
/* TODO: Mutex? */
/* Load the map, if we haven't already. */
if (AMS_UNLIKELY(!s_is_map_loaded)) {
/* Attempt to load the map, allowing for failure if acceptable. */
const auto result = LoadKeyValueStoreMap(map);
if (!force_load) {
R_TRY(result);
}
/* Note that the map is loaded. */
s_is_map_loaded = true;
}
/* Set the output pointer. */
*out = map;
R_SUCCEED();
}
Result GetKeyValueStoreMapForciblyForDebug(Map **out) {
/* Check preconditions. */
AMS_ASSERT(out != nullptr);
/* Get the map. */
R_RETURN(GetKeyValueStoreMap(out, true));
}
Result GetMapValueOfKeyValueStoreItemForDebug(MapValue *out, const KeyValueStoreItemForDebug &item) {
/* Check preconditions. */
AMS_ASSERT(out != nullptr);
/* Create the map value. */
MapValue map_value = {
.type = item.type,
.current_value_size = item.current_value_size,
.default_value_size = item.default_value_size,
.current_value = nullptr,
.default_value = nullptr,
};
/* Ensure we free any buffers we allocate, if we fail. */
ON_SCOPE_EXIT { FreeMapValueToHeap(map_value); };
/* If the default value size is > 0, copy it to the map value. */
if (map_value.default_value_size > 0) {
/* Allocate the default value if there is sufficient memory available. */
R_UNLESS(GetHeapAllocatableSize() >= map_value.default_value_size, settings::ResultSettingsItemValueAllocationFailed());
map_value.default_value = AllocateFromHeap(map_value.default_value_size);
AMS_ASSERT(map_value.default_value != nullptr);
/* Copy the default value from the item. */
std::memcpy(map_value.default_value, item.default_value, map_value.default_value_size);
}
/* If the current value and the default values are identical, set the map value to the default value. */
if (CompareValue(item.current_value, item.current_value_size, item.default_value, item.default_value_size)) {
map_value.current_value_size = map_value.default_value_size;
map_value.current_value = map_value.default_value;
} else if (map_value.current_value_size > 0) {
/* Allocate the current value if there is sufficient memory available. */
R_UNLESS(GetHeapAllocatableSize() >= map_value.current_value_size, settings::ResultSettingsItemValueAllocationFailed());
map_value.current_value = AllocateFromHeap(map_value.current_value_size);
AMS_ASSERT(map_value.current_value != nullptr);
/* Copy the current value from the item. */
std::memcpy(map_value.current_value, item.current_value, map_value.current_value_size);
}
/* Set the output map value. */
*out = map_value;
/* Ensure we don't free the value buffers we returned. */
map_value.current_value = nullptr;
map_value.default_value = nullptr;
R_SUCCEED();
}
template<typename T>
const char *GetSystemDataMountName();
template<>
const char *GetSystemDataMountName<SystemDataTag::Fwdbg>() {
return FwdbgSystemDataMountName;
}
template<>
const char *GetSystemDataMountName<SystemDataTag::PfCfg>() {
return PfCfgSystemDataMountName;
}
template<typename T>
Result GetSystemData(SystemData **out_data, ncm::SystemDataId id) {
/* Check pre-conditions. */
AMS_ASSERT(out_data != nullptr);
/* Declare static instance variables. */
AMS_FUNCTION_LOCAL_STATIC(SystemData, s_data, id, GetSystemDataMountName<T>());
AMS_FUNCTION_LOCAL_STATIC_CONSTINIT(bool, s_mounted, false);
/* Get pointer to the system data. */
SystemData *data = std::addressof(s_data);
/* TODO: Mutex? */
/* Mount the system data, if we haven't already. */
if (AMS_UNLIKELY(!s_mounted)) {
/* Mount the system data. */
R_TRY(data->Mount());
/* Note that we mounted. */
s_mounted = true;
}
/* Set the output pointer. */
*out_data = data;
R_SUCCEED();
}
Result GetSystemSaveData(SystemSaveData **out_data, bool create_save) {
/* Check pre-conditions. */
AMS_ASSERT(out_data != nullptr);
/* Declare static instance variables. */
AMS_FUNCTION_LOCAL_STATIC(SystemSaveData, s_data, SystemSaveDataId, SystemSaveDataSize, SystemSaveDataJournalSize, SystemSaveDataFlags, SystemSaveDataMountName);
AMS_FUNCTION_LOCAL_STATIC_CONSTINIT(bool, s_mounted, false);
/* Get pointer to the system save data. */
SystemSaveData *data = std::addressof(s_data);
/* Mount the system data, if we haven't already. */
if (AMS_UNLIKELY(!s_mounted)) {
/* Mount the system data. */
R_TRY(data->Mount(create_save));
/* Note that we mounted. */
s_mounted = true;
}
/* Set the output pointer. */
*out_data = data;
R_SUCCEED();
}
Result LoadKeyValueStoreMap(Map *out) {
/* Check pre-conditions. */
AMS_ASSERT(out != nullptr);
/* Clear the key value store map. */
ClearKeyValueStoreMap(*out);
/* Get the firmware debug system data. */
SystemData *system_data = nullptr;
R_TRY(GetSystemData<SystemDataTag::Fwdbg>(std::addressof(system_data), ncm::SystemDataId::FirmwareDebugSettings));
AMS_ASSERT(system_data != nullptr);
/* Load the default keys/values for the firmware debug system data. */
R_TRY(LoadKeyValueStoreMapDefault(out, *system_data));
/* Load the keys/values based on the hardware type. */
R_TRY(LoadKeyValueStoreMap(out, GetSplHardwareType()));
if (IsSplDevelopment()) {
/* Get the system save data. */
SystemSaveData *system_save_data = nullptr;
R_SUCCEED_IF(R_FAILED(GetSystemSaveData(std::addressof(system_save_data), false)));
AMS_ASSERT(system_save_data != nullptr);
/* Attempt to load the current keys/values from the system save data. */
if (const auto result = LoadKeyValueStoreMapCurrent(out, *system_save_data); R_FAILED(result)) {
/* Reset all values to their defaults. */
for (auto &kv_pair : *out) {
MapValue &map_value = kv_pair.second;
/* Free the current value. */
if (map_value.current_value != nullptr && map_value.current_value != map_value.default_value) {
FreeToHeap(map_value.current_value, map_value.current_value_size);
}
/* Reset the current value to the default value. */
map_value.current_value_size = map_value.default_value_size;
map_value.current_value = map_value.default_value;
}
/* Log failure to load system save data. TODO: Make this a warning. */
AMS_LOG("[firmware debug settings] Warning: Failed to load the system save data. (%08x, %d%03d-%04d)\n", result.GetInnerValue(), 2, result.GetModule(), result.GetDescription());
}
}
R_SUCCEED();
}
Result LoadKeyValueStoreMap(Map *out, SplHardwareType hardware_type) {
SystemData *data = nullptr;
/* Get the platform configuration system data for the hardware type. */
switch (hardware_type) {
case SplHardwareType_None:
R_SUCCEED();
case SplHardwareType_Icosa:
R_TRY(GetSystemData<SystemDataTag::PfCfg>(std::addressof(data), ncm::SystemDataId::PlatformConfigIcosa));
break;
case SplHardwareType_IcosaMariko:
R_TRY(GetSystemData<SystemDataTag::PfCfg>(std::addressof(data), ncm::SystemDataId::PlatformConfigIcosaMariko));
break;
case SplHardwareType_Copper:
R_TRY(GetSystemData<SystemDataTag::PfCfg>(std::addressof(data), ncm::SystemDataId::PlatformConfigCopper));
break;
case SplHardwareType_Hoag:
R_TRY(GetSystemData<SystemDataTag::PfCfg>(std::addressof(data), ncm::SystemDataId::PlatformConfigHoag));
break;
case SplHardwareType_Calcio:
R_TRY(GetSystemData<SystemDataTag::PfCfg>(std::addressof(data), ncm::SystemDataId::PlatformConfigCalcio));
break;
case SplHardwareType_Aula:
R_TRY(GetSystemData<SystemDataTag::PfCfg>(std::addressof(data), ncm::SystemDataId::PlatformConfigAula));
break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
/* Ensure data is not null. */
AMS_ASSERT(data != nullptr);
/* Load the key value store map. */
R_RETURN(LoadKeyValueStoreMapDefault(out, *data));
}
template<typename T>
Result LoadKeyValueStoreMapCurrent(Map *out, T &data) {
/* Check pre-conditions. */
AMS_ASSERT(out != nullptr);
/* Open the data for reading. */
R_TRY(data.OpenToRead());
ON_SCOPE_EXIT { data.Close(); };
/* Load the map entries. */
R_TRY(LoadKeyValueStoreMapEntries(out, data, [](Map &map, const MapKey &key, u8 type, const void *value_buffer, u32 value_size) -> Result {
AMS_UNUSED(type);
/* Find the key in the map. */
if (auto it = map.find(key); it != map.end()) {
MapValue &map_value = it->second;
size_t current_value_size = value_size;
void *current_value_buffer = nullptr;
if (current_value_size > 0) {
/* Ensure there is sufficient memory for the value. */
R_UNLESS(GetHeapAllocatableSize() >= current_value_size, settings::ResultSettingsItemValueAllocationFailed());
/* Allocate the value buffer. */
current_value_buffer = AllocateFromHeap(current_value_size);
AMS_ASSERT(current_value_buffer != nullptr);
/* Copy the value to the current value buffer. */
std::memcpy(current_value_buffer, value_buffer, current_value_size);
}
/* Replace the current value buffer with a new one. */
std::swap(map_value.current_value_size, current_value_size);
std::swap(map_value.current_value, current_value_buffer);
/* Free the old buffer if it is no longer in use. */
if (current_value_buffer != nullptr && current_value_buffer != map_value.default_value) {
FreeToHeap(current_value_buffer, current_value_size);
}
}
R_SUCCEED();
}));
R_SUCCEED();
}
template<typename T>
Result LoadKeyValueStoreMapDefault(Map *out, T &data) {
/* Check pre-conditions. */
AMS_ASSERT(out != nullptr);
/* Open the data for reading. */
R_TRY(data.OpenToRead());
ON_SCOPE_EXIT { data.Close(); };
/* Load the map entries. */
R_TRY(LoadKeyValueStoreMapEntries(out, data, [](Map &map, const MapKey &key, u8 type, const void *value_buffer, u32 value_size) -> Result {
/* Ensure there is sufficient memory for two keys. */
R_UNLESS(GetHeapAllocatableSize() >= MapKeyBufferSize, settings::ResultSettingsItemKeyAllocationFailed());
/* Copy the map key. */
MapKey default_key = key;
void *default_value_buffer = nullptr;
ON_SCOPE_EXIT {
/* Free the value buffer if allocated. */
if (default_value_buffer != nullptr) {
FreeToHeap(default_value_buffer, value_size);
}
};
if (value_size > 0) {
/* Ensure there is sufficient memory for the value. */
R_UNLESS(GetHeapAllocatableSize() >= value_size, settings::ResultSettingsItemValueAllocationFailed());
/* Allocate the value buffer. */
default_value_buffer = AllocateFromHeap(value_size);
AMS_ASSERT(default_value_buffer != nullptr);
/* Copy the value to the new value buffer. */
std::memcpy(default_value_buffer, value_buffer, value_size);
}
/* Create the map value. */
MapValue default_value {
.type = type,
.current_value_size = value_size,
.default_value_size = value_size,
.current_value = default_value_buffer,
.default_value = default_value_buffer,
};
/* Ensure there is sufficient memory for the value. */
R_UNLESS(GetHeapAllocatableSize() >= MapEntryBufferSize, settings::ResultSettingsItemValueAllocationFailed());
/* Insert the value into the map. */
map[std::move(default_key)] = default_value;
R_SUCCEED();
}));
R_SUCCEED();
}
template<typename T, typename F>
Result LoadKeyValueStoreMapEntries(Map *out, T &data, F load) {
/* Check pre-conditions. */
AMS_ASSERT(out != nullptr);
/* Read the number of entries. */
s64 offset = 0;
u32 total_size = 0;
R_TRY(ReadData(data, offset, std::addressof(total_size), sizeof(total_size)));
/* Iterate through all entries. NOTE: The offset is updated within LoadKeyValueStoreMapEntry. */
while (offset < total_size) {
R_TRY(LoadKeyValueStoreMapEntry(out, data, offset, load));
}
R_SUCCEED();
}
template<typename T, typename F>
Result LoadKeyValueStoreMapEntry(Map *out, T &data, s64 &offset, F load) {
/* Check pre-conditions. */
AMS_ASSERT(out != nullptr);
/* Read the size of the key. */
u32 key_size = 0;
R_TRY(ReadData(data, offset, std::addressof(key_size), sizeof(key_size)));
AMS_ASSERT(key_size > 1);
/* Ensure there is sufficient memory for this key. */
R_UNLESS(GetHeapAllocatableSize() >= key_size, settings::ResultSettingsItemKeyAllocationFailed());
/* Read the key. */
void *key_buffer = nullptr;
R_TRY(ReadDataToHeap(data, offset, std::addressof(key_buffer), key_size));
AMS_ASSERT(key_buffer != nullptr);
ON_SCOPE_EXIT { FreeToHeap(key_buffer, key_size); };
/* Ensure there is sufficient memory for two keys. */
R_UNLESS(GetHeapAllocatableSize() >= MapKeyBufferSize, settings::ResultSettingsItemKeyAllocationFailed());
const MapKey key(static_cast<const char *>(key_buffer), key_size - 1);
/* Read the type from the data. */
u8 type = 0;
R_TRY(ReadData(data, offset, std::addressof(type), sizeof(type)));
/* Read the size of the value. */
u32 value_size = 0;
R_TRY(ReadData(data, offset, std::addressof(value_size), sizeof(value_size)));
void *value_buffer = nullptr;
ON_SCOPE_EXIT {
if (value_buffer != nullptr) {
FreeToHeap(value_buffer, value_size);
}
};
if (value_size > 0) {
/* Ensure there is sufficient memory for the value. */
R_UNLESS(GetHeapAllocatableSize() >= value_size, settings::ResultSettingsItemValueAllocationFailed());
/* Read the value to the buffer. */
R_TRY(ReadDataToHeap(data, offset, std::addressof(value_buffer), value_size));
}
/* Load the value. */
R_RETURN(load(*out, key, type, value_buffer, value_size));
}
Result LoadKeyValueStoreMapForDebug(Map *out, SystemSaveData *system_save_data, SystemSaveData *fwdbg_system_save_data, SystemSaveData *pfcfg_system_save_data) {
/* Check pre-conditions. */
AMS_ASSERT(out != nullptr);
AMS_ASSERT(system_save_data != nullptr);
AMS_ASSERT(fwdbg_system_save_data != nullptr);
AMS_ASSERT(pfcfg_system_save_data != nullptr);
/* Clear the map. */
ClearKeyValueStoreMap(*out);
/* Load the default keys/values for the firmware debug system save data. */
R_TRY(LoadKeyValueStoreMapDefault(out, *fwdbg_system_save_data));
/* Load the default keys/values for the platform configuration system save data. */
R_TRY(LoadKeyValueStoreMapDefault(out, *pfcfg_system_save_data));
/* Load the current values for the system save data. */
R_TRY(LoadKeyValueStoreMapCurrent(out, *system_save_data));
R_SUCCEED();
}
template<typename T>
Result ReadData(T &data, s64 &offset, void *buffer, size_t size) {
AMS_ASSERT(buffer != nullptr);
/* Read the data. */
R_TRY(data.Read(offset, buffer, size));
/* Increment the offset. */
offset += static_cast<s64>(size);
R_SUCCEED();
}
template<typename T>
Result ReadDataToHeap(T &data, s64 &offset, void **buffer, size_t size) {
/* Check pre-conditions. */
AMS_ASSERT(buffer != nullptr);
AMS_ASSERT(size > 0);
/* Allocate a buffer from the heap. */
*buffer = AllocateFromHeap(size);
AMS_ASSERT(*buffer != nullptr);
/* Ensure we free the buffer if we fail. */
auto alloc_guard = SCOPE_GUARD { FreeToHeap(*buffer, size); *buffer = nullptr; };
/* Read data to the buffer. */
R_TRY(ReadData(data, offset, *buffer, size));
/* We succeeded. */
alloc_guard.Cancel();
R_SUCCEED();
}
template<typename T>
Result ReadAllBytes(T *data, u64 *out_count, char * const out_buffer, size_t out_buffer_size) {
/* Check preconditions. */
AMS_ASSERT(data != nullptr);
AMS_ASSERT(out_count != nullptr);
AMS_ASSERT(out_buffer != nullptr);
/* Open data for reading. */
R_TRY(data->OpenToRead());
ON_SCOPE_EXIT { data->Close(); };
/* Read the data size. */
u32 size = 0;
R_TRY(data->Read(0, std::addressof(size), sizeof(size)));
/* Ensure the data size does not exceed the buffer size. */
size = std::min(size, static_cast<u32>(out_buffer_size));
/* Read the data. */
R_TRY(data->Read(0, out_buffer, size));
/* Set the count. */
*out_count = size;
R_SUCCEED();
}
Result ReadSystemDataFirmwareDebug(u64 *out_count, char * const out_buffer, size_t out_buffer_size) {
/* Check preconditions. */
AMS_ASSERT(out_count != nullptr);
AMS_ASSERT(out_buffer);
/* Attempt to get the firmware debug system data. */
SystemData *system_data = nullptr;
if (R_SUCCEEDED(GetSystemData<SystemDataTag::Fwdbg>(std::addressof(system_data), ncm::SystemDataId::FirmwareDebugSettings))) {
AMS_ASSERT(system_data != nullptr);
/* Read the data. */
R_TRY(ReadAllBytes(system_data, out_count, out_buffer, out_buffer_size));
} else {
/* Set the output count to 0. */
*out_count = 0;
}
R_SUCCEED();
}
Result ReadSystemDataPlatformConfiguration(u64 *out_count, char * const out_buffer, size_t out_buffer_size) {
/* Check preconditions. */
AMS_ASSERT(out_count != nullptr);
AMS_ASSERT(out_buffer);
ncm::SystemDataId system_data_id;
switch (GetSplHardwareType()) {
case SplHardwareType_None:
*out_count = 0;
R_SUCCEED();
case SplHardwareType_Icosa:
system_data_id = ncm::SystemDataId::PlatformConfigIcosa;
break;
case SplHardwareType_IcosaMariko:
system_data_id = ncm::SystemDataId::PlatformConfigIcosaMariko;
break;
case SplHardwareType_Copper:
system_data_id = ncm::SystemDataId::PlatformConfigCopper;
break;
case SplHardwareType_Hoag:
system_data_id = ncm::SystemDataId::PlatformConfigHoag;
break;
case SplHardwareType_Calcio:
system_data_id = ncm::SystemDataId::PlatformConfigCalcio;
break;
case SplHardwareType_Aula:
system_data_id = ncm::SystemDataId::PlatformConfigAula;
break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
/* Attempt to get the platform configuration system data. */
SystemData *system_data = nullptr;
if (R_SUCCEEDED(GetSystemData<SystemDataTag::PfCfg>(std::addressof(system_data), system_data_id))) {
AMS_ASSERT(system_data != nullptr);
/* Read the data. */
R_TRY(ReadAllBytes(system_data, out_count, out_buffer, out_buffer_size));
} else {
/* Set the output count to 0. */
*out_count = 0;
}
R_SUCCEED();
}
Result ReadSystemSaveData(u64 *out_count, char * const out_buffer, size_t out_buffer_size) {
/* Check preconditions. */
AMS_ASSERT(out_count != nullptr);
AMS_ASSERT(out_buffer);
/* Attempt to get the system save data. */
SystemSaveData *system_save_data = nullptr;
if (R_SUCCEEDED(GetSystemSaveData(std::addressof(system_save_data), false))) {
AMS_ASSERT(system_save_data != nullptr);
/* Read the data. */
R_TRY(ReadAllBytes(system_save_data, out_count, out_buffer, out_buffer_size));
} else {
/* Set the output count to 0. */
*out_count = 0;
}
R_SUCCEED();
}
Result SaveKeyValueStoreMap(const Map &map) {
/* Get the system save data. */
SystemSaveData *system_save_data = nullptr;
R_TRY(GetSystemSaveData(std::addressof(system_save_data), false));
AMS_ASSERT(system_save_data != nullptr);
/* Save the current values of the key value store map. */
R_RETURN(SaveKeyValueStoreMapCurrent(*system_save_data, map));
}
template<typename T, typename F>
Result SaveKeyValueStoreMap(T &data, const Map &map, F test) {
/* Create the save data if necessary. */
R_TRY_CATCH(data.Create(HeapMemorySize)) {
R_CATCH(fs::ResultPathAlreadyExists) { /* It's okay if the save data already exists. */ }
} R_END_TRY_CATCH;
{
/* Open the save data for writing. */
R_TRY(data.OpenToWrite());
ON_SCOPE_EXIT {
/* Flush and close the save data. NOTE: Nintendo only does this if SetFileSize succeeds. */
R_ABORT_UNLESS(data.Flush());
data.Close();
};
/* Set the file size of the save data. */
R_TRY(data.SetFileSize(HeapMemorySize));
/* Write the data size, which includes itself. */
u32 data_size = sizeof(data_size);
R_TRY(data.Write(0, std::addressof(data_size), sizeof(data_size)));
/* Set the current offset to after the data size. */
s64 current_offset = sizeof(data_size);
/* Iterate through map entries. */
for (const auto &kv_pair : map) {
/* Declare variables for test. */
u8 type = 0;
const void *value_buffer = nullptr;
u32 value_size = 0;
/* Test if the map value varies from the default. */
if (test(std::addressof(type), std::addressof(value_buffer), std::addressof(value_size), kv_pair.second)) {
R_TRY(SaveKeyValueStoreMapEntry(data, current_offset, kv_pair.first, type, value_buffer, value_size));
}
}
/* Write the updated save data size. */
data_size = static_cast<u32>(current_offset);
R_TRY(data.Write(0, std::addressof(data_size), sizeof(data_size)));
}
/* Commit the save data. */
R_RETURN(data.Commit(false));
}
template<typename T>
Result SaveKeyValueStoreMapCurrent(T &data, const Map &map) {
/* Save the current values in the map to the data. */
R_RETURN(SaveKeyValueStoreMap(data, map, [](u8 *out_type, const void **out_value_buffer, u32 *out_value_size, const MapValue &map_value) -> bool {
/* Check preconditions. */
AMS_ASSERT(out_type != nullptr);
AMS_ASSERT(out_value_buffer != nullptr);
AMS_ASSERT(out_value_size != nullptr);
/* Check if the current value matches the default value. */
if (CompareValue(map_value.current_value, map_value.current_value_size, map_value.default_value, map_value.default_value_size)) {
return false;
}
/* Output the map value type, current value and current value size. */
*out_type = map_value.type;
*out_value_buffer = map_value.current_value;
*out_value_size = map_value.current_value_size;
return true;
}));
}
template<typename T>
Result SaveKeyValueStoreMapDefault(T &data, const Map &map) {
/* Save the default values in the map to the data. */
R_RETURN(SaveKeyValueStoreMap(data, map, [](u8 *out_type, const void **out_value_buffer, u32 *out_value_size, const MapValue &map_value) -> bool {
/* Check preconditions. */
AMS_ASSERT(out_type != nullptr);
AMS_ASSERT(out_value_buffer != nullptr);
AMS_ASSERT(out_value_size != nullptr);
/* Output the map value type, default value and default value size. */
*out_type = map_value.type;
*out_value_buffer = map_value.default_value;
*out_value_size = map_value.default_value_size;
return true;
}));
}
Result SaveKeyValueStoreMapDefaultForDebug(SystemSaveData &data, const Map &map) {
R_RETURN(SaveKeyValueStoreMapDefault(data, map));
}
template<typename T>
Result SaveKeyValueStoreMapEntry(T &data, s64 &offset, const MapKey &key, u8 type, const void *value_buffer, u32 value_size) {
/* Write the key size and increment the offset. */
const u32 key_size = key.GetCount() + 1;
R_TRY(data.Write(offset, std::addressof(key_size), sizeof(key_size)));
offset += static_cast<s64>(sizeof(key_size));
/* Write the key string and increment the offset. */
R_TRY(data.Write(offset, key.GetString(), key_size));
offset += static_cast<s64>(key_size);
/* Write the type and increment the offset. */
R_TRY(data.Write(offset, std::addressof(type), sizeof(type)));
offset += static_cast<s64>(sizeof(type));
/* Write the value size and increment the offset. */
R_TRY(data.Write(offset, std::addressof(value_size), sizeof(value_size)));
offset += static_cast<s64>(sizeof(value_size));
/* If the value is larger than 0, write it to the data. */
if (value_size > 0) {
/* Check preconditions. */
AMS_ASSERT(value_buffer != nullptr);
R_TRY(data.Write(offset, value_buffer, value_size));
offset += static_cast<s64>(value_size);
}
R_SUCCEED();
}
}
Result KeyValueStore::CreateKeyIterator(KeyValueStoreKeyIterator *out) {
/* Check preconditions. */
AMS_ASSERT(out != nullptr);
/* Acquire exclusive access to global state. */
std::scoped_lock lk(g_key_value_store_mutex);
/* Get the key value store map. */
Map *map = nullptr;
R_TRY(GetKeyValueStoreMap(std::addressof(map)));
AMS_ASSERT(map != nullptr);
/* Ensure there is sufficient memory for two keys. */
R_UNLESS(GetHeapAllocatableSize() >= MapKeyBufferSize, settings::ResultSettingsItemKeyAllocationFailed());
/* Create a map key from the key value store's name. */
MapKey map_key_header(m_name.value);
/* Append the settings name separator. */
map_key_header.Append(SettingsNameSeparator);
/* Define the item map key. */
const MapKey *item_map_key = nullptr;
/* Find an item map key with the name as a prefix. */
for (const auto &kv_pair : *map) {
const MapKey &map_key = kv_pair.first;
/* Check if the name map key is smaller than the current map key, and the current map key contains the name map key. */
if (map_key_header < map_key && map_key.Find(map_key_header)) {
item_map_key = std::addressof(map_key);
break;
}
}
/* Ensure we have located an item map key. */
R_UNLESS(item_map_key != nullptr, settings::ResultSettingsItemNotFound());
/* Ensure there is sufficient memory for the item map key. */
const size_t item_map_key_size = item_map_key->GetCount() + 1;
R_UNLESS(GetHeapAllocatableSize() >= item_map_key_size, settings::ResultSettingsItemKeyIteratorAllocationFailed());
/* Allocate the key buffer. */
char *buffer = static_cast<char *>(AllocateFromHeap(item_map_key_size));
AMS_ASSERT(buffer != nullptr);
/* Copy the item map key's string to the buffer. */
std::memcpy(buffer, item_map_key->GetString(), item_map_key_size);
/* Output the iterator. */
*out = {
.header_size = static_cast<size_t>(map_key_header.GetCount()),
.entire_size = item_map_key_size,
.map_key = buffer,
};
R_SUCCEED();
}
Result KeyValueStore::GetValue(u64 *out_count, char *out_buffer, size_t out_buffer_size, const SettingsItemKey &item_key) {
/* Check preconditions. */
AMS_ASSERT(out_count != nullptr);
AMS_ASSERT(out_buffer != nullptr);
/* Acquire exclusive access to global state. */
std::scoped_lock lk(g_key_value_store_mutex);
/* Get the key value store map. */
Map *map = nullptr;
R_TRY(GetKeyValueStoreMap(std::addressof(map)));
AMS_ASSERT(map != nullptr);
/* Ensure there is sufficient memory for two keys. */
R_UNLESS(GetHeapAllocatableSize() >= MapKeyBufferSize, settings::ResultSettingsItemKeyAllocationFailed());
/* Find the key in the map. */
const Map::const_iterator it = map->find(MakeMapKey(m_name, item_key));
R_UNLESS(it != map->end(), settings::ResultSettingsItemNotFound());
/* Get the map value from the iterator. */
const MapValue &map_value = it->second;
/* Calculate the current value size. */
const size_t current_value_size = std::min(map_value.current_value_size, out_buffer_size);
/* If the current value size is > 0, copy to the output buffer. */
if (current_value_size > 0) {
AMS_ASSERT(map_value.current_value != nullptr);
std::memcpy(out_buffer, map_value.current_value, current_value_size);
}
/* Set the output count. */
*out_count = current_value_size;
R_SUCCEED();
}
Result KeyValueStore::GetValueSize(u64 *out_value_size, const SettingsItemKey &item_key) {
/* Check preconditions. */
AMS_ASSERT(out_value_size != nullptr);
/* Acquire exclusive access to global state. */
std::scoped_lock lk(g_key_value_store_mutex);
/* Get the key value store map. */
Map *map = nullptr;
R_TRY(GetKeyValueStoreMap(std::addressof(map)));
AMS_ASSERT(map != nullptr);
/* Ensure there is sufficient memory for two keys. */
R_UNLESS(GetHeapAllocatableSize() >= MapKeyBufferSize, settings::ResultSettingsItemKeyAllocationFailed());
/* Find the key in the map. */
const Map::const_iterator it = map->find(MakeMapKey(m_name, item_key));
R_UNLESS(it != map->end(), settings::ResultSettingsItemNotFound());
/* Output the value size. */
*out_value_size = it->second.current_value_size;
R_SUCCEED();
}
Result KeyValueStore::ResetValue(const SettingsItemKey &item_key) {
/* Acquire exclusive access to global state. */
std::scoped_lock lk(g_key_value_store_mutex);
/* Get the key value store map. */
Map *map = nullptr;
R_TRY(GetKeyValueStoreMap(std::addressof(map)));
AMS_ASSERT(map != nullptr);
/* Ensure there is sufficient memory for two keys. */
R_UNLESS(GetHeapAllocatableSize() >= MapKeyBufferSize, settings::ResultSettingsItemKeyAllocationFailed());
/* Find the key in the map. */
const Map::iterator it = map->find(MakeMapKey(m_name, item_key));
R_UNLESS(it != map->end(), settings::ResultSettingsItemNotFound());
/* Get the map value from the iterator. */
MapValue &map_value = it->second;
/* Succeed if the map value has already been reset. */
R_SUCCEED_IF(map_value.current_value == map_value.default_value);
/* Store the previous value and its size. */
size_t prev_value_size = map_value.current_value_size;
void *prev_value = map_value.current_value;
/* Reset the current value to default. */
map_value.current_value_size = map_value.default_value_size;
map_value.current_value = map_value.default_value;
/* If we fail, revert the map. */
ON_RESULT_FAILURE {
/* Revert to the previous value. */
map_value.current_value_size = prev_value_size;
map_value.current_value = prev_value;
SaveKeyValueStoreMap(*map);
};
/* Attempt to save the key value store map. */
R_TRY(SaveKeyValueStoreMap(*map));
/* If present, free the previous value. */
if (prev_value != nullptr && prev_value != map_value.default_value) {
FreeToHeap(prev_value, prev_value_size);
}
R_SUCCEED();
}
Result KeyValueStore::SetValue(const SettingsItemKey &item_key, const void *buffer, size_t buffer_size) {
/* Check preconditions. */
AMS_ASSERT(buffer != nullptr);
/* Acquire exclusive access to global state. */
std::scoped_lock lk(g_key_value_store_mutex);
/* Get the key value store map. */
Map *map = nullptr;
R_TRY(GetKeyValueStoreMap(std::addressof(map)));
AMS_ASSERT(map != nullptr);
/* Ensure there is sufficient memory for two keys. */
R_UNLESS(GetHeapAllocatableSize() >= MapKeyBufferSize, settings::ResultSettingsItemKeyAllocationFailed());
/* Find the key in the map. */
const Map::iterator it = map->find(MakeMapKey(m_name, item_key));
R_UNLESS(it != map->end(), settings::ResultSettingsItemNotFound());
/* Get the map value from the iterator. */
MapValue &map_value = it->second;
/* Succeed if the map value is already set to the new value. */
R_SUCCEED_IF(CompareValue(map_value.current_value, map_value.current_value_size, buffer, buffer_size));
/* Define the value buffer and size variables. */
size_t value_size = buffer_size;
void *value_buffer = nullptr;
/* Set the value buffer to the default value if the new value is the same. */
if (CompareValue(map_value.default_value, map_value.default_value_size, buffer, buffer_size)) {
value_buffer = map_value.default_value;
} else if (buffer_size > 0) {
/* Allocate the new value if there is sufficient memory available. */
R_UNLESS(GetHeapAllocatableSize() >= value_size, settings::ResultSettingsItemValueAllocationFailed());
value_buffer = AllocateFromHeap(value_size);
AMS_ASSERT(value_buffer != nullptr);
/* Copy the value to the value buffer. */
std::memcpy(value_buffer, buffer, value_size);
}
/* When we're done, free the unused value buffer. */
ON_SCOPE_EXIT {
if (value_buffer != nullptr && value_buffer != map_value.default_value) {
FreeToHeap(value_buffer, value_size);
}
};
/* Swap the current value with the new value. */
std::swap(map_value.current_value_size, value_size);
std::swap(map_value.current_value, value_buffer);
/* If we fail, revert. */
ON_RESULT_FAILURE {
std::swap(map_value.current_value_size, value_size);
std::swap(map_value.current_value, value_buffer);
SaveKeyValueStoreMap(*map);
};
/* Attempt to save the key value store map. */
R_RETURN(SaveKeyValueStoreMap(*map));
}
Result AddKeyValueStoreItemForDebug(const KeyValueStoreItemForDebug * const items, size_t items_count) {
/* Check preconditions. */
AMS_ASSERT(items != nullptr);
/* Acquire exclusive access to global state. */
std::scoped_lock lk(g_key_value_store_mutex);
/* Get the key value store map. */
Map *map = nullptr;
R_TRY(GetKeyValueStoreMapForciblyForDebug(std::addressof(map)));
AMS_ASSERT(map != nullptr);
/* Iterate through each item. */
for (size_t i = 0; i < items_count; i++) {
const KeyValueStoreItemForDebug &item = items[i];
/* Create a map value for our scope. */
MapValue map_value = {};
ON_SCOPE_EXIT { FreeMapValueToHeap(map_value); };
/* Get the map value for the item. */
R_TRY(GetMapValueOfKeyValueStoreItemForDebug(std::addressof(map_value), item));
/* Ensure there is sufficient memory for two keys. */
R_UNLESS(GetHeapAllocatableSize() >= MapKeyBufferSize, settings::ResultSettingsItemKeyAllocationFailed());
/* Create the map key. */
MapKey map_key(item.key);
/* Replace the existing value in the map if it already exists. */
if (const Map::iterator it = map->find(map_key); it != map->end()) {
/* Free the existing map value. */
FreeMapValueToHeap(it->second);
/* Replace the existing map value. */
it->second = map_value;
} else {
/* Ensure there is sufficient memory for the value. */
R_UNLESS(GetHeapAllocatableSize() >= MapEntryBufferSize, settings::ResultSettingsItemValueAllocationFailed());
/* Assign the map value to the map key in the map. */
(*map)[std::move(map_key)] = map_value;
}
/* Ensure we don't free the value buffers we added. */
map_value.current_value = nullptr;
map_value.default_value = nullptr;
}
R_SUCCEED();
}
Result AdvanceKeyValueStoreKeyIterator(KeyValueStoreKeyIterator *out) {
/* Check preconditions. */
AMS_ASSERT(out != nullptr);
AMS_ASSERT(out->header_size > 0);
AMS_ASSERT(out->header_size < out->entire_size);
AMS_ASSERT(out->map_key != nullptr);
/* Acquire exclusive access to global state. */
std::scoped_lock lk(g_key_value_store_mutex);
/* Get the key value store map. */
Map *map = nullptr;
R_TRY(GetKeyValueStoreMap(std::addressof(map)));
AMS_ASSERT(map != nullptr);
/* Ensure there is sufficient memory for two keys. */
R_UNLESS(GetHeapAllocatableSize() >= MapKeyBufferSize, settings::ResultSettingsItemKeyAllocationFailed());
/* Locate the iterator's current key. */
Map::const_iterator it = map->find(MapKey(out->map_key, static_cast<s32>(out->entire_size) - 1));
R_UNLESS(it != map->end(), settings::ResultNotFoundSettingsItemKeyIterator());
/* Increment the iterator, ensuring we aren't at the end of the map. */
R_UNLESS((++it) != map->end(), settings::ResultStopIteration());
/* Get the map key. */
const MapKey &map_key = it->first;
/* Ensure the advanced iterator retains the required name. */
R_UNLESS(std::strncmp(map_key.GetString(), out->map_key, out->header_size) == 0, settings::ResultStopIteration());
/* Ensure there is sufficient memory for the map key. */
const size_t map_key_size = map_key.GetCount() + 1;
R_UNLESS(GetHeapAllocatableSize() >= map_key_size, settings::ResultSettingsItemKeyIteratorAllocationFailed());
/* Free the iterator's old map key. */
FreeToHeap(out->map_key, out->entire_size);
/* Allocate the new map key. */
char *buffer = static_cast<char *>(AllocateFromHeap(map_key_size));
AMS_ASSERT(buffer != nullptr);
/* Copy the new map key to the buffer. */
std::memcpy(buffer, map_key.GetString(), map_key_size);
/* Set the output map key. */
out->entire_size = map_key_size;
out->map_key = buffer;
R_SUCCEED();
}
Result DestroyKeyValueStoreKeyIterator(KeyValueStoreKeyIterator *out) {
/* Check preconditions. */
AMS_ASSERT(out != nullptr);
AMS_ASSERT(out->header_size > 0);
AMS_ASSERT(out->header_size < out->entire_size);
AMS_ASSERT(out->map_key != nullptr);
/* Acquire exclusive access to global state. */
std::scoped_lock lk(g_key_value_store_mutex);
/* Free the key to the heap. */
FreeToHeap(out->map_key, out->entire_size);
/* Reset the name and key. */
out->header_size = 0;
out->entire_size = 0;
out->map_key = nullptr;
R_SUCCEED();
}
Result GetKeyValueStoreItemCountForDebug(u64 *out_count) {
/* Check preconditions. */
AMS_ASSERT(out_count != nullptr);
/* Acquire exclusive access to global state. */
std::scoped_lock lk(g_key_value_store_mutex);
/* Get the key value store map. */
Map *map = nullptr;
R_TRY(GetKeyValueStoreMap(std::addressof(map)));
AMS_ASSERT(map != nullptr);
/* Output the item count. */
*out_count = map->size();
R_SUCCEED();
}
Result GetKeyValueStoreItemForDebug(u64 *out_count, KeyValueStoreItemForDebug * const out_items, size_t out_items_count) {
/* Check preconditions. */
AMS_ASSERT(out_count != nullptr);
AMS_ASSERT(out_items != nullptr);
/* Acquire exclusive access to global state. */
std::scoped_lock lk(g_key_value_store_mutex);
/* Get the key value store map. */
Map *map = nullptr;
R_TRY(GetKeyValueStoreMap(std::addressof(map)));
AMS_ASSERT(map != nullptr);
/* Define the count variable. */
size_t count = 0;
/* Iterate through each value in the map and output kvs items. */
for (const auto &kv_pair : *map) {
/* Get the current map value. */
const MapValue &map_value = kv_pair.second;
/* Break if the count exceeds the output items count. */
if (count >= out_items_count) {
break;
}
/* Get the current item. */
KeyValueStoreItemForDebug &item = out_items[count++];
/* Copy the map key and value to the item. */
item.key = kv_pair.first.GetString();
item.type = map_value.type;
item.current_value_size = map_value.current_value_size;
item.default_value_size = map_value.default_value_size;
item.current_value = map_value.current_value;
item.default_value = map_value.default_value;
}
/* Set the output count. */
*out_count = count;
R_SUCCEED();
}
Result GetKeyValueStoreKeyIteratorKey(u64 *out_count, char *out_buffer, size_t out_buffer_size, const KeyValueStoreKeyIterator &iterator) {
/* Check preconditions. */
AMS_ASSERT(out_count != nullptr);
AMS_ASSERT(out_buffer != nullptr);
AMS_ASSERT(iterator.header_size > 0);
AMS_ASSERT(iterator.header_size < iterator.entire_size);
AMS_ASSERT(iterator.map_key != nullptr);
/* Copy the key from the iterator to the output buffer. */
const size_t key_size = std::min(out_buffer_size, std::min(iterator.entire_size - iterator.header_size, SettingsItemKeyLengthMax + 1));
std::strncpy(out_buffer, iterator.map_key + iterator.header_size, key_size);
/* Set the end of the key to null. */
if (key_size > 0) {
out_buffer[key_size - 1] = '\x00';
}
/* Output the key size. */
*out_count = key_size;
R_SUCCEED();
}
Result GetKeyValueStoreKeyIteratorKeySize(u64 *out_count, const KeyValueStoreKeyIterator &iterator) {
/* Check preconditions. */
AMS_ASSERT(out_count != nullptr);
AMS_ASSERT(iterator.header_size > 0);
AMS_ASSERT(iterator.header_size < iterator.entire_size);
AMS_ASSERT(iterator.map_key != nullptr);
/* Output the key size. */
*out_count = std::min(iterator.entire_size - iterator.header_size, SettingsItemKeyLengthMax + 1);
R_SUCCEED();
}
Result ReadKeyValueStoreFirmwareDebug(u64 *out_count, char * const out_buffer, size_t out_buffer_size) {
/* Check preconditions. */
AMS_ASSERT(out_count != nullptr);
AMS_ASSERT(out_buffer != nullptr);
/* Acquire exclusive access to global state. */
std::scoped_lock lk(g_key_value_store_mutex);
/* Read the firmware debug system data. */
R_RETURN(ReadSystemDataFirmwareDebug(out_count, out_buffer, out_buffer_size));
}
Result ReadKeyValueStorePlatformConfiguration(u64 *out_count, char * const out_buffer, size_t out_buffer_size) {
/* Check preconditions. */
AMS_ASSERT(out_count != nullptr);
AMS_ASSERT(out_buffer != nullptr);
/* Acquire exclusive access to global state. */
std::scoped_lock lk(g_key_value_store_mutex);
/* Read the platform configuration system data. */
R_RETURN(ReadSystemDataPlatformConfiguration(out_count, out_buffer, out_buffer_size));
}
Result ReadKeyValueStoreSaveData(u64 *out_count, char * const out_buffer, size_t out_buffer_size) {
/* Check preconditions. */
AMS_ASSERT(out_count != nullptr);
AMS_ASSERT(out_buffer != nullptr);
/* Acquire exclusive access to global state. */
std::scoped_lock lk(g_key_value_store_mutex);
/* Read the system save data. */
R_RETURN(ReadSystemSaveData(out_count, out_buffer, out_buffer_size));
}
Result ReloadKeyValueStoreForDebug(SystemSaveData *system_save_data, SystemSaveData *fwdbg_system_data, SystemSaveData *pfcfg_system_data) {
/* Check preconditions. */
AMS_ASSERT(system_save_data != nullptr);
AMS_ASSERT(fwdbg_system_data != nullptr);
AMS_ASSERT(pfcfg_system_data != nullptr);
/* Acquire exclusive access to global state. */
std::scoped_lock lk(g_key_value_store_mutex);
/* Get the key value store map. */
Map *map = nullptr;
R_TRY(GetKeyValueStoreMapForciblyForDebug(std::addressof(map)));
AMS_ASSERT(map != nullptr);
/* Load the key value store map. */
R_RETURN(LoadKeyValueStoreMapForDebug(map, system_save_data, fwdbg_system_data, pfcfg_system_data));
}
Result ReloadKeyValueStoreForDebug() {
/* Acquire exclusive access to global state. */
std::scoped_lock lk(g_key_value_store_mutex);
/* Get the key value store map. */
Map *map = nullptr;
R_TRY(GetKeyValueStoreMap(std::addressof(map)));
AMS_ASSERT(map != nullptr);
/* Load the key value store map. */
R_RETURN(LoadKeyValueStoreMap(map));
}
Result ResetKeyValueStoreSaveData() {
/* Acquire exclusive access to global state. */
std::scoped_lock lk(g_key_value_store_mutex);
/* Get the key value store map. */
Map *map = nullptr;
R_TRY(GetKeyValueStoreMap(std::addressof(map)));
AMS_ASSERT(map != nullptr);
/* Reset all values in the map. */
for (auto &kv_pair : *map) {
/* Get the map value. */
MapValue &map_value = kv_pair.second;
/* If the current value isn't the default value, reset it. */
if (map_value.current_value != map_value.default_value) {
/* Store the previous value and size. */
size_t prev_value_size = map_value.current_value_size;
void *prev_value = map_value.current_value;
/* Reset the current value to the default value. */
map_value.current_value_size = map_value.default_value_size;
map_value.current_value = map_value.default_value;
/* Free the current value if present. */
if (prev_value != nullptr) {
FreeToHeap(prev_value, prev_value_size);
}
}
}
/* Save the key value store map. */
R_RETURN(SaveKeyValueStoreMap(*map));
}
Result SaveKeyValueStoreAllForDebug(SystemSaveData *data) {
/* Check preconditions. */
AMS_ASSERT(data != nullptr);
/* Acquire exclusive access to global state. */
std::scoped_lock lk(g_key_value_store_mutex);
/* Get the key value store map. */
Map *map = nullptr;
R_TRY(GetKeyValueStoreMap(std::addressof(map)));
AMS_ASSERT(map != nullptr);
/* Save the key value store map default values. */
R_TRY(SaveKeyValueStoreMapDefaultForDebug(*data, *map));
/* Save the key value store map. */
R_RETURN(SaveKeyValueStoreMap(*map));
}
}
| 65,000
|
C++
|
.cpp
| 1,254
| 38.84689
| 197
| 0.571548
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,578
|
settings_serial_number_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/settings/impl/settings_serial_number_impl.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "settings_serial_number_impl.hpp"
namespace ams::settings::impl {
Result GetSerialNumber(settings::factory::SerialNumber *out) {
#if defined(ATMOSPHERE_OS_HORIZON)
static_assert(sizeof(*out) == sizeof(::SetCalSerialNumber));
R_RETURN(::setcalGetSerialNumber(reinterpret_cast<::SetCalSerialNumber *>(out)));
#else
AMS_UNUSED(out);
AMS_ABORT("TODO");
#endif
}
Result GetSerialNumber(settings::system::SerialNumber *out) {
#if defined(ATMOSPHERE_OS_HORIZON)
static_assert(sizeof(*out) == sizeof(::SetSysSerialNumber));
R_RETURN(::setsysGetSerialNumber(reinterpret_cast<::SetSysSerialNumber *>(out)));
#else
AMS_UNUSED(out);
AMS_ABORT("TODO");
#endif
}
}
| 1,455
|
C++
|
.cpp
| 37
| 34.378378
| 89
| 0.700141
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,579
|
settings_platform_region_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/settings/impl/settings_platform_region_impl.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "settings_platform_region_impl.hpp"
namespace ams::settings::impl {
Result GetPlatformRegion(s32 *out) {
#if defined(ATMOSPHERE_OS_HORIZON)
static_assert(sizeof(*out) == sizeof(::SetSysPlatformRegion));
R_RETURN(::setsysGetPlatformRegion(reinterpret_cast<::SetSysPlatformRegion *>(out)));
#else
AMS_UNUSED(out);
AMS_ABORT("TODO");
#endif
}
}
| 1,081
|
C++
|
.cpp
| 28
| 34.714286
| 93
| 0.72
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,580
|
settings_product_model_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/settings/impl/settings_product_model_impl.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "settings_product_model_impl.hpp"
namespace ams::settings::impl {
Result GetProductModel(s32 *out) {
#if defined(ATMOSPHERE_OS_HORIZON)
static_assert(sizeof(*out) == sizeof(::SetSysProductModel));
R_RETURN(::setsysGetProductModel(reinterpret_cast<::SetSysProductModel *>(out)));
#else
AMS_UNUSED(out);
AMS_ABORT("TODO");
#endif
}
}
| 1,071
|
C++
|
.cpp
| 28
| 34.357143
| 89
| 0.717308
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,581
|
settings_firmware_version_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/settings/impl/settings_firmware_version_impl.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "settings_firmware_version_impl.hpp"
namespace ams::settings::impl {
Result GetFirmwareVersion(settings::system::FirmwareVersion *out) {
#if defined(ATMOSPHERE_OS_HORIZON)
static_assert(sizeof(*out) == sizeof(::SetSysFirmwareVersion));
R_RETURN(::setsysGetFirmwareVersion(reinterpret_cast<::SetSysFirmwareVersion *>(out)));
#else
AMS_UNUSED(out);
AMS_ABORT("TODO");
#endif
}
}
| 1,116
|
C++
|
.cpp
| 28
| 35.964286
| 95
| 0.725346
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,582
|
settings_system_save_data.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/settings/impl/settings_system_save_data.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "settings_static_object.hpp"
#include "settings_system_save_data.hpp"
namespace ams::settings::impl {
namespace {
constexpr s64 LazyWriterDelayMilliSeconds = 500;
constexpr inline const char *MountNameSeparator = ":";
constexpr inline const char *DirectoryNameSeparator = "/";
constexpr inline const char *SystemSaveDataFileName = "file";
class LazyFileAccessor final {
NON_COPYABLE(LazyFileAccessor);
NON_MOVEABLE(LazyFileAccessor);
private:
static constexpr size_t FileNameLengthMax = 31;
private:
bool m_is_activated;
bool m_is_busy;
bool m_is_cached;
bool m_is_modified;
bool m_is_file_size_changed;
char m_mount_name[fs::MountNameLengthMax + 1];
char m_file_path[fs::MountNameLengthMax + 1 + 1 + FileNameLengthMax + 1];
int m_open_mode;
s64 m_file_size;
s64 m_offset;
size_t m_size;
u8 m_buffer[512_KB];
os::Mutex m_mutex;
os::TimerEvent m_timer_event;
os::ThreadType m_thread;
alignas(os::ThreadStackAlignment) u8 m_thread_stack[4_KB];
public:
LazyFileAccessor() : m_is_activated(false), m_is_busy(false), m_is_cached(false), m_is_modified(false), m_is_file_size_changed(false), m_mount_name{}, m_file_path{}, m_open_mode(0), m_file_size(0), m_offset(0), m_size(0), m_mutex(false), m_timer_event(os::EventClearMode_AutoClear), m_thread{} {
std::memset(m_buffer, 0, sizeof(m_buffer));
std::memset(m_thread_stack, 0, sizeof(m_thread_stack));
}
Result Activate();
Result Commit(const char *name, bool synchronous);
Result Create(const char *name, s64 size);
Result Open(const char *name, int mode);
void Close();
Result Read(s64 offset, void *dst, size_t size);
Result Write(s64 offset, const void *src, size_t size);
Result SetFileSize(s64 size);
private:
static void ThreadFunc(void *arg);
template<size_t N>
static int CreateFilePath(char (&path)[N], const char *name);
static bool AreEqual(const void *lhs, const void *rhs, size_t size);
void SetMountName(const char *name);
bool CompareMountName(const char *name) const;
void InvokeWriteBackLoop();
Result CommitSynchronously();
};
LazyFileAccessor &GetLazyFileAccessor() {
return StaticObject<LazyFileAccessor, void>::Get();
}
Result LazyFileAccessor::Activate() {
std::scoped_lock lk(m_mutex);
if (!m_is_activated) {
/* Create and start the lazy writer thread. */
R_TRY(os::CreateThread(std::addressof(m_thread), LazyFileAccessor::ThreadFunc, this, m_thread_stack, sizeof(m_thread_stack), AMS_GET_SYSTEM_THREAD_PRIORITY(settings, LazyWriter)));
os::SetThreadNamePointer(std::addressof(m_thread), AMS_GET_SYSTEM_THREAD_NAME(settings, LazyWriter));
os::StartThread(std::addressof(m_thread));
m_is_activated = true;
}
R_SUCCEED();
}
Result LazyFileAccessor::Commit(const char *name, bool synchronous) {
AMS_ASSERT(name != nullptr);
AMS_UNUSED(name);
std::scoped_lock lk(m_mutex);
AMS_ASSERT(m_is_activated);
AMS_ASSERT(!m_is_busy);
AMS_ASSERT(this->CompareMountName(name));
if (synchronous) {
/* Stop the timer and commit synchronously. */
m_timer_event.Stop();
R_TRY(this->CommitSynchronously());
} else {
/* Start the timer to write. */
m_timer_event.StartOneShot(TimeSpan::FromMilliSeconds(LazyWriterDelayMilliSeconds));
}
R_SUCCEED();
}
Result LazyFileAccessor::Create(const char *name, s64 size) {
AMS_ASSERT(name != nullptr);
AMS_ASSERT(size >= 0);
std::scoped_lock lk(m_mutex);
AMS_ASSERT(m_is_activated);
AMS_ASSERT(!m_is_busy);
if (m_is_cached) {
/* Stop the timer and commit synchronously. */
m_timer_event.Stop();
R_TRY(this->CommitSynchronously());
/* Reset the current state. */
m_is_cached = false;
this->SetMountName("");
m_open_mode = 0;
m_file_size = 0;
/* Clear the buffer. */
std::memset(m_buffer, 0, sizeof(m_buffer));
}
/* Create the save file. */
this->CreateFilePath(m_file_path, name);
R_TRY(fs::CreateFile(m_file_path, size));
/* Initialize the accessor. */
m_is_cached = true;
m_is_modified = true;
this->SetMountName(name);
m_open_mode = fs::OpenMode_Write;
m_file_size = size;
m_offset = 0;
m_size = size;
/* Start the timer to write. */
m_timer_event.StartOneShot(TimeSpan::FromMilliSeconds(LazyWriterDelayMilliSeconds));
R_SUCCEED();
}
Result LazyFileAccessor::Open(const char *name, int mode) {
AMS_ASSERT(name != nullptr);
std::scoped_lock lk(m_mutex);
AMS_ASSERT(m_is_activated);
AMS_ASSERT(!m_is_busy);
bool caches = true;
if (m_is_cached) {
/* Check if the current mount matches the requested mount. */
if (this->CompareMountName(name)) {
/* Check if the mode matches, or the existing mode is read-only. */
if (m_open_mode == mode || m_open_mode == fs::OpenMode_Read) {
m_is_busy = true;
m_open_mode = mode;
R_SUCCEED();
}
caches = false;
}
/* Stop the timer and commit synchronously. */
m_timer_event.Stop();
R_TRY(this->CommitSynchronously());
}
if (caches) {
/* Create the save file if needed. */
this->CreateFilePath(m_file_path, name);
/* Open the save file. */
fs::FileHandle file = {};
R_TRY(fs::OpenFile(std::addressof(file), m_file_path, fs::OpenMode_Read));
ON_SCOPE_EXIT { fs::CloseFile(file); };
/* Get the save size. */
s64 file_size = 0;
R_TRY(fs::GetFileSize(std::addressof(file_size), file));
AMS_ASSERT(0 <= file_size && file_size <= static_cast<s64>(sizeof(m_buffer)));
R_UNLESS(file_size <= static_cast<s64>(sizeof(m_buffer)), settings::ResultTooLargeSystemSaveData());
/* Read the save file. */
R_TRY(fs::ReadFile(file, 0, m_buffer, static_cast<size_t>(file_size)));
m_is_cached = true;
this->SetMountName(name);
m_file_size = file_size;
}
m_is_busy = true;
m_open_mode = mode;
R_SUCCEED();
}
void LazyFileAccessor::Close() {
std::scoped_lock lk(m_mutex);
AMS_ASSERT(m_is_activated);
AMS_ASSERT(m_is_busy);
m_is_busy = false;
}
Result LazyFileAccessor::Read(s64 offset, void *dst, size_t size) {
AMS_ASSERT(offset >= 0);
AMS_ASSERT(dst != nullptr);
std::scoped_lock lk(m_mutex);
AMS_ASSERT(m_is_activated);
AMS_ASSERT(m_is_busy);
AMS_ASSERT(m_is_cached);
AMS_ASSERT((m_open_mode & fs::OpenMode_Read) != 0);
AMS_ASSERT(offset + static_cast<s64>(size) <= m_file_size);
std::memcpy(dst, m_buffer + offset, size);
R_SUCCEED();
}
Result LazyFileAccessor::Write(s64 offset, const void *src, size_t size) {
AMS_ASSERT(offset >= 0);
AMS_ASSERT(src != nullptr);
std::scoped_lock lk(m_mutex);
AMS_ASSERT(m_is_activated);
AMS_ASSERT(m_is_busy);
AMS_ASSERT(m_is_cached);
AMS_ASSERT((m_open_mode & ::ams::fs::OpenMode_Write) != 0);
s64 end = offset + static_cast<s64>(size);
AMS_ASSERT(end <= static_cast<s64>(m_size));
/* Succeed if there's nothing to write. */
R_SUCCEED_IF(this->AreEqual(m_buffer + offset, src, size));
/* Copy to dst. */
std::memcpy(m_buffer + offset, src, size);
/* Update offset and size. */
if (m_is_modified) {
end = std::max(end, m_offset + static_cast<s64>(m_size));
m_offset = std::min(m_offset, offset);
m_size = static_cast<size_t>(end - m_offset);
} else {
m_is_modified = true;
m_offset = offset;
m_size = size;
}
R_SUCCEED();
}
Result LazyFileAccessor::SetFileSize(s64 size) {
std::scoped_lock lk(m_mutex);
const s64 prev_file_size = m_file_size;
/* If the existing file size exceeds the new file size, reset the state or truncate. */
if (m_file_size >= size) {
if (m_is_modified) {
/* If the current offset exceeds the new file size, reset the state. */
if (m_offset >= size) {
m_is_modified = false;
m_offset = 0;
m_size = 0;
} else if (m_offset + static_cast<s64>(m_size) > size) {
/* Truncate the buffer for the new file size. */
m_size = size - m_offset;
}
}
} else {
/* If unmodified, mark as modified and move the offset to the current end of the file. */
if (!m_is_modified) {
m_is_modified = true;
m_offset = m_file_size;
}
/* Zero-initialize the expanded file segment. */
std::memset(m_buffer + m_file_size, 0, size - m_file_size);
/* Update the current buffer size. */
m_size = size - m_offset;
}
/* Update state. */
m_is_file_size_changed = prev_file_size != size;
m_file_size = size;
R_SUCCEED();
}
void LazyFileAccessor::ThreadFunc(void *arg) {
AMS_ASSERT(arg != nullptr);
reinterpret_cast<LazyFileAccessor *>(arg)->InvokeWriteBackLoop();
}
template<size_t N>
int LazyFileAccessor::CreateFilePath(char (&path)[N], const char *name) {
AMS_ASSERT(name != nullptr);
const auto len = static_cast<int>(N);
s32 pos = util::Strlcpy(path, name, len);
pos += util::Strlcpy(path + pos, MountNameSeparator, len - pos);
pos += util::Strlcpy(path + pos, DirectoryNameSeparator, len - pos);
pos += util::Strlcpy(path + pos, SystemSaveDataFileName, len - pos);
return pos;
}
bool LazyFileAccessor::AreEqual(const void *lhs, const void *rhs, size_t size) {
AMS_ASSERT(lhs != nullptr);
AMS_ASSERT(rhs != nullptr);
auto lhs8 = static_cast<const u8 *>(lhs);
auto rhs8 = static_cast<const u8 *>(rhs);
for (size_t i = 0; i < size; i++) {
if (*(lhs8++) != *(rhs8++)) {
return false;
}
}
return true;
}
void LazyFileAccessor::SetMountName(const char *name) {
AMS_ASSERT(name != nullptr);
util::Strlcpy(m_mount_name, name, sizeof(m_mount_name));
}
bool LazyFileAccessor::CompareMountName(const char *name) const {
return util::Strncmp(m_mount_name, name, sizeof(m_mount_name)) == 0;
}
void LazyFileAccessor::InvokeWriteBackLoop() {
while (true) {
m_timer_event.Wait();
std::scoped_lock lk(m_mutex);
if (!m_is_busy) {
R_ABORT_UNLESS(this->CommitSynchronously());
}
}
}
Result LazyFileAccessor::CommitSynchronously() {
/* If we have data cached/modified, we need to commit. */
if (m_is_cached && (m_is_file_size_changed || m_is_modified)) {
/* Get the save file path. */
this->CreateFilePath(m_file_path, m_mount_name);
{
/* Open the save file. */
fs::FileHandle file;
R_TRY(fs::OpenFile(std::addressof(file), m_file_path, fs::OpenMode_Write));
ON_SCOPE_EXIT { fs::CloseFile(file); };
/* If we need to, update the file size. */
if (m_is_file_size_changed) {
R_TRY(fs::SetFileSize(file, m_file_size));
m_is_file_size_changed = false;
}
/* If we need to, write the file data. */
if (m_is_modified) {
/* Write to the file. */
R_TRY(fs::WriteFile(file, m_offset, m_buffer + m_offset, m_size, fs::WriteOption::None));
R_TRY(fs::FlushFile(file));
/* Reset state. */
m_is_modified = false;
m_offset = 0;
m_size = 0;
}
}
/* Commit the savedata. */
R_TRY(fs::CommitSaveData(m_mount_name));
}
R_SUCCEED();
}
}
void SystemSaveData::SetSystemSaveDataId(u64 id) {
m_system_save_data_id = id;
}
void SystemSaveData::SetTotalSize(s64 size) {
m_total_size = size;
}
void SystemSaveData::SetJournalSize(s64 size) {
m_journal_size = size;
}
void SystemSaveData::SetFlags(u32 flags) {
m_flags = flags;
}
void SystemSaveData::SetMountName(const char *name) {
AMS_ASSERT(name != nullptr);
util::Strlcpy(m_mount_name, name, sizeof(m_mount_name));
}
Result SystemSaveData::Mount(bool create_save) {
/* Activate the file accessor. */
R_TRY(GetLazyFileAccessor().Activate());
/* Don't allow automatic save data creation. */
fs::DisableAutoSaveDataCreation();
/* Attempt to get the flags of existing save data. */
u32 cur_flags = 0;
const auto flags_result = fs::GetSaveDataFlags(std::addressof(cur_flags), m_save_data_space_id, m_system_save_data_id);
/* If the save data exists, ensure flags are correct. */
if (R_SUCCEEDED(flags_result)) {
if (cur_flags != m_flags) {
R_TRY(fs::SetSaveDataFlags(m_system_save_data_id, m_save_data_space_id, m_flags));
}
} else {
/* Unless we can create save data, return the error we got when retrieving flags. */
R_UNLESS(create_save, flags_result);
/* Create the save data. */
R_TRY(fs::CreateSystemSaveData(m_save_data_space_id, m_system_save_data_id, ncm::SystemProgramId::Settings.value, m_total_size, m_journal_size, m_flags));
}
/* Mount the save data. */
R_RETURN(fs::MountSystemSaveData(m_mount_name, m_save_data_space_id, m_system_save_data_id));
}
Result SystemSaveData::Commit(bool synchronous) {
R_RETURN(GetLazyFileAccessor().Commit(m_mount_name, synchronous));
}
Result SystemSaveData::Create(s64 size) {
R_RETURN(GetLazyFileAccessor().Create(m_mount_name, size));
}
Result SystemSaveData::OpenToRead() {
R_RETURN(GetLazyFileAccessor().Open(m_mount_name, fs::OpenMode_Read));
}
Result SystemSaveData::OpenToWrite() {
R_RETURN(GetLazyFileAccessor().Open(m_mount_name, fs::OpenMode_Write));
}
void SystemSaveData::Close() {
GetLazyFileAccessor().Close();
}
Result SystemSaveData::Read(s64 offset, void *buf, size_t size) {
AMS_ASSERT(offset >= 0);
AMS_ASSERT(buf != nullptr);
R_RETURN(GetLazyFileAccessor().Read(offset, buf, size));
}
Result SystemSaveData::Write(s64 offset, const void *buf, size_t size) {
AMS_ASSERT(offset >= 0);
AMS_ASSERT(buf != nullptr);
R_RETURN(GetLazyFileAccessor().Write(offset, buf, size));
}
Result SystemSaveData::Flush() {
/* N doesn't do anything here. */
R_SUCCEED();
}
Result SystemSaveData::SetFileSize(s64 size) {
R_RETURN(GetLazyFileAccessor().SetFileSize(size));
}
}
| 18,193
|
C++
|
.cpp
| 397
| 32.445844
| 312
| 0.530639
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,583
|
settings_spl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/settings/impl/settings_spl.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "settings_spl.hpp"
namespace ams::settings::impl {
namespace {
struct SplConfig {
bool is_development;
SplHardwareType hardware_type;
bool is_quest;
u64 device_id_low;
};
constexpr SplHardwareType ConvertToSplHardwareType(spl::HardwareType type) {
switch (type) {
case spl::HardwareType::Icosa:
return SplHardwareType_Icosa;
case spl::HardwareType::Copper:
return SplHardwareType_Copper;
case spl::HardwareType::Hoag:
return SplHardwareType_Hoag;
case spl::HardwareType::Iowa:
return SplHardwareType_IcosaMariko;
case spl::HardwareType::Calcio:
return SplHardwareType_Calcio;
case spl::HardwareType::Aula:
return SplHardwareType_Aula;
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
constexpr bool IsSplRetailInteractiveDisplayStateEnabled(spl::RetailInteractiveDisplayState quest_state) {
switch (quest_state) {
case spl::RetailInteractiveDisplayState_Disabled:
return false;
case spl::RetailInteractiveDisplayState_Enabled:
return true;
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
SplConfig GetSplConfig() {
class SplConfigHolder {
NON_COPYABLE(SplConfigHolder);
NON_MOVEABLE(SplConfigHolder);
private:
SplConfig m_config;
public:
SplConfigHolder() {
/* Initialize spl. */
spl::Initialize();
ON_SCOPE_EXIT { spl::Finalize(); };
/* Create the config. */
m_config = {
.is_development = spl::IsDevelopment(),
.hardware_type = ConvertToSplHardwareType(spl::GetHardwareType()),
.is_quest = IsSplRetailInteractiveDisplayStateEnabled(spl::GetRetailInteractiveDisplayState()),
.device_id_low = spl::GetDeviceIdLow(),
};
}
ALWAYS_INLINE operator SplConfig() {
return m_config;
}
};
AMS_FUNCTION_LOCAL_STATIC(SplConfigHolder, s_config_holder);
return s_config_holder;
}
}
bool IsSplDevelopment() {
return GetSplConfig().is_development;
}
SplHardwareType GetSplHardwareType() {
return GetSplConfig().hardware_type;
}
bool IsSplRetailInteractiveDisplayStateEnabled() {
return GetSplConfig().is_quest;
}
u64 GetSplDeviceIdLow() {
return GetSplConfig().device_id_low;
}
}
| 3,679
|
C++
|
.cpp
| 91
| 27.637363
| 129
| 0.567031
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,584
|
settings_region_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/settings/impl/settings_region_impl.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "settings_region_impl.hpp"
namespace ams::settings::impl {
Result GetRegionCode(s32 *out) {
#if defined(ATMOSPHERE_OS_HORIZON)
static_assert(sizeof(*out) == sizeof(::SetRegion));
R_RETURN(::setGetRegionCode(reinterpret_cast<::SetRegion *>(out)));
#else
AMS_UNUSED(out);
AMS_ABORT("TODO");
#endif
}
}
| 1,039
|
C++
|
.cpp
| 28
| 33.214286
| 76
| 0.709325
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,585
|
settings_system_data.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/settings/impl/settings_system_data.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "settings_static_object.hpp"
#include "settings_system_data.hpp"
namespace ams::settings::impl {
namespace {
constexpr inline const char MountNameSeparator[] = ":";
constexpr inline const char DirectoryNameSeparator[] = "/";
constexpr inline const char SystemDataFileName[] = "file";
class LazyFileAccessor final {
NON_COPYABLE(LazyFileAccessor);
NON_MOVEABLE(LazyFileAccessor);
private:
bool m_is_cached;
fs::FileHandle m_file;
s64 m_offset;
size_t m_size;
u8 m_buffer[16_KB];
public:
LazyFileAccessor() : m_is_cached(false), m_file(), m_offset(), m_size(), m_buffer() {
/* ... */
}
Result Open(const char *path, int mode);
void Close();
Result Read(s64 offset, void *dst, size_t size);
private:
bool GetCache(s64 offset, void *dst, size_t size);
};
Result LazyFileAccessor::Open(const char *path, int mode) {
/* Open our file. */
R_RETURN(fs::OpenFile(std::addressof(m_file), path, mode));
}
void LazyFileAccessor::Close() {
/* Close our file. */
fs::CloseFile(m_file);
/* Reset our state. */
m_is_cached = false;
m_file = {};
m_size = 0;
m_offset = 0;
}
bool LazyFileAccessor::GetCache(s64 offset, void *dst, size_t size) {
/* Check pre-conditions. */
AMS_ASSERT(offset >= 0);
AMS_ASSERT(dst != nullptr);
/* Check that we're cached. */
if (!m_is_cached) {
return false;
}
/* Check that offset is within cache. */
if (offset < m_offset) {
return false;
}
/* Check that the read remains within range. */
const size_t offset_in_cache = offset - m_offset;
if (m_size < offset_in_cache + size) {
return false;
}
/* Copy the cached data. */
std::memcpy(dst, m_buffer + offset_in_cache, size);
return true;
}
Result LazyFileAccessor::Read(s64 offset, void *dst, size_t size) {
/* Check pre-conditions. */
AMS_ASSERT(offset >= 0);
AMS_ASSERT(dst != nullptr);
/* Try to read from cache. */
R_SUCCEED_IF(this->GetCache(offset, dst, size));
/* If the read is too big for the cache, read the data directly. */
if (size > sizeof(m_buffer)) {
R_RETURN(fs::ReadFile(m_file, offset, dst, size));
}
/* Get the file size. */
s64 file_size;
R_TRY(fs::GetFileSize(std::addressof(file_size), m_file));
/* If the file is too small, read the data directly. */
if (file_size < offset + static_cast<s64>(size)) {
R_RETURN(fs::ReadFile(m_file, offset, dst, size));
}
/* Determine the read size. */
const size_t read_size = std::min<size_t>(file_size - offset, sizeof(m_buffer));
/* Read into the cache. */
if (read_size > 0) {
R_TRY(fs::ReadFile(m_file, offset, m_buffer, read_size));
}
/* Update cache statement. */
m_offset = offset;
m_size = read_size;
m_is_cached = true;
/* Get the data from the cache. */
const bool succeeded = this->GetCache(offset, dst, size);
AMS_ASSERT(succeeded);
AMS_UNUSED(succeeded);
R_SUCCEED();
}
LazyFileAccessor &GetLazyFileAccessor() {
return StaticObject<LazyFileAccessor, void>::Get();
}
}
void SystemData::SetSystemDataId(ncm::SystemDataId id) {
m_system_data_id = id;
}
void SystemData::SetMountName(const char *name) {
util::Strlcpy(m_mount_name, name, sizeof(m_mount_name));
int pos = 0;
pos += util::Strlcpy(m_file_path + pos, name, sizeof(m_mount_name));
pos += util::Strlcpy(m_file_path + pos, MountNameSeparator, sizeof(MountNameSeparator));
pos += util::Strlcpy(m_file_path + pos, DirectoryNameSeparator, sizeof(DirectoryNameSeparator));
pos += util::Strlcpy(m_file_path + pos, SystemDataFileName, sizeof(SystemDataFileName));
}
Result SystemData::Mount() {
R_RETURN(fs::MountSystemData(m_mount_name, m_system_data_id));
}
Result SystemData::OpenToRead() {
R_RETURN(GetLazyFileAccessor().Open(m_file_path, fs::OpenMode_Read));
}
void SystemData::Close() {
return GetLazyFileAccessor().Close();
}
Result SystemData::Read(s64 offset, void *dst, size_t size) {
R_RETURN(GetLazyFileAccessor().Read(offset, dst, size));
}
}
| 5,733
|
C++
|
.cpp
| 137
| 31.277372
| 104
| 0.560669
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,586
|
settings_configuration_id_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/settings/impl/settings_configuration_id_impl.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "settings_serial_number_impl.hpp"
namespace ams::settings::impl {
Result GetConfigurationId1(settings::factory::ConfigurationId1 *out) {
#if defined(ATMOSPHERE_OS_HORIZON)
static_assert(sizeof(*out) == sizeof(::SetCalConfigurationId1));
R_RETURN(::setcalGetConfigurationId1(reinterpret_cast<::SetCalConfigurationId1 *>(out)));
#else
AMS_UNUSED(out);
AMS_ABORT("TODO");
#endif
}
}
| 1,119
|
C++
|
.cpp
| 28
| 36.071429
| 97
| 0.726103
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,587
|
settings_error_report_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/settings/impl/settings_error_report_impl.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "settings_error_report_impl.hpp"
namespace ams::settings::impl {
Result GetErrorReportSharePermission(s32 *out) {
#if defined(ATMOSPHERE_OS_HORIZON)
static_assert(sizeof(*out) == sizeof(::SetSysErrorReportSharePermission));
R_RETURN(::setsysGetErrorReportSharePermission(reinterpret_cast<::SetSysErrorReportSharePermission *>(out)));
#else
AMS_UNUSED(out);
AMS_ABORT("TODO");
#endif
}
}
| 1,126
|
C++
|
.cpp
| 28
| 36.321429
| 117
| 0.731507
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,588
|
hid_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/hid/hid_api.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams::hid {
#if defined(ATMOSPHERE_OS_HORIZON)
namespace {
/* Global lock. */
constinit os::SdkMutex g_hid_lock;
constinit bool g_initialized_hid = false;
/* Set of supported NpadIds (we want to read from any connected controllers). */
constexpr const HidNpadIdType NpadIdTypes[] = {
HidNpadIdType_No1,
HidNpadIdType_No2,
HidNpadIdType_No3,
HidNpadIdType_No4,
HidNpadIdType_No5,
HidNpadIdType_No6,
HidNpadIdType_No7,
HidNpadIdType_No8,
HidNpadIdType_Handheld,
};
constexpr const size_t NumNpadIdTypes = util::size(NpadIdTypes);
/* Helper. */
void InitializeHid() {
R_ABORT_UNLESS(sm::Initialize());
R_ABORT_UNLESS(hidInitialize());
hidInitializeNpad();
R_ABORT_UNLESS(hidSetSupportedNpadIdType(NpadIdTypes, NumNpadIdTypes));
R_ABORT_UNLESS(hidSetSupportedNpadStyleSet(HidNpadStyleSet_NpadStandard | HidNpadStyleTag_NpadSystemExt));
}
Result EnsureHidInitialized() {
if (!g_initialized_hid) {
if (!serviceIsActive(hidGetServiceSession())) {
if (!pm::info::HasLaunchedBootProgram(ncm::SystemProgramId::Hid)) {
R_THROW(MAKERESULT(Module_Libnx, LibnxError_InitFail_HID));
}
InitializeHid();
}
g_initialized_hid = true;
}
R_SUCCEED();
}
u64 ReadHidNpad(HidNpadIdType id) {
HidNpadSystemExtState state;
size_t count = hidGetNpadStatesSystemExt(id, std::addressof(state), 1);
if (count != 0 && (state.attributes & HidNpadAttribute_IsConnected)) {
return state.buttons;
}
return 0;
}
}
Result GetKeysHeld(u64 *out) {
std::scoped_lock lk(g_hid_lock);
R_TRY(EnsureHidInitialized());
*out = ReadHidNpad(HidNpadIdType_Handheld);
for (size_t controller = 0; controller < 8; controller++) {
*out |= ReadHidNpad(static_cast<HidNpadIdType>(controller));
}
R_SUCCEED();
}
#endif
}
| 2,962
|
C++
|
.cpp
| 75
| 29.96
| 118
| 0.615545
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,589
|
htcs_socket.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htcs/htcs_socket.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "client/htcs_session.hpp"
#include "client/htcs_virtual_socket_collection.hpp"
namespace ams::htcs {
namespace {
constinit bool g_initialized = false;
constinit bool g_enable_disconnection_emulation = false;
constinit AllocateFunction g_allocate_function = nullptr;
constinit DeallocateFunction g_deallocate_function = nullptr;
constinit void *g_buffer = nullptr;
constinit size_t g_buffer_size = 0;
constinit os::TlsSlot g_tls_slot = {};
constinit tma::IHtcsManager *g_manager = nullptr;
constinit tma::IHtcsManager *g_monitor = nullptr;
constinit client::VirtualSocketCollection *g_sockets = nullptr;
void SetLastError(uintptr_t error_code) {
os::SetTlsValue(g_tls_slot, error_code);
}
void InitializeImpl(void *buffer, size_t buffer_size, int num_sessions) {
/* Check the session count. */
AMS_ASSERT(0 < num_sessions && num_sessions <= SessionCountMax);
/* Initialize the manager and monitor. */
client::InitializeSessionManager(std::addressof(g_manager), std::addressof(g_monitor), num_sessions);
/* Register the process. */
const sf::ClientProcessId process_id{0};
R_ABORT_UNLESS(g_manager->RegisterProcessId(process_id));
R_ABORT_UNLESS(g_monitor->MonitorManager(process_id));
/* Allocate a tls slot for our last error. */
os::SdkAllocateTlsSlot(std::addressof(g_tls_slot), nullptr);
/* Setup the virtual socket collection. */
AMS_ASSERT(buffer != nullptr);
g_sockets = reinterpret_cast<client::VirtualSocketCollection *>(buffer);
std::construct_at(g_sockets);
g_sockets->Init(static_cast<u8 *>(buffer) + sizeof(*g_sockets), buffer_size - sizeof(*g_sockets));
/* Mark initialized. */
g_initialized = true;
}
void InitializeImpl(AllocateFunction allocate, DeallocateFunction deallocate, int num_sessions, int num_sockets) {
/* Check the session count. */
AMS_ASSERT(0 < num_sessions && num_sessions <= SessionCountMax);
/* Set the allocation functions. */
g_allocate_function = allocate;
g_deallocate_function = deallocate;
/* Allocate a buffer. */
g_buffer_size = sizeof(client::VirtualSocketCollection) + client::VirtualSocketCollection::GetWorkingMemorySize(num_sockets);
g_buffer = g_allocate_function(g_buffer_size);
/* Initialize. */
InitializeImpl(g_buffer, g_buffer_size, num_sessions);
}
}
bool IsInitialized() {
return g_initialized;
}
size_t GetWorkingMemorySize(int num_sockets) {
AMS_ASSERT(num_sockets <= SocketCountMax);
return sizeof(client::VirtualSocketCollection) + client::VirtualSocketCollection::GetWorkingMemorySize(num_sockets);
}
void Initialize(AllocateFunction allocate, DeallocateFunction deallocate, int num_sessions) {
/* Check that we're not already initialized. */
AMS_ASSERT(!IsInitialized());
/* Configure disconnection emulation. */
g_enable_disconnection_emulation = true;
/* Initialize. */
InitializeImpl(allocate, deallocate, num_sessions, htcs::SocketCountMax);
}
void Initialize(void *buffer, size_t buffer_size) {
/* Check that we're not already initialized. */
AMS_ASSERT(!IsInitialized());
/* Configure disconnection emulation. */
g_enable_disconnection_emulation = true;
/* Initialize. */
InitializeImpl(buffer, buffer_size, htcs::SessionCountMax);
}
void InitializeForDisableDisconnectionEmulation(AllocateFunction allocate, DeallocateFunction deallocate, int num_sessions) {
/* Check that we're not already initialized. */
AMS_ASSERT(!IsInitialized());
/* Configure disconnection emulation. */
g_enable_disconnection_emulation = false;
/* Initialize. */
InitializeImpl(allocate, deallocate, num_sessions, htcs::SocketCountMax);
}
void InitializeForDisableDisconnectionEmulation(void *buffer, size_t buffer_size) {
/* Check that we're not already initialized. */
AMS_ASSERT(!IsInitialized());
/* Configure disconnection emulation. */
g_enable_disconnection_emulation = false;
/* Initialize. */
InitializeImpl(buffer, buffer_size, htcs::SessionCountMax);
}
void InitializeForSystem(void *buffer, size_t buffer_size, int num_sessions) {
/* Check that we're not already initialized. */
AMS_ASSERT(!IsInitialized());
/* Configure disconnection emulation. */
g_enable_disconnection_emulation = true;
/* Initialize. */
InitializeImpl(buffer, buffer_size, num_sessions);
}
void Finalize() {
/* Check that we're initialized. */
AMS_ASSERT(IsInitialized());
/* Set not initialized. */
g_initialized = false;
/* Destroy the virtual socket collection. */
std::destroy_at(g_sockets);
g_sockets = nullptr;
/* Free the buffer, if we have one. */
if (g_buffer != nullptr) {
g_deallocate_function(g_buffer, g_buffer_size);
g_buffer = nullptr;
g_buffer_size = 0;
}
/* Free the tls slot. */
os::FreeTlsSlot(g_tls_slot);
/* Release the manager objects. */
sf::ReleaseSharedObject(g_manager);
sf::ReleaseSharedObject(g_monitor);
g_manager = nullptr;
g_monitor = nullptr;
/* Finalize the htcs client sessions. */
client::FinalizeSessionManager();
}
const HtcsPeerName GetPeerNameAny() {
/* Check that we have a manager. */
AMS_ASSERT(g_manager != nullptr);
/* Get name. */
HtcsPeerName name;
g_manager->GetPeerNameAny(std::addressof(name));
return name;
}
const HtcsPeerName GetDefaultHostName() {
/* Check that we have a manager. */
AMS_ASSERT(g_manager != nullptr);
/* Get name. */
HtcsPeerName name;
g_manager->GetDefaultHostName(std::addressof(name));
return name;
}
s32 GetLastError() {
/* Check that we have a manager. */
AMS_ASSERT(g_manager != nullptr);
return static_cast<s32>(os::GetTlsValue(g_tls_slot));
}
s32 Socket() {
/* Check that we have a manager. */
AMS_ASSERT(g_manager != nullptr);
/* Check that we have a socket collection. */
AMS_ASSERT(g_sockets != nullptr);
/* Perform the operation. */
s32 error_code = 0;
const s32 ret = g_sockets->Socket(error_code);
if (ret < 0) {
SetLastError(static_cast<uintptr_t>(error_code));
}
return ret;
}
s32 Close(s32 desc) {
/* Check that we have a manager. */
AMS_ASSERT(g_manager != nullptr);
/* Check that we have a socket collection. */
AMS_ASSERT(g_sockets != nullptr);
/* Perform the operation. */
s32 error_code = 0;
const s32 ret = g_sockets->Close(desc, error_code);
if (ret < 0) {
SetLastError(static_cast<uintptr_t>(error_code));
}
return ret;
}
s32 Connect(s32 desc, const SockAddrHtcs *address) {
/* Check that we have a manager. */
AMS_ASSERT(g_manager != nullptr);
/* Check that we have a socket collection. */
AMS_ASSERT(g_sockets != nullptr);
/* Check that the address family is correct. */
AMS_ASSERT(address->family == HTCS_AF_HTCS);
/* Perform the operation. */
s32 error_code = 0;
const s32 ret = g_sockets->Connect(desc, address, error_code);
if (ret < 0) {
SetLastError(static_cast<uintptr_t>(error_code));
}
return ret;
}
s32 Bind(s32 desc, const SockAddrHtcs *address) {
/* Check that we have a manager. */
AMS_ASSERT(g_manager != nullptr);
/* Check that we have a socket collection. */
AMS_ASSERT(g_sockets != nullptr);
/* Check that the address family is correct. */
AMS_ASSERT(address->family == HTCS_AF_HTCS);
/* Perform the operation. */
s32 error_code = 0;
const s32 ret = g_sockets->Bind(desc, address, error_code);
if (ret < 0) {
SetLastError(static_cast<uintptr_t>(error_code));
}
return ret;
}
s32 Listen(s32 desc, s32 backlog_count) {
/* Check that we have a manager. */
AMS_ASSERT(g_manager != nullptr);
/* Check that we have a socket collection. */
AMS_ASSERT(g_sockets != nullptr);
/* Perform the operation. */
s32 error_code = 0;
const s32 ret = g_sockets->Listen(desc, backlog_count, error_code);
if (ret < 0) {
SetLastError(static_cast<uintptr_t>(error_code));
}
return ret;
}
s32 Accept(s32 desc, SockAddrHtcs *address) {
/* Check that we have a manager. */
AMS_ASSERT(g_manager != nullptr);
/* Check that we have a socket collection. */
AMS_ASSERT(g_sockets != nullptr);
/* Ensure we have an address. */
SockAddrHtcs tmp;
if (address == nullptr) {
address = std::addressof(tmp);
}
/* Perform the operation. */
s32 error_code = 0;
const s32 ret = g_sockets->Accept(desc, address, error_code);
if (ret < 0) {
SetLastError(static_cast<uintptr_t>(error_code));
}
return ret;
}
s32 Shutdown(s32 desc, s32 how) {
/* Check that we have a manager. */
AMS_ASSERT(g_manager != nullptr);
/* Check that we have a socket collection. */
AMS_ASSERT(g_sockets != nullptr);
/* Perform the operation. */
s32 error_code = 0;
const s32 ret = g_sockets->Shutdown(desc, how, error_code);
if (ret < 0) {
SetLastError(static_cast<uintptr_t>(error_code));
}
return ret;
}
s32 Fcntl(s32 desc, s32 command, s32 value) {
/* Check that we have a manager. */
AMS_ASSERT(g_manager != nullptr);
/* Check that we have a socket collection. */
AMS_ASSERT(g_sockets != nullptr);
/* Perform the operation. */
s32 error_code = 0;
const s32 ret = g_sockets->Fcntl(desc, command, value, error_code);
if (ret < 0) {
SetLastError(static_cast<uintptr_t>(error_code));
}
return ret;
}
s32 Select(s32 count, FdSet *read, FdSet *write, FdSet *exception, TimeVal *timeout) {
AMS_UNUSED(count);
/* Check that we have a manager. */
AMS_ASSERT(g_manager != nullptr);
/* Check that we have a socket collection. */
AMS_ASSERT(g_sockets != nullptr);
/* Check that we have some form of input. */
if (read == nullptr && write == nullptr && exception == nullptr) {
SetLastError(static_cast<uintptr_t>(HTCS_EINVAL));
return -1;
}
/* Check that the timeout is valid. */
if (timeout != nullptr && (timeout->tv_sec < 0 || timeout->tv_usec < 0)) {
SetLastError(static_cast<uintptr_t>(HTCS_EINVAL));
return -1;
}
/* Perform the operation. */
s32 error_code = 0;
const s32 ret = g_sockets->Select(read, write, exception, timeout, error_code);
if (ret < 0) {
SetLastError(static_cast<uintptr_t>(error_code));
}
return ret;
}
ssize_t Recv(s32 desc, void *buffer, size_t buffer_size, s32 flags) {
/* Check that we have a manager. */
AMS_ASSERT(g_manager != nullptr);
/* Check that we have a socket collection. */
AMS_ASSERT(g_sockets != nullptr);
/* Perform the operation. */
s32 error_code = 0;
const ssize_t ret = g_sockets->Recv(desc, buffer, buffer_size, flags, error_code);
if (ret < 0) {
SetLastError(static_cast<uintptr_t>(error_code));
}
return ret;
}
ssize_t Send(s32 desc, const void *buffer, size_t buffer_size, s32 flags) {
/* Check that we have a manager. */
AMS_ASSERT(g_manager != nullptr);
/* Check that we have a socket collection. */
AMS_ASSERT(g_sockets != nullptr);
/* Perform the operation. */
s32 error_code = 0;
const ssize_t ret = g_sockets->Send(desc, buffer, buffer_size, flags, error_code);
if (ret < 0) {
SetLastError(static_cast<uintptr_t>(error_code));
}
return ret;
}
void FdSetZero(FdSet *set) {
AMS_ASSERT(set != nullptr);
std::memset(set, 0, sizeof(*set));
}
void FdSetSet(s32 fd, FdSet *set) {
AMS_ASSERT(set != nullptr);
for (auto i = 0; i < FdSetSize; ++i) {
if (set->fds[i] == 0) {
set->fds[i] = fd;
break;
}
}
}
void FdSetClr(s32 fd, FdSet *set) {
AMS_ASSERT(set != nullptr);
for (auto i = 0; i < FdSetSize; ++i) {
if (set->fds[i] == fd) {
std::memcpy(set->fds + i, set->fds + i + 1, (FdSetSize - (i + 1)) * sizeof(fd));
set->fds[FdSetSize - 1] = 0;
break;
}
}
}
bool FdSetIsSet(s32 fd, const FdSet *set) {
AMS_ASSERT(set != nullptr);
for (auto i = 0; i < FdSetSize; ++i) {
if (set->fds[i] == fd) {
return true;
}
}
return false;
}
namespace client {
sf::SharedPointer<tma::ISocket> socket(s32 &last_error) {
sf::SharedPointer<tma::ISocket> socket = nullptr;
R_ABORT_UNLESS(g_manager->CreateSocket(std::addressof(last_error), std::addressof(socket), g_enable_disconnection_emulation));
return socket;
}
s32 close(sf::SharedPointer<tma::ISocket> socket, s32 &last_error) {
s32 res;
socket->Close(std::addressof(last_error), std::addressof(res));
return res;
}
s32 bind(sf::SharedPointer<tma::ISocket> socket, const htcs::SockAddrHtcs *address, s32 &last_error) {
/* Create null-terminated address. */
htcs::SockAddrHtcs null_terminated_address;
null_terminated_address.family = address->family;
util::Strlcpy(null_terminated_address.peer_name.name, address->peer_name.name, PeerNameBufferLength);
util::Strlcpy(null_terminated_address.port_name.name, address->port_name.name, PortNameBufferLength);
s32 res;
socket->Bind(std::addressof(last_error), std::addressof(res), null_terminated_address);
return res;
}
s32 listen(sf::SharedPointer<tma::ISocket> socket, s32 backlog_count, s32 &last_error) {
s32 res;
socket->Listen(std::addressof(last_error), std::addressof(res), backlog_count);
return res;
}
sf::SharedPointer<tma::ISocket> accept(sf::SharedPointer<tma::ISocket> socket, htcs::SockAddrHtcs *address, s32 &last_error) {
/* Begin the accept. */
sf::SharedPointer<tma::ISocket> res = nullptr;
u32 task_id = 0;
sf::NativeHandle event_handle;
if (R_SUCCEEDED(socket->AcceptStart(std::addressof(task_id), std::addressof(event_handle)))) {
/* Create system event. */
os::SystemEventType event;
os::AttachReadableHandleToSystemEvent(std::addressof(event), event_handle.GetOsHandle(), event_handle.IsManaged(), os::EventClearMode_ManualClear);
event_handle.Detach();
/* When we're done, clean up the event. */
ON_SCOPE_EXIT { os::DestroySystemEvent(std::addressof(event)); };
/* Wait for the accept to finish. */
os::WaitSystemEvent(std::addressof(event));
/* End the accept. */
socket->AcceptResults(std::addressof(last_error), std::addressof(res), address, task_id);
} else {
/* Set error. */
last_error = HTCS_EINTR;
}
/* Sleep, if an error occurred. */
if (last_error != HTCS_ENONE) {
os::SleepThread(TimeSpan::FromMilliSeconds(1));
}
return res;
}
s32 fcntl(sf::SharedPointer<tma::ISocket> socket, s32 command, s32 value, s32 &last_error) {
s32 res;
socket->Fcntl(std::addressof(last_error), std::addressof(res), command, value);
return res;
}
s32 shutdown(sf::SharedPointer<tma::ISocket> socket, s32 how, s32 &last_error) {
s32 res;
socket->Shutdown(std::addressof(last_error), std::addressof(res), how);
return res;
}
s32 connect(sf::SharedPointer<tma::ISocket> socket, const htcs::SockAddrHtcs *address, s32 &last_error) {
/* Create null-terminated address. */
htcs::SockAddrHtcs null_terminated_address;
null_terminated_address.family = address->family;
util::Strlcpy(null_terminated_address.peer_name.name, address->peer_name.name, PeerNameBufferLength);
util::Strlcpy(null_terminated_address.port_name.name, address->port_name.name, PortNameBufferLength);
s32 res;
socket->Connect(std::addressof(last_error), std::addressof(res), null_terminated_address);
return res;
}
s32 select(s32 * const read, s32 &num_read, s32 * const write, s32 &num_write, s32 * const except, s32 &num_except, htcs::TimeVal *timeout, s32 &last_error) {
/* Determine the timeout values. */
s64 tv_sec = -1;
s64 tv_usec = -1;
if (timeout != nullptr) {
tv_sec = timeout->tv_sec;
tv_usec = timeout->tv_usec;
}
using InArray = sf::InMapAliasArray<s32>;
using OutArray = sf::OutMapAliasArray<s32>;
/* Begin the select. */
s32 res = -1;
u32 task_id = 0;
sf::NativeHandle event_handle;
if (R_SUCCEEDED(g_manager->StartSelect(std::addressof(task_id), std::addressof(event_handle), InArray(read, num_read), InArray(write, num_write), InArray(except, num_except), tv_sec, tv_usec))) {
/* Create system event. */
os::SystemEventType event;
os::AttachReadableHandleToSystemEvent(std::addressof(event), event_handle.GetOsHandle(), event_handle.IsManaged(), os::EventClearMode_ManualClear);
event_handle.Detach();
/* When we're done, clean up the event. */
ON_SCOPE_EXIT { os::DestroySystemEvent(std::addressof(event)); };
/* Wait for the select to finish. */
os::WaitSystemEvent(std::addressof(event));
/* End the select. */
g_manager->EndSelect(std::addressof(last_error), std::addressof(res), OutArray(read, num_read), OutArray(write, num_write), OutArray(except, num_except), task_id);
} else {
/* Set error. */
last_error = HTCS_EINTR;
os::SleepThread(TimeSpan::FromMilliSeconds(1));
}
return res;
}
namespace {
constexpr size_t MaximumBufferSizeForSmallTransfer = 0xDFE0;
ssize_t recvLarge(sf::SharedPointer<tma::ISocket> socket, void *buffer, size_t buffer_size, s32 flags, s32 &last_error) {
/* Setup. */
s64 res = -1;
last_error = HTCS_EINTR;
/* Start the receive. */
u32 task_id = 0;
sf::NativeHandle event_handle;
if (R_SUCCEEDED(socket->StartRecv(std::addressof(task_id), std::addressof(event_handle), static_cast<s64>(buffer_size), flags))) {
/* Create system event. */
os::SystemEventType event;
os::AttachReadableHandleToSystemEvent(std::addressof(event), event_handle.GetOsHandle(), event_handle.IsManaged(), os::EventClearMode_ManualClear);
event_handle.Detach();
/* When we're done, clean up the event. */
ON_SCOPE_EXIT { os::DestroySystemEvent(std::addressof(event)); };
/* Wait for the receive to finish. */
os::WaitSystemEvent(std::addressof(event));
/* End the receive. */
socket->EndRecv(std::addressof(last_error), std::addressof(res), sf::OutAutoSelectBuffer(buffer, buffer_size), task_id);
} else {
/* Set error. */
last_error = HTCS_EINTR;
os::SleepThread(TimeSpan::FromMilliSeconds(1));
}
return static_cast<ssize_t>(res);
}
ssize_t sendLarge(sf::SharedPointer<tma::ISocket> socket, const void *buffer, size_t buffer_size, s32 flags, s32 &last_error) {
/* Setup. */
s64 res = -1;
last_error = HTCS_EINTR;
/* Start the send. */
u32 task_id = 0;
s64 max_size = 0;
sf::NativeHandle event_handle;
if (R_SUCCEEDED(socket->StartSend(std::addressof(task_id), std::addressof(event_handle), std::addressof(max_size), static_cast<s64>(buffer_size), flags))) {
/* Create system event. */
os::SystemEventType event;
os::AttachReadableHandleToSystemEvent(std::addressof(event), event_handle.GetOsHandle(), event_handle.IsManaged(), os::EventClearMode_ManualClear);
event_handle.Detach();
/* When we're done, clean up the event. */
ON_SCOPE_EXIT { os::DestroySystemEvent(std::addressof(event)); };
/* Send all the data. */
bool done = false;
size_t sent = 0;
while (sent < buffer_size) {
/* Determine how much to send, this iteration. */
const u8 *cur = static_cast<const u8 *>(buffer) + sent;
const s64 cur_size = std::min(max_size, static_cast<s64>(buffer_size - sent));
/* Continue sending data. */
s64 cur_sent = 0;
bool wait = false;
const Result result = socket->ContinueSend(std::addressof(cur_sent), std::addressof(wait), sf::InNonSecureAutoSelectBuffer(cur, cur_size), task_id);
if (cur_sent <= 0 || R_FAILED(result)) {
done = true;
break;
}
/* Wait if we should. */
if (wait) {
os::WaitSystemEvent(std::addressof(event));
os::ClearSystemEvent(std::addressof(event));
}
/* Advance. */
sent += cur_sent;
}
/* Wait for the send to finish. */
if (!done) {
os::WaitSystemEvent(std::addressof(event));
}
/* End the send. */
socket->EndSend(std::addressof(last_error), std::addressof(res), task_id);
} else {
/* Set error. */
last_error = HTCS_EINTR;
os::SleepThread(TimeSpan::FromMilliSeconds(1));
}
return static_cast<ssize_t>(res);
}
}
ssize_t recv(sf::SharedPointer<tma::ISocket> socket, void *buffer, size_t buffer_size, s32 flags, s32 &last_error) {
/* Determine how much to receive. */
size_t recv_size = buffer_size;
if ((flags & HTCS_MSG_WAITALL) == 0) {
recv_size = std::min(MaximumBufferSizeForSmallTransfer, buffer_size);
}
/* Perform a large receive, if we have to. */
if (recv_size > MaximumBufferSizeForSmallTransfer) {
return recvLarge(socket, buffer, recv_size, flags, last_error);
}
/* Start the receive. */
s64 res = -1;
u32 task_id = 0;
sf::NativeHandle event_handle;
if (R_SUCCEEDED(socket->RecvStart(std::addressof(task_id), std::addressof(event_handle), static_cast<s32>(recv_size), flags))) {
/* Create system event. */
os::SystemEventType event;
os::AttachReadableHandleToSystemEvent(std::addressof(event), event_handle.GetOsHandle(), event_handle.IsManaged(), os::EventClearMode_ManualClear);
event_handle.Detach();
/* When we're done, clean up the event. */
ON_SCOPE_EXIT { os::DestroySystemEvent(std::addressof(event)); };
/* Wait for the receive to finish. */
os::WaitSystemEvent(std::addressof(event));
/* End the receive. */
socket->RecvResults(std::addressof(last_error), std::addressof(res), sf::OutAutoSelectBuffer(buffer, recv_size), task_id);
} else {
/* Set error. */
last_error = HTCS_EINTR;
os::SleepThread(TimeSpan::FromMilliSeconds(1));
}
return static_cast<ssize_t>(res);
}
ssize_t send(sf::SharedPointer<tma::ISocket> socket, const void *buffer, size_t buffer_size, s32 flags, s32 &last_error) {
/* Perform a large send, if we have to. */
if (buffer_size > MaximumBufferSizeForSmallTransfer) {
return sendLarge(socket, buffer, buffer_size, flags, last_error);
}
/* Start the send. */
s64 res = -1;
u32 task_id = 0;
sf::NativeHandle event_handle;
if (R_SUCCEEDED(socket->SendStart(std::addressof(task_id), std::addressof(event_handle), sf::InNonSecureAutoSelectBuffer(buffer, buffer_size), flags))) {
/* Create system event. */
os::SystemEventType event;
os::AttachReadableHandleToSystemEvent(std::addressof(event), event_handle.GetOsHandle(), event_handle.IsManaged(), os::EventClearMode_ManualClear);
event_handle.Detach();
/* When we're done, clean up the event. */
ON_SCOPE_EXIT { os::DestroySystemEvent(std::addressof(event)); };
/* Wait for the send to finish. */
os::WaitSystemEvent(std::addressof(event));
/* End the send. */
socket->SendResults(std::addressof(last_error), std::addressof(res), task_id);
} else {
/* Set error. */
last_error = HTCS_EINTR;
os::SleepThread(TimeSpan::FromMilliSeconds(1));
}
return static_cast<ssize_t>(res);
}
}
}
| 28,273
|
C++
|
.cpp
| 596
| 35.520134
| 207
| 0.569907
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,590
|
htcs_manager_holder.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htcs/impl/htcs_manager_holder.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "htcs_manager.hpp"
namespace ams::htcs::impl::HtcsManagerHolder {
namespace {
constinit os::SdkMutex g_holder_mutex;
constinit int g_holder_reference_count = 0;
mem::StandardAllocator g_allocator;
constinit HtcsManager *g_manager = nullptr;
alignas(os::MemoryPageSize) u8 g_heap_buffer[416_KB];
}
void AddReference() {
std::scoped_lock lk(g_holder_mutex);
if ((g_holder_reference_count++) == 0) {
/* Add reference to the htclow manager. */
htclow::HtclowManagerHolder::AddReference();
/* Initialize the allocator for the manager. */
g_allocator.Initialize(g_heap_buffer, sizeof(g_heap_buffer));
/* Allocate the manager. */
g_manager = static_cast<HtcsManager *>(g_allocator.Allocate(sizeof(HtcsManager), alignof(HtcsManager)));
/* Construct the manager. */
std::construct_at(g_manager, std::addressof(g_allocator), htclow::HtclowManagerHolder::GetHtclowManager());
}
AMS_ASSERT(g_holder_reference_count > 0);
}
void Release() {
std::scoped_lock lk(g_holder_mutex);
AMS_ASSERT(g_holder_reference_count > 0);
if ((--g_holder_reference_count) == 0) {
/* Destroy the manager. */
std::destroy_at(g_manager);
g_allocator.Free(g_manager);
g_manager = nullptr;
/* Finalize the allocator. */
g_allocator.Finalize();
/* Release reference to the htclow manager. */
htclow::HtclowManagerHolder::Release();
}
}
HtcsManager *GetHtcsManager() {
std::scoped_lock lk(g_holder_mutex);
return g_manager;
}
}
| 2,426
|
C++
|
.cpp
| 58
| 34.293103
| 119
| 0.646783
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,591
|
htcs_manager_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htcs/impl/htcs_manager_impl.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "htcs_manager.hpp"
#include "htcs_manager_impl.hpp"
namespace ams::htcs::impl {
HtcsManagerImpl::HtcsManagerImpl(mem::StandardAllocator *allocator, htclow::HtclowManager *htclow_manager)
: m_allocator(allocator),
m_driver(htclow_manager, htclow::ModuleId::Htcs),
m_driver_manager(std::addressof(m_driver)),
m_rpc_client(m_allocator, std::addressof(m_driver), HtcsClientChannelId),
m_data_channel_manager(std::addressof(m_rpc_client), htclow_manager),
m_service(m_allocator, m_driver_manager.GetDriver(), std::addressof(m_rpc_client), std::addressof(m_data_channel_manager)),
m_monitor(m_allocator, m_driver_manager.GetDriver(), std::addressof(m_rpc_client), std::addressof(m_service))
{
/* Start the monitor. */
m_monitor.Start();
}
HtcsManagerImpl::~HtcsManagerImpl() {
/* Cancel our monitor. */
m_monitor.Cancel();
m_monitor.Wait();
}
os::EventType *HtcsManagerImpl::GetServiceAvailabilityEvent() {
return m_monitor.GetServiceAvailabilityEvent();
}
bool HtcsManagerImpl::IsServiceAvailable() {
return m_monitor.IsServiceAvailable();
}
Result HtcsManagerImpl::CreateSocket(s32 *out_err, s32 *out_desc, bool enable_disconnection_emulation) {
R_RETURN(m_service.CreateSocket(out_err, out_desc, enable_disconnection_emulation));
}
Result HtcsManagerImpl::DestroySocket(s32 desc) {
R_RETURN(m_service.DestroySocket(desc));
}
Result HtcsManagerImpl::Connect(s32 *out_err, s32 desc, const SockAddrHtcs &address) {
R_RETURN(m_service.Connect(out_err, desc, address));
}
Result HtcsManagerImpl::Bind(s32 *out_err, s32 desc, const SockAddrHtcs &address) {
R_RETURN(m_service.Bind(out_err, desc, address));
}
Result HtcsManagerImpl::Listen(s32 *out_err, s32 desc, s32 backlog_count) {
R_RETURN(m_service.Listen(out_err, desc, backlog_count));
}
Result HtcsManagerImpl::Receive(s32 *out_err, s64 *out_size, char *buffer, size_t size, s32 desc, s32 flags) {
R_RETURN(m_service.Receive(out_err, out_size, buffer, size, desc, flags));
}
Result HtcsManagerImpl::Send(s32 *out_err, s64 *out_size, const char *buffer, size_t size, s32 desc, s32 flags) {
R_RETURN(m_service.Send(out_err, out_size, buffer, size, desc, flags));
}
Result HtcsManagerImpl::Shutdown(s32 *out_err, s32 desc, s32 how) {
R_RETURN(m_service.Shutdown(out_err, desc, how));
}
Result HtcsManagerImpl::Fcntl(s32 *out_err, s32 *out_res, s32 desc, s32 command, s32 value) {
R_RETURN(m_service.Fcntl(out_err, out_res, desc, command, value));
}
Result HtcsManagerImpl::AcceptStart(u32 *out_task_id, os::NativeHandle *out_handle, s32 desc) {
R_RETURN(m_service.AcceptStart(out_task_id, out_handle, desc));
}
Result HtcsManagerImpl::AcceptResults(s32 *out_err, s32 *out_desc, SockAddrHtcs *out_address, u32 task_id, s32 desc) {
R_RETURN(m_service.AcceptResults(out_err, out_desc, out_address, task_id, desc));
}
Result HtcsManagerImpl::RecvStart(u32 *out_task_id, os::NativeHandle *out_handle, s64 size, s32 desc, s32 flags) {
R_RETURN(m_service.ReceiveSmallStart(out_task_id, out_handle, size, desc, flags));
}
Result HtcsManagerImpl::RecvResults(s32 *out_err, s64 *out_size, char *buffer, s64 buffer_size, u32 task_id, s32 desc) {
R_RETURN(m_service.ReceiveSmallResults(out_err, out_size, buffer, buffer_size, task_id, desc));
}
Result HtcsManagerImpl::SendStart(u32 *out_task_id, os::NativeHandle *out_handle, const char *buffer, s64 size, s32 desc, s32 flags) {
/* Start the send. */
u32 task_id{};
os::NativeHandle handle;
R_TRY(m_service.SendSmallStart(std::addressof(task_id), std::addressof(handle), desc, size, flags));
/* Continue the send. */
s64 continue_size;
const Result result = m_service.SendSmallContinue(std::addressof(continue_size), buffer, size, task_id, desc);
if (R_SUCCEEDED(result) || htcs::ResultCompleted::Includes(result) || htc::ResultTaskQueueNotAvailable::Includes(result)) {
*out_task_id = task_id;
*out_handle = handle;
R_SUCCEED();
} else {
os::SystemEventType event;
os::AttachReadableHandleToSystemEvent(std::addressof(event), handle, true, os::EventClearMode_ManualClear);
s32 err;
s64 rsize;
m_service.SendSmallResults(std::addressof(err), std::addressof(rsize), task_id, desc);
os::DestroySystemEvent(std::addressof(event));
R_RETURN(result);
}
}
Result HtcsManagerImpl::SendLargeStart(u32 *out_task_id, os::NativeHandle *out_handle, const char **buffers, const s64 *sizes, s32 count, s32 desc, s32 flags) {
/* NOTE: Nintendo aborts here, too. */
AMS_UNUSED(out_task_id, out_handle, buffers, sizes, count, desc, flags);
AMS_ABORT("HtcsManagerImpl::SendLargeStart is not implemented");
}
Result HtcsManagerImpl::SendResults(s32 *out_err, s64 *out_size, u32 task_id, s32 desc) {
R_RETURN(m_service.SendSmallResults(out_err, out_size, task_id, desc));
}
Result HtcsManagerImpl::StartSend(u32 *out_task_id, os::NativeHandle *out_handle, s32 desc, s64 size, s32 flags) {
R_RETURN(m_service.SendStart(out_task_id, out_handle, desc, size, flags));
}
Result HtcsManagerImpl::ContinueSend(s64 *out_size, const char *buffer, s64 buffer_size, u32 task_id, s32 desc) {
R_RETURN(m_service.SendContinue(out_size, buffer, buffer_size, task_id, desc));
}
Result HtcsManagerImpl::EndSend(s32 *out_err, s64 *out_size, u32 task_id, s32 desc) {
R_RETURN(m_service.SendResults(out_err, out_size, task_id, desc));
}
Result HtcsManagerImpl::StartRecv(u32 *out_task_id, os::NativeHandle *out_handle, s64 size, s32 desc, s32 flags) {
R_RETURN(m_service.ReceiveStart(out_task_id, out_handle, size, desc, flags));
}
Result HtcsManagerImpl::EndRecv(s32 *out_err, s64 *out_size, char *buffer, s64 buffer_size, u32 task_id, s32 desc) {
R_RETURN(m_service.ReceiveResults(out_err, out_size, buffer, buffer_size, task_id, desc));
}
Result HtcsManagerImpl::StartSelect(u32 *out_task_id, os::NativeHandle *out_handle, Span<const int> read_handles, Span<const int> write_handles, Span<const int> exception_handles, s64 tv_sec, s64 tv_usec) {
/* Start the select. */
u32 task_id{};
os::NativeHandle handle = os::InvalidNativeHandle;
const Result result = m_service.SelectStart(std::addressof(task_id), std::addressof(handle), read_handles, write_handles, exception_handles, tv_sec, tv_usec);
/* Ensure our state ends up clean. */
if (htcs::ResultCancelled::Includes(result)) {
s32 err;
bool empty;
m_service.SelectEnd(std::addressof(err), std::addressof(empty), Span<int>{}, Span<int>{}, Span<int>{}, task_id);
if (handle != os::InvalidNativeHandle) {
os::SystemEventType event;
os::AttachReadableHandleToSystemEvent(std::addressof(event), handle, true, os::EventClearMode_ManualClear);
os::DestroySystemEvent(std::addressof(event));
}
} else if (R_SUCCEEDED(result)) {
*out_task_id = task_id;
*out_handle = handle;
}
R_RETURN(result);
}
Result HtcsManagerImpl::EndSelect(s32 *out_err, bool *out_empty, Span<int> read_handles, Span<int> write_handles, Span<int> exception_handles, u32 task_id) {
R_RETURN(m_service.SelectEnd(out_err, out_empty, read_handles, write_handles, exception_handles, task_id));
}
}
| 8,503
|
C++
|
.cpp
| 151
| 48.794702
| 210
| 0.674886
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,592
|
htcs_manager.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htcs/impl/htcs_manager.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "htcs_manager.hpp"
#include "htcs_manager_impl.hpp"
#include "htcs_util.hpp"
namespace ams::htcs::impl {
HtcsManager::HtcsManager(mem::StandardAllocator *allocator, htclow::HtclowManager *htclow_manager) : m_allocator(allocator), m_impl(static_cast<HtcsManagerImpl *>(allocator->Allocate(sizeof(HtcsManagerImpl), alignof(HtcsManagerImpl)))) {
std::construct_at(m_impl, m_allocator, htclow_manager);
}
HtcsManager::~HtcsManager() {
std::destroy_at(m_impl);
m_allocator->Free(m_impl);
}
os::EventType *HtcsManager::GetServiceAvailabilityEvent() {
return m_impl->GetServiceAvailabilityEvent();
}
bool HtcsManager::IsServiceAvailable() {
return m_impl->IsServiceAvailable();
}
void HtcsManager::Socket(s32 *out_err, s32 *out_desc, bool enable_disconnection_emulation) {
/* Invoke our implementation. */
s32 err = -1, desc = -1;
const Result result = m_impl->CreateSocket(std::addressof(err), std::addressof(desc), enable_disconnection_emulation);
/* Set output. */
if (R_SUCCEEDED(result)) {
*out_err = err;
if (err == 0) {
*out_desc = desc;
} else {
*out_desc = -1;
}
} else {
*out_err = ConvertResultToErrorCode(result);
*out_desc = -1;
}
}
void HtcsManager::Close(s32 *out_err, s32 *out_res, s32 desc) {
/* Invoke our implementation. */
const Result result = m_impl->DestroySocket(desc);
/* Set output. */
*out_err = ConvertResultToErrorCode(result);
if (R_SUCCEEDED(result)) {
*out_res = 0;
} else {
*out_res = -1;
}
}
void HtcsManager::Connect(s32 *out_err, s32 *out_res, const SockAddrHtcs &address, s32 desc) {
/* Invoke our implementation. */
s32 err = -1;
const Result result = m_impl->Connect(std::addressof(err), desc, address);
/* Set output. */
if (R_SUCCEEDED(result)) {
*out_err = err;
if (err == 0) {
*out_res = 0;
} else {
*out_res = -1;
}
} else {
*out_err = ConvertResultToErrorCode(result);
*out_res = -1;
}
}
void HtcsManager::Bind(s32 *out_err, s32 *out_res, const SockAddrHtcs &address, s32 desc) {
/* Invoke our implementation. */
s32 err = -1;
const Result result = m_impl->Bind(std::addressof(err), desc, address);
/* Set output. */
if (R_SUCCEEDED(result)) {
*out_err = err;
if (err == 0) {
*out_res = 0;
} else {
*out_res = -1;
}
} else {
*out_err = ConvertResultToErrorCode(result);
*out_res = -1;
}
}
void HtcsManager::Listen(s32 *out_err, s32 *out_res, s32 backlog_count, s32 desc) {
/* Invoke our implementation. */
s32 err = -1;
const Result result = m_impl->Listen(std::addressof(err), desc, backlog_count);
/* Set output. */
if (R_SUCCEEDED(result)) {
*out_err = err;
if (err == 0) {
*out_res = 0;
} else {
*out_res = -1;
}
} else {
*out_err = ConvertResultToErrorCode(result);
*out_res = -1;
}
}
void HtcsManager::Recv(s32 *out_err, s64 *out_size, char *buffer, size_t size, s32 flags, s32 desc) {
/* Invoke our implementation. */
s32 err = -1;
s64 recv_size = -1;
const Result result = m_impl->Receive(std::addressof(err), std::addressof(recv_size), buffer, size, desc, flags);
/* Set output. */
if (R_SUCCEEDED(result)) {
*out_err = err;
if (err == 0) {
*out_size = recv_size;
} else {
*out_size = -1;
}
} else {
*out_err = ConvertResultToErrorCode(result);
*out_size = -1;
}
}
void HtcsManager::Send(s32 *out_err, s64 *out_size, const char *buffer, size_t size, s32 flags, s32 desc) {
/* Invoke our implementation. */
s32 err = -1;
s64 send_size = -1;
const Result result = m_impl->Send(std::addressof(err), std::addressof(send_size), buffer, size, desc, flags);
/* Set output. */
if (R_SUCCEEDED(result)) {
*out_err = err;
if (err == 0) {
*out_size = send_size;
} else {
*out_size = -1;
}
} else {
*out_err = ConvertResultToErrorCode(result);
*out_size = -1;
}
}
void HtcsManager::Shutdown(s32 *out_err, s32 *out_res, s32 how, s32 desc) {
/* Invoke our implementation. */
s32 err = -1;
const Result result = m_impl->Shutdown(std::addressof(err), desc, how);
/* Set output. */
if (R_SUCCEEDED(result)) {
*out_err = err;
if (err == 0) {
*out_res = 0;
} else {
*out_res = -1;
}
} else {
if (htcs::ResultInvalidHandle::Includes(result)) {
*out_err = HTCS_ENOTCONN;
} else {
*out_err = ConvertResultToErrorCode(result);
}
*out_res = -1;
}
}
void HtcsManager::Fcntl(s32 *out_err, s32 *out_res, s32 command, s32 value, s32 desc) {
/* Invoke our implementation. */
s32 err = -1, res = -1;
const Result result = m_impl->Fcntl(std::addressof(err), std::addressof(res), desc, command, value);
/* Set output. */
if (R_SUCCEEDED(result)) {
*out_err = err;
*out_res = res;
} else {
*out_err = ConvertResultToErrorCode(result);
*out_res = -1;
}
}
Result HtcsManager::AcceptStart(u32 *out_task_id, os::NativeHandle *out_handle, s32 desc) {
R_RETURN(m_impl->AcceptStart(out_task_id, out_handle, desc));
}
void HtcsManager::AcceptResults(s32 *out_err, s32 *out_desc, SockAddrHtcs *out_address, u32 task_id, s32 desc) {
/* Invoke our implementation. */
s32 err = -1;
const Result result = m_impl->AcceptResults(std::addressof(err), out_desc, out_address, task_id, desc);
/* Set output. */
if (R_SUCCEEDED(result)) {
*out_err = err;
} else {
if (htc::ResultCancelled::Includes(result)) {
*out_err = HTCS_ENETDOWN;
} else if (htc::ResultTaskQueueNotAvailable::Includes(result)) {
*out_err = HTCS_EINTR;
} else {
*out_err = ConvertResultToErrorCode(result);
}
}
}
Result HtcsManager::RecvStart(u32 *out_task_id, os::NativeHandle *out_handle, s64 size, s32 desc, s32 flags) {
R_RETURN(m_impl->RecvStart(out_task_id, out_handle, size, desc, flags));
}
void HtcsManager::RecvResults(s32 *out_err, s64 *out_size, char *buffer, s64 buffer_size, u32 task_id, s32 desc) {
/* Invoke our implementation. */
s32 err = -1;
s64 size = -1;
const Result result = m_impl->RecvResults(std::addressof(err), std::addressof(size), buffer, buffer_size, task_id, desc);
/* Set output. */
if (R_SUCCEEDED(result)) {
*out_err = err;
if (err == 0) {
*out_size = size;
} else {
*out_size = -1;
}
} else {
if (htc::ResultTaskQueueNotAvailable::Includes(result)) {
*out_err = HTCS_EINTR;
} else {
*out_err = ConvertResultToErrorCode(result);
}
*out_size = -1;
}
}
Result HtcsManager::SendStart(u32 *out_task_id, os::NativeHandle *out_handle, const char *buffer, s64 size, s32 desc, s32 flags) {
R_RETURN(m_impl->SendStart(out_task_id, out_handle, buffer, size, desc, flags));
}
Result HtcsManager::SendLargeStart(u32 *out_task_id, os::NativeHandle *out_handle, const char **buffers, const s64 *sizes, s32 count, s32 desc, s32 flags) {
R_RETURN(m_impl->SendLargeStart(out_task_id, out_handle, buffers, sizes, count, desc, flags));
}
void HtcsManager::SendResults(s32 *out_err, s64 *out_size, u32 task_id, s32 desc) {
/* Invoke our implementation. */
s32 err = -1;
s64 size = -1;
const Result result = m_impl->SendResults(std::addressof(err), std::addressof(size), task_id, desc);
/* Set output. */
if (R_SUCCEEDED(result)) {
*out_err = err;
if (err == 0) {
*out_size = size;
} else {
*out_size = -1;
}
} else {
if (htc::ResultTaskQueueNotAvailable::Includes(result)) {
*out_err = HTCS_EINTR;
} else {
*out_err = ConvertResultToErrorCode(result);
}
*out_size = -1;
}
}
Result HtcsManager::StartSend(u32 *out_task_id, os::NativeHandle *out_handle, s32 desc, s64 size, s32 flags) {
R_RETURN(m_impl->StartSend(out_task_id, out_handle, desc, size, flags));
}
Result HtcsManager::ContinueSend(s64 *out_size, const char *buffer, s64 buffer_size, u32 task_id, s32 desc) {
/* Invoke our implementation. */
s64 size = -1;
R_TRY_CATCH(m_impl->ContinueSend(std::addressof(size), buffer, buffer_size, task_id, desc)) {
R_CONVERT(htclow::ResultInvalidChannelState, tma::ResultUnknown())
R_CONVERT(htc::ResultTaskCancelled, tma::ResultUnknown())
} R_END_TRY_CATCH;
/* Set output. */
*out_size = size;
R_SUCCEED();
}
void HtcsManager::EndSend(s32 *out_err, s64 *out_size, u32 task_id, s32 desc) {
/* Invoke our implementation. */
s32 err = -1;
s64 size = -1;
const Result result = m_impl->EndSend(std::addressof(err), std::addressof(size), task_id, desc);
/* Set output. */
if (R_SUCCEEDED(result)) {
*out_err = err;
if (err == 0) {
*out_size = size;
} else {
*out_size = -1;
}
} else {
if (htc::ResultTaskQueueNotAvailable::Includes(result)) {
*out_err = HTCS_EINTR;
} else {
*out_err = ConvertResultToErrorCode(result);
}
*out_size = -1;
}
}
Result HtcsManager::StartRecv(u32 *out_task_id, os::NativeHandle *out_handle, s64 size, s32 desc, s32 flags) {
R_RETURN(m_impl->StartRecv(out_task_id, out_handle, size, desc, flags));
}
void HtcsManager::EndRecv(s32 *out_err, s64 *out_size, char *buffer, s64 buffer_size, u32 task_id, s32 desc) {
/* Invoke our implementation. */
s32 err = -1;
s64 size = -1;
const Result result = m_impl->EndRecv(std::addressof(err), std::addressof(size), buffer, buffer_size, task_id, desc);
/* Set output. */
if (R_SUCCEEDED(result)) {
*out_err = err;
if (err == 0) {
*out_size = size;
} else {
*out_size = -1;
}
} else {
if (htc::ResultCancelled::Includes(result) || htc::ResultTaskQueueNotAvailable::Includes(result)) {
*out_err = 0;
} else {
*out_err = ConvertResultToErrorCode(result);
}
*out_size = -1;
}
}
Result HtcsManager::StartSelect(u32 *out_task_id, os::NativeHandle *out_handle, Span<const int> read_handles, Span<const int> write_handles, Span<const int> exception_handles, s64 tv_sec, s64 tv_usec) {
/* Invoke our implementation. */
R_TRY_CATCH(m_impl->StartSelect(out_task_id, out_handle, read_handles, write_handles, exception_handles, tv_sec, tv_usec)) {
R_CONVERT(htc::ResultTaskCancelled, tma::ResultUnknown())
} R_END_TRY_CATCH;
R_SUCCEED();
}
Result HtcsManager::EndSelect(s32 *out_err, s32 *out_count, Span<int> read_handles, Span<int> write_handles, Span<int> exception_handles, u32 task_id) {
/* Invoke our implementation. */
s32 err = -1;
bool empty = false;
const Result result = m_impl->EndSelect(std::addressof(err), std::addressof(empty), read_handles, write_handles, exception_handles, task_id);
/* Set output. */
if (R_SUCCEEDED(result) && !empty) {
*out_err = err;
if (err == 0) {
const auto num_read = std::count_if(read_handles.begin(), read_handles.end(), [](int handle) { return handle != 0; });
const auto num_write = std::count_if(write_handles.begin(), write_handles.end(), [](int handle) { return handle != 0; });
const auto num_exception = std::count_if(exception_handles.begin(), exception_handles.end(), [](int handle) { return handle != 0; });
*out_count = num_read + num_write + num_exception;
} else {
*out_count = -1;
}
} else {
if (R_SUCCEEDED(result)) {
*out_err = 0;
*out_count = 0;
} else {
*out_err = ConvertResultToErrorCode(err);
*out_count = -1;
}
}
R_SUCCEED();
}
}
| 14,354
|
C++
|
.cpp
| 351
| 30.706553
| 241
| 0.544497
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,593
|
htcs_service.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htcs/impl/htcs_service.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "htcs_service.hpp"
#include "rpc/htcs_rpc_tasks.hpp"
#include "htcs_util.hpp"
namespace ams::htcs::impl {
void HtcsService::WaitTask(u32 task_id) {
return m_rpc_client->Wait(task_id);
}
Result HtcsService::CreateSocket(s32 *out_err, s32 *out_desc, bool enable_disconnection_emulation) {
/* Set disconnection emulation enabled. */
m_driver->SetDisconnectionEmulationEnabled(enable_disconnection_emulation);
/* Begin the task. */
u32 task_id{};
R_TRY(m_rpc_client->Begin<rpc::SocketTask>(std::addressof(task_id)));
/* Wait for the task to complete. */
this->WaitTask(task_id);
/* Finish the task. */
htcs::SocketError err;
s32 desc;
R_TRY(m_rpc_client->End<rpc::SocketTask>(task_id, std::addressof(err), std::addressof(desc)));
/* Set output. */
*out_err = err;
*out_desc = desc;
R_SUCCEED();
}
Result HtcsService::DestroySocket(s32 desc) {
/* Begin the task. */
u32 task_id{};
R_TRY(m_rpc_client->Begin<rpc::CloseTask>(std::addressof(task_id), desc));
/* Wait for the task to complete. */
this->WaitTask(task_id);
/* Cancel the socket. */
m_rpc_client->CancelBySocket(desc);
/* Finish the task. */
htcs::SocketError err;
R_TRY(m_rpc_client->End<rpc::CloseTask>(task_id, std::addressof(err)));
R_SUCCEED();
}
Result HtcsService::Connect(s32 *out_err, s32 desc, const SockAddrHtcs &address) {
/* Validate the address. */
R_UNLESS(address.family == 0, htcs::ResultInvalidArgument());
R_UNLESS(IsValidName(address.peer_name), htcs::ResultInvalidArgument());
R_UNLESS(IsValidName(address.port_name), htcs::ResultInvalidArgument());
/* Begin the task. */
u32 task_id{};
R_TRY(m_rpc_client->Begin<rpc::ConnectTask>(std::addressof(task_id), desc, address.peer_name, address.port_name));
/* Wait for the task to complete. */
this->WaitTask(task_id);
/* Finish the task. */
htcs::SocketError err;
R_TRY(m_rpc_client->End<rpc::ConnectTask>(task_id, std::addressof(err)));
/* Set output. */
*out_err = err;
R_SUCCEED();
}
Result HtcsService::Bind(s32 *out_err, s32 desc, const SockAddrHtcs &address) {
/* Validate the address. */
R_UNLESS(address.family == 0, htcs::ResultInvalidArgument());
R_UNLESS(IsValidName(address.peer_name), htcs::ResultInvalidArgument());
R_UNLESS(IsValidName(address.port_name), htcs::ResultInvalidArgument());
/* Begin the task. */
u32 task_id{};
R_TRY(m_rpc_client->Begin<rpc::BindTask>(std::addressof(task_id), desc, address.peer_name, address.port_name));
/* Wait for the task to complete. */
this->WaitTask(task_id);
/* Finish the task. */
htcs::SocketError err;
R_TRY(m_rpc_client->End<rpc::BindTask>(task_id, std::addressof(err)));
/* Set output. */
*out_err = err;
R_SUCCEED();
}
Result HtcsService::Listen(s32 *out_err, s32 desc, s32 backlog_count) {
/* Begin the task. */
u32 task_id{};
R_TRY(m_rpc_client->Begin<rpc::ListenTask>(std::addressof(task_id), desc, backlog_count));
/* Wait for the task to complete. */
this->WaitTask(task_id);
/* Finish the task. */
htcs::SocketError err;
R_TRY(m_rpc_client->End<rpc::ListenTask>(task_id, std::addressof(err)));
/* Set output. */
*out_err = err;
R_SUCCEED();
}
Result HtcsService::Receive(s32 *out_err, s64 *out_size, char *buffer, s64 size, s32 desc, s32 flags) {
/* Begin the task. */
u32 task_id{};
R_TRY(m_rpc_client->Begin<rpc::ReceiveTask>(std::addressof(task_id), desc, size, static_cast<htcs::MessageFlag>(flags)));
/* Wait for the task to complete. */
this->WaitTask(task_id);
/* Finish the task. */
R_TRY(this->ReceiveResults(out_err, out_size, buffer, size, task_id, desc));
R_SUCCEED();
}
Result HtcsService::Send(s32 *out_err, s64 *out_size, const char *buffer, s64 size, s32 desc, s32 flags) {
/* Begin the task. */
u32 task_id{};
R_TRY(m_rpc_client->Begin<rpc::SendTask>(std::addressof(task_id), desc, size, static_cast<htcs::MessageFlag>(flags)));
/* Send the data. */
s64 cont_size;
const Result result = this->SendContinue(std::addressof(cont_size), buffer, size, task_id, desc);
if (R_FAILED(result)) {
R_RETURN(this->SendResults(out_err, out_size, task_id, desc));
}
/* Wait for the task to complete. */
this->WaitTask(task_id);
/* Finish the task. */
R_TRY(this->SendResults(out_err, out_size, task_id, desc));
R_SUCCEED();
}
Result HtcsService::Shutdown(s32 *out_err, s32 desc, s32 how) {
/* Begin the task. */
u32 task_id{};
R_TRY(m_rpc_client->Begin<rpc::ShutdownTask>(std::addressof(task_id), desc, static_cast<htcs::ShutdownType>(how)));
/* Wait for the task to complete. */
this->WaitTask(task_id);
/* Finish the task. */
htcs::SocketError err;
R_TRY(m_rpc_client->End<rpc::ShutdownTask>(task_id, std::addressof(err)));
/* Set output. */
*out_err = err;
R_SUCCEED();
}
Result HtcsService::Fcntl(s32 *out_err, s32 *out_res, s32 desc, s32 command, s32 value) {
/* Begin the task. */
u32 task_id{};
R_TRY(m_rpc_client->Begin<rpc::FcntlTask>(std::addressof(task_id), desc, command, value));
/* Wait for the task to complete. */
this->WaitTask(task_id);
/* Finish the task. */
htcs::SocketError err;
s32 res;
R_TRY(m_rpc_client->End<rpc::FcntlTask>(task_id, std::addressof(err), std::addressof(res)));
/* Set output. */
*out_err = err;
*out_res = res;
R_SUCCEED();
}
Result HtcsService::AcceptStart(u32 *out_task_id, os::NativeHandle *out_handle, s32 desc) {
/* Begin the task. */
u32 task_id{};
R_TRY(m_rpc_client->Begin<rpc::AcceptTask>(std::addressof(task_id), desc));
/* Detach the task. */
*out_task_id = task_id;
*out_handle = m_rpc_client->DetachReadableHandle(task_id);
R_SUCCEED();
}
Result HtcsService::AcceptResults(s32 *out_err, s32 *out_desc, SockAddrHtcs *out_address, u32 task_id, s32 desc) {
AMS_UNUSED(out_address);
/* Finish the task. */
htcs::SocketError err;
s32 ret_desc;
R_TRY(m_rpc_client->End<rpc::AcceptTask>(task_id, std::addressof(err), std::addressof(ret_desc), desc));
/* Set output. */
*out_err = err;
*out_desc = ret_desc;
R_SUCCEED();
}
Result HtcsService::ReceiveSmallStart(u32 *out_task_id, os::NativeHandle *out_handle, s64 size, s32 desc, s32 flags) {
/* Begin the task. */
u32 task_id{};
R_TRY(m_rpc_client->Begin<rpc::ReceiveSmallTask>(std::addressof(task_id), desc, size, static_cast<htcs::MessageFlag>(flags)));
/* Detach the task. */
*out_task_id = task_id;
*out_handle = m_rpc_client->DetachReadableHandle(task_id);
R_SUCCEED();
}
Result HtcsService::ReceiveSmallResults(s32 *out_err, s64 *out_size, char *buffer, s64 buffer_size, u32 task_id, s32 desc) {
AMS_UNUSED(desc);
/* Continue the task. */
m_rpc_client->ReceiveContinue<rpc::ReceiveSmallTask>(task_id, buffer, buffer_size);
/* Finish the task. */
htcs::SocketError err;
R_TRY(m_rpc_client->End<rpc::ReceiveSmallTask>(task_id, std::addressof(err), out_size));
/* Set output. */
*out_err = err;
R_SUCCEED();
}
Result HtcsService::SendSmallStart(u32 *out_task_id, os::NativeHandle *out_handle, s32 desc, s64 size, s32 flags) {
/* Begin the task. */
u32 task_id{};
R_TRY(m_rpc_client->Begin<rpc::SendSmallTask>(std::addressof(task_id), desc, size, static_cast<htcs::MessageFlag>(flags)));
/* Detach the task. */
*out_task_id = task_id;
*out_handle = m_rpc_client->DetachReadableHandle(task_id);
R_SUCCEED();
}
Result HtcsService::SendSmallContinue(s64 *out_size, const char *buffer, s64 buffer_size, u32 task_id, s32 desc) {
/* Verify the task. */
R_TRY(m_rpc_client->VerifyTaskIdWithHandle<rpc::SendSmallTask>(task_id, desc));
/* Continue the task. */
R_TRY(m_rpc_client->SendContinue<rpc::SendSmallTask>(task_id, buffer, buffer_size));
/* Set output. */
*out_size = buffer_size;
R_SUCCEED();
}
Result HtcsService::SendSmallResults(s32 *out_err, s64 *out_size, u32 task_id, s32 desc) {
AMS_UNUSED(desc);
/* Finish the task. */
htcs::SocketError err;
R_TRY(m_rpc_client->End<rpc::SendSmallTask>(task_id, std::addressof(err), out_size));
/* Set output. */
*out_err = err;
R_SUCCEED();
}
Result HtcsService::SendStart(u32 *out_task_id, os::NativeHandle *out_handle, s32 desc, s64 size, s32 flags) {
/* Begin the task. */
u32 task_id{};
R_TRY(m_rpc_client->Begin<rpc::SendTask>(std::addressof(task_id), desc, size, static_cast<htcs::MessageFlag>(flags)));
/* Detach the task. */
*out_task_id = task_id;
*out_handle = m_rpc_client->DetachReadableHandle(task_id);
R_SUCCEED();
}
Result HtcsService::SendContinue(s64 *out_size, const char *buffer, s64 buffer_size, u32 task_id, s32 desc) {
/* Verify the task. */
R_TRY(m_rpc_client->VerifyTaskIdWithHandle<rpc::SendTask>(task_id, desc));
/* Wait for the task to notify. */
m_rpc_client->WaitNotification<rpc::SendTask>(task_id);
/* Check the task status. */
R_UNLESS(!m_rpc_client->IsCompleted<rpc::SendTask>(task_id), htcs::ResultCompleted());
R_UNLESS(!m_rpc_client->IsCancelled<rpc::SendTask>(task_id), htcs::ResultCancelled());
/* Send the data. */
if (buffer_size > 0) {
R_TRY(m_data_channel_manager->Send(buffer, buffer_size, task_id));
}
/* Set output. */
*out_size = buffer_size;
R_SUCCEED();
}
Result HtcsService::SendResults(s32 *out_err, s64 *out_size, u32 task_id, s32 desc) {
/* Verify the task. */
R_TRY(m_rpc_client->VerifyTaskIdWithHandle<rpc::SendTask>(task_id, desc));
/* Finish the task. */
htcs::SocketError err;
R_TRY(m_rpc_client->End<rpc::SendTask>(task_id, std::addressof(err), out_size));
/* Set output. */
*out_err = err;
R_SUCCEED();
}
Result HtcsService::ReceiveStart(u32 *out_task_id, os::NativeHandle *out_handle, s64 size, s32 desc, s32 flags) {
/* Begin the task. */
u32 task_id{};
R_TRY(m_rpc_client->Begin<rpc::ReceiveTask>(std::addressof(task_id), desc, size, static_cast<htcs::MessageFlag>(flags)));
/* Detach the task. */
*out_task_id = task_id;
*out_handle = m_rpc_client->DetachReadableHandle(task_id);
R_SUCCEED();
}
Result HtcsService::ReceiveResults(s32 *out_err, s64 *out_size, char *buffer, s64 buffer_size, u32 task_id, s32 desc) {
/* Verify the task. */
R_TRY(m_rpc_client->VerifyTaskIdWithHandle<rpc::ReceiveTask>(task_id, desc));
/* Get the result. */
htcs::SocketError err{};
s64 recv_size{};
const Result result = m_rpc_client->GetResult<rpc::ReceiveTask>(task_id, std::addressof(err), std::addressof(recv_size));
if (R_FAILED(result) || err != HTCS_ENONE) {
/* Finish the task. */
R_TRY(m_rpc_client->End<rpc::ReceiveTask>(task_id, std::addressof(err), out_size));
/* Set output. */
*out_err = err;
R_SUCCEED();
}
/* Check the size. */
R_UNLESS(recv_size <= buffer_size, htcs::ResultInvalidArgument());
/* Perform remaining processing. */
if (recv_size > 0) {
/* Receive data. */
const Result recv_result = m_data_channel_manager->Receive(buffer, recv_size, task_id);
/* Finish the task. */
R_TRY(m_rpc_client->End<rpc::ReceiveTask>(task_id, std::addressof(err), out_size));
/* Check that our receive succeeded. */
R_TRY(recv_result);
} else {
/* Finish the task. */
R_TRY(m_rpc_client->End<rpc::ReceiveTask>(task_id, std::addressof(err), out_size));
}
/* Set output. */
*out_err = err;
R_SUCCEED();
}
Result HtcsService::SelectStart(u32 *out_task_id, os::NativeHandle *out_handle, Span<const int> read_handles, Span<const int> write_handles, Span<const int> exception_handles, s64 tv_sec, s64 tv_usec) {
/* Begin the task. */
u32 task_id{};
R_TRY(m_rpc_client->Begin<rpc::SelectTask>(std::addressof(task_id), read_handles, write_handles, exception_handles, tv_sec, tv_usec));
/* Detach the task. */
*out_task_id = task_id;
*out_handle = m_rpc_client->DetachReadableHandle(task_id);
/* Check that the task isn't cancelled. */
R_UNLESS(!m_rpc_client->IsCancelled<rpc::SelectTask>(task_id), htcs::ResultCancelled());
R_SUCCEED();
}
Result HtcsService::SelectEnd(s32 *out_err, bool *out_empty, Span<int> read_handles, Span<int> write_handles, Span<int> exception_handles, u32 task_id) {
/* Finish the task. */
htcs::SocketError err;
bool empty;
R_TRY(m_rpc_client->End<rpc::SelectTask>(task_id, std::addressof(err), std::addressof(empty), read_handles, write_handles, exception_handles));
/* Set output. */
*out_err = err;
*out_empty = empty;
R_SUCCEED();
}
}
| 14,792
|
C++
|
.cpp
| 319
| 37.971787
| 206
| 0.604214
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,594
|
htcs_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htcs/impl/htcs_impl.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "htcs_impl.hpp"
namespace ams::htcs::impl {
namespace {
constexpr const htcs::HtcsPeerName PeerNameAny = {""};
constexpr const htcs::HtcsPeerName DefaultHostName = {""};
}
const htcs::HtcsPeerName GetPeerNameAny() { return PeerNameAny; }
const htcs::HtcsPeerName GetDefaultHostName() { return DefaultHostName; }
}
| 1,024
|
C++
|
.cpp
| 25
| 37.88
| 77
| 0.741188
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,595
|
htcs_monitor.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htcs/impl/htcs_monitor.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "htcs_manager.hpp"
#include "htcs_manager_impl.hpp"
namespace ams::htcs::impl {
HtcsMonitor::HtcsMonitor(mem::StandardAllocator *allocator, htc::server::driver::IDriver *drv, htc::server::rpc::RpcClient *rc, HtcsService *srv)
: m_allocator(allocator),
m_driver(drv),
m_rpc_client(rc),
m_service(srv),
m_monitor_thread_stack(m_allocator->Allocate(os::MemoryPageSize, os::ThreadStackAlignment)),
m_mutex(),
m_cancel_event(os::EventClearMode_ManualClear),
m_service_availability_event(os::EventClearMode_ManualClear),
m_cancelled(false),
m_is_service_available(false)
{
/* ... */
}
HtcsMonitor::~HtcsMonitor() {
/* Free thread stack. */
m_allocator->Free(m_monitor_thread_stack);
}
void HtcsMonitor::Start() {
/* Create the monitor thread. */
R_ABORT_UNLESS(os::CreateThread(std::addressof(m_monitor_thread), ThreadEntry, this, m_monitor_thread_stack, os::MemoryPageSize, AMS_GET_SYSTEM_THREAD_PRIORITY(htc, HtcsMonitor)));
/* Set thread name. */
os::SetThreadNamePointer(std::addressof(m_monitor_thread), AMS_GET_SYSTEM_THREAD_NAME(htc, HtcsMonitor));
/* Start the monitor thread. */
os::StartThread(std::addressof(m_monitor_thread));
}
void HtcsMonitor::Cancel() {
/* Cancel, and signal. */
m_cancelled = true;
m_cancel_event.Signal();
}
void HtcsMonitor::Wait() {
/* Wait for the thread. */
os::WaitThread(std::addressof(m_monitor_thread));
os::DestroyThread(std::addressof(m_monitor_thread));
}
void HtcsMonitor::ThreadBody() {
/* Loop so long as we're not cancelled. */
while (!m_cancelled) {
/* Open the rpc client. */
m_rpc_client->Open();
/* Ensure we close, if something goes wrong. */
auto client_guard = SCOPE_GUARD { m_rpc_client->Close(); };
/* Wait for the rpc server. */
if (m_rpc_client->WaitAny(htclow::ChannelState_Connectable, m_cancel_event.GetBase()) != 0) {
break;
}
/* Start the rpc client. */
const Result start_result = m_rpc_client->Start();
if (R_FAILED(start_result)) {
/* DEBUG */
R_ABORT_UNLESS(start_result);
continue;
}
/* We're available! */
this->SetServiceAvailability(true);
client_guard.Cancel();
/* We're available, so we want to cleanup when we're done. */
ON_SCOPE_EXIT {
m_rpc_client->Close();
m_rpc_client->Cancel();
m_rpc_client->Wait();
this->SetServiceAvailability(false);
};
/* Wait to become disconnected. */
if (m_rpc_client->WaitAny(htclow::ChannelState_Disconnected, m_cancel_event.GetBase()) != 0) {
break;
}
}
}
}
| 3,729
|
C++
|
.cpp
| 90
| 32.566667
| 188
| 0.603367
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,596
|
htcs_util.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htcs/impl/htcs_util.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "htcs_util.hpp"
namespace ams::htcs::impl {
s32 ConvertResultToErrorCode(const Result result) {
/* Convert success. */
if (R_SUCCEEDED(result)) {
return 0;
}
R_TRY_CATCH(result) {
R_CATCH(htclow::ResultNonBlockingReceiveFailed) { return HTCS_EWOULDBLOCK; }
R_CATCH(htcs::ResultInvalidHandle) { return HTCS_EBADF; }
R_CATCH(htc::ResultUnknown2001) { return HTCS_EINVAL; }
R_CATCH(htc::ResultUnknown2101) { return HTCS_EMFILE; }
R_CATCH(htc::ResultTaskCancelled) { return HTCS_EINTR; }
R_CATCH(htc::ResultInvalidTaskId) { return HTCS_EINTR; }
R_CATCH(htc::ResultCancelled) { return HTCS_EINTR; }
R_CATCH(htc::ResultTaskQueueNotAvailable) { return HTCS_ENETDOWN; }
R_CATCH(htclow::ResultConnectionFailure) { return HTCS_ENETDOWN; }
R_CATCH(htclow::ResultChannelNotExist) { return HTCS_ENOTCONN; }
R_CATCH_ALL() { return HTCS_EUNKNOWN; }
} R_END_TRY_CATCH_WITH_ABORT_UNLESS;
__builtin_unreachable();
}
}
| 1,924
|
C++
|
.cpp
| 39
| 42.717949
| 88
| 0.623936
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,597
|
htcs_rpc_bind_task.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htcs/impl/rpc/htcs_rpc_bind_task.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "htcs_rpc_tasks.hpp"
namespace ams::htcs::impl::rpc {
Result BindTask::SetArguments(s32 handle, const HtcsPeerName &peer_name, const HtcsPortName &port_name) {
/* Set our arguments. */
m_handle = handle;
m_peer_name = peer_name;
m_port_name = port_name;
R_SUCCEED();
}
void BindTask::Complete(htcs::SocketError err) {
/* Set our results. */
m_err = err;
/* Complete. */
HtcsTask::Complete();
}
Result BindTask::GetResult(htcs::SocketError *out_err) const {
/* Sanity check our state. */
AMS_ASSERT(this->GetTaskState() == htc::server::rpc::RpcTaskState::Completed);
/* Set the output. */
*out_err = m_err;
R_SUCCEED();
}
Result BindTask::ProcessResponse(const char *data, size_t size) {
AMS_UNUSED(size);
/* Convert the input to a packet. */
auto *packet = reinterpret_cast<const HtcsRpcPacket *>(data);
/* Complete the task. */
this->Complete(static_cast<htcs::SocketError>(packet->params[0]));
R_SUCCEED();
}
Result BindTask::CreateRequest(size_t *out, char *data, size_t size, u32 task_id) {
AMS_UNUSED(size);
/* Create the packet. */
auto *packet = reinterpret_cast<HtcsRpcPacket *>(data);
*packet = {
.protocol = HtcsProtocol,
.version = this->GetVersion(),
.category = HtcsPacketCategory::Request,
.type = HtcsPacketType::Bind,
.body_size = sizeof(m_peer_name) + sizeof(m_port_name),
.task_id = task_id,
.params = {
m_handle,
},
};
std::memcpy(packet->data + 0, std::addressof(m_peer_name), sizeof(m_peer_name));
std::memcpy(packet->data + sizeof(m_peer_name), std::addressof(m_port_name), sizeof(m_port_name));
/* Set the output size. */
*out = sizeof(*packet) + sizeof(m_peer_name) + sizeof(m_port_name);
R_SUCCEED();
}
}
| 2,730
|
C++
|
.cpp
| 68
| 32.926471
| 109
| 0.615501
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,598
|
htcs_rpc_receive_task.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htcs/impl/rpc/htcs_rpc_receive_task.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "htcs_rpc_tasks.hpp"
namespace ams::htcs::impl::rpc {
Result ReceiveTask::SetArguments(s32 handle, s64 size, htcs::MessageFlag flags) {
/* Check that we're valid. */
R_UNLESS(this->IsValid(), htcs::ResultInvalidTask());
/* Set our arguments. */
m_handle = handle;
m_size = size;
m_flags = flags;
R_SUCCEED();
}
void ReceiveTask::Complete(htcs::SocketError err, s64 size) {
/* Set our results. */
m_err = err;
m_result_size = size;
/* Complete. */
HtcsSignalingTask::Complete();
}
Result ReceiveTask::GetResult(htcs::SocketError *out_err, s64 *out_size) const {
/* Sanity check our state. */
AMS_ASSERT(this->GetTaskState() == htc::server::rpc::RpcTaskState::Completed);
/* Set the output. */
*out_err = m_err;
*out_size = m_result_size;
R_SUCCEED();
}
Result ReceiveTask::ProcessResponse(const char *data, size_t size) {
AMS_UNUSED(size);
/* Convert the input to a packet. */
auto *packet = reinterpret_cast<const HtcsRpcPacket *>(data);
/* Complete the task. */
this->Complete(static_cast<htcs::SocketError>(packet->params[0]), packet->params[1]);
R_SUCCEED();
}
Result ReceiveTask::CreateRequest(size_t *out, char *data, size_t size, u32 task_id) {
AMS_UNUSED(size);
/* Create the packet. */
auto *packet = reinterpret_cast<HtcsRpcPacket *>(data);
*packet = {
.protocol = HtcsProtocol,
.version = this->GetVersion(),
.category = HtcsPacketCategory::Request,
.type = HtcsPacketType::ReceiveLarge,
.body_size = 0,
.task_id = task_id,
.params = {
m_handle,
m_size,
static_cast<s64>(m_flags),
GetReceiveDataChannelId(task_id),
},
};
/* Set the output size. */
*out = sizeof(*packet);
R_SUCCEED();
}
Result ReceiveTask::CreateNotification(size_t *out, char *data, size_t size, u32 task_id) {
AMS_UNUSED(size);
/* Create the packet. */
auto *packet = reinterpret_cast<HtcsRpcPacket *>(data);
*packet = {
.protocol = HtcsProtocol,
.version = this->GetVersion(),
.category = HtcsPacketCategory::Notification,
.type = HtcsPacketType::ReceiveLarge,
.body_size = 0,
.task_id = task_id,
.params = {
/* ... */
},
};
/* Set the output size. */
*out = sizeof(*packet);
R_SUCCEED();
}
}
| 3,447
|
C++
|
.cpp
| 92
| 29.119565
| 95
| 0.579358
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,599
|
htcs_rpc_select_task.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htcs/impl/rpc/htcs_rpc_select_task.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "htcs_rpc_tasks.hpp"
namespace ams::htcs::impl::rpc {
Result SelectTask::SetArguments(Span<const int> read_handles, Span<const int> write_handles, Span<const int> exception_handles, s64 tv_sec, s64 tv_usec) {
/* Check that we're valid. */
R_UNLESS(this->IsValid(), htcs::ResultInvalidTask());
/* Sanity check the spans. */
AMS_ASSERT(read_handles.size() < static_cast<size_t>(SocketCountMax));
AMS_ASSERT(write_handles.size() < static_cast<size_t>(SocketCountMax));
AMS_ASSERT(exception_handles.size() < static_cast<size_t>(SocketCountMax));
/* Set our arguments. */
m_read_handle_count = static_cast<s32>(read_handles.size());
m_write_handle_count = static_cast<s32>(write_handles.size());
m_exception_handle_count = static_cast<s32>(exception_handles.size());
m_tv_sec = tv_sec;
m_tv_usec = tv_usec;
/* Copy the handles. */
std::memcpy(m_handles, read_handles.data(), read_handles.size_bytes());
std::memcpy(m_handles + m_read_handle_count, write_handles.data(), write_handles.size_bytes());
std::memcpy(m_handles + m_read_handle_count + m_write_handle_count, exception_handles.data(), exception_handles.size_bytes());
R_SUCCEED();
}
void SelectTask::Complete(htcs::SocketError err, s32 read_handle_count, s32 write_handle_count, s32 exception_handle_count, const void *body, s64 body_size) {
/* Sanity check the handle counts. */
const auto handle_count = read_handle_count + write_handle_count + exception_handle_count;
AMS_ASSERT(0 <= read_handle_count && read_handle_count < SocketCountMax);
AMS_ASSERT(0 <= write_handle_count && write_handle_count < SocketCountMax);
AMS_ASSERT(0 <= exception_handle_count && exception_handle_count < SocketCountMax);
AMS_ASSERT(handle_count * static_cast<s64>(sizeof(s32)) == body_size);
AMS_UNUSED(handle_count, body_size);
/* Set our results. */
m_err = err;
m_out_read_handle_count = read_handle_count;
m_out_write_handle_count = write_handle_count;
m_out_exception_handle_count = exception_handle_count;
/* Copy the handles. */
std::memcpy(m_out_handles, static_cast<const s32 *>(body), sizeof(s32) * read_handle_count);
std::memcpy(m_out_handles + read_handle_count, static_cast<const s32 *>(body) + read_handle_count, sizeof(s32) * write_handle_count);
std::memcpy(m_out_handles + read_handle_count + write_handle_count, static_cast<const s32 *>(body) + read_handle_count + write_handle_count, sizeof(s32) * exception_handle_count);
/* Complete. */
HtcsSignalingTask::Complete();
}
Result SelectTask::GetResult(htcs::SocketError *out_err, bool *out_empty, Span<int> read_handles, Span<int> write_handles, Span<int> exception_handles) const {
/* Set the output error. */
*out_err = m_err;
/* Set the output empty value. */
const bool empty = m_err == HTCS_ENONE && m_out_read_handle_count == 0 && m_out_write_handle_count == 0 && m_out_exception_handle_count == 0;
*out_empty = empty;
/* Clear the output spans. */
std::fill(read_handles.begin(), read_handles.end(), 0);
std::fill(write_handles.begin(), write_handles.end(), 0);
std::fill(exception_handles.begin(), exception_handles.end(), 0);
/* Copy the handles. */
if (m_err == HTCS_ENONE && !empty) {
const s32 * const out_read_start = m_out_handles;
const s32 * const out_read_end = out_read_start + m_out_read_handle_count;
const s32 * const out_write_start = out_read_end;
const s32 * const out_write_end = out_write_start + m_out_write_handle_count;
const s32 * const out_exception_start = out_write_end;
const s32 * const out_exception_end = out_exception_start + m_out_exception_handle_count;
std::copy(out_read_start, out_read_end, read_handles.begin());
std::copy(out_write_start, out_write_end, write_handles.begin());
std::copy(out_exception_start, out_exception_end, exception_handles.begin());
} else {
const s32 * const read_start = m_handles;
const s32 * const read_end = read_start + m_read_handle_count;
const s32 * const write_start = read_end;
const s32 * const write_end = write_start + m_write_handle_count;
const s32 * const exception_start = write_end;
const s32 * const exception_end = exception_start + m_exception_handle_count;
std::copy(read_start, read_end, read_handles.begin());
std::copy(write_start, write_end, write_handles.begin());
std::copy(exception_start, exception_end, exception_handles.begin());
}
R_SUCCEED();
}
Result SelectTask::ProcessResponse(const char *data, size_t size) {
AMS_UNUSED(size);
/* Convert the input to a packet. */
auto *packet = reinterpret_cast<const HtcsRpcPacket *>(data);
/* Complete the task. */
this->Complete(static_cast<htcs::SocketError>(packet->params[0]), packet->params[1], packet->params[2], packet->params[3], packet->data, size - sizeof(*packet));
R_SUCCEED();
}
Result SelectTask::CreateRequest(size_t *out, char *data, size_t size, u32 task_id) {
AMS_UNUSED(size);
/* Determine the body size. */
const auto handle_count = m_read_handle_count + m_write_handle_count + m_exception_handle_count;
const s64 body_size = static_cast<s64>(handle_count * sizeof(s32));
AMS_ASSERT(sizeof(HtcsRpcPacket) + body_size <= size);
/* Create the packet. */
auto *packet = reinterpret_cast<HtcsRpcPacket *>(data);
*packet = {
.protocol = HtcsProtocol,
.version = this->GetVersion(),
.category = HtcsPacketCategory::Request,
.type = HtcsPacketType::Select,
.body_size = body_size,
.task_id = task_id,
.params = {
m_read_handle_count,
m_write_handle_count,
m_exception_handle_count,
m_tv_sec,
m_tv_usec,
},
};
/* Set the packet body. */
std::memcpy(packet->data, m_handles, body_size);
/* Set the output size. */
*out = sizeof(*packet) + body_size;
R_SUCCEED();
}
}
| 7,507
|
C++
|
.cpp
| 129
| 49.255814
| 187
| 0.606774
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,600
|
htcs_rpc_signaling_task.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htcs/impl/rpc/htcs_rpc_signaling_task.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "htcs_rpc_tasks.hpp"
namespace ams::htcs::impl::rpc {
namespace {
constexpr int MaxEventCount = 0x22;
constinit os::SdkMutex g_event_count_mutex;
constinit int g_event_count = 0;
}
HtcsSignalingTask::HtcsSignalingTask(HtcsTaskType type) : HtcsTask(type), m_is_valid(false) {
/* Acquire the exclusive right to create an event. */
std::scoped_lock lk(g_event_count_mutex);
/* Create an event. */
if (AMS_LIKELY(g_event_count < MaxEventCount)) {
/* Make the event. */
R_ABORT_UNLESS(os::CreateSystemEvent(std::addressof(m_system_event), os::EventClearMode_ManualClear, true));
/* Increment the event count. */
++g_event_count;
/* Mark ourselves as valid. */
m_is_valid = true;
}
}
HtcsSignalingTask::~HtcsSignalingTask() {
/* If we have an event, we need to destroy it. */
if (AMS_LIKELY(m_is_valid)) {
/* Acquire exclusive access to the event count. */
std::scoped_lock lk(g_event_count_mutex);
/* Destroy our event. */
os::DestroySystemEvent(std::addressof(m_system_event));
/* Decrement the event count. */
if ((--g_event_count) < 0) {
g_event_count = 0;
}
}
}
}
| 2,032
|
C++
|
.cpp
| 50
| 33.42
| 120
| 0.634332
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,601
|
htcs_rpc_shutdown_task.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htcs/impl/rpc/htcs_rpc_shutdown_task.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "htcs_rpc_tasks.hpp"
namespace ams::htcs::impl::rpc {
Result ShutdownTask::SetArguments(s32 handle, ShutdownType how) {
/* Set our arguments. */
m_handle = handle;
m_how = how;
R_SUCCEED();
}
void ShutdownTask::Complete(htcs::SocketError err) {
/* Set our results. */
m_err = err;
/* Complete. */
HtcsTask::Complete();
}
Result ShutdownTask::GetResult(htcs::SocketError *out_err) const {
/* Sanity check our state. */
AMS_ASSERT(this->GetTaskState() == htc::server::rpc::RpcTaskState::Completed);
/* Set the output. */
*out_err = m_err;
R_SUCCEED();
}
Result ShutdownTask::ProcessResponse(const char *data, size_t size) {
AMS_UNUSED(size);
/* Convert the input to a packet. */
auto *packet = reinterpret_cast<const HtcsRpcPacket *>(data);
/* Complete the task. */
this->Complete(static_cast<htcs::SocketError>(packet->params[0]));
R_SUCCEED();
}
Result ShutdownTask::CreateRequest(size_t *out, char *data, size_t size, u32 task_id) {
AMS_UNUSED(size);
/* Create the packet. */
auto *packet = reinterpret_cast<HtcsRpcPacket *>(data);
*packet = {
.protocol = HtcsProtocol,
.version = this->GetVersion(),
.category = HtcsPacketCategory::Request,
.type = HtcsPacketType::Shutdown,
.body_size = 0,
.task_id = task_id,
.params = {
m_handle,
static_cast<s64>(m_how),
},
};
/* Set the output size. */
*out = sizeof(*packet);
R_SUCCEED();
}
}
| 2,426
|
C++
|
.cpp
| 66
| 29.469697
| 91
| 0.606914
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,602
|
htcs_rpc_close_task.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htcs/impl/rpc/htcs_rpc_close_task.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "htcs_rpc_tasks.hpp"
namespace ams::htcs::impl::rpc {
Result CloseTask::SetArguments(s32 handle) {
/* Set our arguments. */
m_handle = handle;
R_SUCCEED();
}
void CloseTask::Complete(htcs::SocketError err) {
/* Set our results. */
m_err = err;
/* Complete. */
HtcsTask::Complete();
}
Result CloseTask::GetResult(htcs::SocketError *out_err) const {
/* Sanity check our state. */
AMS_ASSERT(this->GetTaskState() == htc::server::rpc::RpcTaskState::Completed);
/* Set the output. */
*out_err = m_err;
R_SUCCEED();
}
Result CloseTask::ProcessResponse(const char *data, size_t size) {
AMS_UNUSED(size);
/* Convert the input to a packet. */
auto *packet = reinterpret_cast<const HtcsRpcPacket *>(data);
/* Complete the task. */
this->Complete(static_cast<htcs::SocketError>(packet->params[0]));
R_SUCCEED();
}
Result CloseTask::CreateRequest(size_t *out, char *data, size_t size, u32 task_id) {
AMS_UNUSED(size);
/* Create the packet. */
auto *packet = reinterpret_cast<HtcsRpcPacket *>(data);
*packet = {
.protocol = HtcsProtocol,
.version = this->GetVersion(),
.category = HtcsPacketCategory::Request,
.type = HtcsPacketType::Close,
.body_size = 0,
.task_id = task_id,
.params = {
m_handle,
},
};
/* Set the output size. */
*out = sizeof(*packet);
R_SUCCEED();
}
}
| 2,325
|
C++
|
.cpp
| 64
| 29.21875
| 88
| 0.608289
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,603
|
htcs_rpc_connect_task.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htcs/impl/rpc/htcs_rpc_connect_task.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "htcs_rpc_tasks.hpp"
namespace ams::htcs::impl::rpc {
Result ConnectTask::SetArguments(s32 handle, const HtcsPeerName &peer_name, const HtcsPortName &port_name) {
/* Set our arguments. */
m_handle = handle;
m_peer_name = peer_name;
m_port_name = port_name;
R_SUCCEED();
}
void ConnectTask::Complete(htcs::SocketError err) {
/* Set our results. */
m_err = err;
/* Complete. */
HtcsTask::Complete();
}
Result ConnectTask::GetResult(htcs::SocketError *out_err) const {
/* Sanity check our state. */
AMS_ASSERT(this->GetTaskState() == htc::server::rpc::RpcTaskState::Completed);
/* Set the output. */
*out_err = m_err;
R_SUCCEED();
}
Result ConnectTask::ProcessResponse(const char *data, size_t size) {
AMS_UNUSED(size);
/* Convert the input to a packet. */
auto *packet = reinterpret_cast<const HtcsRpcPacket *>(data);
/* Complete the task. */
this->Complete(static_cast<htcs::SocketError>(packet->params[0]));
R_SUCCEED();
}
Result ConnectTask::CreateRequest(size_t *out, char *data, size_t size, u32 task_id) {
AMS_UNUSED(size);
/* Create the packet. */
auto *packet = reinterpret_cast<HtcsRpcPacket *>(data);
*packet = {
.protocol = HtcsProtocol,
.version = this->GetVersion(),
.category = HtcsPacketCategory::Request,
.type = HtcsPacketType::Connect,
.body_size = sizeof(m_peer_name) + sizeof(m_port_name),
.task_id = task_id,
.params = {
m_handle,
},
};
std::memcpy(packet->data + 0, std::addressof(m_peer_name), sizeof(m_peer_name));
std::memcpy(packet->data + sizeof(m_peer_name), std::addressof(m_port_name), sizeof(m_port_name));
/* Set the output size. */
*out = sizeof(*packet) + sizeof(m_peer_name) + sizeof(m_port_name);
R_SUCCEED();
}
}
| 2,748
|
C++
|
.cpp
| 68
| 33.191176
| 112
| 0.6181
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,604
|
htcs_rpc_receive_small_task.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htcs/impl/rpc/htcs_rpc_receive_small_task.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "htcs_rpc_tasks.hpp"
namespace ams::htcs::impl::rpc {
Result ReceiveSmallTask::SetArguments(s32 handle, s64 size, htcs::MessageFlag flags) {
/* Check that we're valid. */
R_UNLESS(this->IsValid(), htcs::ResultInvalidTask());
/* Set our arguments. */
m_handle = handle;
m_size = size;
m_flags = flags;
R_SUCCEED();
}
void ReceiveSmallTask::Complete(htcs::SocketError err, s64 size) {
/* Set our results. */
m_err = err;
m_result_size = size;
/* Complete. */
HtcsSignalingTask::Complete();
}
Result ReceiveSmallTask::GetResult(htcs::SocketError *out_err, s64 *out_size) const {
/* Sanity check our state. */
AMS_ASSERT(this->GetTaskState() == htc::server::rpc::RpcTaskState::Completed);
/* Set the output. */
*out_err = m_err;
*out_size = m_result_size;
R_SUCCEED();
}
Result ReceiveSmallTask::ProcessResponse(const char *data, size_t size) {
AMS_UNUSED(size);
/* Convert the input to a packet. */
auto *packet = reinterpret_cast<const HtcsRpcPacket *>(data);
/* Copy the data to our buffer. */
std::memcpy(m_buffer, packet->data, packet->body_size);
/* Complete the task. */
this->Complete(static_cast<htcs::SocketError>(packet->params[0]), packet->body_size);
R_SUCCEED();
}
Result ReceiveSmallTask::CreateRequest(size_t *out, char *data, size_t size, u32 task_id) {
AMS_UNUSED(size);
/* Create the packet. */
auto *packet = reinterpret_cast<HtcsRpcPacket *>(data);
*packet = {
.protocol = HtcsProtocol,
.version = this->GetVersion(),
.category = HtcsPacketCategory::Request,
.type = HtcsPacketType::Receive,
.body_size = 0,
.task_id = task_id,
.params = {
m_handle,
m_size,
static_cast<s64>(m_flags),
},
};
/* Set the output size. */
*out = sizeof(*packet);
R_SUCCEED();
}
bool ReceiveSmallTask::IsReceiveBufferRequired() {
return true;
}
}
| 2,932
|
C++
|
.cpp
| 77
| 30.506494
| 95
| 0.605996
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,605
|
htcs_rpc_send_small_task.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htcs/impl/rpc/htcs_rpc_send_small_task.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "htcs_rpc_tasks.hpp"
namespace ams::htcs::impl::rpc {
void SendSmallTask::SetBuffer(const void *buffer, s64 buffer_size) {
/* Sanity check the buffer size. */
AMS_ASSERT(0 <= buffer_size && buffer_size <= static_cast<s64>(sizeof(m_buffer)));
/* Set our buffer. */
if (buffer_size > 0) {
std::memcpy(m_buffer, buffer, buffer_size);
}
m_buffer_size = buffer_size;
}
void SendSmallTask::NotifyDataChannelReady() {
/* Notify. */
this->Notify();
/* Signal our ready event. */
m_ready_event.Signal();
}
void SendSmallTask::WaitNotification() {
/* Wait on our ready event. */
m_ready_event.Wait();
}
Result SendSmallTask::SetArguments(s32 handle, s64 size, htcs::MessageFlag flags) {
/* Check that we're valid. */
R_UNLESS(this->IsValid(), htcs::ResultInvalidTask());
/* Set our arguments. */
m_handle = handle;
m_size = size;
m_flags = flags;
R_SUCCEED();
}
void SendSmallTask::Complete(htcs::SocketError err, s64 size) {
/* Set our results. */
m_err = err;
m_result_size = size;
/* Signal our ready event. */
m_ready_event.Signal();
/* Complete. */
HtcsSignalingTask::Complete();
}
Result SendSmallTask::GetResult(htcs::SocketError *out_err, s64 *out_size) const {
/* Sanity check our state. */
AMS_ASSERT(this->GetTaskState() == htc::server::rpc::RpcTaskState::Completed);
/* Set the output. */
*out_err = m_err;
*out_size = m_result_size;
R_SUCCEED();
}
void SendSmallTask::Cancel(htc::server::rpc::RpcTaskCancelReason reason) {
/* Cancel the task. */
HtcsSignalingTask::Cancel(reason);
/* Signal our ready event. */
m_ready_event.Signal();
}
Result SendSmallTask::ProcessResponse(const char *data, size_t size) {
AMS_UNUSED(size);
/* Convert the input to a packet. */
auto *packet = reinterpret_cast<const HtcsRpcPacket *>(data);
/* Complete the task. */
this->Complete(static_cast<htcs::SocketError>(packet->params[0]), this->GetSize());
R_SUCCEED();
}
Result SendSmallTask::CreateRequest(size_t *out, char *data, size_t size, u32 task_id) {
AMS_UNUSED(size);
/* Sanity check our size. */
AMS_ASSERT(sizeof(HtcsRpcPacket) + this->GetBufferSize() <= size);
/* Create the packet. */
auto *packet = reinterpret_cast<HtcsRpcPacket *>(data);
*packet = {
.protocol = HtcsProtocol,
.version = this->GetVersion(),
.category = HtcsPacketCategory::Request,
.type = HtcsPacketType::Send,
.body_size = this->GetSize(),
.task_id = task_id,
.params = {
m_handle,
m_size,
static_cast<s64>(m_flags),
},
};
/* Set the body. */
if (this->GetSize() > 0) {
std::memcpy(packet->data, this->GetBuffer(), this->GetSize());
}
/* Set the output size. */
*out = sizeof(*packet) + this->GetSize();
R_SUCCEED();
}
bool SendSmallTask::IsSendBufferRequired() {
return this->GetSize() > 0;
}
}
| 4,085
|
C++
|
.cpp
| 108
| 29.981481
| 92
| 0.591692
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,606
|
htcs_rpc_send_task.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htcs/impl/rpc/htcs_rpc_send_task.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "htcs_rpc_tasks.hpp"
namespace ams::htcs::impl::rpc {
void SendTask::SetBuffer(const void *buffer, s64 buffer_size) {
/* Set our buffer. */
m_buffer = buffer;
m_buffer_size = buffer_size;
}
void SendTask::NotifyDataChannelReady() {
/* Notify. */
this->Notify();
/* Signal our ready event. */
m_ready_event.Signal();
}
void SendTask::WaitNotification() {
/* Wait on our ready event. */
m_ready_event.Wait();
}
Result SendTask::SetArguments(s32 handle, s64 size, htcs::MessageFlag flags) {
/* Check that we're valid. */
R_UNLESS(this->IsValid(), htcs::ResultInvalidTask());
/* Set our arguments. */
m_handle = handle;
m_size = size;
m_flags = flags;
R_SUCCEED();
}
void SendTask::Complete(htcs::SocketError err, s64 size) {
/* Set our results. */
m_err = err;
m_result_size = size;
/* Signal our ready event. */
m_ready_event.Signal();
/* Complete. */
HtcsSignalingTask::Complete();
}
Result SendTask::GetResult(htcs::SocketError *out_err, s64 *out_size) const {
/* Sanity check our state. */
AMS_ASSERT(this->GetTaskState() == htc::server::rpc::RpcTaskState::Completed);
/* Set the output. */
*out_err = m_err;
*out_size = m_result_size;
R_SUCCEED();
}
void SendTask::Cancel(htc::server::rpc::RpcTaskCancelReason reason) {
/* Cancel the task. */
HtcsSignalingTask::Cancel(reason);
/* Signal our ready event. */
m_ready_event.Signal();
}
Result SendTask::ProcessResponse(const char *data, size_t size) {
AMS_UNUSED(size);
/* Convert the input to a packet. */
auto *packet = reinterpret_cast<const HtcsRpcPacket *>(data);
/* Complete the task. */
this->Complete(static_cast<htcs::SocketError>(packet->params[0]), packet->params[1]);
R_SUCCEED();
}
Result SendTask::CreateRequest(size_t *out, char *data, size_t size, u32 task_id) {
AMS_UNUSED(size);
/* Create the packet. */
auto *packet = reinterpret_cast<HtcsRpcPacket *>(data);
*packet = {
.protocol = HtcsProtocol,
.version = this->GetVersion(),
.category = HtcsPacketCategory::Request,
.type = HtcsPacketType::SendLarge,
.body_size = 0,
.task_id = task_id,
.params = {
m_handle,
m_size,
static_cast<s64>(m_flags),
GetSendDataChannelId(task_id),
},
};
/* Set the output size. */
*out = sizeof(*packet);
R_SUCCEED();
}
Result SendTask::ProcessNotification(const char *data, size_t size) {
AMS_UNUSED(data, size);
this->NotifyDataChannelReady();
R_SUCCEED();
}
Result SendTask::CreateNotification(size_t *out, char *data, size_t size, u32 task_id) {
AMS_UNUSED(size);
/* Create the packet. */
auto *packet = reinterpret_cast<HtcsRpcPacket *>(data);
*packet = {
.protocol = HtcsProtocol,
.version = this->GetVersion(),
.category = HtcsPacketCategory::Notification,
.type = HtcsPacketType::SendLarge,
.body_size = 0,
.task_id = task_id,
.params = {
/* ... */
},
};
/* Set the output size. */
*out = sizeof(*packet);
R_SUCCEED();
}
}
| 4,352
|
C++
|
.cpp
| 120
| 28.025
| 93
| 0.576529
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,607
|
htcs_rpc_socket_task.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htcs/impl/rpc/htcs_rpc_socket_task.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "htcs_rpc_tasks.hpp"
namespace ams::htcs::impl::rpc {
namespace {
constinit s16 g_protocol_version = HtcsMaxVersion;
}
HtcsTask::HtcsTask(HtcsTaskType type) : m_task_type(type), m_version(g_protocol_version) {
/* ... */
}
Result SocketTask::SetArguments() {
R_SUCCEED();
}
void SocketTask::Complete(htcs::SocketError err, s32 desc) {
/* Set our results. */
m_err = err;
m_desc = desc;
/* Complete. */
HtcsTask::Complete();
}
Result SocketTask::GetResult(htcs::SocketError *out_err, s32 *out_desc) const {
/* Sanity check our state. */
AMS_ASSERT(this->GetTaskState() == htc::server::rpc::RpcTaskState::Completed);
/* Set the output. */
*out_err = m_err;
*out_desc = m_desc;
R_SUCCEED();
}
Result SocketTask::ProcessResponse(const char *data, size_t size) {
AMS_UNUSED(size);
/* Convert the input to a packet. */
auto *packet = reinterpret_cast<const HtcsRpcPacket *>(data);
/* Update the global protocol version. */
g_protocol_version = std::min(g_protocol_version, packet->version);
/* Complete the task. */
this->Complete(static_cast<htcs::SocketError>(packet->params[0]), packet->params[1]);
R_SUCCEED();
}
Result SocketTask::CreateRequest(size_t *out, char *data, size_t size, u32 task_id) {
AMS_UNUSED(size);
/* Create the packet. */
auto *packet = reinterpret_cast<HtcsRpcPacket *>(data);
*packet = {
.protocol = HtcsProtocol,
.version = 3,
.category = HtcsPacketCategory::Request,
.type = HtcsPacketType::Socket,
.body_size = 0,
.task_id = task_id,
.params = {
/* ... */
},
};
/* Set the output size. */
*out = sizeof(*packet);
R_SUCCEED();
}
}
| 2,669
|
C++
|
.cpp
| 72
| 29.916667
| 94
| 0.607919
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,608
|
htcs_rpc_accept_task.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htcs/impl/rpc/htcs_rpc_accept_task.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "htcs_rpc_tasks.hpp"
namespace ams::htcs::impl::rpc {
Result AcceptTask::SetArguments(s32 server_handle) {
/* Check that we're valid. */
R_UNLESS(this->IsValid(), htcs::ResultInvalidTask());
/* Set our arguments. */
m_server_handle = server_handle;
R_SUCCEED();
}
void AcceptTask::Complete(htcs::SocketError err, s32 desc) {
/* Set our results. */
m_err = err;
m_desc = desc;
/* Complete. */
HtcsSignalingTask::Complete();
}
Result AcceptTask::GetResult(htcs::SocketError *out_err, s32 *out_desc, s32 server_handle) const {
/* Check the server handle. */
R_UNLESS(m_server_handle == server_handle, htcs::ResultInvalidServerHandle());
/* Sanity check our state. */
AMS_ASSERT(this->GetTaskState() == htc::server::rpc::RpcTaskState::Completed);
/* Set the output. */
*out_err = m_err;
*out_desc = m_desc;
R_SUCCEED();
}
Result AcceptTask::ProcessResponse(const char *data, size_t size) {
AMS_UNUSED(size);
/* Convert the input to a packet. */
auto *packet = reinterpret_cast<const HtcsRpcPacket *>(data);
/* Complete the task. */
this->Complete(static_cast<htcs::SocketError>(packet->params[0]), packet->params[1]);
R_SUCCEED();
}
Result AcceptTask::CreateRequest(size_t *out, char *data, size_t size, u32 task_id) {
AMS_UNUSED(size);
/* Create the packet. */
auto *packet = reinterpret_cast<HtcsRpcPacket *>(data);
*packet = {
.protocol = HtcsProtocol,
.version = this->GetVersion(),
.category = HtcsPacketCategory::Request,
.type = HtcsPacketType::Accept,
.body_size = 0,
.task_id = task_id,
.params = {
m_server_handle,
},
};
/* Set the output size. */
*out = sizeof(*packet);
R_SUCCEED();
}
}
| 2,710
|
C++
|
.cpp
| 70
| 31.414286
| 102
| 0.613506
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,609
|
htcs_rpc_fcntl_task.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htcs/impl/rpc/htcs_rpc_fcntl_task.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "htcs_rpc_tasks.hpp"
namespace ams::htcs::impl::rpc {
Result FcntlTask::SetArguments(s32 handle, s32 command, s32 value) {
/* Set our arguments. */
m_handle = handle;
m_command = command;
m_value = value;
R_SUCCEED();
}
void FcntlTask::Complete(htcs::SocketError err, s32 res) {
/* Set our results. */
m_err = err;
m_res = res;
/* Complete. */
HtcsTask::Complete();
}
Result FcntlTask::GetResult(htcs::SocketError *out_err, s32 *out_res) const {
/* Sanity check our state. */
AMS_ASSERT(this->GetTaskState() == htc::server::rpc::RpcTaskState::Completed);
/* Set the output. */
*out_err = m_err;
*out_res = m_res;
R_SUCCEED();
}
Result FcntlTask::ProcessResponse(const char *data, size_t size) {
AMS_UNUSED(size);
/* Convert the input to a packet. */
auto *packet = reinterpret_cast<const HtcsRpcPacket *>(data);
/* Complete the task. */
this->Complete(static_cast<htcs::SocketError>(packet->params[0]), packet->params[1]);
R_SUCCEED();
}
Result FcntlTask::CreateRequest(size_t *out, char *data, size_t size, u32 task_id) {
AMS_UNUSED(size);
/* Create the packet. */
auto *packet = reinterpret_cast<HtcsRpcPacket *>(data);
*packet = {
.protocol = HtcsProtocol,
.version = this->GetVersion(),
.category = HtcsPacketCategory::Request,
.type = HtcsPacketType::Fcntl,
.body_size = 0,
.task_id = task_id,
.params = {
m_handle,
m_command,
m_value,
},
};
/* Set the output size. */
*out = sizeof(*packet);
R_SUCCEED();
}
}
| 2,545
|
C++
|
.cpp
| 70
| 28.857143
| 93
| 0.597234
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,610
|
htcs_rpc_listen_task.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htcs/impl/rpc/htcs_rpc_listen_task.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "htcs_rpc_tasks.hpp"
namespace ams::htcs::impl::rpc {
Result ListenTask::SetArguments(s32 handle, s32 backlog) {
/* Set our arguments. */
m_handle = handle;
m_backlog = backlog;
R_SUCCEED();
}
void ListenTask::Complete(htcs::SocketError err) {
/* Set our results. */
m_err = err;
/* Complete. */
HtcsTask::Complete();
}
Result ListenTask::GetResult(htcs::SocketError *out_err) const {
/* Sanity check our state. */
AMS_ASSERT(this->GetTaskState() == htc::server::rpc::RpcTaskState::Completed);
/* Set the output. */
*out_err = m_err;
R_SUCCEED();
}
Result ListenTask::ProcessResponse(const char *data, size_t size) {
AMS_UNUSED(size);
/* Convert the input to a packet. */
auto *packet = reinterpret_cast<const HtcsRpcPacket *>(data);
/* Complete the task. */
this->Complete(static_cast<htcs::SocketError>(packet->params[0]));
R_SUCCEED();
}
Result ListenTask::CreateRequest(size_t *out, char *data, size_t size, u32 task_id) {
AMS_UNUSED(size);
/* Create the packet. */
auto *packet = reinterpret_cast<HtcsRpcPacket *>(data);
*packet = {
.protocol = HtcsProtocol,
.version = this->GetVersion(),
.category = HtcsPacketCategory::Request,
.type = HtcsPacketType::Listen,
.body_size = 0,
.task_id = task_id,
.params = {
m_handle,
m_backlog,
},
};
/* Set the output size. */
*out = sizeof(*packet);
R_SUCCEED();
}
}
| 2,401
|
C++
|
.cpp
| 66
| 29.090909
| 89
| 0.605695
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,611
|
htcs_data_channel_manager.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htcs/impl/rpc/htcs_data_channel_manager.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "htcs_rpc_tasks.hpp"
#include "htcs_data_channel_manager.hpp"
#include "../../../htclow/htclow_channel.hpp"
namespace ams::htcs::impl::rpc {
Result DataChannelManager::Receive(void *buffer, s64 buffer_size, u32 task_id) {
/* Check that the buffer size is allowable. */
R_UNLESS(util::IsIntValueRepresentable<size_t>(buffer_size), htcs::ResultInvalidSize());
/* Create an htclow channel. */
htclow::Channel channel(m_htclow_manager);
/* Open the channel. */
R_ABORT_UNLESS(channel.Open(std::addressof(m_module), GetReceiveDataChannelId(task_id)));
/* Ensure that we close the channel, when we're done. */
ON_SCOPE_EXIT { channel.Close(); };
/* Set the channel config. */
constexpr htclow::ChannelConfig BulkReceiveConfig = {
.flow_control_enabled = false,
.handshake_enabled = false,
.max_packet_size = 0x3E000,
};
channel.SetConfig(BulkReceiveConfig);
/* Set the receive buffer. */
channel.SetReceiveBuffer(buffer, buffer_size);
/* Connect the channel. */
R_TRY(channel.Connect());
/* Ensure that we clean up when we're done. */
ON_SCOPE_EXIT { channel.Shutdown(); };
/* Notify the receive task. */
R_TRY(m_rpc_client->Notify<ReceiveTask>(task_id));
/* Wait to receive the data. */
R_TRY(channel.WaitReceive(buffer_size));
R_SUCCEED();
}
Result DataChannelManager::Send(const void *buffer, s64 buffer_size, u32 task_id) {
/* Check that the buffer size is allowable. */
R_UNLESS(util::IsIntValueRepresentable<size_t>(buffer_size), htcs::ResultInvalidSize());
/* Create an htclow channel. */
htclow::Channel channel(m_htclow_manager);
/* Open the channel. */
R_ABORT_UNLESS(channel.Open(std::addressof(m_module), GetSendDataChannelId(task_id)));
/* Ensure that we close the channel, when we're done. */
ON_SCOPE_EXIT { channel.Close(); };
/* Set the channel config. */
constexpr htclow::ChannelConfig BulkSendConfig = {
.flow_control_enabled = false,
.handshake_enabled = false,
.max_packet_size = 0x3E000,
};
channel.SetConfig(BulkSendConfig);
/* Set the send buffer. */
channel.SetSendBufferWithData(buffer, buffer_size);
/* Connect the channel. */
R_TRY(channel.Connect());
/* Ensure that we clean up when we're done. */
ON_SCOPE_EXIT { channel.Shutdown(); };
/* Wait to send the data. */
R_TRY(channel.Flush());
R_SUCCEED();
}
}
| 3,382
|
C++
|
.cpp
| 75
| 37.733333
| 97
| 0.6419
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,612
|
htcs_hipc_server.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htcs/server/htcs_hipc_server.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "htcs_manager_service_object.hpp"
namespace ams::htcs::server {
namespace {
static constexpr inline size_t NumServers = 1;
static constexpr inline size_t MaxSessions = 63;
static constexpr inline sm::ServiceName ServiceName = sm::ServiceName::Encode("htcs");
struct ServerOptions {
static constexpr size_t PointerBufferSize = 0x80;
static constexpr size_t MaxDomains = 0x10;
static constexpr size_t MaxDomainObjects = 100;
static constexpr bool CanDeferInvokeRequest = false;
static constexpr bool CanManageMitmServers = false;
};
using ServerManager = sf::hipc::ServerManager<NumServers, ServerOptions, MaxSessions>;
/* Service object. */
ServerManager g_server_manager;
/* Service object. */
constinit sf::UnmanagedServiceObject<tma::IHtcsManager, ManagerServiceObject> g_htcs_service_object;
}
void Initialize() {
/* Add a reference to the htcs manager. */
htcs::impl::HtcsManagerHolder::AddReference();
}
void RegisterHipcServer() {
/* Register the service. */
R_ABORT_UNLESS(g_server_manager.RegisterObjectForServer(g_htcs_service_object.GetShared(), ServiceName, MaxSessions));
}
void LoopHipcServer() {
/* Loop, servicing services. */
g_server_manager.LoopProcess();
}
}
| 2,116
|
C++
|
.cpp
| 48
| 37.958333
| 126
| 0.687743
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,613
|
htcs_manager_service_object_deprecated.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htcs/server/htcs_manager_service_object_deprecated.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "htcs_manager_service_object.hpp"
#include "htcs_socket_service_object.hpp"
namespace ams::htcs::server {
#define AMS_HTCS_MANAGER_DEPRECATED_API(...) ({ AMS_UNUSED(__VA_ARGS__); AMS_ABORT("Deprecated IHtcsManager API %s was called.\n", AMS_CURRENT_FUNCTION_NAME); })
Result ManagerServiceObject::Socket(sf::Out<s32> out_err, sf::Out<s32> out_sock) {
/* NOTE: This is a deprecated API, and Nintendo aborts when it is called. */
AMS_HTCS_MANAGER_DEPRECATED_API(out_err, out_sock);
}
Result ManagerServiceObject::Close(sf::Out<s32> out_err, sf::Out<s32> out_res, s32 desc) {
/* NOTE: This is a deprecated API, and Nintendo aborts when it is called. */
AMS_HTCS_MANAGER_DEPRECATED_API(out_err, out_res, desc);
}
Result ManagerServiceObject::Connect(sf::Out<s32> out_err, sf::Out<s32> out_res, s32 desc, const htcs::SockAddrHtcs &address) {
/* NOTE: This is a deprecated API, and Nintendo aborts when it is called. */
AMS_HTCS_MANAGER_DEPRECATED_API(out_err, out_res, desc, address);
}
Result ManagerServiceObject::Bind(sf::Out<s32> out_err, sf::Out<s32> out_res, s32 desc, const htcs::SockAddrHtcs &address) {
/* NOTE: This is a deprecated API, and Nintendo aborts when it is called. */
AMS_HTCS_MANAGER_DEPRECATED_API(out_err, out_res, desc, address);
}
Result ManagerServiceObject::Listen(sf::Out<s32> out_err, sf::Out<s32> out_res, s32 desc, s32 backlog_count) {
/* NOTE: This is a deprecated API, and Nintendo aborts when it is called. */
AMS_HTCS_MANAGER_DEPRECATED_API(out_err, out_res, desc, backlog_count);
}
Result ManagerServiceObject::Accept(sf::Out<s32> out_err, sf::Out<s32> out_res, sf::Out<htcs::SockAddrHtcs> out_address, s32 desc) {
/* NOTE: This is a deprecated API, and Nintendo aborts when it is called. */
AMS_HTCS_MANAGER_DEPRECATED_API(out_err, out_res, out_address, desc);
}
Result ManagerServiceObject::Recv(sf::Out<s32> out_err, sf::Out<s64> out_size, const sf::OutBuffer &buffer, s32 desc, s32 flags) {
/* NOTE: This is a deprecated API, and Nintendo aborts when it is called. */
AMS_HTCS_MANAGER_DEPRECATED_API(out_err, out_size, buffer, desc, flags);
}
Result ManagerServiceObject::Send(sf::Out<s32> out_err, sf::Out<s64> out_size, s32 desc, const sf::InBuffer &buffer, s32 flags) {
/* NOTE: This is a deprecated API, and Nintendo aborts when it is called. */
AMS_HTCS_MANAGER_DEPRECATED_API(out_err, out_size, desc, buffer, flags);
}
Result ManagerServiceObject::Shutdown(sf::Out<s32> out_err, sf::Out<s32> out_res, s32 desc, s32 how) {
/* NOTE: This is a deprecated API, and Nintendo aborts when it is called. */
AMS_HTCS_MANAGER_DEPRECATED_API(out_err, out_res, desc, how);
}
Result ManagerServiceObject::Fcntl(sf::Out<s32> out_err, sf::Out<s32> out_res, s32 desc, s32 command, s32 value) {
/* NOTE: This is a deprecated API, and Nintendo aborts when it is called. */
AMS_HTCS_MANAGER_DEPRECATED_API(out_err, out_res, desc, command, value);
}
}
| 3,803
|
C++
|
.cpp
| 61
| 56.901639
| 165
| 0.695093
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,614
|
htcs_socket_service_object_deprecated.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htcs/server/htcs_socket_service_object_deprecated.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "htcs_manager_service_object.hpp"
#include "htcs_socket_service_object.hpp"
namespace ams::htcs::server {
#define AMS_HTCS_MANAGER_DEPRECATED_API(...) ({ AMS_UNUSED(__VA_ARGS__); AMS_ABORT("Deprecated IHtcsManager API %s was called.\n", AMS_CURRENT_FUNCTION_NAME); })
Result SocketServiceObject::Accept(sf::Out<s32> out_err, sf::Out<sf::SharedPointer<tma::ISocket>> out, sf::Out<htcs::SockAddrHtcs> out_address) {
/* NOTE: This is a deprecated API, and Nintendo aborts when it is called. */
AMS_HTCS_MANAGER_DEPRECATED_API(out_err, out, out_address);
}
}
| 1,259
|
C++
|
.cpp
| 25
| 47.52
| 165
| 0.734959
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,615
|
htcs_manager_service_object.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htcs/server/htcs_manager_service_object.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "htcs_manager_service_object.hpp"
#include "htcs_socket_service_object.hpp"
#include "htcs_service_object_allocator.hpp"
#include "../impl/htcs_manager.hpp"
#include "../impl/htcs_impl.hpp"
namespace ams::htcs::server {
namespace {
class StaticAllocatorInitializer {
public:
StaticAllocatorInitializer() {
ServiceObjectAllocator::Initialize(lmem::CreateOption_ThreadSafe);
}
} g_static_allocator_initializer;
}
Result ManagerServiceObject::GetPeerNameAny(sf::Out<htcs::HtcsPeerName> out) {
*out = impl::GetPeerNameAny();
R_SUCCEED();
}
Result ManagerServiceObject::GetDefaultHostName(sf::Out<htcs::HtcsPeerName> out) {
*out = impl::GetDefaultHostName();
R_SUCCEED();
}
Result ManagerServiceObject::CreateSocketOld(sf::Out<s32> out_err, sf::Out<sf::SharedPointer<tma::ISocket>> out) {
R_RETURN(this->CreateSocket(out_err, out, false));
}
Result ManagerServiceObject::CreateSocket(sf::Out<s32> out_err, sf::Out<sf::SharedPointer<tma::ISocket>> out, bool enable_disconnection_emulation) {
/* Get the htcs manager. */
auto *manager = impl::HtcsManagerHolder::GetHtcsManager();
/* Create a new socket. */
s32 desc;
manager->Socket(out_err.GetPointer(), std::addressof(desc), enable_disconnection_emulation);
/* If an error occurred, we're done. */
R_SUCCEED_IF(*out_err != 0);
/* Create a new socket object. */
*out = ServiceObjectFactory::CreateSharedEmplaced<tma::ISocket, SocketServiceObject>(this, desc);
R_SUCCEED();
}
Result ManagerServiceObject::RegisterProcessId(const sf::ClientProcessId &client_pid) {
/* NOTE: Nintendo does nothing here. */
AMS_UNUSED(client_pid);
R_SUCCEED();
}
Result ManagerServiceObject::MonitorManager(const sf::ClientProcessId &client_pid) {
/* NOTE: Nintendo does nothing here. */
AMS_UNUSED(client_pid);
R_SUCCEED();
}
Result ManagerServiceObject::StartSelect(sf::Out<u32> out_task_id, sf::OutCopyHandle out_event, const sf::InMapAliasArray<s32> &read_handles, const sf::InMapAliasArray<s32> &write_handles, const sf::InMapAliasArray<s32> &exception_handles, s64 tv_sec, s64 tv_usec) {
/* Get the htcs manager. */
auto *manager = impl::HtcsManagerHolder::GetHtcsManager();
/* Start the select. */
os::NativeHandle event_handle;
R_TRY(manager->StartSelect(out_task_id.GetPointer(), std::addressof(event_handle), read_handles.ToSpan(), write_handles.ToSpan(), exception_handles.ToSpan(), tv_sec, tv_usec));
/* Set the output event handle. */
out_event.SetValue(event_handle, true);
R_SUCCEED();
}
Result ManagerServiceObject::EndSelect(sf::Out<s32> out_err, sf::Out<s32> out_count, const sf::OutMapAliasArray<s32> &read_handles, const sf::OutMapAliasArray<s32> &write_handles, const sf::OutMapAliasArray<s32> &exception_handles, u32 task_id) {
/* Get the htcs manager. */
auto *manager = impl::HtcsManagerHolder::GetHtcsManager();
/* End the select. */
R_RETURN(manager->EndSelect(out_err.GetPointer(), out_count.GetPointer(), read_handles.ToSpan(), write_handles.ToSpan(), exception_handles.ToSpan(), task_id));
}
}
| 4,054
|
C++
|
.cpp
| 80
| 44.05
| 270
| 0.684876
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,616
|
htcs_socket_service_object.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htcs/server/htcs_socket_service_object.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "htcs_socket_service_object.hpp"
#include "htcs_service_object_allocator.hpp"
#include "../impl/htcs_manager.hpp"
namespace ams::htcs::server {
SocketServiceObject::SocketServiceObject(ManagerServiceObject *manager, s32 desc) : m_manager(manager, true), m_desc(desc) {
/* ... */
}
SocketServiceObject::~SocketServiceObject() {
/* Get the htcs manager. */
auto *manager = impl::HtcsManagerHolder::GetHtcsManager();
/* Close the underlying socket. */
s32 dummy_err, dummy_res;
manager->Close(std::addressof(dummy_err), std::addressof(dummy_res), m_desc);
}
Result SocketServiceObject::Close(sf::Out<s32> out_err, sf::Out<s32> out_res) {
/* Get the htcs manager. */
auto *manager = impl::HtcsManagerHolder::GetHtcsManager();
/* Close the underlying socket. */
manager->Close(out_err.GetPointer(), out_res.GetPointer(), m_desc);
R_SUCCEED();
}
Result SocketServiceObject::Connect(sf::Out<s32> out_err, sf::Out<s32> out_res, const htcs::SockAddrHtcs &address) {
/* Get the htcs manager. */
auto *manager = impl::HtcsManagerHolder::GetHtcsManager();
/* Perform the connect. */
manager->Connect(out_err.GetPointer(), out_res.GetPointer(), address, m_desc);
R_SUCCEED();
}
Result SocketServiceObject::Bind(sf::Out<s32> out_err, sf::Out<s32> out_res, const htcs::SockAddrHtcs &address) {
/* Get the htcs manager. */
auto *manager = impl::HtcsManagerHolder::GetHtcsManager();
/* Perform the bind. */
manager->Bind(out_err.GetPointer(), out_res.GetPointer(), address, m_desc);
R_SUCCEED();
}
Result SocketServiceObject::Listen(sf::Out<s32> out_err, sf::Out<s32> out_res, s32 backlog_count) {
/* Get the htcs manager. */
auto *manager = impl::HtcsManagerHolder::GetHtcsManager();
/* Perform the listen. */
manager->Listen(out_err.GetPointer(), out_res.GetPointer(), backlog_count, m_desc);
R_SUCCEED();
}
Result SocketServiceObject::Recv(sf::Out<s32> out_err, sf::Out<s64> out_size, const sf::OutAutoSelectBuffer &buffer, s32 flags) {
/* Get the htcs manager. */
auto *manager = impl::HtcsManagerHolder::GetHtcsManager();
/* Perform the recv. */
manager->Recv(out_err.GetPointer(), out_size.GetPointer(), reinterpret_cast<char *>(buffer.GetPointer()), buffer.GetSize(), flags, m_desc);
R_SUCCEED();
}
Result SocketServiceObject::Send(sf::Out<s32> out_err, sf::Out<s64> out_size, const sf::InAutoSelectBuffer &buffer, s32 flags) {
/* Get the htcs manager. */
auto *manager = impl::HtcsManagerHolder::GetHtcsManager();
/* Perform the send. */
manager->Send(out_err.GetPointer(), out_size.GetPointer(), reinterpret_cast<const char *>(buffer.GetPointer()), buffer.GetSize(), flags, m_desc);
R_SUCCEED();
}
Result SocketServiceObject::Shutdown(sf::Out<s32> out_err, sf::Out<s32> out_res, s32 how) {
/* Get the htcs manager. */
auto *manager = impl::HtcsManagerHolder::GetHtcsManager();
/* Perform the shutdown. */
manager->Shutdown(out_err.GetPointer(), out_res.GetPointer(), how, m_desc);
R_SUCCEED();
}
Result SocketServiceObject::Fcntl(sf::Out<s32> out_err, sf::Out<s32> out_res, s32 command, s32 value) {
/* Get the htcs manager. */
auto *manager = impl::HtcsManagerHolder::GetHtcsManager();
/* Perform the fcntl. */
manager->Fcntl(out_err.GetPointer(), out_res.GetPointer(), command, value, m_desc);
R_SUCCEED();
}
Result SocketServiceObject::AcceptStart(sf::Out<u32> out_task_id, sf::OutCopyHandle out_event) {
/* Get the htcs manager. */
auto *manager = impl::HtcsManagerHolder::GetHtcsManager();
/* Start the accept. */
os::NativeHandle event_handle;
R_TRY(manager->AcceptStart(out_task_id.GetPointer(), std::addressof(event_handle), m_desc));
/* Set the output event handle. */
out_event.SetValue(event_handle, true);
R_SUCCEED();
}
Result SocketServiceObject::AcceptResults(sf::Out<s32> out_err, sf::Out<sf::SharedPointer<tma::ISocket>> out, sf::Out<htcs::SockAddrHtcs> out_address, u32 task_id) {
/* Get the htcs manager. */
auto *manager = impl::HtcsManagerHolder::GetHtcsManager();
/* Get the accept results. */
s32 desc = -1;
manager->AcceptResults(out_err.GetPointer(), std::addressof(desc), out_address.GetPointer(), task_id, m_desc);
/* If an error occurred, we're done. */
R_SUCCEED_IF(*out_err != 0);
/* Create a new socket object. */
*out = ServiceObjectFactory::CreateSharedEmplaced<tma::ISocket, SocketServiceObject>(m_manager.Get(), desc);
R_SUCCEED();
}
Result SocketServiceObject::RecvStart(sf::Out<u32> out_task_id, sf::OutCopyHandle out_event, s32 mem_size, s32 flags) {
/* Get the htcs manager. */
auto *manager = impl::HtcsManagerHolder::GetHtcsManager();
/* Start the recv. */
os::NativeHandle event_handle;
R_TRY(manager->RecvStart(out_task_id.GetPointer(), std::addressof(event_handle), mem_size, m_desc, flags));
/* Set the output event handle. */
out_event.SetValue(event_handle, true);
R_SUCCEED();
}
Result SocketServiceObject::RecvResults(sf::Out<s32> out_err, sf::Out<s64> out_size, const sf::OutAutoSelectBuffer &buffer, u32 task_id) {
/* Get the htcs manager. */
auto *manager = impl::HtcsManagerHolder::GetHtcsManager();
/* Get the recv results. */
manager->RecvResults(out_err.GetPointer(), out_size.GetPointer(), reinterpret_cast<char *>(buffer.GetPointer()), buffer.GetSize(), task_id, m_desc);
R_SUCCEED();
}
Result SocketServiceObject::RecvLargeStart(sf::Out<u32> out_task_id, sf::OutCopyHandle out_event, s32 unaligned_size_start, s32 unaligned_size_end, s64 aligned_size, sf::CopyHandle &&mem_handle, s32 flags) {
/* Check that the transfer memory size is okay. */
R_UNLESS(util::IsIntValueRepresentable<size_t>(aligned_size), htcs::ResultInvalidSize());
/* Attach the transfer memory. */
os::TransferMemoryType tmem;
os::AttachTransferMemory(std::addressof(tmem), static_cast<size_t>(aligned_size), mem_handle.GetOsHandle(), mem_handle.IsManaged());
mem_handle.Detach();
ON_SCOPE_EXIT { os::DestroyTransferMemory(std::addressof(tmem)); };
/* Map the transfer memory. */
void *address;
R_TRY(os::MapTransferMemory(std::addressof(address), std::addressof(tmem), os::MemoryPermission_None));
ON_SCOPE_EXIT { os::UnmapTransferMemory(std::addressof(tmem)); };
/* Get the htcs manager. */
auto *manager = impl::HtcsManagerHolder::GetHtcsManager();
/* Start the large receive. */
os::NativeHandle event_handle;
R_TRY(manager->RecvStart(out_task_id.GetPointer(), std::addressof(event_handle), unaligned_size_start + aligned_size + unaligned_size_end, m_desc, flags));
/* Set the output event handle. */
out_event.SetValue(event_handle, true);
R_SUCCEED();
}
Result SocketServiceObject::SendStartOld(sf::Out<u32> out_task_id, sf::OutCopyHandle out_event, const sf::InAutoSelectBuffer &buffer, s32 flags) {
R_RETURN(this->SendStart(out_task_id, out_event, sf::InNonSecureAutoSelectBuffer(buffer.GetPointer(), buffer.GetSize()), flags));
}
Result SocketServiceObject::SendLargeStart(sf::Out<u32> out_task_id, sf::OutCopyHandle out_event, const sf::InAutoSelectBuffer &start_buffer, const sf::InAutoSelectBuffer &end_buffer, sf::CopyHandle &&mem_handle, s64 aligned_size, s32 flags) {
/* Check that the sizes are okay. */
R_UNLESS(util::IsIntValueRepresentable<s64>(start_buffer.GetSize()), htcs::ResultInvalidSize());
R_UNLESS(util::IsIntValueRepresentable<s64>(end_buffer.GetSize()), htcs::ResultInvalidSize());
R_UNLESS(util::IsIntValueRepresentable<size_t>(aligned_size), htcs::ResultInvalidSize());
/* Attach the transfer memory. */
os::TransferMemoryType tmem;
os::AttachTransferMemory(std::addressof(tmem), static_cast<size_t>(aligned_size), mem_handle.GetOsHandle(), mem_handle.IsManaged());
mem_handle.Detach();
ON_SCOPE_EXIT { os::DestroyTransferMemory(std::addressof(tmem)); };
/* Map the transfer memory. */
void *address;
R_TRY(os::MapTransferMemory(std::addressof(address), std::addressof(tmem), os::MemoryPermission_None));
ON_SCOPE_EXIT { os::UnmapTransferMemory(std::addressof(tmem)); };
/* Get the htcs manager. */
auto *manager = impl::HtcsManagerHolder::GetHtcsManager();
/* Start the large send. */
constexpr auto NumBuffers = 3;
const char *pointers[NumBuffers] = { reinterpret_cast<const char *>(start_buffer.GetPointer()), static_cast<const char *>(address), reinterpret_cast<const char *>(end_buffer.GetPointer()) };
s64 sizes[NumBuffers] = { static_cast<s64>(start_buffer.GetSize()), aligned_size, static_cast<s64>(end_buffer.GetSize()) };
os::NativeHandle event_handle;
R_TRY(manager->SendLargeStart(out_task_id.GetPointer(), std::addressof(event_handle), pointers, sizes, NumBuffers, m_desc, flags));
/* Set the output event handle. */
out_event.SetValue(event_handle, true);
R_SUCCEED();
}
Result SocketServiceObject::SendResults(sf::Out<s32> out_err, sf::Out<s64> out_size, u32 task_id) {
/* Get the htcs manager. */
auto *manager = impl::HtcsManagerHolder::GetHtcsManager();
/* Get the send results. */
manager->SendResults(out_err.GetPointer(), out_size.GetPointer(), task_id, m_desc);
R_SUCCEED();
}
Result SocketServiceObject::StartSend(sf::Out<u32> out_task_id, sf::OutCopyHandle out_event, sf::Out<s64> out_max_size, s64 size, s32 flags) {
/* Get the htcs manager. */
auto *manager = impl::HtcsManagerHolder::GetHtcsManager();
/* Start the send. */
os::NativeHandle event_handle;
R_TRY(manager->StartSend(out_task_id.GetPointer(), std::addressof(event_handle), m_desc, size, flags));
/* Set the output max size to the size. */
*out_max_size = size;
/* Set the output event handle. */
out_event.SetValue(event_handle, true);
R_SUCCEED();
}
Result SocketServiceObject::ContinueSendOld(sf::Out<s64> out_size, sf::Out<bool> out_wait, const sf::InAutoSelectBuffer &buffer, u32 task_id) {
R_RETURN(this->ContinueSend(out_size, out_wait, sf::InNonSecureAutoSelectBuffer(buffer.GetPointer(), buffer.GetSize()), task_id));
}
Result SocketServiceObject::EndSend(sf::Out<s32> out_err, sf::Out<s64> out_size, u32 task_id) {
/* Get the htcs manager. */
auto *manager = impl::HtcsManagerHolder::GetHtcsManager();
/* End the send. */
manager->EndSend(out_err.GetPointer(), out_size.GetPointer(), task_id, m_desc);
R_SUCCEED();
}
Result SocketServiceObject::StartRecv(sf::Out<u32> out_task_id, sf::OutCopyHandle out_event, s64 size, s32 flags) {
/* Get the htcs manager. */
auto *manager = impl::HtcsManagerHolder::GetHtcsManager();
/* Start the recv. */
os::NativeHandle event_handle;
R_TRY(manager->StartRecv(out_task_id.GetPointer(), std::addressof(event_handle), size, m_desc, flags));
/* Set the output event handle. */
out_event.SetValue(event_handle, true);
R_SUCCEED();
}
Result SocketServiceObject::EndRecv(sf::Out<s32> out_err, sf::Out<s64> out_size, const sf::OutAutoSelectBuffer &buffer, u32 task_id) {
/* Get the htcs manager. */
auto *manager = impl::HtcsManagerHolder::GetHtcsManager();
/* End the recv. */
manager->EndRecv(out_err.GetPointer(), out_size.GetPointer(), reinterpret_cast<char *>(buffer.GetPointer()), buffer.GetSize(), task_id, m_desc);
R_SUCCEED();
}
Result SocketServiceObject::SendStart(sf::Out<u32> out_task_id, sf::OutCopyHandle out_event, const sf::InNonSecureAutoSelectBuffer &buffer, s32 flags) {
/* Check that the sizes are okay. */
R_UNLESS(util::IsIntValueRepresentable<s64>(buffer.GetSize()), htcs::ResultInvalidSize());
/* Get the htcs manager. */
auto *manager = impl::HtcsManagerHolder::GetHtcsManager();
/* Start the send. */
os::NativeHandle event_handle;
R_TRY(manager->SendStart(out_task_id.GetPointer(), std::addressof(event_handle), reinterpret_cast<const char *>(buffer.GetPointer()), buffer.GetSize(), m_desc, flags));
/* Set the output event handle. */
out_event.SetValue(event_handle, true);
R_SUCCEED();
}
Result SocketServiceObject::ContinueSend(sf::Out<s64> out_size, sf::Out<bool> out_wait, const sf::InNonSecureAutoSelectBuffer &buffer, u32 task_id) {
/* Check that the sizes are okay. */
R_UNLESS(util::IsIntValueRepresentable<s64>(buffer.GetSize()), htcs::ResultInvalidSize());
/* Get the htcs manager. */
auto *manager = impl::HtcsManagerHolder::GetHtcsManager();
/* Continue the send. */
R_TRY(manager->ContinueSend(out_size.GetPointer(), reinterpret_cast<const char *>(buffer.GetPointer()), buffer.GetSize(), task_id, m_desc));
/* We aren't doing a waiting send. */
*out_wait = false;
R_SUCCEED();
}
Result SocketServiceObject::GetPrimitive(sf::Out<s32> out) {
/* Get our descriptor. */
*out = m_desc;
R_SUCCEED();
}
}
| 14,512
|
C++
|
.cpp
| 250
| 50.164
| 247
| 0.659355
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,617
|
htcs_virtual_socket_collection.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htcs/client/htcs_virtual_socket_collection.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "htcs_session.hpp"
#include "htcs_virtual_socket_collection.hpp"
namespace ams::htcs::client {
namespace {
constexpr inline s32 InvalidSocket = -1;
constexpr inline s32 InvalidPrimitive = -1;
}
/* Declare client functions. */
sf::SharedPointer<tma::ISocket> socket(s32 &last_error);
s32 close(sf::SharedPointer<tma::ISocket> socket, s32 &last_error);
s32 bind(sf::SharedPointer<tma::ISocket> socket, const htcs::SockAddrHtcs *address, s32 &last_error);
s32 listen(sf::SharedPointer<tma::ISocket> socket, s32 backlog_count, s32 &last_error);
sf::SharedPointer<tma::ISocket> accept(sf::SharedPointer<tma::ISocket> socket, htcs::SockAddrHtcs *address, s32 &last_error);
s32 fcntl(sf::SharedPointer<tma::ISocket> socket, s32 command, s32 value, s32 &last_error);
s32 shutdown(sf::SharedPointer<tma::ISocket> socket, s32 how, s32 &last_error);
ssize_t recv(sf::SharedPointer<tma::ISocket> socket, void *buffer, size_t buffer_size, s32 flags, s32 &last_error);
ssize_t send(sf::SharedPointer<tma::ISocket> socket, const void *buffer, size_t buffer_size, s32 flags, s32 &last_error);
s32 connect(sf::SharedPointer<tma::ISocket> socket, const htcs::SockAddrHtcs *address, s32 &last_error);
s32 select(s32 * const read, s32 &num_read, s32 * const write, s32 &num_write, s32 * const except, s32 &num_except, htcs::TimeVal *timeout, s32 &last_error);
struct VirtualSocket {
s32 m_id;
s32 m_primitive;
sf::SharedPointer<tma::ISocket> m_socket;
bool m_do_bind;
htcs::SockAddrHtcs m_address;
s32 m_listen_backlog_count;
s32 m_fcntl_command;
s32 m_fcntl_value;
bool m_blocking;
VirtualSocket() {
/* Initialize. */
this->Init();
}
~VirtualSocket() { /* ... */ }
void Init() {
/* Setup fields. */
m_id = InvalidSocket;
m_primitive = InvalidPrimitive;
m_socket = nullptr;
m_blocking = true;
m_do_bind = false;
std::memset(std::addressof(m_address), 0, sizeof(m_address));
m_listen_backlog_count = -1;
m_fcntl_command = -1;
m_fcntl_value = 0;
}
s32 Bind(const htcs::SockAddrHtcs *address, s32 &last_error) {
/* Mark the bind. */
m_do_bind = true;
/* Set our address. */
std::memcpy(std::addressof(m_address), address, sizeof(m_address));
/* Clear the error. */
last_error = 0;
return 0;
}
s32 Listen(s32 backlog_count, s32 &last_error) {
s32 res = -1;
if (m_do_bind) {
/* Set backlog count. */
m_listen_backlog_count = std::max(backlog_count, 1);
/* Clear error. */
last_error = 0;
res = 0;
} else {
last_error = HTCS_EINVAL;
}
return res;
}
s32 Fcntl(s32 command, s32 value, s32 &last_error) {
/* Clear error. */
s32 res = 0;
last_error = 0;
if (command == HTCS_F_SETFL) {
m_fcntl_command = command;
m_fcntl_value = value;
m_blocking = (value & HTCS_O_NONBLOCK) == 0;
} else if (command == HTCS_F_GETFL) {
res = m_fcntl_value;
} else {
last_error = HTCS_EINVAL;
res = -1;
}
return res;
}
s32 SetSocket(sf::SharedPointer<tma::ISocket> socket, s32 &last_error) {
s32 res = 0;
if (m_socket == nullptr && socket != nullptr) {
/* Set our socket. */
m_socket = socket;
/* Bind, fcntl, and listen, since those may have been deferred. */
if (m_do_bind) {
res = bind(m_socket, std::addressof(m_address), last_error);
}
if (res == 0 && m_fcntl_command != -1) {
res = fcntl(m_socket, m_fcntl_command, m_fcntl_value, last_error);
}
if (res == 0 && m_listen_backlog_count > 0) {
res = listen(m_socket, m_listen_backlog_count, last_error);
}
}
return res;
}
};
VirtualSocketCollection::VirtualSocketCollection()
: m_socket_list(nullptr),
m_list_count(0),
m_list_size(0),
m_next_id(1),
m_mutex()
{
/* ... */
}
VirtualSocketCollection::~VirtualSocketCollection() {
/* Clear ourselves. */
this->Clear();
/* Destroy all sockets in our list. */
for (auto i = 0; i < m_list_size; ++i) {
std::destroy_at(m_socket_list + i);
}
/* Clear the backing memory for our socket list. */
std::memset(m_buffer, 0, sizeof(VirtualSocket) * m_list_size);
}
size_t VirtualSocketCollection::GetWorkingMemorySize(int num_sockets) {
AMS_ASSERT(num_sockets < htcs::SocketCountMax);
return num_sockets * sizeof(VirtualSocket);
}
void VirtualSocketCollection::Init(void *buffer, size_t buffer_size) {
/* Set our buffer. */
m_buffer = buffer;
m_buffer_size = buffer_size;
/* Configure our list. */
m_list_size = static_cast<s32>(m_buffer_size / sizeof(VirtualSocket));
m_list_size = std::min(m_list_size, htcs::SocketCountMax);
/* Initialize our list. */
m_socket_list = static_cast<VirtualSocket *>(m_buffer);
for (auto i = 0; i < m_list_size; ++i) {
std::construct_at(m_socket_list + i);
}
}
void VirtualSocketCollection::Clear() {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Clear our list. */
m_list_count = 0;
}
s32 VirtualSocketCollection::Socket(s32 &error_code) {
/* Clear error code. */
error_code = 0;
/* Create the socket. */
return this->CreateSocket(sf::SharedPointer<tma::ISocket>{nullptr}, error_code);
}
s32 VirtualSocketCollection::Close(s32 id, s32 &error_code) {
/* Clear error code. */
error_code = 0;
/* Prepare to find the socket. */
s32 res = 0;
sf::SharedPointer<tma::ISocket> socket = nullptr;
/* Find the socket. */
s32 index;
{
std::scoped_lock lk(m_mutex);
if (index = this->Find(id, std::addressof(error_code)); index >= 0) {
/* Get the socket's object. */
VirtualSocket *virt_socket = m_socket_list + index;
socket = virt_socket->m_socket;
/* Move the list. */
for (/* ... */; index < m_list_count - 1; ++index) {
m_socket_list[index] = m_socket_list[index + 1];
}
/* Clear the now unused last list entry. */
m_socket_list[index].Init();
/* Decrement our list count. */
--m_list_count;
}
}
/* If we found the socket, close it. */
if (socket != nullptr) {
close(socket, error_code);
/* Clear the error code. */
res = 0;
error_code = 0;
}
return index >= 0 ? res : -1;
}
s32 VirtualSocketCollection::Bind(s32 id, const htcs::SockAddrHtcs *address, s32 &error_code) {
/* Setup result/error code. */
s32 res = -1;
error_code = 0;
/* Get the socket. */
sf::SharedPointer<tma::ISocket> socket = this->GetSocket(id, std::addressof(error_code));
/* If we found the socket, bind. */
if (socket != nullptr) {
res = bind(socket, address, error_code);
} else if (error_code != HTCS_EBADF) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Check if the socket is already bound. */
if (const auto index = this->Find(id); index >= 0) {
const auto exists = this->HasAddr(address);
if (m_socket_list[index].m_do_bind) {
error_code = HTCS_EINVAL;
res = -1;
} else if (exists) {
error_code = HTCS_EADDRINUSE;
res = -1;
} else {
res = m_socket_list[index].Bind(address, error_code);
}
} else {
error_code = HTCS_EBADF;
}
}
return res;
}
s32 VirtualSocketCollection::Listen(s32 id, s32 backlog_count, s32 &error_code) {
/* Setup result/error code. */
s32 res = -1;
error_code = 0;
/* Get the socket. */
sf::SharedPointer<tma::ISocket> socket = this->GetSocket(id, std::addressof(error_code));
/* If we found the socket, bind. */
if (socket != nullptr) {
res = listen(socket, backlog_count, error_code);
} else if (error_code != HTCS_EBADF) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Try to listen on the virtual socket. */
if (const auto index = this->Find(id); index >= 0) {
res = m_socket_list[index].Listen(backlog_count, error_code);
}
}
return res;
}
s32 VirtualSocketCollection::Accept(s32 id, htcs::SockAddrHtcs *address, s32 &error_code) {
/* Setup result/error code. */
s32 res = -1;
error_code = 0;
/* Declare socket that we're creating. */
sf::SharedPointer<tma::ISocket> new_socket = nullptr;
/* Get the socket. */
sf::SharedPointer<tma::ISocket> socket = this->GetSocket(id, std::addressof(error_code));
/* If we found the socket, bind. */
if (socket != nullptr) {
if (error_code != HTCS_ENONE) {
return -1;
}
new_socket = this->DoAccept(socket, id, address, error_code);
} else if (error_code != HTCS_EBADF) {
/* Fetch the socket. */
socket = this->FetchSocket(id, error_code);
/* Wait for the socket. */
while (socket == nullptr) {
/* Determine whether we should block/listen. */
bool block_until_done = true;
bool listened = false;
s32 index;
{
std::scoped_lock lk(m_mutex);
if (index = this->Find(id, std::addressof(error_code)); index >= 0) {
block_until_done = m_socket_list[index].m_blocking;
listened = m_socket_list[index].m_listen_backlog_count > 0;
}
}
/* Check that the socket exists. */
if (index < 0) {
error_code = HTCS_EINTR;
return -1;
}
/* Check that the socket has been listened. */
if (!listened) {
error_code = HTCS_EINVAL;
return -1;
}
/* Check that we should block. */
if (!block_until_done) {
error_code = HTCS_EWOULDBLOCK;
return -1;
}
/* Wait before trying again. */
os::SleepThread(TimeSpan::FromMilliSeconds(500));
/* Fetch the potentially updated socket. */
socket = this->FetchSocket(id, error_code);
}
/* Check that we haven't errored. */
if (error_code != HTCS_ENONE) {
return -1;
}
/* Do the accept. */
new_socket = this->DoAccept(socket, id, address, error_code);
}
/* If we have a new socket, register it. */
if (new_socket != 0) {
res = this->CreateSocket(new_socket, error_code);
if (res < 0) {
s32 tmp_error_code;
close(new_socket, tmp_error_code);
}
}
return res;
}
s32 VirtualSocketCollection::Fcntl(s32 id, s32 command, s32 value, s32 &error_code) {
/* Setup result/error code. */
s32 res = -1;
error_code = 0;
/* Get the socket. */
sf::SharedPointer<tma::ISocket> socket = this->GetSocket(id, std::addressof(error_code));
/* If we found the socket, bind. */
if (socket != nullptr) {
res = fcntl(socket, command, value, error_code);
} else if (error_code != HTCS_EBADF) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Try to listen on the virtual socket. */
if (const auto index = this->Find(id); index >= 0) {
res = m_socket_list[index].Fcntl(command, value, error_code);
}
}
return res;
}
s32 VirtualSocketCollection::Shutdown(s32 id, s32 how, s32 &error_code) {
/* Setup result/error code. */
s32 res = -1;
error_code = 0;
/* Get the socket. */
sf::SharedPointer<tma::ISocket> socket = this->GetSocket(id, std::addressof(error_code));
/* If we found the socket, bind. */
if (socket != nullptr) {
res = shutdown(socket, how, error_code);
} else if (error_code != HTCS_EBADF) {
error_code = HTCS_ENOTCONN;
}
return res;
}
ssize_t VirtualSocketCollection::Recv(s32 id, void *buffer, size_t buffer_size, s32 flags, s32 &error_code) {
/* Setup result/error code. */
ssize_t res = -1;
error_code = 0;
/* Fetch the socket. */
sf::SharedPointer<tma::ISocket> socket = this->FetchSocket(id, error_code);
/* If we found the socket, bind. */
if (socket != nullptr) {
if (error_code != HTCS_ENONE) {
return -1;
}
res = recv(socket, buffer, buffer_size, flags, error_code);
} else if (error_code != HTCS_EBADF) {
error_code = HTCS_ENOTCONN;
}
return res;
}
ssize_t VirtualSocketCollection::Send(s32 id, const void *buffer, size_t buffer_size, s32 flags, s32 &error_code) {
/* Setup result/error code. */
ssize_t res = -1;
error_code = 0;
/* Fetch the socket. */
sf::SharedPointer<tma::ISocket> socket = this->FetchSocket(id, error_code);
/* If we found the socket, bind. */
if (socket != nullptr) {
if (error_code != HTCS_ENONE) {
return -1;
}
res = send(socket, buffer, buffer_size, flags, error_code);
} else if (error_code != HTCS_EBADF) {
error_code = HTCS_ENOTCONN;
}
return res;
}
s32 VirtualSocketCollection::Connect(s32 id, const htcs::SockAddrHtcs *address, s32 &error_code) {
/* Setup result/error code. */
s32 res = -1;
error_code = 0;
/* Fetch the socket. */
sf::SharedPointer<tma::ISocket> socket = this->FetchSocket(id, error_code);
/* If we found the socket, bind. */
if (socket != nullptr) {
if (error_code != HTCS_ENONE) {
return -1;
}
res = connect(socket, address, error_code);
} else if (error_code != HTCS_EBADF) {
error_code = HTCS_EADDRNOTAVAIL;
}
return res;
}
s32 VirtualSocketCollection::Select(htcs::FdSet *read, htcs::FdSet *write, htcs::FdSet *except, htcs::TimeVal *timeout, s32 &error_code) {
/* Setup result/error code. */
s32 res = -1;
s32 tmp_error_code = 0;
/* Declare buffers. */
s32 read_primitives[SocketCountMax];
s32 write_primitives[SocketCountMax];
s32 except_primitives[SocketCountMax];
/* Get reads. */
s32 num_read = this->GetSockets(read_primitives, read, tmp_error_code);
if (tmp_error_code != HTCS_ENONE) {
error_code = tmp_error_code;
return res;
}
/* Get writes. */
s32 num_write = this->GetSockets(write_primitives, write, tmp_error_code);
if (tmp_error_code != HTCS_ENONE) {
error_code = tmp_error_code;
return res;
}
/* Get excepts. */
s32 num_except = this->GetSockets(except_primitives, except, tmp_error_code);
if (tmp_error_code != HTCS_ENONE) {
error_code = tmp_error_code;
return res;
}
/* Perform the select. */
if (num_read + num_write + num_except > 0) {
res = select(read_primitives, num_read, write_primitives, num_write, except_primitives, num_except, timeout, error_code);
/* Set the socket primitives. */
this->SetSockets(read, read_primitives, num_read);
this->SetSockets(write, write_primitives, num_write);
this->SetSockets(except, except_primitives, num_except);
} else {
error_code = HTCS_EINVAL;
}
return res;
}
s32 VirtualSocketCollection::CreateId() {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Get a free id. */
s32 res = 0;
do {
res = m_next_id++;
if (m_next_id <= 0) {
m_next_id = 1;
}
} while (this->Find(res) >= 0);
return res;
}
s32 VirtualSocketCollection::Add(sf::SharedPointer<tma::ISocket> socket) {
/* Check that the socket isn't null. */
if (socket == nullptr) {
return -1;
}
/* Create the socket. */
s32 error_code;
return this->CreateSocket(socket, error_code);
}
void VirtualSocketCollection::Insert(s32 id, sf::SharedPointer<tma::ISocket> socket) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Add the socket to the list. */
if (m_list_count != 0) {
/* Ensure the list remains in sorted order. */
s32 index;
for (index = m_list_count - 1; index >= 0; --index) {
if (m_socket_list[index].m_id < id) {
break;
}
m_socket_list[index + 1] = m_socket_list[index];
}
/* Set the socket in the list. */
m_socket_list[index + 1].m_id = id;
m_socket_list[index + 1].m_socket = socket;
} else {
/* Set the socket in the list. */
m_socket_list[0].m_id = id;
m_socket_list[0].m_socket = socket;
}
/* Increment our count. */
++m_list_count;
}
void VirtualSocketCollection::SetSize(s32 size) {
AMS_UNUSED(size);
}
s32 VirtualSocketCollection::Find(s32 id, s32 *error_code) {
/* Perform a binary search to find the socket. */
if (m_list_count > 0) {
s32 left = 0;
s32 right = m_list_count - 1;
while (left <= right) {
const s32 mid = (left + right) / 2;
if (m_socket_list[mid].m_id == id) {
return mid;
} else if (m_socket_list[mid].m_id > id) {
right = mid - 1;
} else /* if (m_socket_list[mid].m_id < id) */ {
left = mid + 1;
}
}
}
/* We failed to find the socket. */
if (error_code != nullptr) {
*error_code = HTCS_EBADF;
}
return InvalidSocket;
}
s32 VirtualSocketCollection::FindByPrimitive(s32 primitive) {
/* Find a socket with the desired primitive. */
for (auto i = 0; i < m_list_size; ++i) {
if (m_socket_list[i].m_primitive == primitive) {
return i;
}
}
return InvalidPrimitive;
}
bool VirtualSocketCollection::HasAddr(const htcs::SockAddrHtcs *address) {
/* Try to find a matching socket. */
for (auto i = 0; i < m_list_count; ++i) {
if (m_socket_list[i].m_address.family == address->family &&
std::strcmp(m_socket_list[i].m_address.peer_name.name, address->peer_name.name) == 0 &&
std::strcmp(m_socket_list[i].m_address.port_name.name, address->port_name.name) == 0)
{
return true;
}
}
return false;
}
sf::SharedPointer<tma::ISocket> VirtualSocketCollection::GetSocket(s32 id, s32 *error_code) {
sf::SharedPointer<tma::ISocket> res = nullptr;
/* Get the socket. */
{
std::scoped_lock lk(m_mutex);
if (const auto index = this->Find(id, error_code); index >= 0) {
res = m_socket_list[index].m_socket;
}
}
return res;
}
sf::SharedPointer<tma::ISocket> VirtualSocketCollection::FetchSocket(s32 id, s32 &error_code) {
/* Clear the error code. */
error_code = 0;
/* Get the socket. */
auto socket = this->GetSocket(id, std::addressof(error_code));
if (socket == nullptr && error_code == HTCS_ENONE) {
socket = this->RealizeSocket(id);
}
return socket;
}
sf::SharedPointer<tma::ISocket> VirtualSocketCollection::RealizeSocket(s32 id) {
/* Clear the error code. */
s32 error_code = 0;
/* Get socket. */
sf::SharedPointer<tma::ISocket> res = socket(error_code);
if (res != nullptr) {
/* Assign the new socket. */
s32 index;
{
std::scoped_lock lk(m_mutex);
index = this->Find(id, std::addressof(error_code));
if (index >= 0) {
m_socket_list[index].SetSocket(res, error_code);
}
}
/* If the socket was deleted, close it. */
if (index < 0) {
s32 temp_error = 0;
close(res, temp_error);
res = nullptr;
}
}
return res;
}
sf::SharedPointer<tma::ISocket> VirtualSocketCollection::DoAccept(sf::SharedPointer<tma::ISocket> socket, s32 id, htcs::SockAddrHtcs *address, s32 &error_code) {
/* Clear the error code. */
error_code = 0;
/* Try to accept. */
sf::SharedPointer<tma::ISocket> new_socket = accept(socket, address, error_code);
if (error_code == HTCS_ENETDOWN) {
new_socket = accept(socket, address, error_code);
std::scoped_lock lk(m_mutex);
if (const auto index = this->Find(id, std::addressof(error_code)); index >= 0) {
m_socket_list[index].m_socket = nullptr;
}
}
return new_socket;
}
s32 VirtualSocketCollection::GetSockets(s32 * const out_primitives, htcs::FdSet *set, s32 &error_code) {
/* Clear the error code. */
error_code = 0;
s32 count = 0;
/* Walk the fdset. */
if (set != nullptr) {
for (auto i = 0; i < FdSetSize; ++i) {
/* If the set no longer has fds, we're done. */
if (set->fds[i] == 0) {
break;
}
/* Find the fd's primitive. */
s32 primitive = InvalidPrimitive;
s32 index;
{
std::scoped_lock lk(m_mutex);
if (index = this->Find(set->fds[i], std::addressof(error_code)); index >= 0) {
/* Get the primitive, if necessary. */
if (m_socket_list[index].m_primitive == InvalidPrimitive && m_socket_list[index].m_socket != nullptr) {
m_socket_list[index].m_socket->GetPrimitive(std::addressof(m_socket_list[index].m_primitive));
}
primitive = m_socket_list[index].m_primitive;
}
}
/* Check that an error didn't occur. */
if (error_code != HTCS_ENONE) {
return 0;
}
/* If the primitive is invalid, try to realize the socket. */
if (primitive == InvalidPrimitive) {
if (this->RealizeSocket(set->fds[i]) != nullptr) {
std::scoped_lock lk(m_mutex);
/* Get the primitive. */
if (index = this->Find(set->fds[i], std::addressof(error_code)); index >= 0) {
m_socket_list[index].m_socket->GetPrimitive(std::addressof(m_socket_list[index].m_primitive));
primitive = m_socket_list[index].m_primitive;
}
}
/* Check that an error didn't occur. */
if (error_code != HTCS_ENONE) {
return 0;
}
}
/* Set the output primitive. */
if (primitive != InvalidPrimitive) {
out_primitives[count++] = primitive;
}
}
}
return count;
}
void VirtualSocketCollection::SetSockets(htcs::FdSet *set, s32 * const primitives, s32 count) {
if (set != nullptr) {
/* Clear the set. */
FdSetZero(set);
/* Copy the fds. */
for (auto i = 0; i < count; ++i) {
std::scoped_lock lk(m_mutex);
if (const auto index = this->FindByPrimitive(primitives[i]); index >= 0) {
set->fds[i] = m_socket_list[index].m_id;
}
}
}
}
s32 VirtualSocketCollection::CreateSocket(sf::SharedPointer<tma::ISocket> socket, s32 &error_code) {
/* Clear the error code. */
error_code = 0;
s32 id = InvalidSocket;
/* Check that we can add to the list. */
if (m_list_count < m_list_size) {
/* Create a new id. */
id = this->CreateId();
/* Insert the socket into the list. */
this->Insert(id, socket);
} else {
if (socket != nullptr) {
s32 tmp_error_code;
close(socket, tmp_error_code);
}
error_code = HTCS_EMFILE;
}
return id;
}
}
| 27,544
|
C++
|
.cpp
| 673
| 29.135215
| 165
| 0.515088
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,618
|
htcs_session.os.horizon.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htcs/client/htcs_session.os.horizon.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "htcs_session.hpp"
extern "C" {
#include <switch/services/htcs.h>
}
namespace ams::htcs::client {
namespace {
struct HtcsObjectAllocatorTag;
using ObjectAllocator = ams::sf::ExpHeapStaticAllocator<16_KB, HtcsObjectAllocatorTag>;
using ObjectFactory = ams::sf::ObjectFactory<typename ObjectAllocator::Policy>;
class StaticAllocatorInitializer {
public:
StaticAllocatorInitializer() {
ObjectAllocator::Initialize(lmem::CreateOption_ThreadSafe);
}
} g_static_allocator_initializer;
}
namespace {
class RemoteSocket {
private:
::HtcsSocket m_s;
public:
RemoteSocket(::HtcsSocket &s) : m_s(s) { /* ... */ }
~RemoteSocket() { ::htcsCloseSocket(std::addressof(m_s)); }
public:
Result Accept(sf::Out<s32> out_err, sf::Out<sf::SharedPointer<tma::ISocket>> out, sf::Out<htcs::SockAddrHtcs> out_address) { AMS_UNUSED(out_err, out, out_address); AMS_ABORT("Not Implemented"); }
Result Recv(sf::Out<s32> out_err, sf::Out<s64> out_size, const sf::OutAutoSelectBuffer &buffer, s32 flags) { AMS_UNUSED(out_err, out_size, buffer, flags); AMS_ABORT("Not Implemented"); }
Result Send(sf::Out<s32> out_err, sf::Out<s64> out_size, const sf::InAutoSelectBuffer &buffer, s32 flags) { AMS_UNUSED(out_err, out_size, buffer, flags); AMS_ABORT("Not Implemented"); }
Result RecvLargeStart(sf::Out<u32> out_task_id, sf::OutCopyHandle out_event, s32 unaligned_size_start, s32 unaligned_size_end, s64 aligned_size, sf::CopyHandle &&mem_handle, s32 flags) { AMS_UNUSED(out_task_id, out_event, unaligned_size_start, unaligned_size_end, aligned_size, mem_handle, flags); AMS_ABORT("Not Implemented"); }
Result SendStartOld(sf::Out<u32> out_task_id, sf::OutCopyHandle out_event, const sf::InAutoSelectBuffer &buffer, s32 flags) { AMS_UNUSED(out_task_id, out_event, buffer, flags); AMS_ABORT("Not Implemented"); }
Result SendLargeStart(sf::Out<u32> out_task_id, sf::OutCopyHandle out_event, const sf::InAutoSelectBuffer &start_buffer, const sf::InAutoSelectBuffer &end_buffer, sf::CopyHandle &&mem_handle, s64 aligned_size, s32 flags) { AMS_UNUSED(out_task_id, out_event, start_buffer, end_buffer, mem_handle, aligned_size, flags); AMS_ABORT("Not Implemented"); }
Result ContinueSendOld(sf::Out<s64> out_size, sf::Out<bool> out_wait, const sf::InAutoSelectBuffer &buffer, u32 task_id) { AMS_UNUSED(out_size, out_wait, buffer, task_id); AMS_ABORT("Not Implemented"); }
Result Close(sf::Out<s32> out_err, sf::Out<s32> out_res);
Result Connect(sf::Out<s32> out_err, sf::Out<s32> out_res, const htcs::SockAddrHtcs &address);
Result Bind(sf::Out<s32> out_err, sf::Out<s32> out_res, const htcs::SockAddrHtcs &address);
Result Listen(sf::Out<s32> out_err, sf::Out<s32> out_res, s32 backlog_count);
Result Shutdown(sf::Out<s32> out_err, sf::Out<s32> out_res, s32 how);
Result Fcntl(sf::Out<s32> out_err, sf::Out<s32> out_res, s32 command, s32 value);
Result AcceptStart(sf::Out<u32> out_task_id, sf::OutCopyHandle out_event);
Result AcceptResults(sf::Out<s32> out_err, sf::Out<sf::SharedPointer<tma::ISocket>> out, sf::Out<htcs::SockAddrHtcs> out_address, u32 task_id);
Result RecvStart(sf::Out<u32> out_task_id, sf::OutCopyHandle out_event, s32 mem_size, s32 flags);
Result RecvResults(sf::Out<s32> out_err, sf::Out<s64> out_size, const sf::OutAutoSelectBuffer &buffer, u32 task_id);
Result SendStart(sf::Out<u32> out_task_id, sf::OutCopyHandle out_event, const sf::InNonSecureAutoSelectBuffer &buffer, s32 flags);
Result SendResults(sf::Out<s32> out_err, sf::Out<s64> out_size, u32 task_id);
Result StartSend(sf::Out<u32> out_task_id, sf::OutCopyHandle out_event, sf::Out<s64> out_max_size, s64 size, s32 flags);
Result ContinueSend(sf::Out<s64> out_size, sf::Out<bool> out_wait, const sf::InNonSecureAutoSelectBuffer &buffer, u32 task_id);
Result EndSend(sf::Out<s32> out_err, sf::Out<s64> out_size, u32 task_id);
Result StartRecv(sf::Out<u32> out_task_id, sf::OutCopyHandle out_event, s64 size, s32 flags);
Result EndRecv(sf::Out<s32> out_err, sf::Out<s64> out_size, const sf::OutAutoSelectBuffer &buffer, u32 task_id);
Result GetPrimitive(sf::Out<s32> out);
};
static_assert(tma::IsISocket<RemoteSocket>);
class RemoteManager {
public:
Result Socket(sf::Out<s32> out_err, sf::Out<s32> out_sock) { AMS_UNUSED(out_err, out_sock); AMS_ABORT("Not Implemented"); }
Result Close(sf::Out<s32> out_err, sf::Out<s32> out_res, s32 desc) { AMS_UNUSED(out_err, out_res, desc); AMS_ABORT("Not Implemented"); }
Result Connect(sf::Out<s32> out_err, sf::Out<s32> out_res, s32 desc, const htcs::SockAddrHtcs &address) { AMS_UNUSED(out_err, out_res, desc, address); AMS_ABORT("Not Implemented"); }
Result Bind(sf::Out<s32> out_err, sf::Out<s32> out_res, s32 desc, const htcs::SockAddrHtcs &address) { AMS_UNUSED(out_err, out_res, desc, address); AMS_ABORT("Not Implemented"); }
Result Listen(sf::Out<s32> out_err, sf::Out<s32> out_res, s32 desc, s32 backlog_count) { AMS_UNUSED(out_err, out_res, desc, backlog_count); AMS_ABORT("Not Implemented"); }
Result Accept(sf::Out<s32> out_err, sf::Out<s32> out_res, sf::Out<htcs::SockAddrHtcs> out_address, s32 desc) { AMS_UNUSED(out_err, out_res, out_address, desc); AMS_ABORT("Not Implemented"); }
Result Recv(sf::Out<s32> out_err, sf::Out<s64> out_size, const sf::OutBuffer &buffer, s32 desc, s32 flags) { AMS_UNUSED(out_err, out_size, buffer, desc, flags); AMS_ABORT("Not Implemented"); }
Result Send(sf::Out<s32> out_err, sf::Out<s64> out_size, s32 desc, const sf::InBuffer &buffer, s32 flags) { AMS_UNUSED(out_err, out_size, desc, buffer, flags); AMS_ABORT("Not Implemented"); }
Result Shutdown(sf::Out<s32> out_err, sf::Out<s32> out_res, s32 desc, s32 how) { AMS_UNUSED(out_err, out_res, desc, how); AMS_ABORT("Not Implemented"); }
Result Fcntl(sf::Out<s32> out_err, sf::Out<s32> out_res, s32 desc, s32 command, s32 value) { AMS_UNUSED(out_err, out_res, desc, command, value); AMS_ABORT("Not Implemented"); }
Result CreateSocketOld(sf::Out<s32> out_err, sf::Out<sf::SharedPointer<tma::ISocket>> out) { AMS_UNUSED(out_err, out); AMS_ABORT("Not Implemented"); }
Result GetPeerNameAny(sf::Out<htcs::HtcsPeerName> out);
Result GetDefaultHostName(sf::Out<htcs::HtcsPeerName> out);
Result CreateSocket(sf::Out<s32> out_err, sf::Out<sf::SharedPointer<tma::ISocket>> out, bool enable_disconnection_emulation);
Result RegisterProcessId(const sf::ClientProcessId &client_pid);
Result MonitorManager(const sf::ClientProcessId &client_pid);
Result StartSelect(sf::Out<u32> out_task_id, sf::OutCopyHandle out_event, const sf::InMapAliasArray<s32> &read_handles, const sf::InMapAliasArray<s32> &write_handles, const sf::InMapAliasArray<s32> &exception_handles, s64 tv_sec, s64 tv_usec);
Result EndSelect(sf::Out<s32> out_err, sf::Out<s32> out_count, const sf::OutMapAliasArray<s32> &read_handles, const sf::OutMapAliasArray<s32> &write_handles, const sf::OutMapAliasArray<s32> &exception_handles, u32 task_id);
};
static_assert(tma::IsIHtcsManager<RemoteManager>);
Result RemoteManager::GetPeerNameAny(sf::Out<htcs::HtcsPeerName> out) {
static_assert(sizeof(htcs::HtcsPeerName) == sizeof(::HtcsPeerName));
R_RETURN(::htcsGetPeerNameAny(reinterpret_cast<::HtcsPeerName *>(out.GetPointer())));
}
Result RemoteManager::GetDefaultHostName(sf::Out<htcs::HtcsPeerName> out) {
static_assert(sizeof(htcs::HtcsPeerName) == sizeof(::HtcsPeerName));
R_RETURN(::htcsGetDefaultHostName(reinterpret_cast<::HtcsPeerName *>(out.GetPointer())));
}
Result RemoteManager::CreateSocket(sf::Out<s32> out_err, sf::Out<sf::SharedPointer<tma::ISocket>> out, bool enable_disconnection_emulation) {
::HtcsSocket libnx_socket;
R_TRY(::htcsCreateSocket(out_err.GetPointer(), std::addressof(libnx_socket), enable_disconnection_emulation));
R_SUCCEED_IF(*out_err != 0);
*out = ObjectFactory::CreateSharedEmplaced<tma::ISocket, RemoteSocket>(libnx_socket);
R_SUCCEED();
}
Result RemoteManager::RegisterProcessId(const sf::ClientProcessId &client_pid) {
/* Handled by libnx init. */
AMS_UNUSED(client_pid);
R_SUCCEED();
}
Result RemoteManager::MonitorManager(const sf::ClientProcessId &client_pid) {
/* Handled by libnx init. */
AMS_UNUSED(client_pid);
R_SUCCEED();
}
Result RemoteManager::StartSelect(sf::Out<u32> out_task_id, sf::OutCopyHandle out_event, const sf::InMapAliasArray<s32> &read_handles, const sf::InMapAliasArray<s32> &write_handles, const sf::InMapAliasArray<s32> &exception_handles, s64 tv_sec, s64 tv_usec) {
os::NativeHandle event_handle;
R_TRY(::htcsStartSelect(out_task_id.GetPointer(), std::addressof(event_handle), read_handles.GetPointer(), read_handles.GetSize(), write_handles.GetPointer(), write_handles.GetSize(), exception_handles.GetPointer(), exception_handles.GetSize(), tv_sec, tv_usec));
out_event.SetValue(event_handle, true);
R_SUCCEED();
}
Result RemoteManager::EndSelect(sf::Out<s32> out_err, sf::Out<s32> out_count, const sf::OutMapAliasArray<s32> &read_handles, const sf::OutMapAliasArray<s32> &write_handles, const sf::OutMapAliasArray<s32> &exception_handles, u32 task_id) {
R_RETURN(::htcsEndSelect(out_err.GetPointer(), out_count.GetPointer(), read_handles.GetPointer(), read_handles.GetSize(), write_handles.GetPointer(), write_handles.GetSize(), exception_handles.GetPointer(), exception_handles.GetSize(), task_id));
}
Result RemoteSocket::Close(sf::Out<s32> out_err, sf::Out<s32> out_res) {
R_RETURN(::htcsSocketClose(std::addressof(m_s), out_err.GetPointer(), out_res.GetPointer()));
}
Result RemoteSocket::Connect(sf::Out<s32> out_err, sf::Out<s32> out_res, const htcs::SockAddrHtcs &address) {
static_assert(sizeof(htcs::SockAddrHtcs) == sizeof(::HtcsSockAddr));
R_RETURN(::htcsSocketConnect(std::addressof(m_s), out_err.GetPointer(), out_res.GetPointer(), reinterpret_cast<const ::HtcsSockAddr *>(std::addressof(address))));
}
Result RemoteSocket::Bind(sf::Out<s32> out_err, sf::Out<s32> out_res, const htcs::SockAddrHtcs &address) {
static_assert(sizeof(htcs::SockAddrHtcs) == sizeof(::HtcsSockAddr));
R_RETURN(::htcsSocketBind(std::addressof(m_s), out_err.GetPointer(), out_res.GetPointer(), reinterpret_cast<const ::HtcsSockAddr *>(std::addressof(address))));
}
Result RemoteSocket::Listen(sf::Out<s32> out_err, sf::Out<s32> out_res, s32 backlog_count) {
R_RETURN(::htcsSocketListen(std::addressof(m_s), out_err.GetPointer(), out_res.GetPointer(), backlog_count));
}
Result RemoteSocket::Shutdown(sf::Out<s32> out_err, sf::Out<s32> out_res, s32 how) {
R_RETURN(::htcsSocketShutdown(std::addressof(m_s), out_err.GetPointer(), out_res.GetPointer(), how));
}
Result RemoteSocket::Fcntl(sf::Out<s32> out_err, sf::Out<s32> out_res, s32 command, s32 value) {
R_RETURN(::htcsSocketFcntl(std::addressof(m_s), out_err.GetPointer(), out_res.GetPointer(), command, value));
}
Result RemoteSocket::AcceptStart(sf::Out<u32> out_task_id, sf::OutCopyHandle out_event) {
os::NativeHandle event_handle;
R_TRY(::htcsSocketAcceptStart(std::addressof(m_s), out_task_id.GetPointer(), std::addressof(event_handle)));
out_event.SetValue(event_handle, true);
R_SUCCEED();
}
Result RemoteSocket::AcceptResults(sf::Out<s32> out_err, sf::Out<sf::SharedPointer<tma::ISocket>> out, sf::Out<htcs::SockAddrHtcs> out_address, u32 task_id) {
static_assert(sizeof(htcs::SockAddrHtcs) == sizeof(::HtcsSockAddr));
::HtcsSocket libnx_socket;
R_TRY(::htcsSocketAcceptResults(std::addressof(m_s), out_err.GetPointer(), std::addressof(libnx_socket), reinterpret_cast<::HtcsSockAddr *>(out_address.GetPointer()), task_id));
R_SUCCEED_IF(*out_err != 0);
*out = ObjectFactory::CreateSharedEmplaced<tma::ISocket, RemoteSocket>(libnx_socket);
R_SUCCEED();
}
Result RemoteSocket::RecvStart(sf::Out<u32> out_task_id, sf::OutCopyHandle out_event, s32 mem_size, s32 flags) {
os::NativeHandle event_handle;
R_TRY(::htcsSocketRecvStart(std::addressof(m_s), out_task_id.GetPointer(), std::addressof(event_handle), mem_size, flags));
out_event.SetValue(event_handle, true);
R_SUCCEED();
}
Result RemoteSocket::RecvResults(sf::Out<s32> out_err, sf::Out<s64> out_size, const sf::OutAutoSelectBuffer &buffer, u32 task_id) {
R_RETURN(::htcsSocketRecvResults(std::addressof(m_s), out_err.GetPointer(), out_size.GetPointer(), buffer.GetPointer(), buffer.GetSize(), task_id));
}
Result RemoteSocket::SendStart(sf::Out<u32> out_task_id, sf::OutCopyHandle out_event, const sf::InNonSecureAutoSelectBuffer &buffer, s32 flags) {
os::NativeHandle event_handle;
R_TRY(::htcsSocketSendStart(std::addressof(m_s), out_task_id.GetPointer(), std::addressof(event_handle), buffer.GetPointer(), buffer.GetSize(), flags));
out_event.SetValue(event_handle, true);
R_SUCCEED();
}
Result RemoteSocket::SendResults(sf::Out<s32> out_err, sf::Out<s64> out_size, u32 task_id) {
R_RETURN(::htcsSocketSendResults(std::addressof(m_s), out_err.GetPointer(), out_size.GetPointer(), task_id));
}
Result RemoteSocket::StartSend(sf::Out<u32> out_task_id, sf::OutCopyHandle out_event, sf::Out<s64> out_max_size, s64 size, s32 flags) {
os::NativeHandle event_handle;
R_TRY(::htcsSocketStartSend(std::addressof(m_s), out_task_id.GetPointer(), std::addressof(event_handle), out_max_size.GetPointer(), size, flags));
out_event.SetValue(event_handle, true);
R_SUCCEED();
}
Result RemoteSocket::ContinueSend(sf::Out<s64> out_size, sf::Out<bool> out_wait, const sf::InNonSecureAutoSelectBuffer &buffer, u32 task_id) {
R_RETURN(::htcsSocketContinueSend(std::addressof(m_s), out_size.GetPointer(), out_wait.GetPointer(), buffer.GetPointer(), buffer.GetSize(), task_id));
}
Result RemoteSocket::EndSend(sf::Out<s32> out_err, sf::Out<s64> out_size, u32 task_id) {
R_RETURN(::htcsSocketEndSend(std::addressof(m_s), out_err.GetPointer(), out_size.GetPointer(), task_id));
}
Result RemoteSocket::StartRecv(sf::Out<u32> out_task_id, sf::OutCopyHandle out_event, s64 size, s32 flags) {
os::NativeHandle event_handle;
R_TRY(::htcsSocketStartRecv(std::addressof(m_s), out_task_id.GetPointer(), std::addressof(event_handle), size, flags));
out_event.SetValue(event_handle, true);
R_SUCCEED();
}
Result RemoteSocket::EndRecv(sf::Out<s32> out_err, sf::Out<s64> out_size, const sf::OutAutoSelectBuffer &buffer, u32 task_id) {
R_RETURN(::htcsSocketEndRecv(std::addressof(m_s), out_err.GetPointer(), out_size.GetPointer(), buffer.GetPointer(), buffer.GetSize(), task_id));
}
Result RemoteSocket::GetPrimitive(sf::Out<s32> out) {
R_RETURN(::htcsSocketGetPrimitive(std::addressof(m_s), out.GetPointer()));
}
}
void InitializeSessionManager(tma::IHtcsManager **out_manager, tma::IHtcsManager **out_monitor, u32 num_sessions) {
/* Ensure we can contact the libnx wrapper. */
R_ABORT_UNLESS(sm::Initialize());
/* Initialize the libnx wrapper. */
R_ABORT_UNLESS(::htcsInitialize(num_sessions));
/* Create the output objects. */
*out_manager = ObjectFactory::CreateSharedEmplaced<tma::IHtcsManager, RemoteManager>().Detach();
/* Create the output objects. */
*out_monitor = ObjectFactory::CreateSharedEmplaced<tma::IHtcsManager, RemoteManager>().Detach();
}
void FinalizeSessionManager() {
/* Exit the libnx wrapper. */
::htcsExit();
}
}
| 17,722
|
C++
|
.cpp
| 215
| 70.995349
| 365
| 0.656139
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,619
|
htcs_session.os.windows.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htcs/client/htcs_session.os.windows.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "htcs_session.hpp"
namespace ams::htcs::client {
void InitializeSessionManager(tma::IHtcsManager **out_manager, tma::IHtcsManager **out_monitor, u32 num_sessions) {
AMS_UNUSED(out_manager, out_monitor, num_sessions);
AMS_ABORT("TODO");
}
void FinalizeSessionManager() {
AMS_ABORT("TODO");
}
}
| 1,009
|
C++
|
.cpp
| 26
| 35.576923
| 119
| 0.731359
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,620
|
i2c_command_list_formatter.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/i2c/i2c_command_list_formatter.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "impl/i2c_command_list_format.hpp"
namespace ams::i2c {
Result CommandListFormatter::IsEnqueueAble(size_t sz) const {
R_UNLESS(m_command_list_length - m_current_index >= sz, i2c::ResultCommandListFull());
R_SUCCEED();
}
Result CommandListFormatter::EnqueueReceiveCommand(i2c::TransactionOption option, size_t size) {
/* Check that we can enqueue the command. */
constexpr size_t CommandLength = 2;
R_TRY(this->IsEnqueueAble(CommandLength));
/* Get the command list. */
util::BitPack8 *cmd_list = static_cast<util::BitPack8 *>(m_command_list);
/* Get references to the header. */
auto &header0 = cmd_list[m_current_index++];
auto &header1 = cmd_list[m_current_index++];
/* Set the header. */
header0 = {};
header0.Set<impl::CommonCommandFormat::CommandId>(impl::CommandId_Receive);
header0.Set<impl::ReceiveCommandFormat::StopCondition>((option & TransactionOption_StopCondition) != 0);
header0.Set<impl::ReceiveCommandFormat::StartCondition>((option & TransactionOption_StartCondition) != 0);
header1 = {};
header1.Set<impl::ReceiveCommandFormat::Size>(size);
R_SUCCEED();
}
Result CommandListFormatter::EnqueueSendCommand(i2c::TransactionOption option, const void *src, size_t size) {
/* Check that we can enqueue the command. */
constexpr size_t CommandLength = 2;
R_TRY(this->IsEnqueueAble(CommandLength + size));
/* Get the command list. */
util::BitPack8 *cmd_list = static_cast<util::BitPack8 *>(m_command_list);
/* Get references to the header. */
auto &header0 = cmd_list[m_current_index++];
auto &header1 = cmd_list[m_current_index++];
/* Set the header. */
header0 = {};
header0.Set<impl::CommonCommandFormat::CommandId>(impl::CommandId_Send);
header0.Set<impl::SendCommandFormat::StopCondition>((option & TransactionOption_StopCondition) != 0);
header0.Set<impl::SendCommandFormat::StartCondition>((option & TransactionOption_StartCondition) != 0);
header1 = {};
header1.Set<impl::SendCommandFormat::Size>(size);
/* Copy the data we're sending. */
std::memcpy(cmd_list + m_current_index, src, size);
m_current_index += size;
R_SUCCEED();
}
Result CommandListFormatter::EnqueueSleepCommand(int us) {
/* Check that we can enqueue the command. */
constexpr size_t CommandLength = 2;
R_TRY(this->IsEnqueueAble(CommandLength));
/* Get the command list. */
util::BitPack8 *cmd_list = static_cast<util::BitPack8 *>(m_command_list);
/* Get references to the header. */
auto &header0 = cmd_list[m_current_index++];
auto &header1 = cmd_list[m_current_index++];
/* Set the header. */
header0 = {};
header0.Set<impl::CommonCommandFormat::CommandId>(impl::CommandId_Extension);
header0.Set<impl::CommonCommandFormat::SubCommandId>(impl::SubCommandId_Sleep);
header1 = {};
header1.Set<impl::SleepCommandFormat::MicroSeconds>(us);
R_SUCCEED();
}
}
| 3,886
|
C++
|
.cpp
| 79
| 42.063291
| 114
| 0.667371
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,621
|
i2c_client_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/i2c/i2c_client_api.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams::i2c {
namespace {
constinit os::SdkMutex g_init_mutex;
constinit int g_initialize_count = 0;
constinit os::SdkMutex g_i2c_mutex;
ams::sf::SharedPointer<sf::IManager> g_i2c_manager;
constinit int g_i2c_count = 0;
constinit os::SdkMutex g_i2c_pcv_mutex;
ams::sf::SharedPointer<sf::IManager> g_i2c_pcv_manager;
constinit int g_i2c_pcv_count = 0;
i2c::sf::ISession *GetInterface(const I2cSession &session) {
AMS_ASSERT(session._session != nullptr);
return static_cast<i2c::sf::ISession *>(session._session);
}
ams::sf::SharedPointer<sf::IManager> GetManager(DeviceCode device_code) {
if (IsPowerBusDeviceCode(device_code)) {
return g_i2c_pcv_manager;
} else {
return g_i2c_manager;
}
}
}
void InitializeWith(ams::sf::SharedPointer<i2c::sf::IManager> sp, ams::sf::SharedPointer<i2c::sf::IManager> sp_pcv) {
std::scoped_lock lk(g_init_mutex);
AMS_ABORT_UNLESS(g_initialize_count == 0);
{
std::scoped_lock lk(g_i2c_mutex);
g_i2c_manager = std::move(sp);
AMS_ABORT_UNLESS(g_i2c_count == 0);
g_i2c_count = 1;
}
{
std::scoped_lock lk(g_i2c_pcv_mutex);
g_i2c_pcv_manager = std::move(sp_pcv);
AMS_ABORT_UNLESS(g_i2c_pcv_count == 0);
g_i2c_pcv_count = 1;
}
g_initialize_count = 1;
}
void InitializeEmpty() {
std::scoped_lock lk(g_init_mutex);
++g_initialize_count;
}
void Finalize() {
std::scoped_lock lk(g_init_mutex);
AMS_ASSERT(g_initialize_count > 0);
if ((--g_initialize_count) == 0) {
{
std::scoped_lock lk(g_i2c_mutex);
AMS_ASSERT(g_i2c_count > 0);
if (g_i2c_count > 0) {
if ((--g_i2c_count) == 0) {
g_i2c_manager = nullptr;
}
}
}
{
std::scoped_lock lk(g_i2c_pcv_mutex);
AMS_ASSERT(g_i2c_pcv_count > 0);
if (g_i2c_pcv_count > 0) {
if ((--g_i2c_pcv_count) == 0) {
g_i2c_manager = nullptr;
}
}
}
}
}
Result OpenSession(I2cSession *out, DeviceCode device_code) {
/* Get manager for the device. */
auto manager = GetManager(device_code);
/* Get the session. */
ams::sf::SharedPointer<i2c::sf::ISession> session;
{
if (hos::GetVersion() >= hos::Version_6_0_0) {
R_TRY(manager->OpenSession2(std::addressof(session), device_code));
} else {
R_TRY(manager->OpenSession(std::addressof(session), ConvertToI2cDevice(device_code)));
}
}
/* Set output. */
out->_session = session.Detach();
/* We succeeded. */
R_SUCCEED();
}
void CloseSession(I2cSession &session) {
/* Close the session. */
ams::sf::ReleaseSharedObject(GetInterface(session));
session._session = nullptr;
}
Result Send(const I2cSession &session, const void *src, size_t src_size, TransactionOption option) {
const ams::sf::InAutoSelectBuffer buf(src, src_size);
R_RETURN(GetInterface(session)->Send(buf, option));
}
Result Receive(void *dst, size_t dst_size, const I2cSession &session, TransactionOption option) {
const ams::sf::OutAutoSelectBuffer buf(dst, dst_size);
R_RETURN(GetInterface(session)->Receive(buf, option));
}
Result ExecuteCommandList(void *dst, size_t dst_size, const I2cSession &session, const void *src, size_t src_size) {
const ams::sf::OutAutoSelectBuffer buf(dst, dst_size);
const ams::sf::InPointerArray<i2c::I2cCommand> arr(static_cast<const i2c::I2cCommand *>(src), src_size);
R_RETURN(GetInterface(session)->ExecuteCommandList(buf, arr));
}
void SetRetryPolicy(const I2cSession &session, int max_retry_count, int retry_interval_us) {
AMS_ASSERT(max_retry_count >= 0);
AMS_ASSERT(retry_interval_us >= 0);
R_ABORT_UNLESS(GetInterface(session)->SetRetryPolicy(max_retry_count, retry_interval_us));
}
}
| 5,108
|
C++
|
.cpp
| 124
| 31.564516
| 121
| 0.587641
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,622
|
i2c_driver_service_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/i2c/driver/i2c_driver_service_api.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "impl/i2c_driver_core.hpp"
namespace ams::i2c::driver {
void RegisterDriver(II2cDriver *driver) {
return impl::RegisterDriver(driver);
}
void UnregisterDriver(II2cDriver *driver) {
return impl::UnregisterDriver(driver);
}
Result RegisterDeviceCode(DeviceCode device_code, I2cDeviceProperty *device) {
R_RETURN(impl::RegisterDeviceCode(device_code, device));
}
bool UnregisterDeviceCode(DeviceCode device_code) {
return impl::UnregisterDeviceCode(device_code);
}
}
| 1,207
|
C++
|
.cpp
| 31
| 35.193548
| 82
| 0.74166
|
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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.