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,723
|
os_io_region.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/os_io_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/os_io_region_impl.hpp"
namespace ams::os {
namespace {
void InitializeIoRegion(IoRegionType *io_region, NativeHandle handle, size_t size, bool managed) {
/* Set state. */
io_region->state = IoRegionType::State_Initialized;
/* Set member variables. */
io_region->handle = handle;
io_region->size = size;
io_region->handle_managed = managed;
io_region->mapped_address = nullptr;
/* Create critical section. */
util::ConstructAt(io_region->cs_io_region);
}
}
Result CreateIoRegion(IoRegionType *io_region, NativeHandle io_pool_handle, uintptr_t address, size_t size, MemoryMapping mapping, MemoryPermission permission) {
/* Check pre-conditions. */
AMS_ASSERT(io_region != nullptr);
AMS_ASSERT(io_pool_handle != os::InvalidNativeHandle);
AMS_ASSERT(util::IsAligned(address, os::MemoryPageSize));
AMS_ASSERT(util::IsAligned(size, os::MemoryPageSize));
AMS_ASSERT(mapping == MemoryMapping_IoRegister || mapping == MemoryMapping_Uncached || mapping == MemoryMapping_Memory);
AMS_ASSERT(permission == MemoryPermission_ReadOnly || permission == MemoryPermission_ReadWrite);
/* If we fail to create, ensure we reset the state. */
auto state_guard = SCOPE_GUARD { io_region->state = IoRegionType::State_NotInitialized; };
/* Create the io region. */
NativeHandle handle;
R_TRY(impl::IoRegionImpl::CreateIoRegion(std::addressof(handle), io_pool_handle, address, size, mapping, permission));
/* Setup the object. */
InitializeIoRegion(io_region, handle, size, true);
state_guard.Cancel();
R_SUCCEED();
}
void AttachIoRegionHandle(IoRegionType *io_region, size_t size, NativeHandle handle, bool managed) {
/* Check pre-conditions. */
AMS_ASSERT(io_region != nullptr);
AMS_ASSERT(util::IsAligned(size, os::MemoryPageSize));
AMS_ASSERT(handle != os::InvalidNativeHandle);
/* Setup the object. */
InitializeIoRegion(io_region, handle, size, managed);
}
os::NativeHandle DetachIoRegionHandle(IoRegionType *io_region) {
/* Check pre-conditions. */
AMS_ASSERT(io_region->state != IoRegionType::State_NotInitialized);
/* Acquire exclusive access to the io region. */
std::scoped_lock lk(util::GetReference(io_region->cs_io_region));
/* Check that we can detach. */
AMS_ASSERT(io_region->state == IoRegionType::State_Initialized);
/* Set state as detached. */
io_region->state = IoRegionType::State_Detached;
/* Detach the handle. */
const auto handle = io_region->handle;
io_region->handle = os::InvalidNativeHandle;
io_region->handle_managed = false;
return handle;
}
void DestroyIoRegion(IoRegionType *io_region) {
/* Check pre-conditions. */
AMS_ASSERT(io_region->state != IoRegionType::State_NotInitialized);
/* Acquire exclusive access to the io region. */
std::scoped_lock lk(util::GetReference(io_region->cs_io_region));
/* Check that we can destroy. */
AMS_ASSERT(io_region->state == IoRegionType::State_Initialized);
/* If managed, close the handle. */
if (io_region->handle_managed) {
os::CloseNativeHandle(io_region->handle);
}
/* Clear members. */
io_region->handle = os::InvalidNativeHandle;
io_region->handle_managed = false;
io_region->mapped_address = nullptr;
io_region->size = 0;
/* Mark not initialized. */
io_region->state = IoRegionType::State_NotInitialized;
}
NativeHandle GetIoRegionHandle(const IoRegionType *io_region) {
/* Check pre-conditions. */
AMS_ASSERT(io_region->state != IoRegionType::State_NotInitialized);
/* Acquire exclusive access to the io region. */
std::scoped_lock lk(util::GetReference(io_region->cs_io_region));
/* Get the handle. */
return io_region->handle;
}
Result MapIoRegion(void **out, IoRegionType *io_region, MemoryPermission perm) {
/* Check pre-conditions. */
AMS_ASSERT(out != nullptr);
AMS_ASSERT(io_region != nullptr);
AMS_ASSERT(io_region->state != IoRegionType::State_NotInitialized);
AMS_ASSERT(perm == MemoryPermission_ReadOnly || perm == MemoryPermission_ReadWrite);
/* Acquire exclusive access to the io region. */
std::scoped_lock lk(util::GetReference(io_region->cs_io_region));
/* Check that we can map. */
AMS_ASSERT(io_region->state == IoRegionType::State_Initialized);
/* Get the size. */
const size_t size = io_region->size;
AMS_ASSERT(size == io_region->size);
/* Map. */
void *mapped_address;
R_TRY(impl::IoRegionImpl::MapIoRegion(std::addressof(mapped_address), io_region->handle, size, perm));
/* Set mapped address. */
io_region->mapped_address = mapped_address;
/* Set mapped. */
io_region->state = IoRegionType::State_Mapped;
/* Set the output address. */
*out = mapped_address;
R_SUCCEED();
}
void UnmapIoRegion(IoRegionType *io_region) {
/* Check pre-conditions. */
AMS_ASSERT(io_region->state != IoRegionType::State_NotInitialized);
/* Acquire exclusive access to the io region. */
std::scoped_lock lk(util::GetReference(io_region->cs_io_region));
/* Check that we can unmap. */
AMS_ASSERT(io_region->state == IoRegionType::State_Mapped);
/* Get the size. */
const size_t size = io_region->size;
AMS_ASSERT(size == io_region->size);
/* Unmap the io region. */
impl::IoRegionImpl::UnmapIoRegion(io_region->handle, io_region->mapped_address, size);
/* Clear mapped address. */
io_region->mapped_address = nullptr;
/* Set not-mapped. */
io_region->state = IoRegionType::State_NotInitialized;
}
}
| 6,885
|
C++
|
.cpp
| 141
| 40.652482
| 165
| 0.640191
|
Atmosphere-NX/Atmosphere
| 14,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,724
|
os_sdk_reply_and_receive.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/os_sdk_reply_and_receive.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/os_multiple_wait_impl.hpp"
#include "impl/os_multiple_wait_holder_base.hpp"
#include "impl/os_multiple_wait_holder_impl.hpp"
namespace ams::os {
namespace {
ALWAYS_INLINE impl::MultiWaitImpl &GetMultiWaitImpl(MultiWaitType *multi_wait) {
return GetReference(multi_wait->impl_storage);
}
ALWAYS_INLINE MultiWaitHolderType *CastToMultiWaitHolder(impl::MultiWaitHolderBase *base) {
return reinterpret_cast<MultiWaitHolderType *>(base);
}
}
Result SdkReplyAndReceive(os::MultiWaitHolderType **out, NativeHandle reply_target, MultiWaitType *multi_wait) {
auto &impl = GetMultiWaitImpl(multi_wait);
AMS_ASSERT(multi_wait->state == MultiWaitType::State_Initialized);
AMS_ASSERT(impl.IsListNotEmpty());
impl::MultiWaitHolderBase *holder_base = nullptr;
ON_SCOPE_EXIT { *out = CastToMultiWaitHolder(holder_base); };
R_RETURN(impl.ReplyAndReceive(std::addressof(holder_base), reply_target));
}
}
| 1,694
|
C++
|
.cpp
| 37
| 40.891892
| 116
| 0.72799
|
Atmosphere-NX/Atmosphere
| 14,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,725
|
os_memory_permission.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/os_memory_permission.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/os_memory_permission_impl.hpp"
namespace ams::os {
void SetMemoryPermission(uintptr_t address, size_t size, MemoryPermission perm) {
return impl::SetMemoryPermissionImpl(address, size, perm);
}
}
| 893
|
C++
|
.cpp
| 22
| 38.090909
| 85
| 0.75576
|
Atmosphere-NX/Atmosphere
| 14,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,726
|
os_message_queue.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/os_message_queue.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/os_timeout_helper.hpp"
#include "impl/os_multiple_wait_object_list.hpp"
#include "impl/os_multiple_wait_holder_impl.hpp"
#include "impl/os_message_queue_helper.hpp"
namespace ams::os {
namespace {
using MessageQueueHelper = impl::MessageQueueHelper<MessageQueueType>;
}
void InitializeMessageQueue(MessageQueueType *mq, uintptr_t *buffer, size_t count) {
AMS_ASSERT(buffer != nullptr);
AMS_ASSERT(count >= 1);
/* Setup objects. */
util::ConstructAt(mq->cs_queue);
util::ConstructAt(mq->cv_not_full);
util::ConstructAt(mq->cv_not_empty);
/* Setup wait lists. */
util::ConstructAt(mq->waitlist_not_empty);
util::ConstructAt(mq->waitlist_not_full);
/* Set member variables. */
mq->buffer = buffer;
mq->capacity = static_cast<s32>(count);
mq->count = 0;
mq->offset = 0;
/* Mark initialized. */
mq->state = MessageQueueType::State_Initialized;
}
void FinalizeMessageQueue(MessageQueueType *mq) {
AMS_ASSERT(mq->state == MessageQueueType::State_Initialized);
AMS_ASSERT(GetReference(mq->waitlist_not_empty).IsEmpty());
AMS_ASSERT(GetReference(mq->waitlist_not_full).IsEmpty());
/* Mark uninitialized. */
mq->state = MessageQueueType::State_NotInitialized;
/* Destroy wait lists. */
util::DestroyAt(mq->waitlist_not_empty);
util::DestroyAt(mq->waitlist_not_full);
/* Destroy objects. */
util::DestroyAt(mq->cv_not_empty);
util::DestroyAt(mq->cv_not_full);
util::DestroyAt(mq->cs_queue);
}
/* Sending (FIFO functionality) */
void SendMessageQueue(MessageQueueType *mq, uintptr_t data) {
AMS_ASSERT(mq->state == MessageQueueType::State_Initialized);
{
/* Acquire mutex, wait sendable. */
std::scoped_lock lk(GetReference(mq->cs_queue));
while (MessageQueueHelper::IsMessageQueueFull(mq)) {
GetReference(mq->cv_not_full).Wait(GetPointer(mq->cs_queue));
}
/* Send, signal. */
MessageQueueHelper::EnqueueUnsafe(mq, data);
GetReference(mq->cv_not_empty).Broadcast();
GetReference(mq->waitlist_not_empty).WakeupAllMultiWaitThreadsUnsafe();
}
}
bool TrySendMessageQueue(MessageQueueType *mq, uintptr_t data) {
AMS_ASSERT(mq->state == MessageQueueType::State_Initialized);
{
/* Acquire mutex, check sendable. */
std::scoped_lock lk(GetReference(mq->cs_queue));
if (MessageQueueHelper::IsMessageQueueFull(mq)) {
return false;
}
/* Send, signal. */
MessageQueueHelper::EnqueueUnsafe(mq, data);
GetReference(mq->cv_not_empty).Broadcast();
GetReference(mq->waitlist_not_empty).WakeupAllMultiWaitThreadsUnsafe();
}
return true;
}
bool TimedSendMessageQueue(MessageQueueType *mq, uintptr_t data, TimeSpan timeout) {
AMS_ASSERT(mq->state == MessageQueueType::State_Initialized);
AMS_ASSERT(timeout.GetNanoSeconds() >= 0);
{
/* Acquire mutex, wait sendable. */
impl::TimeoutHelper timeout_helper(timeout);
std::scoped_lock lk(GetReference(mq->cs_queue));
while (MessageQueueHelper::IsMessageQueueFull(mq)) {
if (timeout_helper.TimedOut()) {
return false;
}
GetReference(mq->cv_not_full).TimedWait(GetPointer(mq->cs_queue), timeout_helper);
}
/* Send, signal. */
MessageQueueHelper::EnqueueUnsafe(mq, data);
GetReference(mq->cv_not_empty).Broadcast();
GetReference(mq->waitlist_not_empty).WakeupAllMultiWaitThreadsUnsafe();
}
return true;
}
/* Jamming (LIFO functionality) */
void JamMessageQueue(MessageQueueType *mq, uintptr_t data) {
AMS_ASSERT(mq->state == MessageQueueType::State_Initialized);
{
/* Acquire mutex, wait sendable. */
std::scoped_lock lk(GetReference(mq->cs_queue));
while (MessageQueueHelper::IsMessageQueueFull(mq)) {
GetReference(mq->cv_not_full).Wait(GetPointer(mq->cs_queue));
}
/* Send, signal. */
MessageQueueHelper::JamUnsafe(mq, data);
GetReference(mq->cv_not_empty).Broadcast();
GetReference(mq->waitlist_not_empty).WakeupAllMultiWaitThreadsUnsafe();
}
}
bool TryJamMessageQueue(MessageQueueType *mq, uintptr_t data) {
AMS_ASSERT(mq->state == MessageQueueType::State_Initialized);
{
/* Acquire mutex, check sendable. */
std::scoped_lock lk(GetReference(mq->cs_queue));
if (MessageQueueHelper::IsMessageQueueFull(mq)) {
return false;
}
/* Send, signal. */
MessageQueueHelper::JamUnsafe(mq, data);
GetReference(mq->cv_not_empty).Broadcast();
GetReference(mq->waitlist_not_empty).WakeupAllMultiWaitThreadsUnsafe();
}
return true;
}
bool TimedJamMessageQueue(MessageQueueType *mq, uintptr_t data, TimeSpan timeout) {
AMS_ASSERT(mq->state == MessageQueueType::State_Initialized);
AMS_ASSERT(timeout.GetNanoSeconds() >= 0);
{
/* Acquire mutex, wait sendable. */
impl::TimeoutHelper timeout_helper(timeout);
std::scoped_lock lk(GetReference(mq->cs_queue));
while (MessageQueueHelper::IsMessageQueueFull(mq)) {
if (timeout_helper.TimedOut()) {
return false;
}
GetReference(mq->cv_not_full).TimedWait(GetPointer(mq->cs_queue), timeout_helper);
}
/* Send, signal. */
MessageQueueHelper::JamUnsafe(mq, data);
GetReference(mq->cv_not_empty).Broadcast();
GetReference(mq->waitlist_not_empty).WakeupAllMultiWaitThreadsUnsafe();
}
return true;
}
/* Receive functionality */
void ReceiveMessageQueue(uintptr_t *out, MessageQueueType *mq) {
AMS_ASSERT(mq->state == MessageQueueType::State_Initialized);
{
/* Acquire mutex, wait receivable. */
std::scoped_lock lk(GetReference(mq->cs_queue));
while (MessageQueueHelper::IsMessageQueueEmpty(mq)) {
GetReference(mq->cv_not_empty).Wait(GetPointer(mq->cs_queue));
}
/* Receive, signal. */
*out = MessageQueueHelper::DequeueUnsafe(mq);
GetReference(mq->cv_not_full).Broadcast();
GetReference(mq->waitlist_not_full).WakeupAllMultiWaitThreadsUnsafe();
}
}
bool TryReceiveMessageQueue(uintptr_t *out, MessageQueueType *mq) {
AMS_ASSERT(mq->state == MessageQueueType::State_Initialized);
{
/* Acquire mutex, check receivable. */
std::scoped_lock lk(GetReference(mq->cs_queue));
if (MessageQueueHelper::IsMessageQueueEmpty(mq)) {
return false;
}
/* Receive, signal. */
*out = MessageQueueHelper::DequeueUnsafe(mq);
GetReference(mq->cv_not_full).Broadcast();
GetReference(mq->waitlist_not_full).WakeupAllMultiWaitThreadsUnsafe();
}
return true;
}
bool TimedReceiveMessageQueue(uintptr_t *out, MessageQueueType *mq, TimeSpan timeout) {
AMS_ASSERT(mq->state == MessageQueueType::State_Initialized);
AMS_ASSERT(timeout.GetNanoSeconds() >= 0);
{
/* Acquire mutex, wait receivable. */
impl::TimeoutHelper timeout_helper(timeout);
std::scoped_lock lk(GetReference(mq->cs_queue));
while (MessageQueueHelper::IsMessageQueueEmpty(mq)) {
if (timeout_helper.TimedOut()) {
return false;
}
GetReference(mq->cv_not_empty).TimedWait(GetPointer(mq->cs_queue), timeout_helper);
}
/* Receive, signal. */
*out = MessageQueueHelper::DequeueUnsafe(mq);
GetReference(mq->cv_not_full).Broadcast();
GetReference(mq->waitlist_not_full).WakeupAllMultiWaitThreadsUnsafe();
}
return true;
}
/* Peek functionality */
void PeekMessageQueue(uintptr_t *out, const MessageQueueType *mq) {
AMS_ASSERT(mq->state == MessageQueueType::State_Initialized);
{
/* Acquire mutex, wait receivable. */
std::scoped_lock lk(GetReference(mq->cs_queue));
while (MessageQueueHelper::IsMessageQueueEmpty(mq)) {
GetReference(mq->cv_not_empty).Wait(GetPointer(mq->cs_queue));
}
/* Peek. */
*out = MessageQueueHelper::PeekUnsafe(mq);
}
}
bool TryPeekMessageQueue(uintptr_t *out, const MessageQueueType *mq) {
AMS_ASSERT(mq->state == MessageQueueType::State_Initialized);
{
/* Acquire mutex, check receivable. */
std::scoped_lock lk(GetReference(mq->cs_queue));
if (MessageQueueHelper::IsMessageQueueEmpty(mq)) {
return false;
}
/* Peek. */
*out = MessageQueueHelper::PeekUnsafe(mq);
}
return true;
}
bool TimedPeekMessageQueue(uintptr_t *out, const MessageQueueType *mq, TimeSpan timeout) {
AMS_ASSERT(mq->state == MessageQueueType::State_Initialized);
AMS_ASSERT(timeout.GetNanoSeconds() >= 0);
{
/* Acquire mutex, wait receivable. */
impl::TimeoutHelper timeout_helper(timeout);
std::scoped_lock lk(GetReference(mq->cs_queue));
while (MessageQueueHelper::IsMessageQueueEmpty(mq)) {
if (timeout_helper.TimedOut()) {
return false;
}
GetReference(mq->cv_not_empty).TimedWait(GetPointer(mq->cs_queue), timeout_helper);
}
/* Peek. */
*out = MessageQueueHelper::PeekUnsafe(mq);
}
return true;
}
void InitializeMultiWaitHolder(MultiWaitHolderType *multi_wait_holder, MessageQueueType *mq, MessageQueueWaitType type) {
AMS_ASSERT(mq->state == MessageQueueType::State_Initialized);
switch (type) {
case MessageQueueWaitType::ForNotFull:
util::ConstructAt(GetReference(multi_wait_holder->impl_storage).holder_of_mq_not_full_storage, mq);
break;
case MessageQueueWaitType::ForNotEmpty:
util::ConstructAt(GetReference(multi_wait_holder->impl_storage).holder_of_mq_not_empty_storage, mq);
break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
multi_wait_holder->user_data = 0;
}
}
| 11,708
|
C++
|
.cpp
| 264
| 33.848485
| 125
| 0.609323
|
Atmosphere-NX/Atmosphere
| 14,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,727
|
os_sdk_mutex.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/os_sdk_mutex.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(AMS_OS_INTERNAL_CRITICAL_SECTION_IMPL_CAN_CHECK_LOCKED_BY_CURRENT_THREAD)
#include "impl/os_thread_manager.hpp"
#endif
namespace ams::os {
void InitializeSdkMutex(SdkMutexType *mutex) {
/* Initialize the critical section. */
GetReference(mutex->_storage).Initialize();
/* If the underlying critical section can't readily be checked, set owner thread. */
#if !defined(AMS_OS_INTERNAL_CRITICAL_SECTION_IMPL_CAN_CHECK_LOCKED_BY_CURRENT_THREAD)
mutex->owner_thread = nullptr;
#endif
}
bool IsSdkMutexLockedByCurrentThread(const SdkMutexType *mutex) {
#if defined(AMS_OS_INTERNAL_CRITICAL_SECTION_IMPL_CAN_CHECK_LOCKED_BY_CURRENT_THREAD)
/* Check whether the critical section is held. */
return GetReference(mutex->_storage).IsLockedByCurrentThread();
#else
/* Check if the current thread is owner. */
return mutex->owner_thread == os::impl::GetCurrentThread();
#endif
}
void LockSdkMutex(SdkMutexType *mutex) {
/* Check pre-conditions. */
AMS_ABORT_UNLESS(!IsSdkMutexLockedByCurrentThread(mutex));
/* Enter the critical section. */
GetReference(mutex->_storage).Enter();
/* If necessary, set owner thread. */
#if !defined(AMS_OS_INTERNAL_CRITICAL_SECTION_IMPL_CAN_CHECK_LOCKED_BY_CURRENT_THREAD)
mutex->owner_thread = os::impl::GetCurrentThread();
#endif
}
bool TryLockSdkMutex(SdkMutexType *mutex) {
/* Check pre-conditions. */
AMS_ABORT_UNLESS(!IsSdkMutexLockedByCurrentThread(mutex));
/* Try to enter the critical section. */
const bool res = GetReference(mutex->_storage).TryEnter();
/* If necessary, set owner thread. */
#if !defined(AMS_OS_INTERNAL_CRITICAL_SECTION_IMPL_CAN_CHECK_LOCKED_BY_CURRENT_THREAD)
if (res) {
mutex->owner_thread = os::impl::GetCurrentThread();
}
#endif
return res;
}
void UnlockSdkMutex(SdkMutexType *mutex) {
/* Check pre-conditions. */
AMS_ABORT_UNLESS(IsSdkMutexLockedByCurrentThread(mutex));
/* If necessary, clear owner thread. */
#if !defined(AMS_OS_INTERNAL_CRITICAL_SECTION_IMPL_CAN_CHECK_LOCKED_BY_CURRENT_THREAD)
mutex->owner_thread = nullptr;
#endif
/* Leave the critical section. */
GetReference(mutex->_storage).Leave();
}
}
| 3,121
|
C++
|
.cpp
| 71
| 37.422535
| 94
| 0.682043
|
Atmosphere-NX/Atmosphere
| 14,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,728
|
os_insecure_memory.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/os_insecure_memory.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/os_insecure_memory_impl.hpp"
namespace ams::os {
Result AllocateInsecureMemory(uintptr_t *out_address, size_t size) {
/* Check arguments. */
AMS_ASSERT(size > 0);
AMS_ASSERT(util::IsAligned(size, os::MemoryPageSize));
/* Allocate memory. */
R_RETURN(impl::InsecureMemoryImpl::AllocateInsecureMemoryImpl(out_address, size));
}
void FreeInsecureMemory(uintptr_t address, size_t size) {
/* Check arguments. */
AMS_ASSERT(util::IsAligned(address, os::MemoryPageSize));
AMS_ASSERT(util::IsAligned(size, os::MemoryPageSize));
/* Free memory. */
impl::InsecureMemoryImpl::FreeInsecureMemoryImpl(address, size);
}
}
| 1,388
|
C++
|
.cpp
| 33
| 37.545455
| 90
| 0.710897
|
Atmosphere-NX/Atmosphere
| 14,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,729
|
os_unsafe_memory.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/os_unsafe_memory.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/os_unsafe_memory_impl.hpp"
namespace ams::os {
Result AllocateUnsafeMemory(uintptr_t *out_address, size_t size) {
/* Check arguments. */
AMS_ASSERT(size > 0);
AMS_ASSERT(util::IsAligned(size, os::MemoryPageSize));
/* Allocate memory. */
R_RETURN(impl::UnsafeMemoryImpl::AllocateUnsafeMemoryImpl(out_address, size));
}
Result FreeUnsafeMemory(uintptr_t address, size_t size) {
/* Check arguments. */
AMS_ASSERT(util::IsAligned(address, os::MemoryPageSize));
AMS_ASSERT(util::IsAligned(size, os::MemoryPageSize));
/* Free memory. */
R_RETURN(impl::UnsafeMemoryImpl::FreeUnsafeMemoryImpl(address, size));
}
}
| 1,386
|
C++
|
.cpp
| 33
| 37.484848
| 86
| 0.708241
|
Atmosphere-NX/Atmosphere
| 14,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,730
|
os_mutex.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/os_mutex.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/os_thread_manager.hpp"
#include "impl/os_mutex_impl.hpp"
namespace ams::os {
namespace impl {
#ifdef ATMOSPHERE_BUILD_FOR_AUDITING
void PushAndCheckLockLevel(const MutexType *mutex) {
/* If auditing isn't specified, don't bother. */
if (mutex->lock_level == 0) {
return;
}
/* TODO: Implement mutex level auditing. */
}
void PopAndCheckLockLevel(const MutexType *mutex) {
/* If auditing isn't specified, don't bother. */
if (mutex->lock_level == 0) {
return;
}
/* TODO: Implement mutex level auditing. */
}
#else
void PushAndCheckLockLevel(const MutexType *mutex) {
AMS_UNUSED(mutex);
}
void PopAndCheckLockLevel(const MutexType *mutex) {
AMS_UNUSED(mutex);
}
#endif
}
namespace {
ALWAYS_INLINE void AfterLockMutex(MutexType *mutex, ThreadType *cur_thread) {
AMS_ASSERT(mutex->nest_count < MutexRecursiveLockCountMax);
impl::PushAndCheckLockLevel(mutex);
++mutex->nest_count;
mutex->owner_thread = cur_thread;
}
}
void InitializeMutex(MutexType *mutex, bool recursive, int lock_level) {
AMS_ASSERT((lock_level == 0) || (MutexLockLevelMin <= lock_level && lock_level <= MutexLockLevelMax));
/* Create object. */
util::ConstructAt(mutex->_storage);
/* Set member variables. */
mutex->is_recursive = recursive;
mutex->lock_level = lock_level;
mutex->nest_count = 0;
mutex->owner_thread = nullptr;
/* Mark initialized. */
mutex->state = MutexType::State_Initialized;
}
void FinalizeMutex(MutexType *mutex) {
AMS_ASSERT(mutex->state == MutexType::State_Initialized);
/* Mark not intialized. */
mutex->state = MutexType::State_NotInitialized;
/* Destroy object. */
util::DestroyAt(mutex->_storage);
}
void LockMutex(MutexType *mutex) {
AMS_ASSERT(mutex->state == MutexType::State_Initialized);
ThreadType *current = impl::GetCurrentThread();
if (!mutex->is_recursive) {
AMS_ASSERT(mutex->owner_thread != current);
GetReference(mutex->_storage).Enter();
} else {
if (mutex->owner_thread == current) {
AMS_ASSERT(mutex->nest_count >= 1);
} else {
GetReference(mutex->_storage).Enter();
}
}
AfterLockMutex(mutex, current);
}
bool TryLockMutex(MutexType *mutex) {
AMS_ASSERT(mutex->state == MutexType::State_Initialized);
ThreadType *current = impl::GetCurrentThread();
if (!mutex->is_recursive) {
AMS_ASSERT(mutex->owner_thread != current);
if (!GetReference(mutex->_storage).TryEnter()) {
return false;
}
} else {
if (mutex->owner_thread == current) {
AMS_ASSERT(mutex->nest_count >= 1);
} else {
if (!GetReference(mutex->_storage).TryEnter()) {
return false;
}
}
}
AfterLockMutex(mutex, current);
return true;
}
void UnlockMutex(MutexType *mutex) {
AMS_ASSERT(mutex->state == MutexType::State_Initialized);
AMS_ASSERT(mutex->nest_count > 0);
AMS_ASSERT(mutex->owner_thread == impl::GetCurrentThread());
impl::PopAndCheckLockLevel(mutex);
if ((--mutex->nest_count) == 0) {
mutex->owner_thread = nullptr;
GetReference(mutex->_storage).Leave();
}
}
bool IsMutexLockedByCurrentThread(const MutexType *mutex) {
AMS_ASSERT(mutex->state == MutexType::State_Initialized);
return mutex->owner_thread == impl::GetCurrentThread();
}
}
| 4,745
|
C++
|
.cpp
| 121
| 29.446281
| 110
| 0.58626
|
Atmosphere-NX/Atmosphere
| 14,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,731
|
os_light_message_queue.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/os_light_message_queue.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/os_timeout_helper.hpp"
#include "impl/os_message_queue_helper.hpp"
namespace ams::os {
namespace {
using MessageQueueHelper = impl::MessageQueueHelper<LightMessageQueueType>;
template<bool ClearEvent, auto EnqueueFunction>
bool TryEnqueueLightMessageQueueImpl(LightMessageQueueType *mq, uintptr_t data) {
/* Perform the enqueue. */
{
/* Acquire exclusive access to the queue. */
std::scoped_lock lk(util::GetReference(mq->mutex_queue));
/* Check that we can enqueue. */
if (MessageQueueHelper::IsMessageQueueFull(mq)) {
/* If we should, clear the event. */
if constexpr (ClearEvent) {
util::GetReference(mq->ev_not_full).Clear();
}
/* We can't enqueue because we're full. */
return false;
}
/* Enqueue the data. */
EnqueueFunction(mq, data);
}
/* Signal that we're not empty. */
util::GetReference(mq->ev_not_empty).SignalWithManualClear();
return true;
}
template<bool ClearEvent>
bool TrySendLightMessageQueueImpl(LightMessageQueueType *mq, uintptr_t data) {
return TryEnqueueLightMessageQueueImpl<ClearEvent, MessageQueueHelper::EnqueueUnsafe>(mq, data);
}
template<bool ClearEvent>
bool TryJamLightMessageQueueImpl(LightMessageQueueType *mq, uintptr_t data) {
return TryEnqueueLightMessageQueueImpl<ClearEvent, MessageQueueHelper::JamUnsafe>(mq, data);
}
template<bool ClearEvent>
bool TryReceiveLightMessageQueueImpl(uintptr_t *out, LightMessageQueueType *mq) {
/* Perform the receive. */
{
/* Acquire exclusive access to the queue. */
std::scoped_lock lk(util::GetReference(mq->mutex_queue));
/* Check that we can receive. */
if (MessageQueueHelper::IsMessageQueueEmpty(mq)) {
/* If we should, clear the event. */
if constexpr (ClearEvent) {
util::GetReference(mq->ev_not_empty).Clear();
}
/* We can't enqueue because we're full. */
return false;
}
/* Receive the data. */
*out = MessageQueueHelper::DequeueUnsafe(mq);
}
/* Signal that we're not full. */
util::GetReference(mq->ev_not_full).SignalWithManualClear();
return true;
}
template<bool ClearEvent>
bool TryPeekLightMessageQueueImpl(uintptr_t *out, const LightMessageQueueType *mq) {
/* Perform the peek. */
{
/* Acquire exclusive access to the queue. */
std::scoped_lock lk(util::GetReference(mq->mutex_queue));
/* Check that we can peek. */
if (MessageQueueHelper::IsMessageQueueEmpty(mq)) {
/* If we should, clear the event. */
if constexpr (ClearEvent) {
util::GetReference(mq->ev_not_empty).Clear();
}
/* We can't enqueue because we're full. */
return false;
}
/* Peek the data. */
*out = MessageQueueHelper::PeekUnsafe(mq);
}
return true;
}
}
void InitializeLightMessageQueue(LightMessageQueueType *mq, uintptr_t *buffer, size_t count) {
/* Check pre-conditions. */
AMS_ASSERT(buffer != nullptr);
AMS_ASSERT(count >= 1);
/* Construct objects. */
util::ConstructAt(mq->mutex_queue);
util::ConstructAt(mq->ev_not_empty, false);
util::ConstructAt(mq->ev_not_full, true);
/* Set member variables. */
mq->buffer = buffer;
mq->capacity = static_cast<s32>(count);
mq->count = 0;
mq->offset = 0;
/* Mark initialized. */
mq->state = LightMessageQueueType::State_Initialized;
}
void FinalizeLightMessageQueue(LightMessageQueueType *mq) {
/* Check pre-conditions. */
AMS_ASSERT(mq->state == LightMessageQueueType::State_Initialized);
/* Mark uninitialized. */
mq->state = LightMessageQueueType::State_NotInitialized;
/* Destroy objects. */
util::DestroyAt(mq->ev_not_empty);
util::DestroyAt(mq->ev_not_full);
util::DestroyAt(mq->mutex_queue);
}
/* Sending (FIFO functionality) */
void SendLightMessageQueue(LightMessageQueueType *mq, uintptr_t data) {
/* Check pre-conditions. */
AMS_ASSERT(mq->state == LightMessageQueueType::State_Initialized);
/* Repeatedly try to send. */
while (!TrySendLightMessageQueueImpl<true>(mq, data)) {
/* Wait until we can try to send again. */
util::GetReference(mq->ev_not_full).WaitWithManualClear();
}
}
bool TrySendLightMessageQueue(LightMessageQueueType *mq, uintptr_t data) {
/* Check pre-conditions. */
AMS_ASSERT(mq->state == LightMessageQueueType::State_Initialized);
/* Try to send. */
return TrySendLightMessageQueueImpl<false>(mq, data);
}
bool TimedSendLightMessageQueue(LightMessageQueueType *mq, uintptr_t data, TimeSpan timeout) {
/* Check pre-conditions. */
AMS_ASSERT(mq->state == LightMessageQueueType::State_Initialized);
AMS_ASSERT(timeout.GetNanoSeconds() >= 0);
/* Create timeout helper. */
impl::TimeoutHelper timeout_helper(timeout);
/* Repeatedly try to send. */
while (!TrySendLightMessageQueueImpl<true>(mq, data)) {
/* Check if we're timed out. */
if (timeout_helper.TimedOut()) {
return false;
}
/* Wait until we can try to send again. */
util::GetReference(mq->ev_not_full).TimedWaitWithManualClear(timeout_helper);
}
return true;
}
/* Jamming (LIFO functionality) */
void JamLightMessageQueue(LightMessageQueueType *mq, uintptr_t data) {
/* Check pre-conditions. */
AMS_ASSERT(mq->state == LightMessageQueueType::State_Initialized);
/* Repeatedly try to jam. */
while (!TryJamLightMessageQueueImpl<true>(mq, data)) {
/* Wait until we can try to jam again. */
util::GetReference(mq->ev_not_full).WaitWithManualClear();
}
}
bool TryJamLightMessageQueue(LightMessageQueueType *mq, uintptr_t data) {
/* Check pre-conditions. */
AMS_ASSERT(mq->state == LightMessageQueueType::State_Initialized);
/* Try to jam. */
return TryJamLightMessageQueueImpl<false>(mq, data);
}
bool TimedJamLightMessageQueue(LightMessageQueueType *mq, uintptr_t data, TimeSpan timeout) {
/* Check pre-conditions. */
AMS_ASSERT(mq->state == LightMessageQueueType::State_Initialized);
AMS_ASSERT(timeout.GetNanoSeconds() >= 0);
/* Create timeout helper. */
impl::TimeoutHelper timeout_helper(timeout);
/* Repeatedly try to jam. */
while (!TryJamLightMessageQueueImpl<true>(mq, data)) {
/* Check if we're timed out. */
if (timeout_helper.TimedOut()) {
return false;
}
/* Wait until we can try to jam again. */
util::GetReference(mq->ev_not_full).TimedWaitWithManualClear(timeout_helper);
}
return true;
}
/* Receive functionality */
void ReceiveLightMessageQueue(uintptr_t *out, LightMessageQueueType *mq) {
/* Check pre-conditions. */
AMS_ASSERT(mq->state == LightMessageQueueType::State_Initialized);
/* Repeatedly try to receive. */
while (!TryReceiveLightMessageQueueImpl<true>(out, mq)) {
/* Wait until we can try to receive again. */
util::GetReference(mq->ev_not_empty).WaitWithManualClear();
}
}
bool TryReceiveLightMessageQueue(uintptr_t *out, LightMessageQueueType *mq) {
/* Check pre-conditions. */
AMS_ASSERT(mq->state == LightMessageQueueType::State_Initialized);
/* Try to receive. */
return TryReceiveLightMessageQueueImpl<false>(out, mq);
}
bool TimedReceiveLightMessageQueue(uintptr_t *out, LightMessageQueueType *mq, TimeSpan timeout) {
/* Check pre-conditions. */
AMS_ASSERT(mq->state == LightMessageQueueType::State_Initialized);
AMS_ASSERT(timeout.GetNanoSeconds() >= 0);
/* Create timeout helper. */
impl::TimeoutHelper timeout_helper(timeout);
/* Repeatedly try to receive. */
while (!TryReceiveLightMessageQueueImpl<true>(out, mq)) {
/* Check if we're timed out. */
if (timeout_helper.TimedOut()) {
return false;
}
/* Wait until we can try to receive again. */
util::GetReference(mq->ev_not_empty).TimedWaitWithManualClear(timeout_helper);
}
return true;
}
/* Peek functionality */
void PeekLightMessageQueue(uintptr_t *out, const LightMessageQueueType *mq) {
/* Check pre-conditions. */
AMS_ASSERT(mq->state == LightMessageQueueType::State_Initialized);
/* Repeatedly try to peek. */
while (!TryPeekLightMessageQueueImpl<true>(out, mq)) {
/* Wait until we can try to peek again. */
util::GetReference(mq->ev_not_empty).WaitWithManualClear();
}
}
bool TryPeekLightMessageQueue(uintptr_t *out, const LightMessageQueueType *mq) {
/* Check pre-conditions. */
AMS_ASSERT(mq->state == LightMessageQueueType::State_Initialized);
/* Try to peek. */
return TryPeekLightMessageQueueImpl<false>(out, mq);
}
bool TimedPeekLightMessageQueue(uintptr_t *out, const LightMessageQueueType *mq, TimeSpan timeout) {
/* Check pre-conditions. */
AMS_ASSERT(mq->state == LightMessageQueueType::State_Initialized);
AMS_ASSERT(timeout.GetNanoSeconds() >= 0);
/* Create timeout helper. */
impl::TimeoutHelper timeout_helper(timeout);
/* Repeatedly try to peek. */
while (!TryPeekLightMessageQueueImpl<true>(out, mq)) {
/* Check if we're timed out. */
if (timeout_helper.TimedOut()) {
return false;
}
/* Wait until we can try to peek again. */
util::GetReference(mq->ev_not_empty).TimedWaitWithManualClear(timeout_helper);
}
return true;
}
}
| 11,523
|
C++
|
.cpp
| 253
| 34.976285
| 108
| 0.605463
|
Atmosphere-NX/Atmosphere
| 14,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,732
|
os_thread_local_storage_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/os_thread_local_storage_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/os_thread_manager.hpp"
#include "impl/os_tls_manager.hpp"
namespace ams::os {
#if defined(ATMOSPHERE_OS_HORIZON)
namespace {
using LibnxTlsDestructor = void (*)(void *);
}
Result AllocateTlsSlot(TlsSlot *out, TlsDestructor destructor) {
s32 slot = ::threadTlsAlloc(reinterpret_cast<LibnxTlsDestructor>(reinterpret_cast<void *>(destructor)));
R_UNLESS(slot >= 0, os::ResultOutOfResource());
*out = { static_cast<u32>(slot) };
R_SUCCEED();
}
void FreeTlsSlot(TlsSlot slot) {
::threadTlsFree(static_cast<s32>(slot._value));
}
uintptr_t GetTlsValue(TlsSlot slot) {
return reinterpret_cast<uintptr_t>(::threadTlsGet(static_cast<s32>(slot._value)));
}
void SetTlsValue(TlsSlot slot, uintptr_t value) {
::threadTlsSet(static_cast<s32>(slot._value), reinterpret_cast<void *>(value));
}
#else
Result AllocateTlsSlot(TlsSlot *out, TlsDestructor destructor) {
R_UNLESS(impl::GetTlsManager().AllocateTlsSlot(out, destructor, false), os::ResultOutOfResource());
R_SUCCEED();
}
void FreeTlsSlot(TlsSlot slot) {
AMS_ASSERT(slot._value < impl::TotalTlsSlotCountMax);
impl::GetTlsManager().FreeTlsSlot(slot);
}
uintptr_t GetTlsValue(TlsSlot slot) {
AMS_ASSERT(slot._value < impl::TotalTlsSlotCountMax);
return impl::GetCurrentThread()->tls_value_array[slot._value];
}
void SetTlsValue(TlsSlot slot, uintptr_t value) {
AMS_ASSERT(slot._value < impl::TotalTlsSlotCountMax);
impl::GetCurrentThread()->tls_value_array[slot._value] = value;
}
#endif
}
| 2,335
|
C++
|
.cpp
| 57
| 35.736842
| 112
| 0.695537
|
Atmosphere-NX/Atmosphere
| 14,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,733
|
os_process_handle_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/os_process_handle_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/os_process_handle_impl.hpp"
namespace ams {
namespace dd {
dd::ProcessHandle __attribute__((const)) GetCurrentProcessHandle() {
return ::ams::os::impl::ProcessHandleImpl::GetCurrentProcessHandle();
}
}
namespace os {
NativeHandle __attribute__((const)) GetCurrentProcessHandle() {
return ::ams::os::impl::ProcessHandleImpl::GetCurrentProcessHandle();
}
Result GetProcessId(os::ProcessId *out, NativeHandle handle) {
R_RETURN(::ams::os::impl::ProcessHandleImpl::GetProcessId(out, handle));
}
Result GetProgramId(ncm::ProgramId *out, NativeHandle handle) {
R_RETURN(::ams::os::impl::ProcessHandleImpl::GetProgramId(out, handle));
}
}
}
| 1,450
|
C++
|
.cpp
| 35
| 36.085714
| 84
| 0.696085
|
Atmosphere-NX/Atmosphere
| 14,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,734
|
os_vamm_manager.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_vamm_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 "os_vamm_manager.hpp"
#if defined(ATMOSPHERE_OS_HORIZON)
#include "os_vamm_manager_impl.os.horizon.hpp"
#elif defined(ATMOSPHERE_OS_WINDOWS)
#include "os_vamm_manager_impl.os.windows.hpp"
#elif defined(ATMOSPHERE_OS_LINUX)
#include "os_vamm_manager_impl.os.linux.hpp"
#elif defined(ATMOSPHERE_OS_MACOS)
#include "os_vamm_manager_impl.os.macos.hpp"
#else
#error "Unknown OS for VammManagerImpl"
#endif
namespace ams::os::impl {
namespace {
class AddressRegion : public util::IntrusiveRedBlackTreeBaseNode<AddressRegion> {
private:
uintptr_t m_address;
size_t m_size;
public:
ALWAYS_INLINE AddressRegion(uintptr_t a, size_t s) : m_address(a), m_size(s) { /* ... */ }
constexpr ALWAYS_INLINE uintptr_t GetAddressBegin() const { return m_address; }
constexpr ALWAYS_INLINE uintptr_t GetAddressEnd() const { return m_address + m_size; }
constexpr ALWAYS_INLINE size_t GetSize() const { return m_size; }
constexpr ALWAYS_INLINE bool IsContained(uintptr_t address) const {
if (address < m_address) {
return false;
} else if (address < this->GetAddressEnd()) {
return true;
} else {
return false;
}
}
constexpr ALWAYS_INLINE bool IsContained(uintptr_t address, size_t size) const {
const uintptr_t end = address + size;
if (!(address <= end)) {
return false;
}
if (!(this->GetAddressBegin() <= address)) {
return false;
}
if (!(end <= this->GetAddressEnd())) {
return false;
}
return true;
}
};
struct AddressRegionCompare {
using RedBlackKeyType = uintptr_t;
static constexpr ALWAYS_INLINE int Compare(const RedBlackKeyType a, const RedBlackKeyType &b) {
if (a < b) {
return -1;
} else if (a > b) {
return 1;
} else {
return 0;
}
}
static constexpr ALWAYS_INLINE int Compare(const RedBlackKeyType &a, const AddressRegion &b) {
return Compare(a, b.GetAddressBegin());
}
static constexpr ALWAYS_INLINE int Compare(const AddressRegion &a, const AddressRegion &b) {
return Compare(a.GetAddressBegin(), b.GetAddressBegin());
}
};
using AddressRegionTree = util::IntrusiveRedBlackTreeBaseTraits<AddressRegion>::TreeType<AddressRegionCompare>;
class DynamicUnitHeap {
private:
static constexpr size_t PhysicalMemoryUnitSize = MemoryPageSize;
private:
uintptr_t m_start;
uintptr_t m_limit;
uintptr_t m_end;
util::TypedStorage<lmem::HeapCommonHead> m_head;
lmem::HeapHandle m_heap;
public:
DynamicUnitHeap(uintptr_t address, size_t size, size_t unit_size) : m_start(address), m_end(address + size) {
/* Allocate the start of our buffer. */
VammManagerImpl::AllocatePhysicalMemoryImpl(m_start, PhysicalMemoryUnitSize);
/* Set our current limit. */
m_limit = m_start + PhysicalMemoryUnitSize;
/* Initialize our heap. */
m_heap = lmem::CreateUnitHeap(reinterpret_cast<void *>(m_start), PhysicalMemoryUnitSize, unit_size, lmem::CreateOption_None, alignof(u64), util::GetPointer(m_head));
}
void *Allocate() {
void *alloc = lmem::AllocateFromUnitHeap(m_heap);
if (alloc == nullptr) {
this->Extend();
alloc = lmem::AllocateFromUnitHeap(m_heap);
}
return alloc;
}
void Free(void *p) {
lmem::FreeToUnitHeap(m_heap, p);
}
private:
void Extend() {
AMS_ABORT_UNLESS(m_limit < m_end);
if (R_SUCCEEDED(VammManagerImpl::AllocatePhysicalMemoryImpl(m_limit, PhysicalMemoryUnitSize))) {
m_limit += PhysicalMemoryUnitSize;
lmem::ExtendUnitHeap(m_heap, PhysicalMemoryUnitSize);
}
}
};
}
class AddressRegionManager {
private:
static constexpr size_t UnitHeapRegionSize = 1_GB - 2_MB;
private:
uintptr_t m_start;
size_t m_size;
AddressRegionTree m_tree;
DynamicUnitHeap m_heap;
public:
AddressRegionManager(uintptr_t start, size_t size) : m_start(start), m_size(size), m_heap(start, UnitHeapRegionSize, sizeof(AddressRegion)) {
/* Insert a block in the tree for our heap. */
m_tree.insert(*(new (m_heap.Allocate()) AddressRegion(m_start, UnitHeapRegionSize)));
/* Insert a zero-size block in the tree at the end of our heap. */
m_tree.insert(*(new (m_heap.Allocate()) AddressRegion(m_start + size, 0)));
}
AddressAllocationResult Allocate(AddressRegion **out, size_t size) {
/* Allocate a region. */
void *p = m_heap.Allocate();
if (p == nullptr) {
return AddressAllocationResult_OutOfMemory;
}
/* Determine alignment for the specified size. */
const size_t align = SelectAlignment(size);
/* Iterate, looking for an appropriate region. */
auto *region = std::addressof(m_tree.back());
while (true) {
/* Get the previous region. */
auto *prev = region->GetPrev();
if (prev == nullptr) {
break;
}
/* Get the space between prev and the current region. */
const uintptr_t space_start = prev->GetAddressEnd() + MemoryPageSize;
const uintptr_t space_end = region->GetAddressBegin() - MemoryPageSize;
const size_t space_size = space_end - space_start;
/* If there's enough space in the region, consider it further. */
if (space_size >= size) {
/* Determine the allocation region extents. */
const uintptr_t alloc_start = util::AlignUp(space_start, align);
const uintptr_t alloc_end = alloc_start + size;
/* If the allocation works, use it. */
if (alloc_end <= space_end) {
auto *address_region = new (p) AddressRegion(alloc_start, size);
m_tree.insert(*address_region);
*out = address_region;
return AddressAllocationResult_Success;
}
}
/* Otherwise, continue. */
region = prev;
}
/* We ran out of space to allocate. */
return AddressAllocationResult_OutOfSpace;
}
void Free(AddressRegion *region) {
m_tree.erase(m_tree.iterator_to(*region));
m_heap.Free(region);
}
bool IsAlreadyAllocated(uintptr_t address, size_t size) const {
/* Find the first region >= our address. */
auto region = std::addressof(*(m_tree.nfind_key(address)));
if (region == nullptr) {
return false;
}
/* If the address matches, return whether the region is contained. */
if (region->GetAddressBegin() == address) {
return size <= region->GetSize();
}
/* Otherwise, check the previous entry. */
if (region = region->GetPrev(); region == nullptr) {
return false;
}
return region->IsContained(address, size);
}
AddressRegion *Find(uintptr_t address) const {
return std::addressof(*(m_tree.find_key(address)));
}
private:
static constexpr size_t SelectAlignment(size_t size) {
if (size < 4_MB) {
if (size < 2_MB) {
return 64_KB;
} else {
return 2_MB;
}
} else {
if (size < 32_MB) {
return 4_MB;
} else if (size < 1_GB) {
return 32_MB;
} else {
return 1_GB;
}
}
}
};
namespace {
constinit util::TypedStorage<AddressRegionManager> g_address_region_manager_storage = {};
}
VammManager::VammManager() : m_lock(), m_region_manager(nullptr) {
/* Get the reserved region. */
VammManagerImpl::GetReservedRegionImpl(std::addressof(m_reserved_region_start), std::addressof(m_reserved_region_size));
}
void VammManager::InitializeIfEnabled() {
/* Acquire exclusive/writer access. */
std::scoped_lock lk(m_lock);
/* Initialize, if we haven't already. */
if (m_region_manager == nullptr && IsVirtualAddressMemoryEnabled()) {
m_region_manager = util::ConstructAt(g_address_region_manager_storage, m_reserved_region_start, m_reserved_region_size);
}
}
Result VammManager::AllocateAddressRegion(uintptr_t *out, size_t size) {
/* Allocate an address. */
uintptr_t address;
{
/* Lock access to our region manager. */
std::scoped_lock lk(m_lock);
AMS_ASSERT(m_region_manager != nullptr);
/* Allocate an address region. */
AddressRegion *region;
switch (m_region_manager->Allocate(std::addressof(region), size)) {
case AddressAllocationResult_Success:
address = region->GetAddressBegin();
break;
case AddressAllocationResult_OutOfSpace:
R_THROW(os::ResultOutOfVirtualAddressSpace());
default:
R_THROW(os::ResultOutOfMemory());
}
}
/* Set the output. */
*out = address;
R_SUCCEED();
}
Result VammManager::AllocateMemory(uintptr_t *out, size_t size) {
/* Allocate an address. */
uintptr_t address;
{
/* Lock access to our region manager. */
std::scoped_lock lk(m_lock);
AMS_ASSERT(m_region_manager != nullptr);
/* Allocate an address region. */
AddressRegion *region;
switch (m_region_manager->Allocate(std::addressof(region), size)) {
case AddressAllocationResult_Success:
address = region->GetAddressBegin();
break;
case AddressAllocationResult_OutOfSpace:
R_THROW(os::ResultOutOfVirtualAddressSpace());
default:
R_THROW(os::ResultOutOfMemory());
}
ON_RESULT_FAILURE { m_region_manager->Free(region); };
/* Allocate memory at the region. */
R_TRY(VammManagerImpl::AllocatePhysicalMemoryImpl(address, size));
}
/* Set the output. */
*out = address;
R_SUCCEED();
}
Result VammManager::AllocateMemoryPages(uintptr_t address, size_t size) {
/* Acquire read access to our region manager. */
std::shared_lock lk(m_lock);
AMS_ASSERT(m_region_manager != nullptr);
/* Check that the region was previously allocated by a call to AllocateAddressRegion. */
R_UNLESS(m_region_manager->IsAlreadyAllocated(address, size), os::ResultInvalidParameter());
/* Allocate the memory. */
R_RETURN(VammManagerImpl::AllocatePhysicalMemoryImpl(address, size));
}
Result VammManager::FreeAddressRegion(uintptr_t address) {
/* Lock access to our region manager. */
std::scoped_lock lk(m_lock);
AMS_ASSERT(m_region_manager != nullptr);
/* Verify the region can be freed. */
auto *region = m_region_manager->Find(address);
R_UNLESS(region != nullptr, os::ResultInvalidParameter());
/* Free any memory present at the address. */
R_TRY(VammManagerImpl::FreePhysicalMemoryImpl(address, region->GetSize()));
/* Free the region. */
m_region_manager->Free(region);
R_SUCCEED();
}
Result VammManager::FreeMemoryPages(uintptr_t address, size_t size) {
/* Acquire read access to our region manager. */
std::shared_lock lk(m_lock);
AMS_ASSERT(m_region_manager != nullptr);
/* Check that the region was previously allocated by a call to AllocateAddressRegion. */
R_UNLESS(m_region_manager->IsAlreadyAllocated(address, size), os::ResultInvalidParameter());
/* Free the memory. */
R_RETURN(VammManagerImpl::FreePhysicalMemoryImpl(address, size));
}
VirtualAddressMemoryResourceUsage VammManager::GetVirtualAddressMemoryResourceUsage() {
const size_t assigned_size = VammManagerImpl::GetExtraSystemResourceAssignedSize();
const size_t used_size = VammManagerImpl::GetExtraSystemResourceUsedSize();
/* Decide on an actual used size. */
const size_t reported_used_size = std::min<size_t>(assigned_size, used_size + 512_KB);
return VirtualAddressMemoryResourceUsage {
.assigned_size = assigned_size,
.used_size = reported_used_size,
};
}
bool VammManager::IsVirtualAddressMemoryEnabled() {
return VammManagerImpl::IsVirtualAddressMemoryEnabled();
}
}
| 15,264
|
C++
|
.cpp
| 325
| 32.796923
| 185
| 0.546494
|
Atmosphere-NX/Atmosphere
| 14,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,735
|
os_memory_permission_impl.os.windows.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_memory_permission_impl.os.windows.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include <stratosphere/windows.hpp>
namespace ams::os::impl {
void SetMemoryPermissionImpl(uintptr_t address, size_t size, MemoryPermission perm) {
DWORD old;
uintptr_t cur_address = address;
size_t remaining = size;
while (remaining > 0) {
const size_t cur_size = std::min<size_t>(remaining, 2_GB);
switch (perm) {
case MemoryPermission_None:
{
auto res = ::VirtualProtect(reinterpret_cast<LPVOID>(cur_address), static_cast<DWORD>(cur_size), PAGE_NOACCESS, std::addressof(old));
AMS_ABORT_UNLESS(res);
AMS_UNUSED(res);
}
break;
case MemoryPermission_ReadOnly:
{
auto res = ::VirtualProtect(reinterpret_cast<LPVOID>(cur_address), static_cast<DWORD>(cur_size), PAGE_READONLY, std::addressof(old));
AMS_ABORT_UNLESS(res);
AMS_UNUSED(res);
}
break;
case MemoryPermission_ReadWrite:
{
auto res = ::VirtualProtect(reinterpret_cast<LPVOID>(cur_address), static_cast<DWORD>(cur_size), PAGE_READWRITE, std::addressof(old));
AMS_ABORT_UNLESS(res);
AMS_UNUSED(res);
}
break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
cur_address += cur_size;
remaining -= cur_size;
}
}
}
| 2,291
|
C++
|
.cpp
| 53
| 31.150943
| 158
| 0.568742
|
Atmosphere-NX/Atmosphere
| 14,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,736
|
os_thread_manager_impl.os.horizon.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_thread_manager_impl.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 "os_thread_manager_impl.os.horizon.hpp"
#include "os_thread_manager.hpp"
namespace ams::os::impl {
thread_local ThreadType *g_current_thread_pointer;
namespace {
s32 ConvertToHorizonPriority(s32 user_priority) {
const s32 horizon_priority = user_priority + UserThreadPriorityOffset;
AMS_ASSERT(HighestTargetThreadPriority <= horizon_priority && horizon_priority <= LowestTargetThreadPriority);
return horizon_priority;
}
s32 ConvertToUserPriority(s32 horizon_priority) {
AMS_ASSERT(HighestTargetThreadPriority <= horizon_priority && horizon_priority <= LowestTargetThreadPriority);
return horizon_priority - UserThreadPriorityOffset;
}
void InvokeThread(uintptr_t _thread) {
ThreadType *thread = reinterpret_cast<ThreadType *>(_thread);
/* Set the thread's id. */
u64 thread_id;
R_ABORT_UNLESS(svc::GetThreadId(std::addressof(thread_id), thread->thread_impl->handle));
thread->thread_id = thread_id;
/* Invoke the thread. */
ThreadManager::InvokeThread(thread);
}
}
ThreadManagerHorizonImpl::ThreadManagerHorizonImpl(ThreadType *main_thread) {
/* Get the thread impl object from libnx. */
ThreadType::ThreadImpl *thread_impl = ::threadGetSelf();
auto * const original_thread_impl = thread_impl;
/* Hack around libnx's main thread, to ensure stratosphere thread type consistency. */
{
auto *tlr = reinterpret_cast<uintptr_t *>(svc::GetThreadLocalRegion());
for (size_t i = sizeof(svc::ThreadLocalRegion) / sizeof(uintptr_t); i > 0; --i) {
if (auto *candidate = reinterpret_cast<ThreadType::ThreadImpl *>(tlr[i - 1]); candidate == thread_impl) {
ThreadType::ThreadImpl *embedded_thread = std::addressof(main_thread->thread_impl_storage);
*embedded_thread = *thread_impl;
if (embedded_thread->next) {
embedded_thread->next->prev_next = std::addressof(embedded_thread->next);
}
thread_impl = embedded_thread;
tlr[i-1] = reinterpret_cast<uintptr_t>(thread_impl);
break;
}
}
}
/* Get the thread priority. */
s32 horizon_priority;
R_ABORT_UNLESS(svc::GetThreadPriority(std::addressof(horizon_priority), thread_impl->handle));
SetupThreadObjectUnsafe(main_thread, thread_impl, nullptr, nullptr, thread_impl->stack_mirror, thread_impl->stack_sz, ConvertToUserPriority(horizon_priority));
/* Fix up the thread impl. */
*thread_impl = *original_thread_impl;
/* Set the thread id. */
u64 thread_id;
R_ABORT_UNLESS(svc::GetThreadId(std::addressof(thread_id), thread_impl->handle));
main_thread->thread_id = thread_id;
/* NOTE: Here Nintendo would set the thread pointer in TLS. */
}
Result ThreadManagerHorizonImpl::CreateThread(ThreadType *thread, s32 ideal_core) {
/* Note: Here Nintendo would set the stack args to point to ThreadManager::InvokeThread. */
s32 count = 0;
while (true) {
R_TRY_CATCH(::threadCreate(thread->thread_impl, reinterpret_cast<::ThreadFunc>(reinterpret_cast<void *>(&InvokeThread)), thread, thread->stack, thread->stack_size, ConvertToHorizonPriority(thread->base_priority), ideal_core)) {
R_CATCH(svc::ResultOutOfResource) {
if ((++count) < 10) {
os::SleepThread(TimeSpan::FromMilliSeconds(10));
continue;
}
R_THROW(os::ResultOutOfResource());
}
} R_END_TRY_CATCH_WITH_ABORT_UNLESS;
R_SUCCEED();
}
}
void ThreadManagerHorizonImpl::DestroyThreadUnsafe(ThreadType *thread) {
R_ABORT_UNLESS(::threadClose(thread->thread_impl));
}
void ThreadManagerHorizonImpl::StartThread(const ThreadType *thread) {
R_ABORT_UNLESS(::threadStart(thread->thread_impl));
}
void ThreadManagerHorizonImpl::WaitForThreadExit(ThreadType *thread) {
const svc::Handle handle = thread->thread_impl->handle;
while (true) {
s32 index;
R_TRY_CATCH(svc::WaitSynchronization(std::addressof(index), std::addressof(handle), 1, svc::WaitInfinite)) {
R_CATCH(svc::ResultCancelled) { continue; }
} R_END_TRY_CATCH_WITH_ABORT_UNLESS;
return;
}
}
bool ThreadManagerHorizonImpl::TryWaitForThreadExit(ThreadType *thread) {
const svc::Handle handle = thread->thread_impl->handle;
while (true) {
/* Continuously wait, until success or timeout. */
s32 index;
Result res = svc::WaitSynchronization(std::addressof(index), std::addressof(handle), 1, 0);
/* If we succeeded, we're signaled. */
if (R_SUCCEEDED(res)) {
return true;
}
/* If we timed out, we're not signaled. */
if (svc::ResultTimedOut::Includes(res)) {
return false;
}
AMS_ABORT_UNLESS(svc::ResultCancelled::Includes(res));
}
}
void ThreadManagerHorizonImpl::YieldThread() {
if (hos::GetVersion() >= hos::Version_4_0_0) {
svc::SleepThread(svc::YieldType_WithCoreMigration);
} else {
svc::SleepThread(svc::YieldType_WithoutCoreMigration);
}
}
bool ThreadManagerHorizonImpl::ChangePriority(ThreadType *thread, s32 priority) {
auto res = svc::SetThreadPriority(thread->thread_impl->handle, ConvertToHorizonPriority(priority));
if (svc::ResultInvalidPriority::Includes(res)) {
AMS_ABORT("Invalid thread priority");
}
return R_SUCCEEDED(res);
}
s32 ThreadManagerHorizonImpl::GetCurrentPriority(const ThreadType *thread) const {
s32 priority;
R_ABORT_UNLESS(svc::GetThreadPriority(std::addressof(priority), thread->thread_impl->handle));
return ConvertToUserPriority(priority);
}
ThreadId ThreadManagerHorizonImpl::GetThreadId(const ThreadType *thread) const {
return thread->thread_id;
}
void ThreadManagerHorizonImpl::SuspendThreadUnsafe(ThreadType *thread) {
R_ABORT_UNLESS(svc::SetThreadActivity(thread->thread_impl->handle, svc::ThreadActivity_Paused));
}
void ThreadManagerHorizonImpl::ResumeThreadUnsafe(ThreadType *thread) {
R_ABORT_UNLESS(svc::SetThreadActivity(thread->thread_impl->handle, svc::ThreadActivity_Runnable));
}
/* TODO: void GetThreadContextUnsafe(ThreadContextInfo *out_context, const ThreadType *thread); */
s32 ThreadManagerHorizonImpl::GetCurrentCoreNumber() const {
return svc::GetCurrentProcessorNumber();
}
void ThreadManagerHorizonImpl::SetThreadCoreMask(ThreadType *thread, s32 ideal_core, u64 affinity_mask) const {
R_ABORT_UNLESS(svc::SetThreadCoreMask(thread->thread_impl->handle, ideal_core, affinity_mask));
}
void ThreadManagerHorizonImpl::GetThreadCoreMask(s32 *out_ideal_core, u64 *out_affinity_mask, const ThreadType *thread) const {
s32 ideal_core;
u64 affinity_mask;
R_ABORT_UNLESS(svc::GetThreadCoreMask(std::addressof(ideal_core), std::addressof(affinity_mask), thread->thread_impl->handle));
if (out_ideal_core) {
*out_ideal_core = ideal_core;
}
if (out_affinity_mask) {
*out_affinity_mask = affinity_mask;
}
}
u64 ThreadManagerHorizonImpl::GetThreadAvailableCoreMask() const {
u64 core_mask;
R_ABORT_UNLESS(svc::GetInfo(std::addressof(core_mask), svc::InfoType_CoreMask, svc::PseudoHandle::CurrentProcess, 0));
return core_mask;
}
bool ThreadManagerHorizonImpl::MapAliasStack(void **out, void *stack, size_t size) {
/* TODO: This will need to be real, if we ever stop using libnx threads. */
AMS_UNUSED(stack, size);
*out = stack;
return true;
}
bool ThreadManagerHorizonImpl::UnmapAliasStack(void *alias_stack, void *original_stack, size_t size) {
/* TODO: This will need to be real, if we ever stop using libnx threads. */
AMS_UNUSED(alias_stack, original_stack, size);
return true;
}
}
| 9,213
|
C++
|
.cpp
| 184
| 40.434783
| 239
| 0.647472
|
Atmosphere-NX/Atmosphere
| 14,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,737
|
os_unsafe_memory_impl.os.horizon.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_unsafe_memory_impl.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 "os_unsafe_memory_impl.hpp"
#include "os_aslr_space_manager.hpp"
namespace ams::os::impl {
Result UnsafeMemoryImpl::AllocateUnsafeMemoryImpl(uintptr_t *out_address, size_t size) {
/* Map at a random address. */
R_RETURN(impl::GetAslrSpaceManager().MapAtRandomAddress(out_address,
[](uintptr_t map_address, size_t map_size) -> Result {
R_TRY_CATCH(svc::MapPhysicalMemoryUnsafe(map_address, map_size)) {
R_CONVERT(svc::ResultOutOfResource, os::ResultOutOfResource())
R_CONVERT(svc::ResultOutOfMemory, os::ResultOutOfMemory())
R_CONVERT(svc::ResultInvalidCurrentMemory, os::ResultInvalidCurrentMemoryState())
R_CONVERT(svc::ResultLimitReached, os::ResultOutOfMemory())
} R_END_TRY_CATCH_WITH_ABORT_UNLESS;
R_SUCCEED();
},
[](uintptr_t map_address, size_t map_size) -> void {
R_ABORT_UNLESS(UnsafeMemoryImpl::FreeUnsafeMemoryImpl(map_address, map_size));
},
size,
0
));
}
Result UnsafeMemoryImpl::FreeUnsafeMemoryImpl(uintptr_t address, size_t size) {
R_TRY_CATCH(svc::UnmapPhysicalMemoryUnsafe(address, size)) {
R_CONVERT(svc::ResultOutOfResource, os::ResultOutOfResource())
R_CONVERT(svc::ResultOutOfMemory, os::ResultOutOfResource())
R_CONVERT(svc::ResultInvalidCurrentMemory, os::ResultBusy())
R_CONVERT(svc::ResultInvalidMemoryRegion, os::ResultInvalidParameter())
} R_END_TRY_CATCH_WITH_ABORT_UNLESS;
R_SUCCEED();
}
}
| 2,367
|
C++
|
.cpp
| 48
| 41.0625
| 101
| 0.655426
|
Atmosphere-NX/Atmosphere
| 14,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,738
|
os_giant_lock.os.linux.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_giant_lock.os.linux.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "os_giant_lock.os.linux.hpp"
#include <sys/syscall.h>
#include <unistd.h>
#include <fcntl.h>
namespace ams::os::impl {
#define AMS_OS_IMPL_GIANT_LOCK_FILE_PATH "/tmp/.ams_os_giant_lock"
void GiantLockLinuxImpl::Lock() {
m_fd = ::open(AMS_OS_IMPL_GIANT_LOCK_FILE_PATH, O_RDWR | O_CREAT | O_CLOEXEC, S_IRUSR | S_IWUSR);
AMS_ABORT_UNLESS(m_fd >= 0);
while (::lockf(m_fd, F_LOCK, 0) < 0) {
AMS_ABORT_UNLESS(errno == EINTR);
}
}
void GiantLockLinuxImpl::Unlock() {
AMS_ASSERT(m_fd >= 0);
while (::lockf(m_fd, F_ULOCK, 0) < 0) {
AMS_ABORT_UNLESS(errno == EINTR);
}
while (::close(m_fd) < 0) {
AMS_ABORT_UNLESS(errno == EINTR);
}
m_fd = os::InvalidNativeHandle;
}
}
| 1,476
|
C++
|
.cpp
| 40
| 31.925
| 105
| 0.652418
|
Atmosphere-NX/Atmosphere
| 14,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,739
|
os_multiple_wait_target_impl.os.linux.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_multiple_wait_target_impl.os.linux.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "os_multiple_wait_holder_base.hpp"
#include "os_multiple_wait_impl.hpp"
#include "os_timeout_helper.hpp"
#include "os_inter_process_event_impl.os.linux.hpp"
#include <poll.h>
namespace ams::os::impl {
MultiWaitLinuxImpl::MultiWaitLinuxImpl() {
R_ABORT_UNLESS(InterProcessEventLinuxImpl::CreateSingle(std::addressof(m_cancel_event)));
}
MultiWaitLinuxImpl::~MultiWaitLinuxImpl() {
InterProcessEventLinuxImpl::Close(m_cancel_event);
m_cancel_event = InvalidNativeHandle;
}
void MultiWaitLinuxImpl::CancelWait() {
InterProcessEventLinuxImpl::Signal(m_cancel_event);
}
Result MultiWaitLinuxImpl::PollNativeHandlesImpl(s32 *out_index, s32 num, NativeHandle arr[], s32 array_size, s64 ns) {
/* Check that we can add our cancel handle to the wait. */
AMS_ABORT_UNLESS(array_size <= static_cast<s32>(MaximumHandleCount));
AMS_UNUSED(array_size);
/* Create poll fds. */
struct pollfd pfds[MaximumHandleCount + 1];
for (auto i = 0; i < num; ++i) {
pfds[i].fd = arr[i];
pfds[i].events = POLLIN;
pfds[i].revents = 0;
}
pfds[num].fd = m_cancel_event;
pfds[num].events = POLLIN;
pfds[num].revents = 0;
/* Determine timeout. */
constexpr s64 NanoSecondsPerSecond = TimeSpan::FromSeconds(1).GetNanoSeconds();
struct timespec ts = { .tv_sec = (ns / NanoSecondsPerSecond), .tv_nsec = ns % NanoSecondsPerSecond };
/* Wait. */
while (true) {
const auto ret = ::ppoll(pfds, num + 1, ns >= 0 ? std::addressof(ts) : nullptr, nullptr);
if (ret < 0) {
/* Treat EINTR like a cancellation event; this will lead to a re-poll if nothing is signaled. */
AMS_ABORT_UNLESS(errno == EINTR);
*out_index = MultiWaitImpl::WaitCancelled;
R_SUCCEED();
}
/* Determine what event was polled. */
if (ret == 0) {
*out_index = MultiWaitImpl::WaitTimedOut;
R_SUCCEED();
} else if (pfds[num].revents != 0) {
*out_index = MultiWaitImpl::WaitCancelled;
/* Reset our cancel event. */
InterProcessEventLinuxImpl::Clear(m_cancel_event);
R_SUCCEED();
} else {
for (auto i = 0; i < num; ++i) {
if (pfds[i].revents != 0) {
*out_index = i;
R_SUCCEED();
}
}
AMS_ABORT("This should be impossible?");
}
}
}
Result MultiWaitLinuxImpl::ReplyAndReceiveImpl(s32 *out_index, s32 num, NativeHandle arr[], s32 array_size, s64 ns, NativeHandle reply_target) {
AMS_UNUSED(out_index, num, arr, array_size, ns, reply_target);
R_ABORT_UNLESS(os::ResultNotImplemented());
}
}
| 3,652
|
C++
|
.cpp
| 83
| 34.855422
| 148
| 0.6049
|
Atmosphere-NX/Atmosphere
| 14,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,740
|
os_giant_lock.os.macos.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_giant_lock.os.macos.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "os_giant_lock.os.macos.hpp"
#include <sys/syscall.h>
#include <unistd.h>
#include <fcntl.h>
namespace ams::os::impl {
#define AMS_OS_IMPL_GIANT_LOCK_FILE_PATH "/tmp/.ams_os_giant_lock"
void GiantLockMacosImpl::Lock() {
m_fd = ::open(AMS_OS_IMPL_GIANT_LOCK_FILE_PATH, O_RDWR | O_CREAT | O_CLOEXEC, S_IRUSR | S_IWUSR);
AMS_ABORT_UNLESS(m_fd >= 0);
while (::lockf(m_fd, F_LOCK, 0) < 0) {
AMS_ABORT_UNLESS(errno == EINTR);
}
}
void GiantLockMacosImpl::Unlock() {
AMS_ASSERT(m_fd >= 0);
while (::lockf(m_fd, F_ULOCK, 0) < 0) {
AMS_ABORT_UNLESS(errno == EINTR);
}
while (::close(m_fd) < 0) {
AMS_ABORT_UNLESS(errno == EINTR);
}
m_fd = os::InvalidNativeHandle;
}
}
| 1,476
|
C++
|
.cpp
| 40
| 31.925
| 105
| 0.652418
|
Atmosphere-NX/Atmosphere
| 14,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,741
|
os_multiple_wait_target_impl.os.horizon.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_multiple_wait_target_impl.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 "os_multiple_wait_holder_base.hpp"
#include "os_multiple_wait_impl.hpp"
namespace ams::os::impl {
Result MultiWaitHorizonImpl::WaitSynchronizationN(s32 *out_index, s32 num, NativeHandle arr[], s32 array_size, s64 ns) {
AMS_UNUSED(array_size);
AMS_ASSERT(!(num == 0 && ns == 0));
s32 index = MultiWaitImpl::WaitInvalid;
R_TRY_CATCH(svc::WaitSynchronization(std::addressof(index), static_cast<const svc::Handle *>(arr), num, ns)) {
R_CATCH(svc::ResultTimedOut) { index = MultiWaitImpl::WaitTimedOut; }
R_CATCH(svc::ResultCancelled) { index = MultiWaitImpl::WaitCancelled; }
/* All other results are critical errors. */
/* svc::ResultThreadTerminating */
/* svc::ResultInvalidHandle. */
/* svc::ResultInvalidPointer */
/* svc::ResultOutOfRange */
} R_END_TRY_CATCH_WITH_ABORT_UNLESS;
*out_index = index;
R_SUCCEED();
}
Result MultiWaitHorizonImpl::ReplyAndReceiveN(s32 *out_index, s32 num, NativeHandle arr[], s32 array_size, s64 ns, NativeHandle reply_target) {
AMS_UNUSED(array_size);
/* NOTE: Nintendo does not initialize this value, which seems like it can cause incorrect behavior. */
s32 index = MultiWaitImpl::WaitInvalid;
static_assert(MultiWaitImpl::WaitInvalid != -1);
R_TRY_CATCH(svc::ReplyAndReceive(std::addressof(index), arr, num, reply_target, ns)) {
R_CATCH(svc::ResultTimedOut) { *out_index = MultiWaitImpl::WaitTimedOut; R_THROW(R_CURRENT_RESULT); }
R_CATCH(svc::ResultCancelled) { *out_index = MultiWaitImpl::WaitCancelled; R_THROW(R_CURRENT_RESULT); }
R_CATCH(svc::ResultSessionClosed) {
if (index == -1) {
*out_index = MultiWaitImpl::WaitInvalid;
R_THROW(os::ResultSessionClosedForReply());
} else {
*out_index = index;
R_THROW(os::ResultSessionClosedForReceive());
}
}
R_CATCH(svc::ResultReceiveListBroken) {
*out_index = index;
R_THROW(os::ResultReceiveListBroken());
}
} R_END_TRY_CATCH_WITH_ABORT_UNLESS;
*out_index = index;
R_SUCCEED();
}
void MultiWaitHorizonImpl::CancelWait() {
R_ABORT_UNLESS(svc::CancelSynchronization(m_handle));
}
}
| 3,118
|
C++
|
.cpp
| 64
| 40.015625
| 147
| 0.639172
|
Atmosphere-NX/Atmosphere
| 14,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,742
|
os_resource_manager.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_resource_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 "os_resource_manager.hpp"
namespace ams::os::impl {
constinit util::TypedStorage<OsResourceManager> ResourceManagerHolder::s_resource_manager_storage = {};
}
| 837
|
C++
|
.cpp
| 20
| 39.8
| 107
| 0.764128
|
Atmosphere-NX/Atmosphere
| 14,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,743
|
os_utility.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_utility.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "os_utility.hpp"
namespace ams::os::impl {
namespace {
constexpr void ExpandUnsignedValueToAsciiImpl(char *dst, u64 value) {
/* Determine size needed. */
constexpr size_t SizeNeeded = (BITSIZEOF(value) / 4) * sizeof(char);
/* Write null-terminator. */
dst[SizeNeeded] = '\x00';
/* Write characters. */
for (size_t i = 0; i < SizeNeeded; ++i) {
/* Determine current character. */
const auto nybble = (value & 0xF);
const char cur_c = (nybble < 10) ? ('0' + nybble) : ('A' + nybble - 10);
/* Write current character. */
dst[SizeNeeded - 1 - i] = cur_c;
/* Shift to next nybble. */
value >>= 4;
}
}
}
void ExpandUnsignedValueToAscii(char *dst, u64 value) {
return ExpandUnsignedValueToAsciiImpl(dst, value);
}
/* Test correctness. */
#if 0
namespace {
consteval bool TestExpandUnsignedValueToAsciiImpl(const char *expected, u64 value) {
/* Create buffer. */
char buffer[17] = {
'\xCC', '\xCC', '\xCC', '\xCC', '\xCC', '\xCC', '\xCC', '\xCC', '\xCC', '\xCC', '\xCC', '\xCC', '\xCC', '\xCC', '\xCC', '\xCC', '\xCC'
};
/* Validate buffer is initially garbage. */
for (size_t i = 0; i < util::size(buffer); ++i) {
if (buffer[i] != '\xCC') {
return false;
}
}
/* Expand the value into the buffer. */
ExpandUnsignedValueToAsciiImpl(buffer, value);
/* Verify the result. */
for (size_t i = 0; i < util::size(buffer); ++i) {
if (buffer[i] != expected[i]) {
return false;
}
}
/* Verify null-termination. */
if (buffer[util::size(buffer) - 1] != 0) {
return false;
}
return true;
}
#define DO_TEST_EXPAND_UNSIGNED_VALUE_TO_ASCII_IMPL(v) static_assert(TestExpandUnsignedValueToAsciiImpl( #v , UINT64_C(0x##v)))
DO_TEST_EXPAND_UNSIGNED_VALUE_TO_ASCII_IMPL(0000000000000000);
DO_TEST_EXPAND_UNSIGNED_VALUE_TO_ASCII_IMPL(FFFFFFFFFFFFFFFF);
DO_TEST_EXPAND_UNSIGNED_VALUE_TO_ASCII_IMPL(FFFFFFFF00000000);
DO_TEST_EXPAND_UNSIGNED_VALUE_TO_ASCII_IMPL(00000000FFFFFFFF);
DO_TEST_EXPAND_UNSIGNED_VALUE_TO_ASCII_IMPL(FFFF0000FFFF0000);
DO_TEST_EXPAND_UNSIGNED_VALUE_TO_ASCII_IMPL(0000FFFF0000FFFF);
DO_TEST_EXPAND_UNSIGNED_VALUE_TO_ASCII_IMPL(F0F0F0F0F0F0F0F0);
DO_TEST_EXPAND_UNSIGNED_VALUE_TO_ASCII_IMPL(0F0F0F0F0F0F0F0F);
DO_TEST_EXPAND_UNSIGNED_VALUE_TO_ASCII_IMPL(0123456789ABCDEF);
DO_TEST_EXPAND_UNSIGNED_VALUE_TO_ASCII_IMPL(FEDCBA9876543210);
DO_TEST_EXPAND_UNSIGNED_VALUE_TO_ASCII_IMPL(A5A5A5A5A5A5A5A5);
#undef DO_TEST_EXPAND_UNSIGNED_VALUE_TO_ASCII_IMPL
}
#endif
}
| 3,738
|
C++
|
.cpp
| 83
| 35.277108
| 150
| 0.591359
|
Atmosphere-NX/Atmosphere
| 14,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,744
|
os_timeout_helper_impl.os.horizon.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_timeout_helper_impl.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 "os_timeout_helper_impl.os.horizon.hpp"
#include "os_thread_manager.hpp"
namespace ams::os::impl {
void TimeoutHelperImpl::Sleep(TimeSpan tm) {
if (tm == TimeSpan(0)) {
GetThreadManager().YieldThread();
} else {
ams::svc::SleepThread(tm.GetNanoSeconds());
}
}
}
| 993
|
C++
|
.cpp
| 27
| 33.074074
| 76
| 0.711319
|
Atmosphere-NX/Atmosphere
| 14,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,745
|
os_shared_memory_impl.os.horizon.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_shared_memory_impl.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 "os_shared_memory_impl.hpp"
#include "os_aslr_space_manager.hpp"
namespace ams::os::impl {
namespace {
svc::MemoryPermission ConvertToSvcMemoryPermission(os::MemoryPermission perm) {
switch (perm) {
case os::MemoryPermission_None: return svc::MemoryPermission_None;
case os::MemoryPermission_ReadOnly: return svc::MemoryPermission_Read;
case os::MemoryPermission_WriteOnly: return svc::MemoryPermission_Write;
case os::MemoryPermission_ReadWrite: return svc::MemoryPermission_ReadWrite;
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
}
Result SharedMemoryImpl::Create(NativeHandle *out, size_t size, MemoryPermission my_perm, MemoryPermission other_perm) {
/* Convert memory permissions. */
const auto svc_my_perm = ConvertToSvcMemoryPermission(my_perm);
const auto svc_other_perm = ConvertToSvcMemoryPermission(other_perm);
/* Create the memory. */
svc::Handle handle;
R_TRY_CATCH(svc::CreateSharedMemory(std::addressof(handle), size, svc_my_perm, svc_other_perm)) {
R_CONVERT(svc::ResultOutOfHandles, os::ResultOutOfHandles())
R_CONVERT(svc::ResultOutOfResource, os::ResultOutOfResource())
} R_END_TRY_CATCH_WITH_ABORT_UNLESS;
*out = handle;
R_SUCCEED();
}
void SharedMemoryImpl::Close(NativeHandle handle) {
R_ABORT_UNLESS(svc::CloseHandle(handle));
}
Result SharedMemoryImpl::Map(void **out, NativeHandle handle, size_t size, MemoryPermission perm) {
/* Convert memory permission. */
const auto svc_perm = ConvertToSvcMemoryPermission(perm);
/* Map at a random address. */
uintptr_t mapped_address;
R_TRY(impl::GetAslrSpaceManager().MapAtRandomAddress(std::addressof(mapped_address),
[handle, svc_perm](uintptr_t map_address, size_t map_size) -> Result {
R_TRY_CATCH(svc::MapSharedMemory(handle, map_address, map_size, svc_perm)) {
R_CONVERT(svc::ResultInvalidCurrentMemory, os::ResultInvalidCurrentMemoryState())
} R_END_TRY_CATCH_WITH_ABORT_UNLESS;
R_SUCCEED();
},
[handle](uintptr_t map_address, size_t map_size) -> void {
return SharedMemoryImpl::Unmap(handle, reinterpret_cast<void *>(map_address), map_size);
},
size,
0
));
/* Return the address we mapped at. */
*out = reinterpret_cast<void *>(mapped_address);
R_SUCCEED();
}
void SharedMemoryImpl::Unmap(NativeHandle handle, void *address, size_t size) {
R_ABORT_UNLESS(svc::UnmapSharedMemory(handle, reinterpret_cast<uintptr_t>(address), size));
}
}
| 3,498
|
C++
|
.cpp
| 72
| 40.25
| 124
| 0.662954
|
Atmosphere-NX/Atmosphere
| 14,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,746
|
os_memory_heap_manager.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_memory_heap_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 "os_memory_heap_manager.hpp"
#include "os_thread_manager.hpp"
namespace ams::os::impl {
Result MemoryHeapManager::SetHeapSize(size_t size) {
/* Check pre-conditions. */
AMS_ASSERT(util::IsAligned(size, MemoryHeapUnitSize));
/* Acquire locks. */
std::scoped_lock lk1(util::GetReference(::ams::os::impl::GetCurrentThread()->cs_thread));
std::scoped_lock lk2(m_cs);
/* If we need to, expand the heap. */
if (size > m_heap_size) {
/* Set the new heap size. */
uintptr_t address = 0;
R_TRY(m_impl.SetHeapSize(std::addressof(address), size));
R_UNLESS(address != 0, os::ResultOutOfMemory());
/* Check that the new heap address is consistent. */
if (m_heap_size == 0) {
AMS_ASSERT(util::IsAligned(address, MemoryHeapUnitSize));
} else {
AMS_ASSERT(address == m_heap_address);
}
/* Set up the new heap address. */
this->AddToFreeSpaceUnsafe(address + m_heap_size, size - m_heap_size);
/* Set our heap address. */
m_heap_address = address;
m_heap_size = size;
} else if (size < m_heap_size) {
/* We're shrinking the heap, so we need to remove memory blocks. */
const uintptr_t end_address = m_heap_address + size;
const size_t remove_size = m_heap_size - size;
/* Get the end of the heap. */
auto it = m_free_memory_list.end();
--it;
R_UNLESS(it != m_free_memory_list.end(), os::ResultBusy());
/* Check that the block can be decommitted. */
R_UNLESS(it->GetAddress() <= end_address, os::ResultBusy());
R_UNLESS(it->GetSize() >= remove_size, os::ResultBusy());
/* Adjust the last node. */
if (const size_t node_size = it->GetSize() - remove_size; node_size == 0) {
m_free_memory_list.erase(it);
it->Clean();
} else {
it->SetSize(node_size);
}
/* Set the reduced heap size. */
uintptr_t address = 0;
R_ABORT_UNLESS(m_impl.SetHeapSize(std::addressof(address), size));
/* Set our heap address. */
m_heap_size = size;
if (size == 0) {
m_heap_address = 0;
}
}
R_SUCCEED();
}
Result MemoryHeapManager::AllocateFromHeap(uintptr_t *out_address, size_t size) {
/* Acquire locks. */
std::scoped_lock lk1(util::GetReference(::ams::os::impl::GetCurrentThread()->cs_thread));
std::scoped_lock lk2(m_cs);
/* Find free space. */
auto it = this->FindFreeSpaceUnsafe(size);
R_UNLESS(it != m_free_memory_list.end(), os::ResultOutOfMemory());
/* If necessary, split the memory block. */
if (it->GetSize() > size) {
this->SplitFreeMemoryNodeUnsafe(it, size);
}
/* Remove the block. */
m_free_memory_list.erase(it);
it->Clean();
/* Increment the used heap size. */
m_used_heap_size += size;
/* Set the output address. */
*out_address = it->GetAddress();
R_SUCCEED();
}
void MemoryHeapManager::ReleaseToHeap(uintptr_t address, size_t size) {
/* Acquire locks. */
std::scoped_lock lk1(util::GetReference(::ams::os::impl::GetCurrentThread()->cs_thread));
std::scoped_lock lk2(m_cs);
/* Check pre-condition. */
AMS_ABORT_UNLESS(this->IsRegionAllocatedMemoryUnsafe(address, size));
/* Restore the permissions on the memory. */
os::SetMemoryPermission(address, size, MemoryPermission_ReadWrite);
os::SetMemoryAttribute(address, size, MemoryAttribute_Normal);
/* Add the memory back to our free list. */
this->AddToFreeSpaceUnsafe(address, size);
/* Decrement the used heap size. */
m_used_heap_size -= size;
}
MemoryHeapManager::FreeMemoryList::iterator MemoryHeapManager::FindFreeSpaceUnsafe(size_t size) {
/* Find the best fit candidate. */
auto best = m_free_memory_list.end();
for (auto it = m_free_memory_list.begin(); it != m_free_memory_list.end(); ++it) {
if (const size_t node_size = it->GetSize(); node_size >= size) {
if (best == m_free_memory_list.end() || node_size < best->GetSize()) {
best = it;
}
}
}
return best;
}
MemoryHeapManager::FreeMemoryList::iterator MemoryHeapManager::ConcatenatePreviousFreeMemoryNodeUnsafe(FreeMemoryList::iterator node) {
/* Get the previous node. */
auto prev = node;
--prev;
/* If there's no previous, we're done. */
if (prev == m_free_memory_list.end() || node == m_free_memory_list.end()) {
return node;
}
/* Otherwise, if the previous isn't contiguous, we can't merge. */
if (prev->GetAddress() + prev->GetSize() != node->GetAddress()) {
return node;
}
/* Otherwise, increase the size of the previous node, and remove the current node. */
prev->SetSize(prev->GetSize() + node->GetSize());
m_free_memory_list.erase(node);
node->Clean();
return prev;
}
void MemoryHeapManager::SplitFreeMemoryNodeUnsafe(FreeMemoryList::iterator it, size_t size) {
/* Check pre-conditions. */
AMS_ASSERT(it->GetSize() > size);
AMS_ASSERT(util::IsAligned(size, MemoryBlockUnitSize));
/* Create new node. */
auto *new_node = std::construct_at(reinterpret_cast<FreeMemoryNode *>(it->GetAddress() + size));
new_node->SetSize(it->GetSize() - size);
/* Set the old node's size. */
it->SetSize(size);
/* Insert the new node. */
m_free_memory_list.insert(++it, *new_node);
}
void MemoryHeapManager::AddToFreeSpaceUnsafe(uintptr_t address, size_t size) {
/* Create new node. */
auto *new_node = std::construct_at(reinterpret_cast<FreeMemoryNode *>(address));
new_node->SetSize(size);
/* Find the appropriate place to insert the node. */
auto it = m_free_memory_list.begin();
for (/* ... */; it != m_free_memory_list.end(); ++it) {
if (address < it->GetAddress()) {
break;
}
}
/* Insert the new node. */
it = m_free_memory_list.insert(it, *new_node);
/* Perform coalescing as relevant. */
it = this->ConcatenatePreviousFreeMemoryNodeUnsafe(it);
this->ConcatenatePreviousFreeMemoryNodeUnsafe(++it);
}
bool MemoryHeapManager::IsRegionAllocatedMemoryUnsafe(uintptr_t address, size_t size) {
/* Look for a node containing the region. */
for (auto it = m_free_memory_list.begin(); it != m_free_memory_list.end(); ++it) {
const uintptr_t node_address = it->GetAddress();
const size_t node_size = it->GetSize();
if (node_address < address + size && address < node_address + node_size) {
return false;
}
}
return true;
}
}
| 7,987
|
C++
|
.cpp
| 176
| 35.772727
| 139
| 0.584728
|
Atmosphere-NX/Atmosphere
| 14,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,747
|
os_thread_manager_impl.pthread.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_thread_manager_impl.pthread.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(AMS_OS_IMPL_USE_PTHREADS)
#include "os_thread_manager_impl.pthread.inc"
#endif
| 759
|
C++
|
.cpp
| 19
| 37.947368
| 76
| 0.759134
|
Atmosphere-NX/Atmosphere
| 14,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,748
|
os_memory_attribute_impl.os.windows.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_memory_attribute_impl.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>
namespace ams::os::impl {
void SetMemoryAttributeImpl(uintptr_t address, size_t size, MemoryAttribute attr) {
/* TODO: Should this do anything? */
AMS_UNUSED(address, size, attr);
}
}
| 874
|
C++
|
.cpp
| 22
| 36.863636
| 87
| 0.737338
|
Atmosphere-NX/Atmosphere
| 14,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,749
|
os_memory_permission_impl.os.horizon.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_memory_permission_impl.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::os::impl {
namespace {
void SetMemoryPermissionBySvc(uintptr_t start, size_t size, svc::MemoryPermission perm) {
uintptr_t cur_address = start;
size_t remaining_size = size;
while (remaining_size > 0) {
svc::MemoryInfo mem_info;
svc::PageInfo page_info;
R_ABORT_UNLESS(svc::QueryMemory(std::addressof(mem_info), std::addressof(page_info), cur_address));
size_t cur_size = std::min(mem_info.base_address + mem_info.size - cur_address, remaining_size);
if (mem_info.permission != perm) {
R_ABORT_UNLESS(svc::SetMemoryPermission(cur_address, cur_size, perm));
}
cur_address += cur_size;
remaining_size -= cur_size;
}
}
}
void SetMemoryPermissionImpl(uintptr_t address, size_t size, MemoryPermission perm) {
switch (perm) {
case MemoryPermission_None:
return SetMemoryPermissionBySvc(address, size, svc::MemoryPermission_None);
case MemoryPermission_ReadOnly:
return SetMemoryPermissionBySvc(address, size, svc::MemoryPermission_Read);
case MemoryPermission_ReadWrite:
return SetMemoryPermissionBySvc(address, size, svc::MemoryPermission_ReadWrite);
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
}
| 2,111
|
C++
|
.cpp
| 46
| 37
| 115
| 0.650778
|
Atmosphere-NX/Atmosphere
| 14,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,750
|
os_initialize.os.macos.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_initialize.os.macos.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "os_resource_manager.hpp"
namespace ams {
void Main();
namespace init {
void InitializeDefaultAllocator();
}
/* TODO: This should probably instead be a custom init::Initialize*()? */
namespace fs {
void InitializeForHostTool();
}
}
namespace ams::os {
void SetHostArgc(int argc);
void SetHostArgv(char **argv);
[[gnu::constructor(101)]] void Initialize() {
/* Only allow os::Initialize to be called once. */
AMS_FUNCTION_LOCAL_STATIC_CONSTINIT(bool, s_initialized, false);
if (s_initialized) {
return;
}
s_initialized = true;
/* Initialize the global os resource manager. */
os::impl::ResourceManagerHolder::InitializeResourceManagerInstance();
/* Initialize virtual address memory. */
os::InitializeVirtualAddressMemory();
/* Ensure that the init library's allocator has been setup. */
init::InitializeDefaultAllocator();
}
}
extern "C" int main(int argc, char **argv) {
/* Ensure os library is initialized. */
::ams::os::Initialize();
/* Set argc/argv. */
::ams::os::SetHostArgc(argc);
::ams::os::SetHostArgv(argv);
/* Ensure filesystem library is initialized. */
::ams::fs::InitializeForHostTool();
/* Call main. */
::ams::Main();
/* TODO: Should we try to implement a custom exit here? */
return 0;
}
| 2,097
|
C++
|
.cpp
| 58
| 31.12069
| 77
| 0.675582
|
Atmosphere-NX/Atmosphere
| 14,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,751
|
os_initialize.os.horizon.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_initialize.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 "os_resource_manager.hpp"
extern "C" { extern u8 __argdata__[]; }
namespace ams::os {
namespace {
class MemoryArranger {
private:
uintptr_t m_address;
public:
constexpr MemoryArranger(uintptr_t address) : m_address(address) { /* ... */ }
template<typename T>
T *Arrange() {
this->Align(alignof(T));
return static_cast<T *>(this->Arrange(sizeof(T)));
}
void *Arrange(size_t size) {
const auto address = m_address;
m_address += size;
return reinterpret_cast<void *>(address);
}
void Align(size_t align) {
m_address = util::AlignUp(m_address, align);
}
char *ArrangeCharArray(size_t size) {
return reinterpret_cast<char *>(Arrange(size));
}
};
bool HasArguments(uintptr_t args_region) {
/* Check that the arguments region is read-write. */
svc::MemoryInfo mi;
svc::PageInfo pi;
if (R_FAILED(svc::QueryMemory(std::addressof(mi), std::addressof(pi), args_region))) {
return false;
}
return mi.permission == svc::MemoryPermission_ReadWrite;
}
const char *SkipSpace(const char *p, const char *end) {
while (p < end && std::isspace(*p)) { ++p; }
return p;
}
const char *GetTokenEnd(const char *p, const char *end) {
while (p < end && !std::isspace(*p)) { ++p; }
return p;
}
const char *GetQuotedTokenEnd(const char *p, const char *end) {
while (p < end && *p != '"') { ++p; }
return p;
}
int MakeArgv(char **out_argv_buf, char *arg_buf, const char *cmd_line, size_t cmd_line_size, int arg_max) {
/* Prepare to parse arguments. */
auto idx = 0;
auto src = cmd_line;
auto dst = arg_buf;
const auto end = src + cmd_line_size;
/* Parse all tokens. */
while (true) {
/* Advance past any spaces. */
src = SkipSpace(src, end);
if (src >= end) {
break;
}
/* Check that we don't have too many arguments. */
if (idx >= arg_max) {
break;
}
/* Find the start/end of the current argument token. */
const char *arg_end;
const char *src_next;
if (*src == '"') {
++src;
arg_end = GetQuotedTokenEnd(src, end);
src_next = arg_end + 1;
} else {
arg_end = GetTokenEnd(src, end);
src_next = arg_end;
}
/* Determine token size. */
const auto arg_size = arg_end - src;
/* Set the argv pointer. */
out_argv_buf[idx++] = dst;
/* Copy the argument. */
std::memcpy(dst, src, arg_size);
dst += arg_size;
/* Null-terminate the argument token. */
*(dst++) = '\x00';
/* Advance to next token. */
src = src_next;
}
/* Null terminate the final token. */
*(dst++) = '\x00';
/* Null terminate argv. */
out_argv_buf[idx] = nullptr;
return idx;
}
}
void SetHostArgc(int argc);
void SetHostArgv(char **argv);
void Initialize() {
/* Only allow os::Initialize to be called once. */
AMS_FUNCTION_LOCAL_STATIC_CONSTINIT(bool, s_initialized, false);
if (s_initialized) {
return;
}
s_initialized = true;
/* Initialize the global os resource manager. */
os::impl::ResourceManagerHolder::InitializeResourceManagerInstance();
/* Setup host argc/argv as needed. */
const uintptr_t args_region = reinterpret_cast<uintptr_t>(__argdata__);
if (HasArguments(args_region)) {
/* Create arguments memory arranger. */
MemoryArranger arranger(args_region);
/* Arrange. */
const auto &header = *arranger.Arrange<ldr::ProgramArguments>();
const char *cmd_line = arranger.ArrangeCharArray(header.arguments_size);
char *arg_buf = arranger.ArrangeCharArray(header.arguments_size + 2);
char **argv_buf = arranger.Arrange<char *>();
/* Determine extents. */
const auto arg_buf_size = reinterpret_cast<uintptr_t>(argv_buf) - args_region;
const auto arg_max = (header.allocated_size - arg_buf_size) / sizeof(char *);
/* Make argv. */
const auto arg_count = MakeArgv(argv_buf, arg_buf, cmd_line, header.arguments_size, arg_max);
/* Set host argc/argv. */
os::SetHostArgc(arg_count);
os::SetHostArgv(argv_buf);
}
}
}
| 5,971
|
C++
|
.cpp
| 142
| 29.443662
| 115
| 0.514587
|
Atmosphere-NX/Atmosphere
| 14,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,752
|
os_random_impl.os.horizon.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_random_impl.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::os::impl {
void InitializeRandomImpl(util::TinyMT *mt) {
/* Retrieve entropy from kernel. */
u32 seed[4];
static_assert(util::size(seed) == util::TinyMT::NumStateWords);
/* Nintendo does not check the result of these invocations, but we will for safety. */
/* Nintendo uses entropy values 0, 1 to seed the public TinyMT random, and values */
/* 2, 3 to seed os::detail::RngManager's private TinyMT random. */
R_ABORT_UNLESS(svc::GetInfo(reinterpret_cast<u64 *>(seed + 0), svc::InfoType_RandomEntropy, svc::InvalidHandle, 0));
R_ABORT_UNLESS(svc::GetInfo(reinterpret_cast<u64 *>(seed + 2), svc::InfoType_RandomEntropy, svc::InvalidHandle, 1));
mt->Initialize(seed, util::size(seed));
}
}
| 1,450
|
C++
|
.cpp
| 29
| 45.586207
| 124
| 0.705508
|
Atmosphere-NX/Atmosphere
| 14,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,753
|
os_io_region_impl.os.windows.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_io_region_impl.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 "os_io_region_impl.hpp"
namespace ams::os::impl {
Result IoRegionImpl::CreateIoRegion(NativeHandle *out, NativeHandle io_pool_handle, uintptr_t address, size_t size, MemoryMapping mapping, MemoryPermission permission) {
AMS_UNUSED(out, io_pool_handle, address, size, mapping, permission);
R_THROW(os::ResultNotSupported());
}
Result IoRegionImpl::MapIoRegion(void **out, NativeHandle handle, size_t size, MemoryPermission perm) {
AMS_UNUSED(out, handle, size, perm);
R_THROW(os::ResultNotSupported());
}
void IoRegionImpl::UnmapIoRegion(NativeHandle handle, void *address, size_t size) {
AMS_UNUSED(handle, address, size);
}
}
| 1,368
|
C++
|
.cpp
| 30
| 41.833333
| 173
| 0.735184
|
Atmosphere-NX/Atmosphere
| 14,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,754
|
os_timeout_helper_impl.os.linux.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_timeout_helper_impl.os.linux.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "os_timeout_helper_impl.os.linux.hpp"
#include <time.h>
namespace ams::os::impl {
void TimeoutHelperImpl::Sleep(TimeSpan tm) {
/* If asked to sleep for no time, do nothing */
if (tm == 0) {
return;
}
constexpr s64 NanoSecondsPerSecond = TimeSpan::FromSeconds(1).GetNanoSeconds();
const s64 ns = tm.GetNanoSeconds();
struct timespec ts = { .tv_sec = (ns / NanoSecondsPerSecond), .tv_nsec = ns % NanoSecondsPerSecond };
while (true) {
const auto ret = ::nanosleep(std::addressof(ts), std::addressof(ts));
if (ret == 0) {
break;
}
AMS_ASSERT(errno == EINTR);
}
}
}
| 1,389
|
C++
|
.cpp
| 36
| 32.888889
| 109
| 0.65899
|
Atmosphere-NX/Atmosphere
| 14,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,755
|
os_timeout_helper_impl.os.macos.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_timeout_helper_impl.os.macos.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "os_timeout_helper_impl.os.macos.hpp"
#include <time.h>
namespace ams::os::impl {
void TimeoutHelperImpl::Sleep(TimeSpan tm) {
/* If asked to sleep for no time, do nothing */
if (tm == 0) {
return;
}
constexpr s64 NanoSecondsPerSecond = TimeSpan::FromSeconds(1).GetNanoSeconds();
const s64 ns = tm.GetNanoSeconds();
struct timespec ts = { .tv_sec = (ns / NanoSecondsPerSecond), .tv_nsec = ns % NanoSecondsPerSecond };
while (true) {
const auto ret = ::nanosleep(std::addressof(ts), std::addressof(ts));
if (ret == 0) {
break;
}
AMS_ASSERT(errno == EINTR);
}
}
}
| 1,389
|
C++
|
.cpp
| 36
| 32.888889
| 109
| 0.65899
|
Atmosphere-NX/Atmosphere
| 14,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,756
|
os_thread_manager_impl.os.windows.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_thread_manager_impl.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 "os_thread_manager_impl.os.windows.hpp"
#include "os_thread_manager.hpp"
namespace ams::os::impl {
namespace {
constexpr size_t DefaultStackSize = 1_MB;
class ScopedSaveLastError {
NON_COPYABLE(ScopedSaveLastError);
NON_MOVEABLE(ScopedSaveLastError);
private:
DWORD m_last_error;
public:
ALWAYS_INLINE ScopedSaveLastError() : m_last_error(::GetLastError()) { /* ... */ }
ALWAYS_INLINE ~ScopedSaveLastError() { ::SetLastError(m_last_error); }
};
unsigned __stdcall InvokeThread(void *arg) {
ThreadType *thread = static_cast<ThreadType *>(arg);
/* Invoke the thread. */
ThreadManager::InvokeThread(thread);
return 0;
}
os::NativeHandle DuplicateThreadHandle(os::NativeHandle thread_handle) {
/* Get the thread's windows handle. */
os::NativeHandle windows_handle = os::InvalidNativeHandle;
AMS_ABORT_UNLESS(::DuplicateHandle(::GetCurrentProcess(), thread_handle, ::GetCurrentProcess(), std::addressof(windows_handle), 0, 0, DUPLICATE_SAME_ACCESS));
return windows_handle;
}
os::ThreadType *DynamicAllocateAndRegisterThreadType() {
/* Get the thread manager. */
auto &thread_manager = GetThreadManager();
/* Allocate a thread. */
auto *thread = thread_manager.AllocateThreadType();
AMS_ABORT_UNLESS(thread != nullptr);
/* Setup the thread object. */
SetupThreadObjectUnsafe(thread, nullptr, nullptr, nullptr, nullptr, 0, DefaultThreadPriority);
thread->state = ThreadType::State_Started;
thread->auto_registered = true;
/* Set the thread's windows handle. */
thread->native_handle = DuplicateThreadHandle(::GetCurrentThread());
thread->ideal_core = ::GetCurrentProcessorNumber();
thread->affinity_mask = thread_manager.GetThreadAvailableCoreMask();
/* Place the object under the thread manager. */
thread_manager.PlaceThreadObjectUnderThreadManagerSafe(thread);
return thread;
}
}
ThreadManagerWindowsImpl::ThreadManagerWindowsImpl(ThreadType *main_thread) : m_tls_index(::TlsAlloc()) {
/* Verify tls index is valid. */
AMS_ASSERT(m_tls_index != TLS_OUT_OF_INDEXES);
/* Setup the main thread object. */
SetupThreadObjectUnsafe(main_thread, nullptr, nullptr, nullptr, nullptr, DefaultStackSize, DefaultThreadPriority);
/* Setup the main thread's windows handle information. */
main_thread->native_handle = DuplicateThreadHandle(::GetCurrentThread());
main_thread->ideal_core = ::GetCurrentProcessorNumber();
main_thread->affinity_mask = this->GetThreadAvailableCoreMask();
}
Result ThreadManagerWindowsImpl::CreateThread(ThreadType *thread, s32 ideal_core) {
/* Create the thread. */
os::NativeHandle thread_handle = reinterpret_cast<os::NativeHandle>(_beginthreadex(nullptr, thread->stack_size, &InvokeThread, thread, CREATE_SUSPENDED, 0));
AMS_ASSERT(thread_handle != os::InvalidNativeHandle);
/* Set the thread's windows handle information. */
thread->native_handle = thread_handle;
thread->ideal_core = ideal_core;
thread->affinity_mask = this->GetThreadAvailableCoreMask();
R_SUCCEED();
}
void ThreadManagerWindowsImpl::DestroyThreadUnsafe(ThreadType *thread) {
/* Close the thread's handle. */
const auto ret = ::CloseHandle(thread->native_handle);
AMS_ASSERT(ret);
AMS_UNUSED(ret);
thread->native_handle = os::InvalidNativeHandle;
}
void ThreadManagerWindowsImpl::StartThread(const ThreadType *thread) {
ScopedSaveLastError save_error;
/* Resume the thread. */
const auto ret = ::ResumeThread(thread->native_handle);
AMS_ASSERT(ret == 1);
AMS_UNUSED(ret);
}
void ThreadManagerWindowsImpl::WaitForThreadExit(ThreadType *thread) {
::WaitForSingleObject(thread->native_handle, INFINITE);
}
bool ThreadManagerWindowsImpl::TryWaitForThreadExit(ThreadType *thread) {
return ::WaitForSingleObject(thread->native_handle, 0) == 0;
}
void ThreadManagerWindowsImpl::YieldThread() {
::Sleep(0);
}
bool ThreadManagerWindowsImpl::ChangePriority(ThreadType *thread, s32 priority) {
AMS_UNUSED(thread, priority);
return true;
}
s32 ThreadManagerWindowsImpl::GetCurrentPriority(const ThreadType *thread) const {
return thread->base_priority;
}
ThreadId ThreadManagerWindowsImpl::GetThreadId(const ThreadType *thread) const {
ScopedSaveLastError save_error;
const auto thread_id = ::GetThreadId(thread->native_handle);
AMS_ASSERT(thread_id != 0);
return thread_id;
}
void ThreadManagerWindowsImpl::SuspendThreadUnsafe(ThreadType *thread) {
ScopedSaveLastError save_error;
const auto ret = ::SuspendThread(thread->native_handle);
AMS_ASSERT(ret == 0);
AMS_UNUSED(ret);
}
void ThreadManagerWindowsImpl::ResumeThreadUnsafe(ThreadType *thread) {
ScopedSaveLastError save_error;
const auto ret = ::ResumeThread(thread->native_handle);
AMS_ASSERT(ret == 1);
AMS_UNUSED(ret);
}
/* TODO: void ThreadManagerWindowsImpl::GetThreadContextUnsafe(ThreadContextInfo *out_context, const ThreadType *thread); */
void ThreadManagerWindowsImpl::NotifyThreadNameChangedImpl(const ThreadType *thread) const {
/* TODO */
AMS_UNUSED(thread);
}
void ThreadManagerWindowsImpl::SetCurrentThread(ThreadType *thread) const {
ScopedSaveLastError save_error;
::TlsSetValue(m_tls_index, thread);
}
ThreadType *ThreadManagerWindowsImpl::GetCurrentThread() const {
ScopedSaveLastError save_error;
/* Get the thread from tls index. */
ThreadType *thread = static_cast<ThreadType *>(static_cast<void *>(::TlsGetValue(m_tls_index)));
/* If the thread's TLS isn't set, we need to find it (and set tls) or make it. */
if (thread == nullptr) {
/* Try to find the thread. */
thread = GetThreadManager().FindThreadTypeById(::GetCurrentThreadId());
if (thread == nullptr) {
/* Create the thread. */
thread = DynamicAllocateAndRegisterThreadType();
}
/* Set the thread's TLS. */
this->SetCurrentThread(thread);
}
return thread;
}
s32 ThreadManagerWindowsImpl::GetCurrentCoreNumber() const {
ScopedSaveLastError save_error;
return ::GetCurrentProcessorNumber();
}
void ThreadManagerWindowsImpl::SetThreadCoreMask(ThreadType *thread, s32 ideal_core, u64 affinity_mask) const {
ScopedSaveLastError save_error;
/* If we should use the default, set the actual ideal core. */
if (ideal_core == IdealCoreUseDefault) {
affinity_mask = this->GetThreadAvailableCoreMask();
ideal_core = util::CountTrailingZeros(affinity_mask);
affinity_mask = static_cast<decltype(affinity_mask)>(1) << ideal_core;
}
/* Lock the thread. */
std::scoped_lock lk(util::GetReference(thread->cs_thread));
/* Set the thread's affinity mask. */
const auto old = ::SetThreadAffinityMask(thread->native_handle, affinity_mask);
AMS_ABORT_UNLESS(old != 0);
/* Set the ideal core. */
if (ideal_core != IdealCoreNoUpdate) {
thread->ideal_core = ideal_core;
}
/* Set the tracked affinity mask. */
thread->affinity_mask = affinity_mask;
}
void ThreadManagerWindowsImpl::GetThreadCoreMask(s32 *out_ideal_core, u64 *out_affinity_mask, const ThreadType *thread) const {
ScopedSaveLastError save_error;
/* Lock the thread. */
std::scoped_lock lk(util::GetReference(thread->cs_thread));
/* Set the output. */
if (out_ideal_core != nullptr) {
*out_ideal_core = thread->ideal_core;
}
if (out_affinity_mask != nullptr) {
*out_affinity_mask = thread->affinity_mask;
}
}
u64 ThreadManagerWindowsImpl::GetThreadAvailableCoreMask() const {
ScopedSaveLastError save_error;
/* Get the process's affinity mask. */
u64 process_affinity, system_affinity;
AMS_ABORT_UNLESS(::GetProcessAffinityMask(::GetCurrentProcess(), std::addressof(process_affinity), std::addressof(system_affinity)) != 0);
return process_affinity;
}
}
| 9,537
|
C++
|
.cpp
| 199
| 39.160804
| 170
| 0.657035
|
Atmosphere-NX/Atmosphere
| 14,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,757
|
os_inter_process_event_impl.os.horizon.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_inter_process_event_impl.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 "os_inter_process_event.hpp"
#include "os_inter_process_event_impl.os.horizon.hpp"
#include "os_timeout_helper.hpp"
namespace ams::os::impl {
Result InterProcessEventHorizonImpl::Create(NativeHandle *out_write, NativeHandle *out_read) {
/* Create the event handles. */
svc::Handle wh, rh;
R_TRY_CATCH(svc::CreateEvent(std::addressof(wh), std::addressof(rh))) {
R_CONVERT(svc::ResultOutOfResource, os::ResultOutOfResource())
} R_END_TRY_CATCH_WITH_ABORT_UNLESS;
*out_write = wh;
*out_read = rh;
R_SUCCEED();
}
void InterProcessEventHorizonImpl::Close(NativeHandle handle) {
if (handle != os::InvalidNativeHandle) {
R_ABORT_UNLESS(svc::CloseHandle(handle));
}
}
void InterProcessEventHorizonImpl::Signal(NativeHandle handle) {
R_ABORT_UNLESS(svc::SignalEvent(handle));
}
void InterProcessEventHorizonImpl::Clear(NativeHandle handle) {
R_ABORT_UNLESS(svc::ClearEvent(handle));
}
void InterProcessEventHorizonImpl::Wait(NativeHandle handle, bool auto_clear) {
while (true) {
/* Continuously wait, until success. */
s32 index;
Result res = svc::WaitSynchronization(std::addressof(index), static_cast<svc::Handle *>(std::addressof(handle)), 1, svc::WaitInfinite);
if (R_SUCCEEDED(res)) {
/* Clear, if we must. */
if (auto_clear) {
R_TRY_CATCH(svc::ResetSignal(handle)) {
/* Some other thread might have caught this before we did. */
R_CATCH(svc::ResultInvalidState) { continue; }
} R_END_TRY_CATCH_WITH_ABORT_UNLESS;
}
return;
}
AMS_ASSERT(svc::ResultCancelled::Includes(res));
}
}
bool InterProcessEventHorizonImpl::TryWait(NativeHandle handle, bool auto_clear) {
/* If we're auto clear, just try to reset. */
if (auto_clear) {
return R_SUCCEEDED(svc::ResetSignal(handle));
}
/* Not auto-clear. */
while (true) {
/* Continuously wait, until success or timeout. */
s32 index;
Result res = svc::WaitSynchronization(std::addressof(index), static_cast<svc::Handle *>(std::addressof(handle)), 1, 0);
/* If we succeeded, we're signaled. */
if (R_SUCCEEDED(res)) {
return true;
}
/* If we timed out, we're not signaled. */
if (svc::ResultTimedOut::Includes(res)) {
return false;
}
AMS_ASSERT(svc::ResultCancelled::Includes(res));
}
}
bool InterProcessEventHorizonImpl::TimedWait(NativeHandle handle, bool auto_clear, TimeSpan timeout) {
TimeoutHelper timeout_helper(timeout);
while (true) {
/* Continuously wait, until success. */
s32 index;
Result res = svc::WaitSynchronization(std::addressof(index), static_cast<svc::Handle *>(std::addressof(handle)), 1, timeout_helper.GetTimeLeftOnTarget().GetNanoSeconds());
if (R_SUCCEEDED(res)) {
/* Clear, if we must. */
if (auto_clear) {
R_TRY_CATCH(svc::ResetSignal(handle)) {
/* Some other thread might have caught this before we did. */
R_CATCH(svc::ResultInvalidState) { continue; }
} R_END_TRY_CATCH_WITH_ABORT_UNLESS;
}
return true;
}
if (svc::ResultTimedOut::Includes(res)) {
return false;
}
AMS_ASSERT(svc::ResultCancelled::Includes(res));
}
}
}
| 4,486
|
C++
|
.cpp
| 103
| 33.407767
| 183
| 0.598671
|
Atmosphere-NX/Atmosphere
| 14,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,758
|
os_process_memory_impl.os.horizon.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_process_memory_impl.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 "os_process_memory_impl.hpp"
#include "os_aslr_space_manager.hpp"
namespace ams::os::impl {
namespace {
svc::MemoryPermission ConvertToSvcMemoryPermission(os::MemoryPermission perm) {
switch (perm) {
case os::MemoryPermission_None: return svc::MemoryPermission_None;
case os::MemoryPermission_ReadOnly: return svc::MemoryPermission_Read;
case os::MemoryPermission_ReadWrite: return svc::MemoryPermission_ReadWrite;
case os::MemoryPermission_ReadExecute: return svc::MemoryPermission_ReadExecute;
case os::MemoryPermission_ExecuteOnly: return svc::MemoryPermission_Execute;
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
}
Result ProcessMemoryImpl::Map(void **out, NativeHandle handle, u64 process_address, size_t size, AddressSpaceGenerateRandomFunction generate_random) {
/* Map at a random address. */
uintptr_t mapped_address;
R_TRY(impl::GetAslrSpaceManager().MapAtRandomAddressWithCustomRandomGenerator(std::addressof(mapped_address),
[handle, process_address](uintptr_t map_address, size_t map_size) -> Result {
R_TRY_CATCH(svc::MapProcessMemory(map_address, handle, process_address, map_size)) {
R_CONVERT(svc::ResultOutOfResource, os::ResultOutOfResource())
R_CONVERT(svc::ResultInvalidCurrentMemory, os::ResultInvalidCurrentMemoryState())
} R_END_TRY_CATCH_WITH_ABORT_UNLESS;
R_SUCCEED();
},
[handle, process_address](uintptr_t map_address, size_t map_size) -> void {
return ProcessMemoryImpl::Unmap(reinterpret_cast<void *>(map_address), handle, process_address, map_size);
},
size,
process_address,
generate_random
));
/* Return the address we mapped at. */
*out = reinterpret_cast<void *>(mapped_address);
R_SUCCEED();
}
void ProcessMemoryImpl::Unmap(void *mapped_memory, NativeHandle handle, u64 process_address, size_t size) {
R_ABORT_UNLESS(svc::UnmapProcessMemory(reinterpret_cast<uintptr_t>(mapped_memory), handle, process_address, size));
}
Result ProcessMemoryImpl::SetMemoryPermission(NativeHandle handle, u64 process_address, u64 size, MemoryPermission perm) {
/* Set the process memory permission. */
R_TRY_CATCH(svc::SetProcessMemoryPermission(handle, process_address, size, ConvertToSvcMemoryPermission(perm))) {
R_CONVERT(svc::ResultOutOfResource, os::ResultOutOfResource())
R_CONVERT(svc::ResultInvalidCurrentMemory, os::ResultInvalidCurrentMemoryState())
} R_END_TRY_CATCH_WITH_ABORT_UNLESS;
R_SUCCEED();
}
}
| 3,510
|
C++
|
.cpp
| 65
| 45.292308
| 154
| 0.678218
|
Atmosphere-NX/Atmosphere
| 14,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,759
|
os_internal_condition_variable_impl.os.horizon.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_internal_condition_variable_impl.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 "os_timeout_helper.hpp"
#include "os_thread_manager.hpp"
namespace ams::os::impl {
void InternalConditionVariableImpl::Signal() {
ams::svc::SignalProcessWideKey(reinterpret_cast<uintptr_t>(std::addressof(m_value)), 1);
}
void InternalConditionVariableImpl::Broadcast() {
ams::svc::SignalProcessWideKey(reinterpret_cast<uintptr_t>(std::addressof(m_value)), -1);
}
void InternalConditionVariableImpl::Wait(InternalCriticalSection *cs) {
const auto cur_handle = GetCurrentThreadHandle();
AMS_ASSERT((cs->Get()->m_thread_handle & ~ams::svc::HandleWaitMask) == cur_handle);
R_ABORT_UNLESS(ams::svc::WaitProcessWideKeyAtomic(reinterpret_cast<uintptr_t>(std::addressof(cs->Get()->m_thread_handle)), reinterpret_cast<uintptr_t>(std::addressof(m_value)), cur_handle, -1));
}
ConditionVariableStatus InternalConditionVariableImpl::TimedWait(InternalCriticalSection *cs, const TimeoutHelper &timeout_helper) {
const auto cur_handle = GetCurrentThreadHandle();
AMS_ASSERT((cs->Get()->m_thread_handle & ~ams::svc::HandleWaitMask) == cur_handle);
const TimeSpan left = timeout_helper.GetTimeLeftOnTarget();
if (left > 0) {
R_TRY_CATCH(ams::svc::WaitProcessWideKeyAtomic(reinterpret_cast<uintptr_t>(std::addressof(cs->Get()->m_thread_handle)), reinterpret_cast<uintptr_t>(std::addressof(m_value)), cur_handle, left.GetNanoSeconds())) {
R_CATCH(svc::ResultTimedOut) {
cs->Enter();
return ConditionVariableStatus::TimedOut;
}
} R_END_TRY_CATCH_WITH_ABORT_UNLESS;
return ConditionVariableStatus::Success;
} else {
return ConditionVariableStatus::TimedOut;
}
}
}
| 2,465
|
C++
|
.cpp
| 47
| 45.851064
| 223
| 0.697385
|
Atmosphere-NX/Atmosphere
| 14,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,760
|
os_internal_critical_section_impl.pthread.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_internal_critical_section_impl.pthread.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_LINUX)
#include <sys/syscall.h>
#include <unistd.h>
#endif
#if defined(AMS_OS_IMPL_USE_PTHREADS)
namespace ams::os::impl {
#if defined(AMS_OS_INTERNAL_CRITICAL_SECTION_IMPL_CAN_CHECK_LOCKED_BY_CURRENT_THREAD)
namespace {
#if defined(ATMOSPHERE_OS_LINUX)
template<typename T>
concept IsGlibcPthreadMutexImplementationWithOwnerField = requires (T &t) {
{ t.__data.__owner } -> std::convertible_to<int>;
};
static_assert(IsGlibcPthreadMutexImplementationWithOwnerField<pthread_mutex_t>);
#endif
}
#endif
void InternalCriticalSectionImpl::Initialize() {
/* TODO: What should be done here? */
}
void InternalCriticalSectionImpl::Finalize() {
/* TODO: What should be done here? */
}
void InternalCriticalSectionImpl::Enter() {
AMS_ABORT_UNLESS(pthread_mutex_lock(std::addressof(m_pthread_mutex)) == 0);
}
bool InternalCriticalSectionImpl::TryEnter() {
return pthread_mutex_trylock(std::addressof(m_pthread_mutex)) == 0;
}
void InternalCriticalSectionImpl::Leave() {
AMS_ABORT_UNLESS(pthread_mutex_unlock(std::addressof(m_pthread_mutex)) == 0);
}
#if defined(AMS_OS_INTERNAL_CRITICAL_SECTION_IMPL_CAN_CHECK_LOCKED_BY_CURRENT_THREAD)
bool InternalCriticalSectionImpl::IsLockedByCurrentThread() const {
/* TODO: This should be less of a terrible hack. */
#if defined(ATMOSPHERE_OS_LINUX)
return m_pthread_mutex.__data.__owner == ::syscall(SYS_gettid);
#else
#error "Unknown OS/underlying implementation for pthread InternalCriticalSectionImpl::IsLockedByCurrentThread()"
#endif
}
#endif
}
#endif
| 2,419
|
C++
|
.cpp
| 60
| 35.033333
| 124
| 0.705205
|
Atmosphere-NX/Atmosphere
| 14,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,761
|
os_io_region_impl.os.horizon.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_io_region_impl.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 "os_io_region_impl.hpp"
#include "os_aslr_space_manager_types.hpp"
#include "os_aslr_space_manager.hpp"
namespace ams::os::impl {
namespace {
constexpr svc::MemoryPermission ConvertToSvcMemoryPermission(os::MemoryPermission perm) {
switch (perm) {
case os::MemoryPermission_None: return svc::MemoryPermission_None;
case os::MemoryPermission_ReadOnly: return svc::MemoryPermission_Read;
case os::MemoryPermission_WriteOnly: return svc::MemoryPermission_Write;
case os::MemoryPermission_ReadWrite: return svc::MemoryPermission_ReadWrite;
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
constexpr svc::MemoryMapping ConvertToSvcMemoryMapping(os::MemoryMapping mapping) {
static_assert(std::same_as<svc::MemoryMapping, os::MemoryMapping>);
return mapping;
}
}
Result IoRegionImpl::CreateIoRegion(NativeHandle *out, NativeHandle io_pool_handle, uintptr_t address, size_t size, MemoryMapping mapping, MemoryPermission permission) {
/* Convert mapping/permission. */
const auto svc_mapping = ConvertToSvcMemoryMapping(mapping);
const auto svc_perm = ConvertToSvcMemoryPermission(permission);
/* Create the io region. */
/* TODO: Result conversion/abort on unexpected result? */
svc::Handle handle;
R_TRY(svc::CreateIoRegion(std::addressof(handle), io_pool_handle, address, size, svc_mapping, svc_perm));
*out = handle;
R_SUCCEED();
}
Result IoRegionImpl::MapIoRegion(void **out, NativeHandle handle, size_t size, MemoryPermission perm) {
/* Convert permission. */
const auto svc_perm = ConvertToSvcMemoryPermission(perm);
/* Map at a random address. */
uintptr_t mapped_address;
R_TRY(impl::GetAslrSpaceManager().MapAtRandomAddress(std::addressof(mapped_address),
[handle, svc_perm](uintptr_t map_address, size_t map_size) -> Result {
R_TRY_CATCH(svc::MapIoRegion(handle, map_address, map_size, svc_perm)) {
/* TODO: What's the correct result for these? */
// R_CONVERT(svc::ResultInvalidHandle, os::ResultInvalidHandle())
// R_CONVERT(svc::ResultInvalidSize, os::Result???())
// R_CONVERT(svc::ResultInvalidState, os::Result???())
R_CONVERT(svc::ResultInvalidCurrentMemory, os::ResultInvalidCurrentMemoryState())
} R_END_TRY_CATCH_WITH_ABORT_UNLESS;
R_SUCCEED();
},
[handle](uintptr_t map_address, size_t map_size) -> void {
return IoRegionImpl::UnmapIoRegion(handle, reinterpret_cast<void *>(map_address), map_size);
},
size,
0
));
/* Return the address we mapped at. */
*out = reinterpret_cast<void *>(mapped_address);
R_SUCCEED();
}
void IoRegionImpl::UnmapIoRegion(NativeHandle handle, void *address, size_t size) {
R_ABORT_UNLESS(svc::UnmapIoRegion(handle, reinterpret_cast<uintptr_t>(address), size));
}
}
| 3,893
|
C++
|
.cpp
| 76
| 42.223684
| 173
| 0.651591
|
Atmosphere-NX/Atmosphere
| 14,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,762
|
os_rng_manager_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_rng_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 "os_rng_manager_impl.hpp"
namespace ams::os::impl {
u64 RngManager::GenerateRandomU64() {
std::scoped_lock lk(m_lock);
if (AMS_UNLIKELY(!m_initialized)) {
this->Initialize();
}
return m_mt.GenerateRandomU64();
}
}
| 943
|
C++
|
.cpp
| 26
| 32.538462
| 76
| 0.712719
|
Atmosphere-NX/Atmosphere
| 14,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,763
|
os_internal_condition_variable_impl.pthread.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_internal_condition_variable_impl.pthread.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "os_timeout_helper.hpp"
#include "os_thread_manager.hpp"
#if defined(AMS_OS_IMPL_USE_PTHREADS)
namespace ams::os::impl {
namespace {
}
void InternalConditionVariableImpl::Initialize() {
/* TODO: What should be done here? */
}
void InternalConditionVariableImpl::Finalize() {
/* TODO: What should be done here? */
}
void InternalConditionVariableImpl::Signal() {
AMS_ABORT_UNLESS(pthread_cond_signal(std::addressof(m_pthread_cond)) == 0);
}
void InternalConditionVariableImpl::Broadcast() {
AMS_ABORT_UNLESS(pthread_cond_broadcast(std::addressof(m_pthread_cond)) == 0);
}
void InternalConditionVariableImpl::Wait(InternalCriticalSection *cs) {
AMS_ABORT_UNLESS(pthread_cond_wait(std::addressof(m_pthread_cond), std::addressof(cs->Get()->m_pthread_mutex)) == 0);
}
ConditionVariableStatus InternalConditionVariableImpl::TimedWait(InternalCriticalSection *cs, const TimeoutHelper &timeout_helper) {
struct timespec ts;
const auto gettime_res = clock_gettime(CLOCK_REALTIME, std::addressof(ts));
AMS_ASSERT(gettime_res == 0);
AMS_UNUSED(gettime_res);
constexpr s64 NanoSecondsPerSecond = TimeSpan::FromSeconds(1).GetNanoSeconds();
const s64 ns = timeout_helper.GetTimeLeftOnTarget().GetNanoSeconds();
ts.tv_sec += (ns / NanoSecondsPerSecond);
ts.tv_nsec += (ns % NanoSecondsPerSecond);
if (ts.tv_nsec >= NanoSecondsPerSecond) {
ts.tv_sec += ts.tv_nsec / NanoSecondsPerSecond;
ts.tv_nsec %= NanoSecondsPerSecond;
}
const auto res = pthread_cond_timedwait(std::addressof(m_pthread_cond), std::addressof(cs->Get()->m_pthread_mutex), std::addressof(ts));
if (res != 0) {
AMS_ABORT_UNLESS(res == ETIMEDOUT);
return ConditionVariableStatus::TimedOut;
}
return ConditionVariableStatus::Success;
}
}
#endif
| 2,639
|
C++
|
.cpp
| 59
| 38.915254
| 144
| 0.695635
|
Atmosphere-NX/Atmosphere
| 14,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,764
|
os_giant_lock.os.windows.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_giant_lock.os.windows.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include <stratosphere/windows.hpp>
#include "os_giant_lock.os.windows.hpp"
namespace ams::os::impl {
GiantLockWindowsImpl::GiantLockWindowsImpl() {
const NativeHandle handle = ::CreateMutexA(nullptr, false, "AMS_OS_STRATOSPHERE_GIANT_LOCK");
AMS_ASSERT(handle != InvalidNativeHandle);
m_handle = handle;
}
GiantLockWindowsImpl::~GiantLockWindowsImpl() {
const auto ret = ::CloseHandle(m_handle);
AMS_ASSERT(ret != 0);
AMS_UNUSED(ret);
}
}
| 1,172
|
C++
|
.cpp
| 30
| 35.3
| 101
| 0.723835
|
Atmosphere-NX/Atmosphere
| 14,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,765
|
os_rw_lock_target_impl.os.horizon.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_rw_lock_target_impl.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 "os_rw_lock_impl.hpp"
#include "os_thread_manager.hpp"
namespace ams::os::impl {
#define ATOMIC_COMPARE_EXCHANGE_LOCK_COUNT(dst_ref, expected_ref, desired_ref, success, fail) \
(__atomic_compare_exchange(reinterpret_cast<u64 *>(std::addressof(dst_ref)), reinterpret_cast<u64 *>(std::addressof(expected_ref)), reinterpret_cast<u64 *>(std::addressof(desired_ref)), true, success, fail))
void ReaderWriterLockHorizonImpl::AcquireReadLockWriteLocked(os::ReaderWriterLockType *rw_lock) {
AMS_ASSERT(GetWriteLocked(GetLockCount(rw_lock)) == 1);
AMS_ASSERT((GetThreadHandle(GetLockCount(rw_lock)) | svc::HandleWaitMask) == (impl::GetCurrentThreadHandle() | svc::HandleWaitMask));
alignas(alignof(u64)) LockCount expected = GetLockCount(rw_lock);
alignas(alignof(u64)) LockCount lock_count;
do {
lock_count = expected;
IncReadLockCount(lock_count);
} while (!ATOMIC_COMPARE_EXCHANGE_LOCK_COUNT(GetLockCount(rw_lock), expected, lock_count, __ATOMIC_RELAXED, __ATOMIC_RELAXED));
}
void ReaderWriterLockHorizonImpl::ReleaseReadLockWriteLocked(os::ReaderWriterLockType *rw_lock) {
AMS_ASSERT(GetWriteLocked(GetLockCount(rw_lock)) == 1);
AMS_ASSERT((GetThreadHandle(GetLockCount(rw_lock)) | svc::HandleWaitMask) == (impl::GetCurrentThreadHandle() | svc::HandleWaitMask));
alignas(alignof(u64)) LockCount expected = GetLockCount(rw_lock);
alignas(alignof(u64)) LockCount lock_count;
do {
lock_count = expected;
DecReadLockCount(lock_count);
} while (!ATOMIC_COMPARE_EXCHANGE_LOCK_COUNT(GetLockCount(rw_lock), expected, lock_count, __ATOMIC_RELAXED, __ATOMIC_RELAXED));
return ReleaseWriteLockImpl(rw_lock);
}
void ReaderWriterLockHorizonImpl::ReleaseWriteLockImpl(os::ReaderWriterLockType *rw_lock) {
alignas(alignof(u64)) LockCount expected = GetLockCount(rw_lock);
alignas(alignof(u64)) LockCount lock_count = expected;
AMS_ASSERT(GetWriteLocked(lock_count) == 1);
if (GetReadLockCount(lock_count) == 0 && GetWriteLockCount(*rw_lock) == 0) {
rw_lock->owner_thread = nullptr;
if (GetWriteLockWaiterCount(lock_count) > 0) {
GetReference(rw_lock->cv_write_lock._storage).Signal();
} else if (GetReadLockWaiterCount(lock_count) > 0) {
GetReference(rw_lock->cv_read_lock._storage).Broadcast();
}
do {
ClearWriteLocked(lock_count);
SetThreadHandle(lock_count, (GetThreadHandle(lock_count) & svc::HandleWaitMask) ? GetThreadHandle(lock_count) : svc::InvalidHandle);
} while(!ATOMIC_COMPARE_EXCHANGE_LOCK_COUNT(GetLockCount(rw_lock), expected, lock_count, __ATOMIC_RELEASE, __ATOMIC_RELAXED));
if (GetThreadHandle(lock_count)) {
R_ABORT_UNLESS(svc::ArbitrateUnlock(GetThreadHandleAddress(GetLockCount(rw_lock))));
}
}
}
void ReaderWriterLockHorizonImpl::AcquireReadLock(os::ReaderWriterLockType *rw_lock) {
AMS_ASSERT(::ams::svc::GetThreadLocalRegion()->disable_count == 0);
auto *cur_thread = impl::GetCurrentThread();
if (rw_lock->owner_thread == cur_thread) {
return AcquireReadLockWriteLocked(rw_lock);
} else {
const u32 cur_handle = cur_thread->thread_impl->handle;
bool arbitrated = false;
bool got_read_lock, needs_arbitrate_lock;
alignas(alignof(u64)) LockCount lock_count;
alignas(alignof(u64)) LockCount expected;
while (true) {
expected = GetLockCount(rw_lock);
do {
lock_count = expected;
AMS_ASSERT(GetWriteLocked(lock_count) == 0 || GetThreadHandle(lock_count) != svc::InvalidHandle);
if (GetWriteLocked(lock_count) != 0 || GetWriteLockWaiterCount(lock_count) != 0) {
if (!arbitrated) {
IncReadLockWaiterCount(lock_count);
}
const u32 h = GetThreadHandle(lock_count);
got_read_lock = false;
needs_arbitrate_lock = h != 0;
SetThreadHandle(lock_count, needs_arbitrate_lock ? (h | svc::HandleWaitMask) : cur_handle);
} else {
if (arbitrated) {
DecReadLockWaiterCount(lock_count);
}
IncReadLockCount(lock_count);
got_read_lock = true;
needs_arbitrate_lock = false;
}
} while (!ATOMIC_COMPARE_EXCHANGE_LOCK_COUNT(GetLockCount(rw_lock), expected, lock_count, __ATOMIC_ACQUIRE, __ATOMIC_RELAXED));
if (!needs_arbitrate_lock) {
break;
}
R_ABORT_UNLESS(svc::ArbitrateLock(GetThreadHandle(lock_count) & ~svc::HandleWaitMask, GetThreadHandleAddress(GetLockCount(rw_lock)), cur_handle));
const u32 new_handle = GetThreadHandle(GetLockCount(rw_lock));
if ((new_handle | svc::HandleWaitMask) == (cur_handle | svc::HandleWaitMask)) {
lock_count = GetLockCount(rw_lock);
break;
}
arbitrated = true;
}
if (got_read_lock) {
return;
}
expected = lock_count;
do {
while (GetWriteLockWaiterCount(lock_count)) {
GetReference(rw_lock->cv_read_lock._storage).Wait(GetPointer(GetLockCount(rw_lock).cs_storage));
expected = GetLockCount(rw_lock);
lock_count = expected;
}
DecReadLockWaiterCount(lock_count);
IncReadLockCount(lock_count);
SetThreadHandle(lock_count, (GetThreadHandle(lock_count) & svc::HandleWaitMask) ? GetThreadHandle(lock_count) : svc::InvalidHandle);
} while(!ATOMIC_COMPARE_EXCHANGE_LOCK_COUNT(GetLockCount(rw_lock), expected, lock_count, __ATOMIC_RELEASE, __ATOMIC_RELAXED));
if (GetThreadHandle(lock_count) & svc::HandleWaitMask) {
R_ABORT_UNLESS(svc::ArbitrateUnlock(GetThreadHandleAddress(GetLockCount(rw_lock))));
}
}
}
bool ReaderWriterLockHorizonImpl::TryAcquireReadLock(os::ReaderWriterLockType *rw_lock) {
AMS_ASSERT(::ams::svc::GetThreadLocalRegion()->disable_count == 0);
auto *cur_thread = impl::GetCurrentThread();
if (rw_lock->owner_thread == cur_thread) {
AcquireReadLockWriteLocked(rw_lock);
return true;
} else {
alignas(alignof(u64)) LockCount expected = GetLockCount(rw_lock);
alignas(alignof(u64)) LockCount lock_count;
while (true) {
lock_count = expected;
AMS_ASSERT(GetWriteLocked(lock_count) == 0 || GetThreadHandle(lock_count) != 0);
if (GetWriteLocked(lock_count) == 0 && GetWriteLockWaiterCount(lock_count) == 0) {
IncReadLockCount(lock_count);
if (ATOMIC_COMPARE_EXCHANGE_LOCK_COUNT(GetLockCount(rw_lock), expected, lock_count, __ATOMIC_ACQUIRE, __ATOMIC_RELAXED)) {
return true;
}
} else {
return false;
}
}
}
}
void ReaderWriterLockHorizonImpl::ReleaseReadLock(os::ReaderWriterLockType *rw_lock) {
AMS_ASSERT(::ams::svc::GetThreadLocalRegion()->disable_count == 0);
AMS_ASSERT(GetReadLockCount(GetLockCount(rw_lock)) > 0);
auto *cur_thread = impl::GetCurrentThread();
if (rw_lock->owner_thread == cur_thread) {
return ReleaseReadLockWriteLocked(rw_lock);
} else {
alignas(alignof(u64)) LockCount expected = GetLockCount(rw_lock);
alignas(alignof(u64)) LockCount lock_count;
while (true) {
lock_count = expected;
DecReadLockCount(lock_count);
if (GetReadLockCount(lock_count) == 0 && GetWriteLockWaiterCount(lock_count) != 0) {
break;
}
if (ATOMIC_COMPARE_EXCHANGE_LOCK_COUNT(GetLockCount(rw_lock), expected, lock_count, __ATOMIC_RELEASE, __ATOMIC_RELAXED)) {
return;
}
}
AMS_ASSERT(GetWriteLocked(lock_count) == 0);
const u32 cur_handle = cur_thread->thread_impl->handle;
do {
do {
const u32 h = GetThreadHandle(lock_count);
SetThreadHandle(lock_count, h != 0 ? (h | svc::HandleWaitMask) : cur_handle);
} while (!ATOMIC_COMPARE_EXCHANGE_LOCK_COUNT(GetLockCount(rw_lock), expected, lock_count, __ATOMIC_ACQUIRE, __ATOMIC_RELAXED));
if (GetThreadHandle(lock_count) == cur_handle) {
break;
}
R_ABORT_UNLESS(svc::ArbitrateLock(GetThreadHandle(lock_count) & ~svc::HandleWaitMask, GetThreadHandleAddress(GetLockCount(rw_lock)), cur_handle));
expected = GetLockCount(rw_lock);
} while ((GetThreadHandle(GetLockCount(rw_lock)) | svc::HandleWaitMask) != (cur_handle | svc::HandleWaitMask));
do {
lock_count = expected;
AMS_ASSERT(GetReadLockCount(lock_count) == 1 && GetWriteLockWaiterCount(lock_count) > 0);
DecReadLockCount(lock_count);
} while (!ATOMIC_COMPARE_EXCHANGE_LOCK_COUNT(GetLockCount(rw_lock), expected, lock_count, __ATOMIC_RELAXED, __ATOMIC_RELAXED));
GetReference(rw_lock->cv_write_lock._storage).Signal();
do {
lock_count = expected;
AMS_ASSERT(GetReadLockCount(lock_count) == 0 && GetWriteLockWaiterCount(lock_count) > 0);
SetThreadHandle(lock_count, (GetThreadHandle(lock_count) & svc::HandleWaitMask) ? GetThreadHandle(lock_count) : svc::InvalidHandle);
} while(!ATOMIC_COMPARE_EXCHANGE_LOCK_COUNT(GetLockCount(rw_lock), expected, lock_count, __ATOMIC_RELEASE, __ATOMIC_RELAXED));
if (GetThreadHandle(lock_count) & svc::HandleWaitMask) {
R_ABORT_UNLESS(svc::ArbitrateUnlock(GetThreadHandleAddress(GetLockCount(rw_lock))));
}
}
}
void ReaderWriterLockHorizonImpl::AcquireWriteLock(os::ReaderWriterLockType *rw_lock) {
AMS_ASSERT(::ams::svc::GetThreadLocalRegion()->disable_count == 0);
auto *cur_thread = impl::GetCurrentThread();
const u32 cur_handle = cur_thread->thread_impl->handle;
if (rw_lock->owner_thread == cur_thread) {
AMS_ASSERT(GetWriteLocked(GetLockCount(rw_lock)) == 1);
AMS_ASSERT((GetThreadHandle(GetLockCount(rw_lock)) | svc::HandleWaitMask) == (cur_handle | svc::HandleWaitMask));
IncWriteLockCount(*rw_lock);
} else {
alignas(alignof(u64)) LockCount expected;
alignas(alignof(u64)) LockCount lock_count;
bool arbitrated = false;
bool got_write_lock, needs_arbitrate_lock;
while (true) {
expected = GetLockCount(rw_lock);
do {
lock_count = expected;
AMS_ASSERT(GetWriteLocked(lock_count) == 0 || GetThreadHandle(lock_count) != svc::InvalidHandle);
if (GetReadLockCount(lock_count) > 0 || GetThreadHandle(lock_count) != svc::InvalidHandle) {
if (!arbitrated) {
IncWriteLockWaiterCount(lock_count);
}
const u32 h = GetThreadHandle(lock_count);
got_write_lock = false;
needs_arbitrate_lock = h != 0;
SetThreadHandle(lock_count, needs_arbitrate_lock ? (h | svc::HandleWaitMask) : cur_handle);
} else {
if (arbitrated) {
DecWriteLockWaiterCount(lock_count);
}
SetWriteLocked(lock_count);
got_write_lock = true;
needs_arbitrate_lock = false;
}
} while (!ATOMIC_COMPARE_EXCHANGE_LOCK_COUNT(GetLockCount(rw_lock), expected, lock_count, __ATOMIC_ACQUIRE, __ATOMIC_RELAXED));
if (got_write_lock) {
break;
}
if (needs_arbitrate_lock) {
R_ABORT_UNLESS(svc::ArbitrateLock(GetThreadHandle(lock_count) & ~svc::HandleWaitMask, GetThreadHandleAddress(GetLockCount(rw_lock)), cur_handle));
arbitrated = true;
expected = GetLockCount(rw_lock);
if ((GetThreadHandle(expected) | svc::HandleWaitMask) != (cur_handle | svc::HandleWaitMask)) {
continue;
}
}
do {
lock_count = expected;
AMS_ASSERT(GetWriteLocked(lock_count) == 0);
while (GetReadLockCount(lock_count) > 0) {
GetReference(rw_lock->cv_write_lock._storage).Wait(GetPointer(GetLockCount(rw_lock).cs_storage));
expected = GetLockCount(rw_lock);
lock_count = expected;
}
AMS_ASSERT(GetWriteLocked(lock_count) == 0);
DecWriteLockWaiterCount(lock_count);
SetWriteLocked(lock_count);
} while (!ATOMIC_COMPARE_EXCHANGE_LOCK_COUNT(GetLockCount(rw_lock), expected, lock_count, __ATOMIC_ACQUIRE, __ATOMIC_RELAXED));
break;
}
AMS_ASSERT(GetWriteLockCount(*rw_lock) == 0);
IncWriteLockCount(*rw_lock);
rw_lock->owner_thread = cur_thread;
}
}
bool ReaderWriterLockHorizonImpl::TryAcquireWriteLock(os::ReaderWriterLockType *rw_lock) {
AMS_ASSERT(::ams::svc::GetThreadLocalRegion()->disable_count == 0);
auto *cur_thread = impl::GetCurrentThread();
if (rw_lock->owner_thread == cur_thread) {
AMS_ASSERT(GetWriteLocked(GetLockCount(rw_lock)) == 1);
IncWriteLockCount(*rw_lock);
return true;
} else {
const u32 cur_handle = cur_thread->thread_impl->handle;
alignas(alignof(u64)) LockCount expected = GetLockCount(rw_lock);
alignas(alignof(u64)) LockCount lock_count;
do {
lock_count = expected;
AMS_ASSERT(GetWriteLocked(lock_count) == 0 || GetThreadHandle(lock_count) != svc::InvalidHandle);
if (GetReadLockCount(lock_count) > 0 || GetThreadHandle(lock_count) != svc::InvalidHandle) {
return false;
}
SetWriteLocked(lock_count);
SetThreadHandle(lock_count, cur_handle);
} while (!ATOMIC_COMPARE_EXCHANGE_LOCK_COUNT(GetLockCount(rw_lock), expected, lock_count, __ATOMIC_ACQUIRE, __ATOMIC_RELAXED));
AMS_ASSERT(GetWriteLockCount(*rw_lock) == 0);
IncWriteLockCount(*rw_lock);
rw_lock->owner_thread = cur_thread;
return true;
}
}
void ReaderWriterLockHorizonImpl::ReleaseWriteLock(os::ReaderWriterLockType *rw_lock) {
AMS_ASSERT(::ams::svc::GetThreadLocalRegion()->disable_count == 0);
AMS_ASSERT(GetWriteLockCount(*rw_lock) > 0);
AMS_ASSERT(GetWriteLocked(GetLockCount(rw_lock)) != 0);
DecWriteLockCount(*rw_lock);
return ReleaseWriteLockImpl(rw_lock);
}
}
| 16,658
|
C++
|
.cpp
| 295
| 42.050847
| 215
| 0.586169
|
Atmosphere-NX/Atmosphere
| 14,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,766
|
os_random_impl.os.macos.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_random_impl.os.macos.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::os::impl {
void InitializeRandomImpl(util::TinyMT *mt) {
/* Initialize twister based on system tick. */
mt->Initialize(os::GetSystemTick().GetInt64Value());
}
}
| 866
|
C++
|
.cpp
| 22
| 36.5
| 76
| 0.736029
|
Atmosphere-NX/Atmosphere
| 14,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,767
|
os_thread_manager.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_thread_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 "os_thread_manager.hpp"
#include "os_multiple_wait_impl.hpp"
#include "os_multiple_wait_holder_base.hpp"
#include "os_multiple_wait_holder_impl.hpp"
#include "os_multiple_wait_object_list.hpp"
#include "os_utility.hpp"
namespace ams::os::impl {
void SetupThreadObjectUnsafe(ThreadType *thread, void *platform, ThreadFunction function, void *arg, void *stack, size_t stack_size, s32 priority) {
/* Clear the thread object. */
std::memset(thread, 0, sizeof(*thread));
/* Setup objects. */
util::ConstructAt(thread->cs_thread);
util::ConstructAt(thread->cv_thread);
util::ConstructAt(thread->all_threads_node);
util::ConstructAt(thread->waitlist);
/* Set member variables. */
thread->magic = os::ThreadType::Magic;
thread->stack_is_aliased = false;
thread->auto_registered = false;
thread->version = 0;
thread->function = function;
thread->argument = arg;
thread->original_stack = stack;
thread->stack = stack;
thread->stack_size = stack_size;
thread->base_priority = priority;
thread->suspend_count = 0;
thread->initial_fiber = nullptr;
thread->current_fiber = nullptr;
thread->name_buffer[0] = '\x00';
thread->name_pointer = thread->name_buffer;
/* Set platform variables. */
#if defined(AMS_OS_IMPL_USE_PTHREADS)
util::ConstructAt(thread->cs_pthread_exit);
util::ConstructAt(thread->cv_pthread_exit);
thread->exited_pthread = false;
std::memset(thread->tls_value_array, 0, sizeof(thread->tls_value_array));
AMS_UNUSED(platform);
#elif defined(ATMOSPHERE_OS_HORIZON)
std::memset(std::addressof(thread->sdk_internal_tls), 0, sizeof(thread->sdk_internal_tls));
thread->thread_impl = (platform != nullptr) ? static_cast<ThreadType::ThreadImpl *>(platform) : std::addressof(thread->thread_impl_storage);
#else
std::memset(thread->tls_value_array, 0, sizeof(thread->tls_value_array));
AMS_UNUSED(platform);
#endif
/* Mark initialized. */
thread->state = ThreadType::State_Initialized;
}
void ThreadManager::InvokeThread(ThreadType *thread) {
auto &manager = GetThreadManager();
manager.SetCurrentThread(thread);
manager.NotifyThreadNameChanged(thread);
{
GetReference(thread->cs_thread).Lock();
while (thread->state == ThreadType::State_Initialized) {
GetReference(thread->cv_thread).Wait(GetPointer(thread->cs_thread));
}
const auto new_state = thread->state;
GetReference(thread->cs_thread).Unlock();
if (new_state == ThreadType::State_Started) {
thread->function(thread->argument);
}
}
manager.CleanupThread();
}
ThreadManager::ThreadManager() : m_impl(std::addressof(m_main_thread)), m_total_thread_stack_size(0), m_num_created_threads(0) {
m_total_thread_stack_size = 0;
m_num_created_threads = 0;
m_main_thread.state = ThreadType::State_Started;
this->SetCurrentThread(std::addressof(m_main_thread));
this->PlaceThreadObjectUnderThreadManagerSafe(std::addressof(m_main_thread));
}
void ThreadManager::CleanupThread(ThreadType *thread) {
/* TODO: TLS Manager->InvokeTlsDestructors(); */
std::scoped_lock lk(GetReference(thread->cs_thread));
thread->state = ThreadType::State_Terminated;
GetReference(thread->cv_thread).Broadcast();
GetReference(thread->waitlist).WakeupAllMultiWaitThreadsUnsafe();
}
void ThreadManager::CleanupThread() {
return this->CleanupThread(this->GetCurrentThread());
}
bool ThreadManager::CreateAliasStackUnsafe(ThreadType *thread) {
void *alias_stack;
if (m_impl.MapAliasStack(std::addressof(alias_stack), thread->stack, thread->stack_size)) {
thread->stack_is_aliased = true;
thread->stack = alias_stack;
return true;
} else {
return false;
}
}
void ThreadManager::DeleteAliasStackUnsafe(ThreadType *thread) {
AMS_ABORT_UNLESS(m_impl.UnmapAliasStack(thread->stack, thread->original_stack, thread->stack_size));
thread->stack_is_aliased = false;
thread->stack = thread->original_stack;
}
Result ThreadManager::CreateThread(ThreadType *thread, ThreadFunction function, void *argument, void *stack, size_t stack_size, s32 priority, s32 ideal_core) {
SetupThreadObjectUnsafe(thread, nullptr, function, argument, stack, stack_size, priority);
AMS_ABORT_UNLESS(this->CreateAliasStackUnsafe(thread));
ON_RESULT_FAILURE {
this->DeleteAliasStackUnsafe(thread);
thread->state = ThreadType::State_NotInitialized;
};
R_TRY(m_impl.CreateThread(thread, ideal_core));
this->PlaceThreadObjectUnderThreadManagerSafe(thread);
R_SUCCEED();
}
Result ThreadManager::CreateThread(ThreadType *thread, ThreadFunction function, void *argument, void *stack, size_t stack_size, s32 priority) {
R_RETURN(this->CreateThread(thread, function, argument, stack, stack_size, priority, m_impl.GetDefaultCoreNumber()));
}
void ThreadManager::DestroyThread(ThreadType *thread) {
{
std::scoped_lock lk(GetReference(thread->cs_thread));
if (thread->state == ThreadType::State_Initialized) {
thread->state = ThreadType::State_DestroyedBeforeStarted;
m_impl.StartThread(thread);
GetReference(thread->cv_thread).Signal();
}
}
m_impl.WaitForThreadExit(thread);
this->DestroyThreadObject(thread);
}
void ThreadManager::DestroyThreadObject(ThreadType *thread) {
{
std::scoped_lock lk(GetReference(thread->cs_thread));
{
std::scoped_lock tlk(m_cs);
this->EraseFromAllThreadsListUnsafe(thread);
}
if (thread->stack_is_aliased) {
this->DeleteAliasStackUnsafe(thread);
}
m_impl.DestroyThreadUnsafe(thread);
thread->state = ThreadType::State_NotInitialized;
thread->name_buffer[0] = '\x00';
thread->magic = 0xCCCC;
util::DestroyAt(thread->waitlist);
}
util::DestroyAt(thread->cs_thread);
util::DestroyAt(thread->cv_thread);
}
void ThreadManager::StartThread(ThreadType *thread) {
std::scoped_lock lk(GetReference(thread->cs_thread));
AMS_ASSERT(thread->state == ThreadType::State_Initialized);
m_impl.StartThread(thread);
thread->state = ThreadType::State_Started;
GetReference(thread->cv_thread).Signal();
}
void ThreadManager::WaitThread(ThreadType *thread) {
m_impl.WaitForThreadExit(thread);
{
std::scoped_lock lk(GetReference(thread->cs_thread));
if (thread->stack_is_aliased) {
this->DeleteAliasStackUnsafe(thread);
}
}
}
bool ThreadManager::TryWaitThread(ThreadType *thread) {
const bool result = m_impl.TryWaitForThreadExit(thread);
if (result) {
std::scoped_lock lk(GetReference(thread->cs_thread));
if (thread->stack_is_aliased) {
this->DeleteAliasStackUnsafe(thread);
}
}
return result;
}
s32 ThreadManager::SuspendThread(ThreadType *thread) {
std::scoped_lock lk(GetReference(thread->cs_thread));
const auto prev_suspend_count = thread->suspend_count;
AMS_ASSERT(prev_suspend_count < ThreadSuspendCountMax);
thread->suspend_count = prev_suspend_count + 1;
if (prev_suspend_count == 0) {
m_impl.SuspendThreadUnsafe(thread);
}
return prev_suspend_count;
}
s32 ThreadManager::ResumeThread(ThreadType *thread) {
std::scoped_lock lk(GetReference(thread->cs_thread));
const auto prev_suspend_count = thread->suspend_count;
if (prev_suspend_count > 0) {
thread->suspend_count = prev_suspend_count - 1;
if (prev_suspend_count == 1) {
m_impl.ResumeThreadUnsafe(thread);
}
}
return prev_suspend_count;
}
#if !defined(ATMOSPHERE_OS_HORIZON)
void ThreadManager::SetZeroToAllThreadsTlsSafe(int slot) {
std::scoped_lock lk(m_cs);
for (auto it = m_all_threads_list.begin(); it != m_all_threads_list.end(); ++it) {
it->tls_value_array[slot] = 0;
}
}
#endif
/* TODO void ThreadManager::GetThreadContext(ThreadContextInfo *out_context, const ThreadType *thread); */
namespace {
constexpr inline const char MainThreadName[] = "MainThread";
constexpr inline const char ThreadNamePrefix[] = "Thread_0x";
}
void ThreadManager::SetInitialThreadNameUnsafe(ThreadType *thread) {
if (thread == std::addressof(m_main_thread)) {
static_assert(sizeof(thread->name_buffer) >= sizeof(MainThreadName));
static_assert(MainThreadName[sizeof(MainThreadName) - 1] == '\x00');
std::memcpy(thread->name_buffer, MainThreadName, sizeof(MainThreadName));
} else {
constexpr size_t ThreadNamePrefixSize = sizeof(ThreadNamePrefix) - 1;
const u64 func = reinterpret_cast<u64>(thread->function);
static_assert(ThreadNamePrefixSize + sizeof(func) * 2 + 1 <= sizeof(thread->name_buffer));
std::memcpy(thread->name_buffer, ThreadNamePrefix, ThreadNamePrefixSize);
os::impl::ExpandUnsignedValueToAscii(thread->name_buffer + ThreadNamePrefixSize, func);
}
thread->name_pointer = thread->name_buffer;
}
}
| 10,756
|
C++
|
.cpp
| 233
| 37.201717
| 163
| 0.638937
|
Atmosphere-NX/Atmosphere
| 14,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,768
|
os_rng_manager_impl.os.linux.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_rng_manager_impl.os.linux.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "os_rng_manager_impl.hpp"
namespace ams::os::impl {
void RngManager::Initialize() {
/* Initialize twister based on system tick. */
m_mt.Initialize(os::GetSystemTick().GetInt64Value());
/* Note that we've initialized. */
m_initialized = true;
}
}
| 962
|
C++
|
.cpp
| 25
| 35.16
| 76
| 0.721329
|
Atmosphere-NX/Atmosphere
| 14,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,769
|
os_timer_event_helper.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_timer_event_helper.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "os_timer_event_helper.hpp"
namespace ams::os::impl {
TimeSpan SaturatedAdd(TimeSpan t1, TimeSpan t2) {
AMS_ASSERT(t1 >= 0);
AMS_ASSERT(t2 >= 0);
const u64 u1 = t1.GetNanoSeconds();
const u64 u2 = t2.GetNanoSeconds();
const u64 sum = u1 + u2;
return TimeSpan::FromNanoSeconds(std::min<u64>(std::numeric_limits<s64>::max(), sum));
}
void StopTimerUnsafe(TimerEventType *event) {
GetReference(event->next_time_to_wakeup) = 0;
event->timer_state = TimerEventType::TimerState_Stop;
}
bool UpdateSignalStateAndRecalcNextTimeToWakeupUnsafe(TimerEventType *event, TimeSpan cur_time) {
TimeSpan next_time = GetReference(event->next_time_to_wakeup);
switch (event->timer_state) {
case TimerEventType::TimerState_Stop:
break;
case TimerEventType::TimerState_OneShot:
if (next_time < cur_time) {
event->signaled = true;
StopTimerUnsafe(event);
return true;
}
break;
case TimerEventType::TimerState_Periodic:
if (next_time < cur_time) {
event->signaled = true;
next_time = SaturatedAdd(next_time, GetReference(event->interval));
if (next_time < cur_time) {
const u64 elapsed_from_first = (cur_time - GetReference(event->first)).GetNanoSeconds();
const u64 interval = GetReference(event->interval).GetNanoSeconds();
const u64 t = std::min<u64>(std::numeric_limits<s64>::max(), ((elapsed_from_first / interval) + 1) * interval);
next_time = SaturatedAdd(TimeSpan::FromNanoSeconds(t), GetReference(event->first));
}
GetReference(event->next_time_to_wakeup) = next_time;
return true;
}
break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
return false;
}
}
| 2,779
|
C++
|
.cpp
| 61
| 35.016393
| 135
| 0.604582
|
Atmosphere-NX/Atmosphere
| 14,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,770
|
os_timeout_helper.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_timeout_helper.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "os_timeout_helper.hpp"
namespace ams::os::impl {
TargetTimeSpan TimeoutHelper::GetTimeLeftOnTarget() const {
/* If the absolute tick is zero, we're expired. */
if (m_absolute_end_tick.GetInt64Value() == 0) {
return 0;
}
/* Check if we've expired. */
const Tick cur_tick = impl::GetTickManager().GetTick();
if (cur_tick >= m_absolute_end_tick) {
return 0;
}
/* Return the converted difference as a timespan. */
return TimeoutHelperImpl::ConvertToImplTime(m_absolute_end_tick - cur_tick);
}
}
| 1,273
|
C++
|
.cpp
| 32
| 34.9375
| 84
| 0.688511
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,771
|
os_inter_process_event.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_inter_process_event.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "os_inter_process_event.hpp"
#include "os_inter_process_event_impl.hpp"
#include "os_multiple_wait_object_list.hpp"
namespace ams::os::impl {
namespace {
inline void SetupInterProcessEventType(InterProcessEventType *event, NativeHandle read_handle, bool read_handle_managed, NativeHandle write_handle, bool write_handle_managed, EventClearMode clear_mode) {
/* Set handles. */
event->readable_handle = read_handle;
event->is_readable_handle_managed = read_handle_managed;
event->writable_handle = write_handle;
event->is_writable_handle_managed = write_handle_managed;
/* Set auto clear. */
event->auto_clear = (clear_mode == EventClearMode_AutoClear);
/* Create the waitlist node. */
util::ConstructAt(event->multi_wait_object_list_storage);
/* Set state. */
event->state = InterProcessEventType::State_Initialized;
}
}
Result CreateInterProcessEvent(InterProcessEventType *event, EventClearMode clear_mode) {
NativeHandle rh, wh;
R_TRY(impl::InterProcessEventImpl::Create(std::addressof(wh), std::addressof(rh)));
SetupInterProcessEventType(event, rh, true, wh, true, clear_mode);
R_SUCCEED();
}
void DestroyInterProcessEvent(InterProcessEventType *event) {
AMS_ASSERT(event->state == InterProcessEventType::State_Initialized);
/* Clear the state. */
event->state = InterProcessEventType::State_NotInitialized;
/* Close handles if required. */
if (event->is_readable_handle_managed) {
if (event->readable_handle != os::InvalidNativeHandle) {
impl::InterProcessEventImpl::Close(event->readable_handle);
}
event->is_readable_handle_managed = false;
}
if (event->is_writable_handle_managed) {
if (event->writable_handle != os::InvalidNativeHandle) {
impl::InterProcessEventImpl::Close(event->writable_handle);
}
event->is_writable_handle_managed = false;
}
/* Destroy the waitlist. */
util::DestroyAt(event->multi_wait_object_list_storage);
}
void AttachInterProcessEvent(InterProcessEventType *event, NativeHandle read_handle, bool read_handle_managed, NativeHandle write_handle, bool write_handle_managed, EventClearMode clear_mode) {
AMS_ASSERT(read_handle != os::InvalidNativeHandle || write_handle != os::InvalidNativeHandle);
return SetupInterProcessEventType(event, read_handle, read_handle_managed, write_handle, write_handle_managed, clear_mode);
}
NativeHandle DetachReadableHandleOfInterProcessEvent(InterProcessEventType *event) {
AMS_ASSERT(event->state == InterProcessEventType::State_Initialized);
const NativeHandle handle = event->readable_handle;
event->readable_handle = os::InvalidNativeHandle;
event->is_readable_handle_managed = false;
return handle;
}
NativeHandle DetachWritableHandleOfInterProcessEvent(InterProcessEventType *event) {
AMS_ASSERT(event->state == InterProcessEventType::State_Initialized);
const NativeHandle handle = event->writable_handle;
event->writable_handle = os::InvalidNativeHandle;
event->is_writable_handle_managed = false;
return handle;
}
void WaitInterProcessEvent(InterProcessEventType *event) {
AMS_ASSERT(event->state == InterProcessEventType::State_Initialized);
return impl::InterProcessEventImpl::Wait(event->readable_handle, event->auto_clear);
}
bool TryWaitInterProcessEvent(InterProcessEventType *event) {
AMS_ASSERT(event->state == InterProcessEventType::State_Initialized);
return impl::InterProcessEventImpl::TryWait(event->readable_handle, event->auto_clear);
}
bool TimedWaitInterProcessEvent(InterProcessEventType *event, TimeSpan timeout) {
AMS_ASSERT(event->state == InterProcessEventType::State_Initialized);
AMS_ASSERT(timeout.GetNanoSeconds() >= 0);
return impl::InterProcessEventImpl::TimedWait(event->readable_handle, event->auto_clear, timeout);
}
void SignalInterProcessEvent(InterProcessEventType *event) {
AMS_ASSERT(event->state != InterProcessEventType::State_NotInitialized);
return impl::InterProcessEventImpl::Signal(event->writable_handle);
}
void ClearInterProcessEvent(InterProcessEventType *event) {
AMS_ASSERT(event->state != InterProcessEventType::State_NotInitialized);
auto handle = event->readable_handle;
if (handle == os::InvalidNativeHandle) {
handle = event->writable_handle;
}
return impl::InterProcessEventImpl::Clear(handle);
}
NativeHandle GetReadableHandleOfInterProcessEvent(const InterProcessEventType *event) {
AMS_ASSERT(event->state != InterProcessEventType::State_NotInitialized);
return event->readable_handle;
}
NativeHandle GetWritableHandleOfInterProcessEvent(const InterProcessEventType *event) {
AMS_ASSERT(event->state != InterProcessEventType::State_NotInitialized);
return event->writable_handle;
}
}
| 5,994
|
C++
|
.cpp
| 113
| 45.20354
| 211
| 0.700274
|
Atmosphere-NX/Atmosphere
| 14,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,772
|
os_internal_condition_variable_impl.os.windows.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_internal_condition_variable_impl.os.windows.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include <stratosphere/windows.hpp>
#include "os_internal_critical_section_impl.os.windows.hpp"
#include "os_timeout_helper.hpp"
#include "os_thread_manager.hpp"
namespace ams::os::impl {
struct WindowsConditionVariable {
CONDITION_VARIABLE cv;
};
void InternalConditionVariableImpl::Initialize() {
::InitializeConditionVariable(std::addressof(util::GetReference(m_windows_cv_storage).cv));
}
void InternalConditionVariableImpl::Finalize() {
/* ... */
}
void InternalConditionVariableImpl::Signal() {
::WakeConditionVariable(std::addressof(util::GetReference(m_windows_cv_storage).cv));
}
void InternalConditionVariableImpl::Broadcast() {
::WakeAllConditionVariable(std::addressof(util::GetReference(m_windows_cv_storage).cv));
}
void InternalConditionVariableImpl::Wait(InternalCriticalSection *cs) {
::SleepConditionVariableCS(std::addressof(util::GetReference(m_windows_cv_storage).cv), std::addressof(util::GetReference(cs->Get()->m_windows_critical_section_storage).cs), INFINITE);
}
ConditionVariableStatus InternalConditionVariableImpl::TimedWait(InternalCriticalSection *cs, const TimeoutHelper &timeout_helper) {
const auto ret = ::SleepConditionVariableCS(std::addressof(util::GetReference(m_windows_cv_storage).cv), std::addressof(util::GetReference(cs->Get()->m_windows_critical_section_storage).cs), timeout_helper.GetTimeLeftOnTarget());
if (ret == 0) {
if (::GetLastError() == ERROR_TIMEOUT) {
return ConditionVariableStatus::TimedOut;
}
}
return ConditionVariableStatus::Success;
}
}
| 2,349
|
C++
|
.cpp
| 49
| 42.857143
| 237
| 0.729694
|
Atmosphere-NX/Atmosphere
| 14,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,773
|
os_inter_process_event_impl.os.macos.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_inter_process_event_impl.os.macos.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "os_inter_process_event.hpp"
#include "os_inter_process_event_impl.os.macos.hpp"
#include "os_timeout_helper.hpp"
#include <unistd.h>
#include <fcntl.h>
#include <poll.h>
namespace ams::os::impl {
namespace {
/* On macOS, the maximum size of a pipe buffer is 64_KB. */
static constexpr size_t PipeBufferSizeMax = 64_KB;
constinit char g_shared_pipe_read_buffer[PipeBufferSizeMax];
bool PollEvent(NativeHandle handle, s64 ns) {
struct pollfd pfd;
pfd.fd = handle;
pfd.events = POLLIN;
pfd.revents = 0;
/* Determine timeout. */
constexpr s64 NanoSecondsPerMilliSecond = TimeSpan::FromMilliSeconds(1).GetNanoSeconds();
/* TODO: Will macos ever support ppoll? */
const int timeout = static_cast<int>(ns >= 0 ? (ns / NanoSecondsPerMilliSecond) : -1);
s32 res;
do {
res = ::poll(std::addressof(pfd), 1, timeout);
} while (res < 0 && errno == EINTR);
AMS_ASSERT(res == 0 || res == 1);
const bool signaled = pfd.revents & POLLIN;
AMS_ASSERT(signaled == (res == 1));
return signaled;
}
}
bool InterProcessEventMacosImpl::ResetEventSignal(NativeHandle handle) {
s32 res;
do {
res = ::read(handle, g_shared_pipe_read_buffer, sizeof(g_shared_pipe_read_buffer));
} while (res < 0 && errno == EINTR);
if (res > 0) {
AMS_ASSERT(res <= static_cast<s32>(sizeof(g_shared_pipe_read_buffer)));
} else {
AMS_ASSERT(res < 0);
AMS_ASSERT(errno == EAGAIN);
}
return res > 0;
}
Result InterProcessEventMacosImpl::Create(NativeHandle *out_write, NativeHandle *out_read) {
/* Create the handles. */
os::NativeHandle handles[2];
s32 res;
do {
res = ::pipe(handles);
} while (res < 0 && errno == EINTR);
R_UNLESS(res == 0, os::ResultOutOfResource());
ON_RESULT_FAILURE { Close(handles[0]); Close(handles[1]); };
/* Set as non-blocking. */
do {
res = ::fcntl(handles[0], F_SETFL, O_NONBLOCK);
} while (res < 0 && errno == EINTR);
R_UNLESS(res == 0, os::ResultOutOfResource());
do {
res = ::fcntl(handles[1], F_SETFL, O_NONBLOCK);
} while (res < 0 && errno == EINTR);
R_UNLESS(res == 0, os::ResultOutOfResource());
/* Set the output. */
*out_read = handles[0];
*out_write = handles[1];
R_SUCCEED();
}
void InterProcessEventMacosImpl::Close(NativeHandle handle) {
if (handle != os::InvalidNativeHandle) {
s32 ret;
do {
ret = ::close(handle);
} while (ret < 0 && errno == EINTR);
AMS_ASSERT(ret == 0);
}
}
void InterProcessEventMacosImpl::Signal(NativeHandle handle) {
const u8 data = 0xCC;
s32 ret;
do {
ret = ::write(handle, std::addressof(data), sizeof(data));
} while (ret < 0 && errno == EINTR);
AMS_ASSERT(ret == sizeof(data) || (ret < 0 && errno == EAGAIN));
}
void InterProcessEventMacosImpl::Clear(NativeHandle handle) {
ResetEventSignal(handle);
}
void InterProcessEventMacosImpl::Wait(NativeHandle handle, bool auto_clear) {
while (true) {
/* Continuously wait, until success. */
auto ret = PollEvent(handle, -1);
AMS_ASSERT(ret);
AMS_UNUSED(ret);
/* If we're not obligated to clear, we're done. */
if (!auto_clear) {
return;
}
/* Try to reset. */
if (ResetEventSignal(handle)) {
return;
}
}
}
bool InterProcessEventMacosImpl::TryWait(NativeHandle handle, bool auto_clear) {
/* If we're auto clear, just try to reset. */
if (auto_clear) {
return ResetEventSignal(handle);
}
return PollEvent(handle, 0);
}
bool InterProcessEventMacosImpl::TimedWait(NativeHandle handle, bool auto_clear, TimeSpan timeout) {
TimeoutHelper timeout_helper(timeout);
do {
if (const auto res = PollEvent(handle, timeout_helper.GetTimeLeftOnTarget().GetNanoSeconds()); res) {
/* If we're not obligated to clear, we're done. */
if (!auto_clear) {
return true;
}
/* Try to reset. */
if (ResetEventSignal(handle)) {
return true;
}
}
} while (!timeout_helper.TimedOut());
return false;
}
}
| 5,488
|
C++
|
.cpp
| 142
| 29.316901
| 113
| 0.569923
|
Atmosphere-NX/Atmosphere
| 14,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,774
|
os_rw_lock_target_impl.os.generic.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_rw_lock_target_impl.os.generic.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "os_rw_lock_impl.hpp"
#include "os_thread_manager.hpp"
namespace ams::os::impl {
void ReaderWriterLockHorizonImpl::AcquireReadLock(os::ReaderWriterLockType *rw_lock) {
/* Acquire exclusive access. */
std::scoped_lock lk(util::GetReference(GetLockCount(rw_lock).cs_storage));
/* Get the lock into a state where we can safely increment the read lock count. */
if (rw_lock->owner_thread == impl::GetCurrentThread()) {
/* If we're the owner thread, we should hold the write lock. */
AMS_ASSERT(GetWriteLocked(GetLockCount(rw_lock)) == 1);
} else {
/* Wait until we're not write locked, and there are no write lock waiters. */
while (true) {
/* Check if we're write locked. */
if (GetWriteLocked(GetLockCount(rw_lock)) != 1) {
/* We're not, so check if we have write lock waiters. */
if (GetWriteLockWaiterCount(GetLockCount(rw_lock)) == 0) {
break;
}
}
/* We're write locked, or we have write lock waiters. */
IncReadLockWaiterCount(GetLockCount(rw_lock));
util::GetReference(rw_lock->cv_read_lock._storage).Wait(util::GetPointer(GetLockCount(rw_lock).cs_storage));
DecReadLockWaiterCount(GetLockCount(rw_lock));
}
/* Verify we're in the desired state. */
AMS_ASSERT(GetWriteLockCount(*rw_lock) == 0);
AMS_ASSERT(rw_lock->owner_thread == nullptr);
}
/* Increment the read lock count. */
IncReadLockCount(GetLockCount(rw_lock));
}
bool ReaderWriterLockHorizonImpl::TryAcquireReadLock(os::ReaderWriterLockType *rw_lock) {
/* Acquire exclusive access. */
std::scoped_lock lk(util::GetReference(GetLockCount(rw_lock).cs_storage));
/* Try to get the lock into a state where we can safely increment the read lock count. */
if (rw_lock->owner_thread == impl::GetCurrentThread()) {
/* If we're the owner thread, we should hold the write lock. */
AMS_ASSERT(GetWriteLocked(GetLockCount(rw_lock)) == 1);
} else {
/* We can only read lock if we're not write locked, and there are no write lock waiters. */
if (GetWriteLocked(GetLockCount(rw_lock)) == 1) {
return false;
}
if (GetWriteLockWaiterCount(GetLockCount(rw_lock)) != 0) {
return false;
}
/* Verify we're in the desired state. */
AMS_ASSERT(GetWriteLockCount(*rw_lock) == 0);
AMS_ASSERT(rw_lock->owner_thread == nullptr);
}
/* Increment the read lock count. */
IncReadLockCount(GetLockCount(rw_lock));
return true;
}
void ReaderWriterLockHorizonImpl::ReleaseReadLock(os::ReaderWriterLockType *rw_lock) {
/* Acquire exclusive access. */
std::scoped_lock lk(util::GetReference(GetLockCount(rw_lock).cs_storage));
/* Sanity check that we hold the read lock. */
AMS_ASSERT(GetReadLockCount(GetLockCount(rw_lock)) > 0);
/* Decrement the read lock count. */
DecReadLockCount(GetLockCount(rw_lock));
/* If we're the owner of the write lock, we may need to check if this causes a full release/signal to waiters. */
if (rw_lock->owner_thread == impl::GetCurrentThread()) {
/* Sanity check that we're write locked. */
AMS_ASSERT(GetWriteLocked(GetLockCount(rw_lock)) == 1);
/* If we've called ReleaseWriteLock and have no remaining read locks, we may need to signal/broadcast. */
if (GetWriteLockCount(*rw_lock) == 0 && GetReadLockCount(GetLockCount(rw_lock)) == 0) {
/* Clear lock owner. */
rw_lock->owner_thread = nullptr;
/* Clear write locked. */
ClearWriteLocked(GetLockCount(rw_lock));
/* If we have lock waiters, signal them. */
if (GetWriteLockWaiterCount(GetLockCount(rw_lock)) != 0) {
util::GetReference(rw_lock->cv_write_lock._storage).Signal();
} else if (GetReadLockWaiterCount(GetLockCount(rw_lock)) != 0) {
util::GetReference(rw_lock->cv_read_lock._storage).Broadcast();
}
}
} else {
/* Sanity check that our read lock release was fine. */
AMS_ASSERT(GetWriteLockCount(*rw_lock) == 0);
AMS_ASSERT(GetWriteLocked(GetLockCount(rw_lock)) == 0);
AMS_ASSERT(rw_lock->owner_thread == nullptr);
/* We need to signal if there are no remaining read locks. */
if (GetReadLockCount(GetLockCount(rw_lock)) == 0) {
if (GetWriteLockWaiterCount(GetLockCount(rw_lock)) != 0) {
util::GetReference(rw_lock->cv_write_lock._storage).Signal();
}
}
}
}
void ReaderWriterLockHorizonImpl::AcquireWriteLock(os::ReaderWriterLockType *rw_lock) {
/* Acquire exclusive access. */
std::scoped_lock lk(util::GetReference(GetLockCount(rw_lock).cs_storage));
/* Get the lock into a state where we can safely increment the read lock count. */
if (rw_lock->owner_thread == impl::GetCurrentThread()) {
/* If we're the owner thread, we should hold the write lock. */
AMS_ASSERT(GetWriteLocked(GetLockCount(rw_lock)) == 1);
/* Increment the write lock count. */
IncWriteLockCount(*rw_lock);
} else {
/* Wait until we're not read locked and not write locked. */
while (true) {
/* Check if we're read locked. */
if (GetReadLockCount(GetLockCount(rw_lock)) == 0) {
/* We're not, so check if we're write locked. */
if (GetWriteLocked(GetLockCount(rw_lock)) != 1) {
break;
}
}
/* We're write locked or read locked. */
IncWriteLockWaiterCount(GetLockCount(rw_lock));
util::GetReference(rw_lock->cv_write_lock._storage).Wait(util::GetPointer(GetLockCount(rw_lock).cs_storage));
DecWriteLockWaiterCount(GetLockCount(rw_lock));
}
/* Verify we're in the desired state. */
AMS_ASSERT(GetWriteLockCount(*rw_lock) == 0);
AMS_ASSERT(rw_lock->owner_thread == nullptr);
/* Increment the write lock count. */
IncWriteLockCount(*rw_lock);
/* Set write locked. */
SetWriteLocked(GetLockCount(rw_lock));
/* Set ourselves as the owner. */
rw_lock->owner_thread = impl::GetCurrentThread();
}
}
bool ReaderWriterLockHorizonImpl::TryAcquireWriteLock(os::ReaderWriterLockType *rw_lock) {
/* Acquire exclusive access. */
std::scoped_lock lk(util::GetReference(GetLockCount(rw_lock).cs_storage));
/* Get the lock into a state where we can safely increment the read lock count. */
if (rw_lock->owner_thread == impl::GetCurrentThread()) {
/* If we're the owner thread, we should hold the write lock. */
AMS_ASSERT(GetWriteLocked(GetLockCount(rw_lock)) == 1);
/* Increment the write lock count. */
IncWriteLockCount(*rw_lock);
} else {
/* Check if we're read locked. */
if (GetReadLockCount(GetLockCount(rw_lock)) != 0) {
return false;
}
/* We're not, so check if we're write locked. */
if (GetWriteLocked(GetLockCount(rw_lock)) == 1) {
return false;
}
/* Verify we're in the desired state. */
AMS_ASSERT(GetWriteLockCount(*rw_lock) == 0);
AMS_ASSERT(rw_lock->owner_thread == nullptr);
/* Increment the write lock count. */
IncWriteLockCount(*rw_lock);
/* Set write locked. */
SetWriteLocked(GetLockCount(rw_lock));
/* Set ourselves as the owner. */
rw_lock->owner_thread = impl::GetCurrentThread();
}
return true;
}
void ReaderWriterLockHorizonImpl::ReleaseWriteLock(os::ReaderWriterLockType *rw_lock) {
/* Acquire exclusive access. */
std::scoped_lock lk(util::GetReference(GetLockCount(rw_lock).cs_storage));
/* Sanity check our state. */
AMS_ASSERT(GetWriteLockCount(*rw_lock) > 0);
AMS_ASSERT(GetWriteLocked(GetLockCount(rw_lock)) != 0);
AMS_ASSERT(rw_lock->owner_thread == impl::GetCurrentThread());
/* Decrement the write lock count. */
DecWriteLockCount(*rw_lock);
/* If we have no remaining write locks, we may need to signal/release. */
if (GetWriteLockCount(*rw_lock) == 0 && GetReadLockCount(GetLockCount(rw_lock)) == 0) {
/* Clear lock owner. */
rw_lock->owner_thread = nullptr;
/* Clear write locked. */
ClearWriteLocked(GetLockCount(rw_lock));
/* If we have lock waiters, signal them. */
if (GetWriteLockWaiterCount(GetLockCount(rw_lock)) != 0) {
util::GetReference(rw_lock->cv_write_lock._storage).Signal();
} else if (GetReadLockWaiterCount(GetLockCount(rw_lock)) != 0) {
util::GetReference(rw_lock->cv_read_lock._storage).Broadcast();
}
}
}
}
| 10,294
|
C++
|
.cpp
| 197
| 40.619289
| 125
| 0.593775
|
Atmosphere-NX/Atmosphere
| 14,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,775
|
os_memory_permission_impl.os.linux.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_memory_permission_impl.os.linux.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 <sys/mman.h>
namespace ams::os::impl {
void SetMemoryPermissionImpl(uintptr_t address, size_t size, MemoryPermission perm) {
switch (perm) {
case MemoryPermission_None:
{
auto res = ::mprotect(reinterpret_cast<void *>(address), size, PROT_NONE);
AMS_ABORT_UNLESS(res);
AMS_UNUSED(res);
}
break;
case MemoryPermission_ReadOnly:
{
auto res = ::mprotect(reinterpret_cast<void *>(address), size, PROT_READ);
AMS_ABORT_UNLESS(res);
AMS_UNUSED(res);
}
break;
case MemoryPermission_ReadWrite:
{
auto res = ::mprotect(reinterpret_cast<void *>(address), size, PROT_READ | PROT_WRITE);
AMS_ABORT_UNLESS(res);
AMS_UNUSED(res);
}
break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
}
| 1,734
|
C++
|
.cpp
| 45
| 28.355556
| 107
| 0.581851
|
Atmosphere-NX/Atmosphere
| 14,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,776
|
os_internal_critical_section_impl.os.horizon.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_internal_critical_section_impl.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 "os_timeout_helper.hpp"
#include "os_thread_manager.hpp"
namespace ams::os::impl {
#if defined(ATMOSPHERE_ARCH_ARM64)
void InternalCriticalSectionImpl::Enter() {
AMS_ASSERT(svc::GetThreadLocalRegion()->disable_count == 0);
/* Use the libnx impl. */
static_assert(std::is_same<decltype(m_thread_handle), ::Mutex>::value);
return ::mutexLock(std::addressof(m_thread_handle));
}
bool InternalCriticalSectionImpl::TryEnter() {
AMS_ASSERT(svc::GetThreadLocalRegion()->disable_count == 0);
/* Use the libnx impl. */
static_assert(std::is_same<decltype(m_thread_handle), ::Mutex>::value);
return ::mutexTryLock(std::addressof(m_thread_handle));
}
void InternalCriticalSectionImpl::Leave() {
AMS_ASSERT(svc::GetThreadLocalRegion()->disable_count == 0);
/* Use the libnx impl. */
static_assert(std::is_same<decltype(m_thread_handle), ::Mutex>::value);
return ::mutexUnlock(std::addressof(m_thread_handle));
}
bool InternalCriticalSectionImpl::IsLockedByCurrentThread() const {
/* Use the libnx impl. */
static_assert(std::is_same<decltype(m_thread_handle), ::Mutex>::value);
return ::mutexIsLockedByCurrentThread(std::addressof(m_thread_handle));
}
#else
#error "Architecture not yet supported for os::InternalCriticalSectionImpl"
#endif
}
| 2,180
|
C++
|
.cpp
| 47
| 39.191489
| 83
| 0.668396
|
Atmosphere-NX/Atmosphere
| 14,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,777
|
os_inter_process_event_impl.os.linux.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_inter_process_event_impl.os.linux.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "os_inter_process_event.hpp"
#include "os_inter_process_event_impl.os.linux.hpp"
#include "os_timeout_helper.hpp"
#include <unistd.h>
#include <sys/eventfd.h>
#include <poll.h>
namespace ams::os::impl {
namespace {
bool PollEvent(NativeHandle handle, s64 ns) {
struct pollfd pfd;
pfd.fd = handle;
pfd.events = POLLIN;
pfd.revents = 0;
/* Determine timeout. */
constexpr s64 NanoSecondsPerSecond = TimeSpan::FromSeconds(1).GetNanoSeconds();
struct timespec ts = { .tv_sec = (ns / NanoSecondsPerSecond), .tv_nsec = ns % NanoSecondsPerSecond };
s32 res;
do {
res = ::ppoll(std::addressof(pfd), 1, ns >= 0 ? std::addressof(ts) : nullptr, nullptr);
} while (res < 0 && errno == EINTR);
AMS_ASSERT(res == 0 || res == 1);
const bool signaled = pfd.revents & POLLIN;
AMS_ASSERT(signaled == (res == 1));
return signaled;
}
}
bool InterProcessEventLinuxImpl::ResetEventSignal(NativeHandle handle) {
u64 dummy;
s32 res;
do {
res = ::read(handle, std::addressof(dummy), sizeof(dummy));
} while (res < 0 && errno == EINTR);
AMS_ASSERT(res == sizeof(u64) || (res < 0 && errno == EAGAIN));
if (res == sizeof(u64)) {
AMS_ASSERT(dummy > 0);
}
return res == sizeof(u64);
}
Result InterProcessEventLinuxImpl::CreateSingle(NativeHandle *out_event) {
/* Create the event handle. */
os::NativeHandle event;
do {
event = ::eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
} while (event < 0 && errno == EINTR);
R_UNLESS(event != os::InvalidNativeHandle, os::ResultOutOfResource());
/* Set the output. */
*out_event = event;
R_SUCCEED();
}
Result InterProcessEventLinuxImpl::Create(NativeHandle *out_write, NativeHandle *out_read) {
/* Create the writable handle. */
os::NativeHandle write;
R_TRY(CreateSingle(std::addressof(write)));
ON_RESULT_FAILURE { Close(write); };
/* Create the read handle. */
os::NativeHandle read;
do {
read = ::dup(write);
} while (read < 0 && errno == EINTR);
R_UNLESS(read != os::InvalidNativeHandle, os::ResultOutOfResource());
/* Set the output. */
*out_write = write;
*out_read = read;
R_SUCCEED();
}
void InterProcessEventLinuxImpl::Close(NativeHandle handle) {
if (handle != os::InvalidNativeHandle) {
s32 ret;
do {
ret = ::close(handle);
} while (ret < 0 && errno == EINTR);
AMS_ASSERT(ret == 0);
}
}
void InterProcessEventLinuxImpl::Signal(NativeHandle handle) {
const u64 counter_add = 1;
s32 ret;
do {
ret = ::write(handle, std::addressof(counter_add), sizeof(counter_add));
} while (ret < 0 && errno == EINTR);
AMS_ASSERT(ret == sizeof(counter_add));
}
void InterProcessEventLinuxImpl::Clear(NativeHandle handle) {
ResetEventSignal(handle);
}
void InterProcessEventLinuxImpl::Wait(NativeHandle handle, bool auto_clear) {
while (true) {
/* Continuously wait, until success. */
auto ret = PollEvent(handle, -1);
AMS_ASSERT(ret);
AMS_UNUSED(ret);
/* If we're not obligated to clear, we're done. */
if (!auto_clear) {
return;
}
/* Try to reset. */
if (ResetEventSignal(handle)) {
return;
}
}
}
bool InterProcessEventLinuxImpl::TryWait(NativeHandle handle, bool auto_clear) {
/* If we're auto clear, just try to reset. */
if (auto_clear) {
return ResetEventSignal(handle);
}
return PollEvent(handle, 0);
}
bool InterProcessEventLinuxImpl::TimedWait(NativeHandle handle, bool auto_clear, TimeSpan timeout) {
TimeoutHelper timeout_helper(timeout);
do {
if (const auto res = PollEvent(handle, timeout_helper.GetTimeLeftOnTarget().GetNanoSeconds()); res) {
/* If we're not obligated to clear, we're done. */
if (!auto_clear) {
return true;
}
/* Try to reset. */
if (ResetEventSignal(handle)) {
return true;
}
}
} while (!timeout_helper.TimedOut());
return false;
}
}
| 5,379
|
C++
|
.cpp
| 141
| 29
| 113
| 0.576147
|
Atmosphere-NX/Atmosphere
| 14,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,778
|
os_memory_attribute_impl.os.horizon.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_memory_attribute_impl.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::os::impl {
void SetMemoryAttributeImpl(uintptr_t address, size_t size, MemoryAttribute attr) {
/* Determine svc arguments. */
u32 svc_mask = svc::MemoryAttribute_Uncached;
u32 svc_attr = 0;
switch (attr) {
case os::MemoryAttribute_Normal: svc_attr = 0; break;
case os::MemoryAttribute_Uncached: svc_attr = svc::MemoryAttribute_Uncached; break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
/* Loop, setting attribute. */
auto cur_address = address;
auto remaining = size;
while (remaining > 0) {
/* Query the memory. */
svc::MemoryInfo mem_info;
svc::PageInfo page_info;
R_ABORT_UNLESS(svc::QueryMemory(std::addressof(mem_info), std::addressof(page_info), cur_address));
/* Determine the current size. */
const size_t cur_size = std::min<size_t>(mem_info.base_address + mem_info.size - cur_address, remaining);
/* Set the attribute, if necessary. */
if (mem_info.attribute != svc_attr) {
if (const auto res = svc::SetMemoryAttribute(address, size, svc_mask, svc_attr); R_FAILED(res)) {
/* NOTE: Nintendo logs here. */
R_ABORT_UNLESS(res);
}
}
/* Advance. */
cur_address += cur_size;
remaining -= cur_size;
}
}
}
| 2,160
|
C++
|
.cpp
| 49
| 35.693878
| 117
| 0.610556
|
Atmosphere-NX/Atmosphere
| 14,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,779
|
os_address_space_allocator.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_address_space_allocator.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "os_address_space_allocator.hpp"
#include "os_rng_manager.hpp"
namespace ams::os::impl {
namespace {
constexpr inline u64 MaxProbabilityVariationInverseShift = 4;
}
u64 AddressSpaceAllocatorDefaultGenerateRandom(u64 max) {
/* Check that max is in range. */
AMS_ASSERT(max + 1 <= (UINT64_C(1) << (BITSIZEOF(u64) - MaxProbabilityVariationInverseShift)));
/* Generate random u64. */
const u64 rand = GetRngManager().GenerateRandomU64();
/* Coerce into range. */
AMS_ASSERT(max < std::numeric_limits<u64>::max());
return rand % (max + 1);
}
template<std::unsigned_integral AddressType, std::unsigned_integral SizeType>
AddressSpaceAllocatorBase<AddressType, SizeType>::AddressSpaceAllocatorBase(u64 start_address, u64 end_address, SizeType guard_size, const AddressSpaceAllocatorForbiddenRegion *forbidden_regions, size_t num_forbidden_regions) : m_critical_section(), m_forbidden_region_count(0) {
/* Check pre-conditions. */
AMS_ASSERT(start_address >= guard_size);
AMS_ASSERT(end_address + guard_size >= end_address);
/* Set member variables. */
m_guard_page_count = util::DivideUp(guard_size, MemoryPageSize);
m_start_page = start_address / MemoryPageSize;
m_end_page = (end_address / MemoryPageSize) + m_guard_page_count;
/* Check forbidden region count. */
AMS_ASSERT(num_forbidden_regions <= MaxForbiddenRegions);
/* Set forbidden regions. */
for (size_t i = 0; i < num_forbidden_regions; ++i) {
if (const auto ®ion = forbidden_regions[i]; region.size > 0) {
/* Check region is valid. */
AMS_ASSERT(util::IsAligned(region.address, MemoryPageSize));
AMS_ASSERT(util::IsAligned(region.size, MemoryPageSize));
AMS_ASSERT((region.address / MemoryPageSize) >= m_guard_page_count);
AMS_ASSERT(region.address < region.address + region.size);
/* Set region. */
const auto idx = m_forbidden_region_count++;
m_forbidden_region_start_pages[idx] = (region.address / MemoryPageSize) - m_guard_page_count;
m_forbidden_region_end_pages[idx] = ((region.address + region.size) / MemoryPageSize) + m_guard_page_count;
}
}
}
template<std::unsigned_integral AddressType, std::unsigned_integral SizeType>
bool AddressSpaceAllocatorBase<AddressType, SizeType>::CheckGuardSpace(AddressType address, SizeType size, SizeType guard_size) {
return this->CheckFreeSpace(address - guard_size, guard_size) && this->CheckFreeSpace(address + size, guard_size);
}
template<std::unsigned_integral AddressType, std::unsigned_integral SizeType>
bool AddressSpaceAllocatorBase<AddressType, SizeType>::GetNextNonOverlappedNodeUnsafe(AddressType page, SizeType page_count) {
/* Check pre-conditions. */
AMS_ASSERT(page < page + page_count);
return this->CheckFreeSpace(page * MemoryPageSize, page_count * MemoryPageSize);
}
template<std::unsigned_integral AddressType, std::unsigned_integral SizeType>
AddressType AddressSpaceAllocatorBase<AddressType, SizeType>::AllocateSpace(SizeType size, SizeType align, SizeType align_offset, AddressSpaceGenerateRandomFunction generate_random) {
/* Check pre-conditions. */
AMS_ASSERT(align > 0);
AMS_ASSERT((align_offset & ~(align - 1)) == 0);
AMS_ASSERT(util::IsAligned(align_offset, MemoryPageSize));
AMS_ASSERT(util::IsAligned(align, MemoryPageSize));
/* Determine the page count. */
const SizeType page_count = util::DivideUp(size, MemoryPageSize);
/* Determine alignment page counts. */
const SizeType align_offset_page_count = align_offset / MemoryPageSize;
const SizeType align_page_count = align / MemoryPageSize;
/* Check page counts. */
if (page_count + align_offset_page_count > m_end_page - m_guard_page_count) {
return 0;
}
/* Determine the range to look in. */
const AddressType rand_start = (align_offset_page_count <= m_start_page + m_guard_page_count) ? util::DivideUp(m_start_page + m_guard_page_count - align_offset_page_count, align_page_count) : 0;
const AddressType rand_end = (m_end_page - page_count - align_offset_page_count - m_guard_page_count) / align_page_count;
/* Check that we can find a space. */
if (rand_start > rand_end) {
return 0;
}
/* Try to find a space up to 512 times. */
for (size_t i = 0; i < 512; ++i) {
/* Acquire exclusive access before doing calculations. */
std::scoped_lock lk(m_critical_section);
/* Determine a random page. */
const u64 random = generate_random(rand_end - rand_start);
const AddressType target = ((random + rand_start) * align_page_count) + align_offset_page_count;
AMS_ASSERT(m_start_page <= target - m_guard_page_count && target + page_count + m_guard_page_count <= m_end_page);
/* Check that the page is not forbidden. */
bool forbidden = false;
for (size_t j = 0; j < m_forbidden_region_count; ++j) {
if (m_forbidden_region_start_pages[j] < target + page_count && target < m_forbidden_region_end_pages[j]) {
forbidden = true;
break;
}
}
/* If the page is valid, use it. */
if (!forbidden && this->GetNextNonOverlappedNodeUnsafe(target - m_guard_page_count, page_count + 2 * m_guard_page_count)) {
return target * MemoryPageSize;
}
}
/* We failed to find space. */
return 0;
}
/* Instantiate template. */
/* TODO: instantiate <u64, u64> on 32-bit? */
template class AddressSpaceAllocatorBase<uintptr_t, size_t>;
}
| 6,716
|
C++
|
.cpp
| 118
| 47.957627
| 283
| 0.649109
|
Atmosphere-NX/Atmosphere
| 14,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,780
|
os_tick_manager_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_tick_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 "os_tick_manager.hpp"
namespace ams::os::impl {
TimeSpan TickManager::ConvertToTimeSpan(Tick tick) const {
/* Get the tick value. */
const s64 tick_val = tick.GetInt64Value();
/* Get the tick frequency. */
const s64 tick_freq = GetTickFrequency();
AMS_AUDIT(tick_freq < MaxTickFrequency);
/* Clamp tick to range. */
if (tick_val > GetMaxTick()) {
return TimeSpan::FromNanoSeconds(std::numeric_limits<s64>::max());
} else if (tick_val < -GetMaxTick()) {
return TimeSpan::FromNanoSeconds(std::numeric_limits<s64>::min());
} else {
/* Convert to timespan. */
constexpr s64 NanoSecondsPerSecond = TimeSpan::FromSeconds(1).GetNanoSeconds();
const s64 seconds = tick_val / tick_freq;
const s64 frac = tick_val % tick_freq;
const TimeSpan ts = TimeSpan::FromSeconds(seconds) + TimeSpan::FromNanoSeconds(frac * NanoSecondsPerSecond / tick_freq);
constexpr TimeSpan ZeroTS = TimeSpan::FromNanoSeconds(0);
AMS_ASSERT(!((tick_val > 0 && ts < ZeroTS) || (tick_val < 0 && ts > ZeroTS)));
AMS_UNUSED(ZeroTS);
return ts;
}
}
Tick TickManager::ConvertToTick(TimeSpan ts) const {
/* Get the TimeSpan in nanoseconds. */
const s64 ns = ts.GetNanoSeconds();
/* Clamp ns to range. */
if (ns > GetMaxTimeSpanNs()) {
return Tick(std::numeric_limits<s64>::max());
} else if (ns < -GetMaxTimeSpanNs()) {
return Tick(std::numeric_limits<s64>::min());
} else {
/* Get the tick frequency. */
const s64 tick_freq = GetTickFrequency();
AMS_AUDIT(tick_freq < MaxTickFrequency);
/* Convert to tick. */
constexpr s64 NanoSecondsPerSecond = TimeSpan::FromSeconds(1).GetNanoSeconds();
const bool negative = ns < 0;
s64 seconds = ns / NanoSecondsPerSecond;
s64 frac = ns % NanoSecondsPerSecond;
/* If negative, negate seconds/frac. */
if (negative) {
seconds = -seconds;
frac = -frac;
}
/* Calculate the tick, and invert back to negative if needed. */
s64 tick = (seconds * tick_freq) + ((frac * tick_freq + NanoSecondsPerSecond - 1) / NanoSecondsPerSecond);
if (negative) {
tick = -tick;
}
return Tick(tick);
}
}
}
| 3,227
|
C++
|
.cpp
| 72
| 35.833333
| 132
| 0.60471
|
Atmosphere-NX/Atmosphere
| 14,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,781
|
os_timeout_helper_impl.os.windows.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_timeout_helper_impl.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 "os_timeout_helper_impl.os.windows.hpp"
#include "os_thread_manager.hpp"
namespace ams::os::impl {
void TimeoutHelperImpl::Sleep(TimeSpan tm) {
/* If asked to sleep for no time, do nothing */
if (tm == 0) {
return;
}
/* Get the end tick. */
auto &tick_manager = GetTickManager();
u64 tick_current = tick_manager.GetTick().GetInt64Value();
u64 tick_timeout = tick_manager.ConvertToTick(tm).GetInt64Value();
u64 tick_end = tick_current + tick_timeout + 1;
const auto end = os::Tick(std::min<u64>(std::numeric_limits<s64>::max(), tick_end));
while (true) {
const auto tick = tick_manager.GetTick();
if (tick >= end) {
return;
}
::Sleep(ConvertToImplTime(end - tick));
}
}
}
| 1,525
|
C++
|
.cpp
| 39
| 33.179487
| 92
| 0.651351
|
Atmosphere-NX/Atmosphere
| 14,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,782
|
os_multiple_wait_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_multiple_wait_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 "os_multiple_wait_impl.hpp"
#include "os_multiple_wait_object_list.hpp"
#include "os_tick_manager.hpp"
namespace ams::os::impl {
template<bool AllowReply>
Result MultiWaitImpl::WaitAnyImpl(MultiWaitHolderBase **out, bool infinite, TimeSpan timeout, NativeHandle reply_target) {
/* Prepare for processing. */
m_signaled_holder = nullptr;
m_target_impl.SetCurrentThreadHandleForCancelWait();
/* Add each holder to the object list, and try to find one that's signaled. */
MultiWaitHolderBase *signaled_holder = this->AddToEachObjectListAndCheckObjectState();
/* When we're done, cleanup and set output. */
ON_SCOPE_EXIT {
/* Remove each holder from the current object list. */
this->RemoveFromEachObjectList();
/* Clear cancel wait. */
m_target_impl.ClearCurrentThreadHandleForCancelWait();
/* Set output holder. */
*out = signaled_holder;
};
/* Check if we've been signaled. */
{
std::scoped_lock lk(m_cs_wait);
if (m_signaled_holder != nullptr) {
signaled_holder = m_signaled_holder;
}
}
/* Process object array. */
if (signaled_holder != nullptr) {
/* If we have a signaled holder and we're allowed to reply, try to do so. */
if constexpr (AllowReply) {
/* Try to reply to the reply target. */
if (reply_target != os::InvalidNativeHandle) {
ON_RESULT_FAILURE { signaled_holder = nullptr; };
s32 index;
R_TRY(m_target_impl.TimedReplyAndReceive(std::addressof(index), nullptr, 0, 0, reply_target, TimeSpan::FromNanoSeconds(0)));
}
}
} else {
/* If there's no signaled holder, wait for one to be signaled. */
R_TRY(this->InternalWaitAnyImpl<AllowReply>(std::addressof(signaled_holder), infinite, timeout, reply_target));
}
R_SUCCEED();
}
template<bool AllowReply>
Result MultiWaitImpl::InternalWaitAnyImpl(MultiWaitHolderBase **out, bool infinite, TimeSpan timeout, NativeHandle reply_target) {
/* Build the objects array. */
NativeHandle object_handles[MaximumHandleCount];
MultiWaitHolderBase *objects[MaximumHandleCount];
const s32 count = this->ConstructObjectsArray(object_handles, objects, MaximumHandleCount);
/* Determine the appropriate end time for our wait. */
const TimeSpan end_time = infinite ? TimeSpan::FromNanoSeconds(std::numeric_limits<s64>::max()) : os::impl::GetCurrentTick().ToTimeSpan() + timeout;
/* Loop, waiting until we're done. */
while (true) {
/* Update the current time for our loop. */
m_current_time = os::impl::GetCurrentTick().ToTimeSpan();
/* Determine which object has the minimum wakeup time. */
TimeSpan min_timeout = 0;
MultiWaitHolderBase *min_timeout_object = this->RecalcMultiWaitTimeout(std::addressof(min_timeout), end_time);
/* Perform the wait using native apis. */
s32 index = WaitInvalid;
Result wait_result = ResultSuccess();
if (infinite && min_timeout_object == nullptr) {
/* If we're performing an infinite wait, just do the appropriate wait or reply/receive. */
if constexpr (AllowReply) {
wait_result = m_target_impl.ReplyAndReceive(std::addressof(index), object_handles, MaximumHandleCount, count, reply_target);
} else {
wait_result = m_target_impl.WaitAny(std::addressof(index), object_handles, MaximumHandleCount, count);
}
} else {
/* We need to do our wait with a timeout. */
if constexpr (AllowReply) {
wait_result = m_target_impl.TimedReplyAndReceive(std::addressof(index), object_handles, MaximumHandleCount, count, reply_target, min_timeout);
} else {
if (count != 0 || min_timeout != 0) {
wait_result = m_target_impl.TimedWaitAny(std::addressof(index), object_handles, MaximumHandleCount, count, min_timeout);
} else {
index = WaitTimedOut;
}
}
}
/* Process the result of our wait. */
switch (index) {
case WaitInvalid:
/* If an invalid wait was performed, just return no signaled holder. */
{
*out = nullptr;
R_RETURN(wait_result);
}
break;
case WaitCancelled:
/* If the wait was canceled, it might be because a non-native waitable was signaled. Check and return it, if this is the case. */
{
std::scoped_lock lk(m_cs_wait);
if (m_signaled_holder) {
*out = m_signaled_holder;
R_RETURN(wait_result);
}
}
break;
case WaitTimedOut:
/* If we timed out, this might have been because a timer is now signaled. */
if (min_timeout_object != nullptr) {
/* Update our current time. */
m_current_time = GetCurrentTick().ToTimeSpan();
/* Check if the minimum timeout object is now signaled. */
if (min_timeout_object->IsSignaled() == TriBool::True) {
std::scoped_lock lk(m_cs_wait);
/* Set our signaled holder (and the output) as the newly signaled minimum timeout object. */
m_signaled_holder = min_timeout_object;
*out = min_timeout_object;
R_RETURN(wait_result);
}
} else {
/* If we have no minimum timeout object but we timed out, just return no signaled holder. */
*out = nullptr;
R_RETURN(wait_result);
}
break;
default: /* 0 - 0x3F, valid. */
{
/* Sanity check that the returned index is within the range of our objects array. */
AMS_ASSERT(0 <= index && index < count);
std::scoped_lock lk(m_cs_wait);
/* Set our signaled holder (and the output) as the newly signaled object. */
m_signaled_holder = objects[index];
*out = objects[index];
R_RETURN(wait_result);
}
break;
}
/* We're going to be looping again; prevent ourselves from replying to the same object twice. */
if constexpr (AllowReply) {
reply_target = os::InvalidNativeHandle;
}
}
}
MultiWaitHolderBase *MultiWaitImpl::WaitAnyImpl(bool infinite, TimeSpan timeout) {
MultiWaitHolderBase *holder = nullptr;
const Result wait_result = this->WaitAnyImpl<false>(std::addressof(holder), infinite, timeout, os::InvalidNativeHandle);
R_ASSERT(wait_result);
AMS_UNUSED(wait_result);
return holder;
}
Result MultiWaitImpl::ReplyAndReceive(MultiWaitHolderBase **out, NativeHandle reply_target) {
R_RETURN(this->WaitAnyImpl<true>(out, true, TimeSpan::FromNanoSeconds(std::numeric_limits<s64>::max()), reply_target));
}
s32 MultiWaitImpl::ConstructObjectsArray(NativeHandle out_handles[], MultiWaitHolderBase *out_objects[], s32 num) {
/* Add all objects with a native handle to the output array. */
s32 count = 0;
for (MultiWaitHolderBase &holder_base : m_multi_wait_list) {
os::NativeHandle handle = os::InvalidNativeHandle;
if (holder_base.GetNativeHandle(std::addressof(handle))) {
AMS_ABORT_UNLESS(count < num);
out_handles[count] = handle;
out_objects[count] = std::addressof(holder_base);
++count;
}
}
return count;
}
MultiWaitHolderBase *MultiWaitImpl::AddToEachObjectListAndCheckObjectState() {
/* Add each holder to the current object list, checking for the first signaled object. */
MultiWaitHolderBase *signaled_holder = nullptr;
for (MultiWaitHolderBase &holder_base : m_multi_wait_list) {
if (const TriBool is_signaled = holder_base.AddToObjectList(); signaled_holder == nullptr && is_signaled == TriBool::True) {
signaled_holder = std::addressof(holder_base);
}
}
return signaled_holder;
}
void MultiWaitImpl::RemoveFromEachObjectList() {
/* Remove each holder from the current object list. */
for (MultiWaitHolderBase &holder_base : m_multi_wait_list) {
holder_base.RemoveFromObjectList();
}
}
MultiWaitHolderBase *MultiWaitImpl::RecalcMultiWaitTimeout(TimeSpan *out_min_timeout, TimeSpan end_time) {
/* Find the holder with the minimum end time. */
MultiWaitHolderBase *min_timeout_holder = nullptr;
TimeSpan min_time = end_time;
for (MultiWaitHolderBase &holder_base : m_multi_wait_list) {
if (const TimeSpan cur_time = holder_base.GetAbsoluteTimeToWakeup(); cur_time < min_time) {
min_timeout_holder = std::addressof(holder_base);
min_time = cur_time;
}
}
/* If the minimum time is under the current time, we can't wait; otherwise, get the time to the minimum end time. */
if (min_time < m_current_time) {
*out_min_timeout = 0;
} else {
*out_min_timeout = min_time - m_current_time;
}
return min_timeout_holder;
}
void MultiWaitImpl::NotifyAndWakeupThread(MultiWaitHolderBase *holder_base) {
std::scoped_lock lk(m_cs_wait);
/* If we don't have a signaled holder, set our signaled holder. */
if (m_signaled_holder == nullptr) {
m_signaled_holder = holder_base;
/* Cancel any ongoing waits. */
m_target_impl.CancelWait();
}
}
}
| 11,391
|
C++
|
.cpp
| 221
| 38.153846
| 162
| 0.57478
|
Atmosphere-NX/Atmosphere
| 14,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,783
|
os_multiple_wait_target_impl.os.windows.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_multiple_wait_target_impl.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 "os_multiple_wait_holder_base.hpp"
#include "os_multiple_wait_impl.hpp"
#include "os_timeout_helper.hpp"
namespace ams::os::impl {
Result MultiWaitWindowsImpl::WaitForMultipleObjectsImpl(s32 *out_index, s32 num, NativeHandle arr[], s32 array_size, DWORD wait_ms) {
/* Check that we can add our cancel handle to the wait. */
AMS_ABORT_UNLESS(num + 1 <= array_size);
AMS_UNUSED(array_size);
/* Add our cancel handle. */
arr[num] = m_cancel_event;
/* Wait. */
auto result = ::WaitForMultipleObjects(num + 1, arr, FALSE, wait_ms);
if (result == WAIT_TIMEOUT) {
*out_index = MultiWaitImpl::WaitTimedOut;
} else {
const s32 index = result - WAIT_OBJECT_0;
AMS_ASSERT((0 <= index) && (index <= num));
if (index == num) {
*out_index = MultiWaitImpl::WaitCancelled;
} else {
*out_index = index;
}
}
R_SUCCEED();
}
Result MultiWaitWindowsImpl::TimedWaitAny(s32 *out_index, NativeHandle arr[], s32 array_size, s32 num, TimeSpan ts) {
impl::TimeoutHelper timeout(ts);
do {
s32 idx;
R_TRY(WaitForMultipleObjectsImpl(std::addressof(idx), num, arr, array_size, timeout.GetTimeLeftOnTarget()));
if (idx != MultiWaitImpl::WaitTimedOut) {
*out_index = idx;
R_SUCCEED();
}
} while (!timeout.TimedOut());
*out_index = MultiWaitImpl::WaitTimedOut;
R_SUCCEED();
}
Result MultiWaitWindowsImpl::ReplyAndReceiveImpl(s32 *out_index, s32 num, NativeHandle arr[], s32 array_size, s64 ns, NativeHandle reply_target) {
AMS_UNUSED(out_index, num, arr, array_size, ns, reply_target);
R_ABORT_UNLESS(os::ResultNotImplemented());
}
}
| 2,534
|
C++
|
.cpp
| 59
| 35.576271
| 150
| 0.638945
|
Atmosphere-NX/Atmosphere
| 14,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,784
|
os_rng_manager_impl.os.horizon.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_rng_manager_impl.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 "os_rng_manager_impl.hpp"
namespace ams::os::impl {
void RngManager::Initialize() {
/* Retrieve entropy from kernel. */
u32 seed[4];
static_assert(util::size(seed) == util::TinyMT::NumStateWords);
/* Nintendo does not check the result of these invocations, but we will for safety. */
/* Nintendo uses entropy values 0, 1 to seed the public TinyMT random, and values */
/* 2, 3 to seed os::detail::RngManager's private TinyMT random. */
R_ABORT_UNLESS(svc::GetInfo(reinterpret_cast<u64 *>(seed + 0), svc::InfoType_RandomEntropy, svc::InvalidHandle, 2));
R_ABORT_UNLESS(svc::GetInfo(reinterpret_cast<u64 *>(seed + 2), svc::InfoType_RandomEntropy, svc::InvalidHandle, 3));
m_mt.Initialize(seed, util::size(seed));
/* Note that we've initialized. */
m_initialized = true;
}
}
| 1,546
|
C++
|
.cpp
| 32
| 43.6875
| 124
| 0.698276
|
Atmosphere-NX/Atmosphere
| 14,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,785
|
os_interrupt_event_target_impl.os.horizon.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_interrupt_event_target_impl.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 "os_interrupt_event_target_impl.os.horizon.hpp"
#include "os_timeout_helper.hpp"
namespace ams::os::impl {
InterruptEventHorizonImpl::InterruptEventHorizonImpl(InterruptName name, EventClearMode clear_mode) {
m_manual_clear = (clear_mode == EventClearMode_ManualClear);
auto interrupt_type = m_manual_clear ? svc::InterruptType_Level : svc::InterruptType_Edge;
svc::Handle handle;
R_ABORT_UNLESS(svc::CreateInterruptEvent(std::addressof(handle), static_cast<s32>(name), interrupt_type));
m_handle = handle;
}
InterruptEventHorizonImpl::~InterruptEventHorizonImpl() {
R_ABORT_UNLESS(svc::CloseHandle(m_handle));
}
void InterruptEventHorizonImpl::Clear() {
R_ABORT_UNLESS(svc::ClearEvent(m_handle));
}
void InterruptEventHorizonImpl::Wait() {
while (true) {
/* Continuously wait, until success. */
s32 index;
Result res = svc::WaitSynchronization(std::addressof(index), std::addressof(m_handle), 1, svc::WaitInfinite);
if (R_SUCCEEDED(res)) {
/* Clear, if we must. */
if (!m_manual_clear) {
R_TRY_CATCH(svc::ResetSignal(m_handle)) {
/* Some other thread might have caught this before we did. */
R_CATCH(svc::ResultInvalidState) { continue; }
} R_END_TRY_CATCH_WITH_ABORT_UNLESS;
}
return;
}
AMS_ASSERT(svc::ResultCancelled::Includes(res));
}
}
bool InterruptEventHorizonImpl::TryWait() {
/* If we're auto clear, just try to reset. */
if (!m_manual_clear) {
return R_SUCCEEDED(svc::ResetSignal(m_handle));
}
/* Not auto-clear. */
while (true) {
/* Continuously wait, until success or timeout. */
s32 index;
Result res = svc::WaitSynchronization(std::addressof(index), std::addressof(m_handle), 1, 0);
/* If we succeeded, we're signaled. */
if (R_SUCCEEDED(res)) {
return true;
}
/* If we timed out, we're not signaled. */
if (svc::ResultTimedOut::Includes(res)) {
return false;
}
AMS_ASSERT(svc::ResultCancelled::Includes(res));
}
}
bool InterruptEventHorizonImpl::TimedWait(TimeSpan timeout) {
TimeoutHelper timeout_helper(timeout);
while (true) {
/* Continuously wait, until success. */
s32 index;
Result res = svc::WaitSynchronization(std::addressof(index), std::addressof(m_handle), 1, timeout_helper.GetTimeLeftOnTarget().GetNanoSeconds());
if (R_SUCCEEDED(res)) {
/* Clear, if we must. */
if (!m_manual_clear) {
R_TRY_CATCH(svc::ResetSignal(m_handle)) {
/* Some other thread might have caught this before we did. */
R_CATCH(svc::ResultInvalidState) { continue; }
} R_END_TRY_CATCH_WITH_ABORT_UNLESS;
}
return true;
}
if (svc::ResultTimedOut::Includes(res)) {
return false;
}
AMS_ASSERT(svc::ResultCancelled::Includes(res));
}
}
}
| 4,069
|
C++
|
.cpp
| 94
| 32.946809
| 157
| 0.593932
|
Atmosphere-NX/Atmosphere
| 14,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,786
|
os_inter_process_event_impl.os.windows.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_inter_process_event_impl.os.windows.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include <stratosphere/windows.hpp>
#include "os_inter_process_event.hpp"
#include "os_inter_process_event_impl.os.windows.hpp"
#include "os_giant_lock.hpp"
#include "os_timeout_helper.hpp"
namespace ams::os::impl {
bool InterProcessEventWindowsImpl::ResetEventSignal(NativeHandle handle) {
std::scoped_lock lk(GetGiantLock());
if (auto ret = ::WaitForSingleObject(handle, 0); ret == WAIT_OBJECT_0) {
::ResetEvent(handle);
return true;
} else {
return false;
}
}
Result InterProcessEventWindowsImpl::Create(NativeHandle *out_write, NativeHandle *out_read) {
/* Create the writable handle. */
auto write = ::CreateEvent(nullptr, true, false, nullptr);
AMS_ASSERT(write != os::InvalidNativeHandle);
/* Create the read handle. */
os::NativeHandle read;
const auto cur_proc = ::GetCurrentProcess();
const auto ret = ::DuplicateHandle(cur_proc, write, cur_proc, std::addressof(read), 0, false, DUPLICATE_SAME_ACCESS);
AMS_ASSERT(ret != 0);
AMS_UNUSED(ret);
/* Set the output. */
*out_write = write;
*out_read = read;
R_SUCCEED();
}
void InterProcessEventWindowsImpl::Close(NativeHandle handle) {
if (handle != os::InvalidNativeHandle) {
const auto ret = ::CloseHandle(handle);
AMS_ASSERT(ret != 0);
AMS_UNUSED(ret);
}
}
void InterProcessEventWindowsImpl::Signal(NativeHandle handle) {
const auto ret = ::SetEvent(handle);
AMS_ASSERT(ret != 0);
AMS_UNUSED(ret);
}
void InterProcessEventWindowsImpl::Clear(NativeHandle handle) {
const auto ret = ::ResetEvent(handle);
AMS_ASSERT(ret != 0);
AMS_UNUSED(ret);
}
void InterProcessEventWindowsImpl::Wait(NativeHandle handle, bool auto_clear) {
while (true) {
/* Continuously wait, until success. */
auto ret = ::WaitForSingleObject(handle, INFINITE);
AMS_ASSERT(ret == WAIT_OBJECT_0);
AMS_UNUSED(ret);
/* If we're not obligated to clear, we're done. */
if (!auto_clear) {
return;
}
/* Try to reset. */
if (ResetEventSignal(handle)) {
return;
}
}
}
bool InterProcessEventWindowsImpl::TryWait(NativeHandle handle, bool auto_clear) {
/* If we're auto clear, just try to reset. */
if (auto_clear) {
return ResetEventSignal(handle);
}
const auto ret = ::WaitForSingleObject(handle, 0);
AMS_ASSERT((ret == WAIT_OBJECT_0) || (ret == WAIT_TIMEOUT));
return ret == WAIT_OBJECT_0;
}
bool InterProcessEventWindowsImpl::TimedWait(NativeHandle handle, bool auto_clear, TimeSpan timeout) {
TimeoutHelper timeout_helper(timeout);
do {
if (const auto res = ::WaitForSingleObject(handle, timeout_helper.GetTimeLeftOnTarget()); res == WAIT_OBJECT_0) {
/* If we're not obligated to clear, we're done. */
if (!auto_clear) {
return true;
}
/* Try to reset. */
if (ResetEventSignal(handle)) {
return true;
}
}
} while (!timeout_helper.TimedOut());
return false;
}
}
| 4,122
|
C++
|
.cpp
| 105
| 30.733333
| 125
| 0.610708
|
Atmosphere-NX/Atmosphere
| 14,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,787
|
os_insecure_memory_impl.os.horizon.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_insecure_memory_impl.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 "os_insecure_memory_impl.hpp"
#include "os_aslr_space_manager.hpp"
namespace ams::os::impl {
Result InsecureMemoryImpl::AllocateInsecureMemoryImpl(uintptr_t *out_address, size_t size) {
/* Map at a random address. */
R_RETURN(impl::GetAslrSpaceManager().MapAtRandomAddress(out_address,
[](uintptr_t map_address, size_t map_size) -> Result {
R_TRY_CATCH(svc::MapInsecurePhysicalMemory(map_address, map_size)) {
R_CONVERT(svc::ResultOutOfMemory, os::ResultOutOfMemory())
R_CONVERT(svc::ResultInvalidCurrentMemory, os::ResultInvalidCurrentMemoryState())
} R_END_TRY_CATCH_WITH_ABORT_UNLESS;
R_SUCCEED();
},
[](uintptr_t map_address, size_t map_size) -> void {
return InsecureMemoryImpl::FreeInsecureMemoryImpl(map_address, map_size);
},
size,
0
));
}
void InsecureMemoryImpl::FreeInsecureMemoryImpl(uintptr_t address, size_t size) {
R_ABORT_UNLESS(svc::UnmapInsecurePhysicalMemory(address, size));
}
}
| 1,809
|
C++
|
.cpp
| 40
| 38.15
| 101
| 0.672336
|
Atmosphere-NX/Atmosphere
| 14,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,788
|
os_transfer_memory_impl.os.horizon.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_transfer_memory_impl.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 "os_transfer_memory_impl.hpp"
#include "os_aslr_space_manager.hpp"
namespace ams::os::impl {
namespace {
svc::MemoryPermission ConvertToSvcMemoryPermission(os::MemoryPermission perm) {
switch (perm) {
case os::MemoryPermission_None: return svc::MemoryPermission_None;
case os::MemoryPermission_ReadOnly: return svc::MemoryPermission_Read;
case os::MemoryPermission_WriteOnly: return svc::MemoryPermission_Write;
case os::MemoryPermission_ReadWrite: return svc::MemoryPermission_ReadWrite;
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
}
Result TransferMemoryImpl::Create(NativeHandle *out, void *address, size_t size, MemoryPermission perm) {
/* Convert memory permission. */
const auto svc_perm = ConvertToSvcMemoryPermission(perm);
/* Create the memory. */
svc::Handle handle;
R_TRY_CATCH(svc::CreateTransferMemory(std::addressof(handle), reinterpret_cast<uintptr_t>(address), size, svc_perm)) {
R_CONVERT(svc::ResultOutOfHandles, os::ResultOutOfHandles())
R_CONVERT(svc::ResultOutOfResource, os::ResultOutOfTransferMemory())
} R_END_TRY_CATCH_WITH_ABORT_UNLESS;
*out = handle;
R_SUCCEED();
}
void TransferMemoryImpl::Close(NativeHandle handle) {
R_ABORT_UNLESS(svc::CloseHandle(handle));
}
Result TransferMemoryImpl::Map(void **out, NativeHandle handle, size_t size, MemoryPermission owner_perm) {
/* Convert memory permission. */
const auto svc_owner_perm = ConvertToSvcMemoryPermission(owner_perm);
/* Map at a random address. */
uintptr_t mapped_address;
R_TRY(impl::GetAslrSpaceManager().MapAtRandomAddress(std::addressof(mapped_address),
[handle, svc_owner_perm](uintptr_t map_address, size_t map_size) -> Result {
R_TRY_CATCH(svc::MapTransferMemory(handle, map_address, map_size, svc_owner_perm)) {
R_CONVERT(svc::ResultInvalidHandle, os::ResultInvalidHandle())
R_CONVERT(svc::ResultInvalidSize, os::ResultInvalidTransferMemorySize())
R_CONVERT(svc::ResultInvalidState, os::ResultInvalidTransferMemoryState())
R_CONVERT(svc::ResultInvalidCurrentMemory, os::ResultInvalidCurrentMemoryState())
} R_END_TRY_CATCH_WITH_ABORT_UNLESS;
R_SUCCEED();
},
[handle](uintptr_t map_address, size_t map_size) -> void {
return TransferMemoryImpl::Unmap(handle, reinterpret_cast<void *>(map_address), map_size);
},
size,
0
));
/* Return the address we mapped at. */
*out = reinterpret_cast<void *>(mapped_address);
R_SUCCEED();
}
void TransferMemoryImpl::Unmap(NativeHandle handle, void *address, size_t size) {
R_ABORT_UNLESS(svc::UnmapTransferMemory(handle, reinterpret_cast<uintptr_t>(address), size));
}
}
| 3,761
|
C++
|
.cpp
| 74
| 41.986486
| 126
| 0.659679
|
Atmosphere-NX/Atmosphere
| 14,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,789
|
os_multiple_wait_holder_of_interrupt_event.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_multiple_wait_holder_of_interrupt_event.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "os_multiple_wait_holder_of_interrupt_event.hpp"
#include "os_interrupt_event_impl.hpp"
namespace ams::os::impl {
bool MultiWaitHolderOfInterruptEvent::GetNativeHandle(os::NativeHandle *out) const {
*out = GetReference(m_event->impl).GetHandle();
return true;
}
}
| 963
|
C++
|
.cpp
| 24
| 37.416667
| 88
| 0.748932
|
Atmosphere-NX/Atmosphere
| 14,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,790
|
os_process_code_memory_impl.os.horizon.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_process_code_memory_impl.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 "os_process_code_memory_impl.hpp"
#include "os_aslr_space_manager.hpp"
namespace ams::os::impl {
namespace {
class ProcessAddressSpaceAllocator final : public AddressSpaceAllocatorBase<u64, u64> {
private:
using Base = AddressSpaceAllocatorBase<u64, u64>;
private:
NativeHandle m_handle;
public:
ProcessAddressSpaceAllocator(u64 start_address, u64 end_address, SizeType guard_size, const AddressSpaceAllocatorForbiddenRegion *forbidden_regions, size_t num_forbidden_regions, NativeHandle handle) : Base(start_address, end_address, guard_size, forbidden_regions, num_forbidden_regions), m_handle(handle) {
/* ... */
}
public:
virtual bool CheckFreeSpace(AddressType address, SizeType size) override {
/* Query the memory. */
svc::MemoryInfo memory_info;
svc::PageInfo page_info;
R_ABORT_UNLESS(svc::QueryProcessMemory(std::addressof(memory_info), std::addressof(page_info), m_handle, address));
return memory_info.state == svc::MemoryState_Free && address + size <= memory_info.base_address + memory_info.size;
}
};
using ProcessAslrSpaceManager = AslrSpaceManagerTemplate<ProcessAddressSpaceAllocator, AslrSpaceManagerImpl>;
size_t GetTotalProcessMemoryRegionSize(const ProcessMemoryRegion *regions, size_t num_regions) {
size_t total = 0;
for (size_t i = 0; i < num_regions; ++i) {
total += regions[i].size;
}
return total;
}
}
Result ProcessCodeMemoryImpl::Map(u64 *out, NativeHandle handle, const ProcessMemoryRegion *regions, size_t num_regions, AddressSpaceGenerateRandomFunction generate_random) {
/* Get the total process memory region size. */
const size_t total_size = GetTotalProcessMemoryRegionSize(regions, num_regions);
/* Create an aslr space manager for the process. */
auto process_aslr_space_manager = ProcessAslrSpaceManager(handle);
/* Map at a random address. */
u64 mapped_address;
R_TRY(process_aslr_space_manager.MapAtRandomAddressWithCustomRandomGenerator(std::addressof(mapped_address),
[handle, regions, num_regions](u64 map_address, u64 map_size) -> Result {
AMS_UNUSED(map_size);
/* Map the regions in order. */
u64 mapped_size = 0;
for (size_t i = 0; i < num_regions; ++i) {
/* If we fail, unmap up to where we've mapped. */
ON_RESULT_FAILURE { R_ABORT_UNLESS(ProcessCodeMemoryImpl::Unmap(handle, map_address, regions, i)); };
/* Map the current region. */
R_TRY_CATCH(svc::MapProcessCodeMemory(handle, map_address + mapped_size, regions[i].address, regions[i].size)) {
R_CONVERT(svc::ResultOutOfResource, os::ResultOutOfResource())
R_CATCH(svc::ResultInvalidCurrentMemory) {
/* Check if the process memory is invalid. */
const u64 last_address = regions[i].address + regions[i].size - 1;
u64 cur_address = regions[i].address;
while (cur_address <= last_address) {
svc::MemoryInfo memory_info;
svc::PageInfo page_info;
R_ABORT_UNLESS(svc::QueryProcessMemory(std::addressof(memory_info), std::addressof(page_info), handle, cur_address));
R_UNLESS(memory_info.state == svc::MemoryState_Normal, os::ResultInvalidProcessMemory());
R_UNLESS(memory_info.permission == svc::MemoryPermission_ReadWrite, os::ResultInvalidProcessMemory());
R_UNLESS(memory_info.attribute == static_cast<svc::MemoryAttribute>(0), os::ResultInvalidProcessMemory());
cur_address = memory_info.base_address + memory_info.size;
}
R_THROW(os::ResultInvalidCurrentMemoryState());
}
} R_END_TRY_CATCH_WITH_ABORT_UNLESS;
mapped_size += regions[i].size;
}
R_SUCCEED();
},
[handle, regions, num_regions](u64 map_address, u64 map_size) -> void {
AMS_UNUSED(map_size);
R_ABORT_UNLESS(ProcessCodeMemoryImpl::Unmap(handle, map_address, regions, num_regions));
},
total_size,
regions[0].address, /* NOTE: This seems like a Nintendo bug, if the caller passed no regions. */
generate_random
));
/* Set the output address. */
*out = mapped_address;
R_SUCCEED();
}
Result ProcessCodeMemoryImpl::Unmap(NativeHandle handle, u64 process_code_address, const ProcessMemoryRegion *regions, size_t num_regions) {
/* Get the total process memory region size. */
const size_t total_size = GetTotalProcessMemoryRegionSize(regions, num_regions);
/* Unmap each region in order. */
size_t cur_offset = total_size;
for (size_t i = 0; i < num_regions; ++i) {
/* We want to unmap in reverse order. */
const auto &cur_region = regions[num_regions - 1 - i];
/* Subtract to update the current offset. */
cur_offset -= cur_region.size;
/* Unmap. */
R_TRY_CATCH(svc::UnmapProcessCodeMemory(handle, process_code_address + cur_offset, cur_region.address, cur_region.size)) {
R_CONVERT(svc::ResultOutOfResource, os::ResultOutOfResource())
R_CONVERT(svc::ResultInvalidCurrentMemory, os::ResultInvalidCurrentMemoryState())
} R_END_TRY_CATCH_WITH_ABORT_UNLESS;
}
R_SUCCEED();
}
}
| 6,809
|
C++
|
.cpp
| 116
| 44.87069
| 324
| 0.60012
|
Atmosphere-NX/Atmosphere
| 14,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,791
|
os_interrupt_event_target_impl.os.windows.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_interrupt_event_target_impl.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 "os_interrupt_event_target_impl.os.windows.hpp"
#include "os_timeout_helper.hpp"
#include "os_giant_lock.hpp"
namespace ams::os::impl {
InterruptEventWindowsImpl::InterruptEventWindowsImpl(InterruptName name, EventClearMode clear_mode) {
const NativeHandle handle = ::OpenEvent(EVENT_MODIFY_STATE | SYNCHRONIZE, FALSE, reinterpret_cast<LPCTSTR>(name));
AMS_ASSERT(handle != InvalidNativeHandle);
m_handle = handle;
m_manual_clear = (clear_mode == EventClearMode_ManualClear);
}
InterruptEventWindowsImpl::~InterruptEventWindowsImpl() {
const auto ret = ::CloseHandle(m_handle);
AMS_ASSERT(ret != 0);
AMS_UNUSED(ret);
}
bool InterruptEventWindowsImpl::ResetEventSignal() {
std::scoped_lock lk(GetGiantLock());
if (auto ret = ::WaitForSingleObject(m_handle, 0); ret == WAIT_OBJECT_0) {
::ResetEvent(m_handle);
return true;
} else {
return false;
}
}
void InterruptEventWindowsImpl::Clear() {
const auto ret = ::ResetEvent(m_handle);
AMS_ASSERT(ret != 0);
AMS_UNUSED(ret);
}
void InterruptEventWindowsImpl::Wait() {
while (true) {
/* Continuously wait, until success. */
auto ret = ::WaitForSingleObject(m_handle, INFINITE);
AMS_ASSERT(ret == WAIT_OBJECT_0);
AMS_UNUSED(ret);
/* If we're not obligated to clear, we're done. */
if (m_manual_clear) {
return;
}
/* Try to reset. */
if (this->ResetEventSignal()) {
return;
}
}
}
bool InterruptEventWindowsImpl::TryWait() {
/* If we're auto clear, just try to reset. */
if (!m_manual_clear) {
return this->ResetEventSignal();
}
const auto ret = ::WaitForSingleObject(m_handle, 0);
AMS_ASSERT((ret == WAIT_OBJECT_0) || (ret == WAIT_TIMEOUT));
return ret == WAIT_OBJECT_0;
}
bool InterruptEventWindowsImpl::TimedWait(TimeSpan timeout) {
TimeoutHelper timeout_helper(timeout);
do {
if (const auto res = ::WaitForSingleObject(m_handle, timeout_helper.GetTimeLeftOnTarget()); res == WAIT_OBJECT_0) {
/* If we're not obligated to clear, we're done. */
if (m_manual_clear) {
return true;
}
/* Try to reset. */
if (this->ResetEventSignal()) {
return true;
}
}
} while (!timeout_helper.TimedOut());
return false;
}
}
| 3,370
|
C++
|
.cpp
| 87
| 30.195402
| 127
| 0.605819
|
Atmosphere-NX/Atmosphere
| 14,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,792
|
os_initialize.os.windows.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_initialize.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 "os_resource_manager.hpp"
namespace ams {
void Main();
namespace init {
void InitializeDefaultAllocator();
}
/* TODO: This should probably instead be a custom init::Initialize*()? */
namespace fs {
void InitializeForHostTool();
}
}
namespace ams::os {
void SetHostArgc(int argc);
void SetHostArgv(char **argv);
namespace {
void SetupWindowsConsole(DWORD which) {
/* Get handle to standard device. */
const auto handle = ::GetStdHandle(which);
if (handle == INVALID_HANDLE_VALUE) {
return;
}
/* Get the console mode. */
DWORD mode;
if (!::GetConsoleMode(handle, std::addressof(mode))) {
return;
}
/* Enable printing with ANSI escape codes. */
mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
/* Set console mode. */
::SetConsoleMode(handle, mode);
}
}
void Initialize() {
/* Only allow os::Initialize to be called once. */
AMS_FUNCTION_LOCAL_STATIC_CONSTINIT(bool, s_initialized, false);
if (s_initialized) {
return;
}
s_initialized = true;
/* Initialize the global os resource manager. */
os::impl::ResourceManagerHolder::InitializeResourceManagerInstance();
/* Initialize virtual address memory. */
os::InitializeVirtualAddressMemory();
/* Ensure that the init library's allocator has been setup. */
init::InitializeDefaultAllocator();
/* Try to set up the windows console. */
SetupWindowsConsole(STD_OUTPUT_HANDLE);
SetupWindowsConsole(STD_ERROR_HANDLE);
}
}
extern "C" int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int) {
/* Ensure os library is initialized. */
::ams::os::Initialize();
/* Set argc/argv. */
::ams::os::SetHostArgc(__argc);
::ams::os::SetHostArgv(__argv);
/* Ensure filesystem library is initialized. */
::ams::fs::InitializeForHostTool();
/* Call main. */
::ams::Main();
/* TODO: Should we try to implement a custom exit here? */
return 0;
}
| 2,883
|
C++
|
.cpp
| 79
| 29.594937
| 77
| 0.636888
|
Atmosphere-NX/Atmosphere
| 14,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,793
|
os_multiple_wait_target_impl.os.macos.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_multiple_wait_target_impl.os.macos.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "os_multiple_wait_holder_base.hpp"
#include "os_multiple_wait_impl.hpp"
#include "os_timeout_helper.hpp"
#include "os_inter_process_event_impl.os.macos.hpp"
#include <poll.h>
namespace ams::os::impl {
MultiWaitMacosImpl::MultiWaitMacosImpl() {
R_ABORT_UNLESS(InterProcessEventMacosImpl::Create(std::addressof(m_cancel_write_handle), std::addressof(m_cancel_read_handle)));
}
MultiWaitMacosImpl::~MultiWaitMacosImpl() {
InterProcessEventMacosImpl::Close(m_cancel_write_handle);
InterProcessEventMacosImpl::Close(m_cancel_read_handle);
m_cancel_write_handle = InvalidNativeHandle;
m_cancel_read_handle = InvalidNativeHandle;
}
void MultiWaitMacosImpl::CancelWait() {
InterProcessEventMacosImpl::Signal(m_cancel_write_handle);
}
Result MultiWaitMacosImpl::PollNativeHandlesImpl(s32 *out_index, s32 num, NativeHandle arr[], s32 array_size, s64 ns) {
/* Check that we can add our cancel handle to the wait. */
AMS_ABORT_UNLESS(array_size <= static_cast<s32>(MaximumHandleCount));
AMS_UNUSED(array_size);
/* Create poll fds. */
struct pollfd pfds[MaximumHandleCount + 1];
for (auto i = 0; i < num; ++i) {
pfds[i].fd = arr[i];
pfds[i].events = POLLIN;
pfds[i].revents = 0;
}
pfds[num].fd = m_cancel_read_handle;
pfds[num].events = POLLIN;
pfds[num].revents = 0;
/* Determine timeout. */
constexpr s64 NanoSecondsPerMilliSecond = TimeSpan::FromMilliSeconds(1).GetNanoSeconds();
/* TODO: Will macos ever support ppoll? */
const int timeout = static_cast<int>(ns >= 0 ? (ns / NanoSecondsPerMilliSecond) : -1);
/* Wait. */
while (true) {
const auto ret = ::poll(pfds, num + 1, timeout);
if (ret < 0) {
/* Treat EINTR like a cancellation event; this will lead to a re-poll if nothing is signaled. */
AMS_ABORT_UNLESS(errno == EINTR);
*out_index = MultiWaitImpl::WaitCancelled;
R_SUCCEED();
}
/* Determine what event was polled. */
if (ret == 0) {
*out_index = MultiWaitImpl::WaitTimedOut;
R_SUCCEED();
} else if (pfds[num].revents != 0) {
*out_index = MultiWaitImpl::WaitCancelled;
/* Reset our cancel event. */
InterProcessEventMacosImpl::Clear(m_cancel_read_handle);
R_SUCCEED();
} else {
for (auto i = 0; i < num; ++i) {
if (pfds[i].revents != 0) {
*out_index = i;
R_SUCCEED();
}
}
AMS_ABORT("This should be impossible?");
}
}
}
Result MultiWaitMacosImpl::ReplyAndReceiveImpl(s32 *out_index, s32 num, NativeHandle arr[], s32 array_size, s64 ns, NativeHandle reply_target) {
AMS_UNUSED(out_index, num, arr, array_size, ns, reply_target);
R_ABORT_UNLESS(os::ResultNotImplemented());
}
}
| 3,848
|
C++
|
.cpp
| 86
| 35.593023
| 148
| 0.612076
|
Atmosphere-NX/Atmosphere
| 14,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,794
|
os_internal_critical_section_impl.os.windows.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_internal_critical_section_impl.os.windows.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include <stratosphere/windows.hpp>
#include "os_internal_critical_section_impl.os.windows.hpp"
namespace ams::os::impl {
void InternalCriticalSectionImpl::Initialize() {
::InitializeCriticalSection(std::addressof(util::GetReference(m_windows_critical_section_storage).cs));
}
void InternalCriticalSectionImpl::Finalize() {
::DeleteCriticalSection(std::addressof(util::GetReference(m_windows_critical_section_storage).cs));
}
void InternalCriticalSectionImpl::Enter() {
::EnterCriticalSection(std::addressof(util::GetReference(m_windows_critical_section_storage).cs));
}
bool InternalCriticalSectionImpl::TryEnter() {
return ::TryEnterCriticalSection(std::addressof(util::GetReference(m_windows_critical_section_storage).cs)) != 0;
}
void InternalCriticalSectionImpl::Leave() {
return ::LeaveCriticalSection(std::addressof(util::GetReference(m_windows_critical_section_storage).cs));
}
bool InternalCriticalSectionImpl::IsLockedByCurrentThread() const {
/* Get the cs. */
CRITICAL_SECTION * const cs = std::addressof(util::GetReference(m_windows_critical_section_storage).cs);
/* If the critical section has no owning thread, it's not locked. */
if (cs->OwningThread == nullptr) {
return false;
}
/* If it has an owner, TryLock() will succeed if and only if we own the critical section. */
if (::TryEnterCriticalSection(cs) == 0) {
return false;
}
/* We now hold the critical section. To avoid a race, check that we didn't just acquire it by chance. */
const auto holds_lock = cs->RecursionCount > 1;
/* Leave, since we just successfully entered. */
::LeaveCriticalSection(cs);
return holds_lock;
}
}
| 2,493
|
C++
|
.cpp
| 52
| 42.269231
| 121
| 0.70799
|
Atmosphere-NX/Atmosphere
| 14,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,795
|
os_tls_manager.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/impl/os_tls_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 "os_tls_manager.hpp"
#include "os_thread_manager.hpp"
namespace ams::os::impl {
/* TODO: Should we migrate away from libnx to this on NX at some point? */
#if !defined(ATMOSPHERE_OS_HORIZON)
namespace {
constexpr auto TryCallDestructorCount = 4;
void DefaultTlsDestructor(uintptr_t) {
/* ... */
}
}
void TlsManager::InvokeTlsDestructors() {
/* Get the curent thread. */
auto * const thread = impl::GetCurrentThread();
/* Call all destructors. */
for (int slot = 0; slot < static_cast<int>(TotalTlsSlotCountMax); ++slot) {
if (const auto destructor = m_destructors[slot]; destructor != nullptr) {
destructor(thread->tls_value_array[slot]);
}
thread->tls_value_array[slot] = 0;
}
/* Verify all tls values are wiped, trying up to four times. */
for (auto i = 0; i < TryCallDestructorCount; ++i) {
bool all_cleared = true;
for (auto slot = 0; slot < static_cast<int>(TotalTlsSlotCountMax); ++slot) {
if (thread->tls_value_array[slot] != 0) {
all_cleared = false;
if (const auto destructor = m_destructors[slot]; destructor != nullptr) {
destructor(thread->tls_value_array[slot]);
}
thread->tls_value_array[slot] = 0;
}
}
if (all_cleared) {
break;
}
}
}
bool TlsManager::AllocateTlsSlot(TlsSlot *out, TlsDestructor destructor, bool sdk) {
/* Decide on a slot. */
int slot;
{
/* Lock appropriately. */
std::scoped_lock lk(util::GetReference(impl::GetCurrentThread()->cs_thread));
std::scoped_lock lk2(m_cs);
/* If we're out of tls slots, fail. */
if (!sdk && m_used >= static_cast<int>(TlsSlotCountMax)) {
return false;
}
/* Get a slot. */
slot = SearchUnusedTlsSlotUnsafe(sdk);
/* Set the destructor. */
m_destructors[slot] = (destructor != nullptr) ? destructor : DefaultTlsDestructor;
/* Increment our used count, if the slot was a user slot. */
if (!sdk) {
++m_used;
}
}
/* Zero the slot in all threads. */
GetThreadManager().SetZeroToAllThreadsTlsSafe(slot);
/* Set the output slot's value. */
out->_value = slot;
return true;
}
void TlsManager::FreeTlsSlot(TlsSlot slot) {
/* Get the slot's index. */
const auto slot_idx = slot._value;
/* Lock appropriately. */
std::scoped_lock lk(util::GetReference(impl::GetCurrentThread()->cs_thread));
std::scoped_lock lk2(m_cs);
/* Verify the slot is allocated. */
AMS_ABORT_UNLESS(m_destructors[slot_idx] != nullptr);
/* Free the slot. */
m_destructors[slot_idx] = nullptr;
/* Decrement our used count, if the slot was a user slot. */
if (slot_idx < TlsSlotCountMax) {
--m_used;
}
}
int TlsManager::SearchUnusedTlsSlotUnsafe(bool sdk) {
if (sdk) {
/* Search backwards for an unused slot. */
for (int slot = static_cast<int>(TotalTlsSlotCountMax) - 1; slot >= static_cast<int>(TlsSlotCountMax + SdkInternalTlsCount); --slot) {
if (m_destructors[slot] == nullptr) {
return slot;
}
}
AMS_ABORT("Failed to allocate SdkTlsSlot");
} else {
/* Search forwards for an unused slot. */
for (int slot = 0; slot < static_cast<int>(TlsSlotCountMax); ++slot) {
if (m_destructors[slot] == nullptr) {
return slot;
}
}
AMS_ABORT("Failed to allocate TlsSlot");
}
}
#endif
}
| 4,702
|
C++
|
.cpp
| 116
| 30.5
| 146
| 0.566447
|
Atmosphere-NX/Atmosphere
| 14,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,796
|
lr_location_resolver_manager_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/lr/lr_location_resolver_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 <stratosphere/lr/lr_location_resolver_manager_impl.hpp>
#include "lr_content_location_resolver_impl.hpp"
#include "lr_redirect_only_location_resolver_impl.hpp"
#include "lr_add_on_content_location_resolver_impl.hpp"
#include "lr_registered_location_resolver_impl.hpp"
namespace ams::lr {
namespace {
using ContentLocationResolverFactory = sf::ObjectFactory<sf::StdAllocationPolicy<std::allocator>>;
using RedirectOnlyLocationResolverFactory = sf::ObjectFactory<sf::StdAllocationPolicy<std::allocator>>;
bool IsAcceptableStorageId(ncm::StorageId storage_id) {
if (ncm::IsInstallableStorage(storage_id)) {
return storage_id != ncm::StorageId::Any;
} else {
return storage_id == ncm::StorageId::Host || storage_id == ncm::StorageId::GameCard;
}
}
}
Result LocationResolverManagerImpl::OpenLocationResolver(sf::Out<sf::SharedPointer<ILocationResolver>> out, ncm::StorageId storage_id) {
std::scoped_lock lk(m_mutex);
/* Find an existing resolver. */
auto resolver = m_location_resolvers.Find(storage_id);
/* No existing resolver is present, create one. */
if (!resolver) {
if (storage_id == ncm::StorageId::Host) {
AMS_ABORT_UNLESS(m_location_resolvers.Insert(storage_id, RedirectOnlyLocationResolverFactory::CreateSharedEmplaced<ILocationResolver, RedirectOnlyLocationResolverImpl>()));
} else {
/* Get enabled. */
auto *enabled = m_location_resolvers_enabled.Find(storage_id);
/* Create the resolver. */
auto content_resolver = ContentLocationResolverFactory::CreateSharedEmplaced<ILocationResolver, ContentLocationResolverImpl>(storage_id, enabled != nullptr ? *enabled : m_default_enabled);
R_TRY(content_resolver->Refresh());
AMS_ABORT_UNLESS(m_location_resolvers.Insert(storage_id, std::move(content_resolver)));
}
/* Acquire the newly-created resolver. */
resolver = m_location_resolvers.Find(storage_id);
}
/* Copy the output interface. */
*out = *resolver;
R_SUCCEED();
}
Result LocationResolverManagerImpl::OpenRegisteredLocationResolver(sf::Out<sf::SharedPointer<IRegisteredLocationResolver>> out) {
std::scoped_lock lk(m_mutex);
/* No existing resolver is present, create one. */
if (!m_registered_location_resolver) {
m_registered_location_resolver = ContentLocationResolverFactory::CreateSharedEmplaced<IRegisteredLocationResolver, RegisteredLocationResolverImpl>();
}
/* Copy the output interface. */
*out = m_registered_location_resolver;
R_SUCCEED();
}
Result LocationResolverManagerImpl::RefreshLocationResolver(ncm::StorageId storage_id) {
std::scoped_lock lk(m_mutex);
/* Attempt to find an existing resolver. */
auto resolver = m_location_resolvers.Find(storage_id);
R_UNLESS(resolver, lr::ResultUnknownStorageId());
/* Refresh the resolver. */
if (storage_id != ncm::StorageId::Host) {
(*resolver)->Refresh();
}
R_SUCCEED();
}
Result LocationResolverManagerImpl::OpenAddOnContentLocationResolver(sf::Out<sf::SharedPointer<IAddOnContentLocationResolver>> out) {
std::scoped_lock lk(m_mutex);
/* No existing resolver is present, create one. */
if (!m_add_on_content_location_resolver) {
m_add_on_content_location_resolver = ContentLocationResolverFactory::CreateSharedEmplaced<IAddOnContentLocationResolver, AddOnContentLocationResolverImpl>();
}
/* Copy the output interface. */
*out = m_add_on_content_location_resolver;
R_SUCCEED();
}
Result LocationResolverManagerImpl::SetEnabled(const sf::InMapAliasArray<ncm::StorageId> &storages) {
std::scoped_lock lk(m_mutex);
/* If we're setting enabled, we're no longer enabled by default. */
m_default_enabled = false;
/* Create entries for each storage. */
for (size_t i = 0; i < storages.GetSize(); ++i) {
/* Get the storage id. */
const auto storage_id = storages[i];
/* Check that the storage id is acceptable. */
R_UNLESS(IsAcceptableStorageId(storage_id), lr::ResultUnknownStorageId());
/* Set the storage id as enabled. */
AMS_ABORT_UNLESS(m_location_resolvers_enabled.InsertOrAssign(storage_id, true));
}
/* Disable any open storages which shouldn't be enabled. */
m_location_resolvers.ForEach([&](ncm::StorageId storage_id, sf::SharedPointer<ILocationResolver> &resolver) -> void {
/* Check if the storage id is contained in the input array. */
for (size_t i = 0; i < storages.GetSize(); ++i) {
if (storages[i] == storage_id) {
/* The storage is enabled, so we can return. */
return;
}
}
/* The storage isn't enabled, so disable it. */
R_ABORT_UNLESS(resolver->Disable());
});
R_SUCCEED();
}
}
| 5,960
|
C++
|
.cpp
| 115
| 42.721739
| 204
| 0.655546
|
Atmosphere-NX/Atmosphere
| 14,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,797
|
lr_location_resolver_manager_factory.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/lr/lr_location_resolver_manager_factory.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include <stratosphere/lr/lr_location_resolver_manager_impl.hpp>
#include "lr_remote_location_resolver_manager_impl.hpp"
namespace ams::lr {
namespace {
class StaticAllocatorInitializer {
public:
StaticAllocatorInitializer() {
LocationResolverManagerAllocator::Initialize(lmem::CreateOption_None);
}
} g_static_allocator_initializer;
}
sf::SharedPointer<ILocationResolverManager> GetLocationResolverManagerService() {
#if defined(ATMOSPHERE_OS_HORIZON)
return LocationResolverManagerFactory::CreateSharedEmplaced<ILocationResolverManager, RemoteLocationResolverManagerImpl>();
#else
return LocationResolverManagerFactory::CreateSharedEmplaced<ILocationResolverManager, LocationResolverManagerImpl>();
#endif
}
}
| 1,516
|
C++
|
.cpp
| 35
| 37.885714
| 131
| 0.740515
|
Atmosphere-NX/Atmosphere
| 14,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,798
|
lr_location_redirector.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/lr/lr_location_redirector.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 "lr_location_redirector.hpp"
namespace ams::lr {
class LocationRedirector::Redirection : public util::IntrusiveListBaseNode<Redirection> {
NON_COPYABLE(Redirection);
NON_MOVEABLE(Redirection);
private:
ncm::ProgramId m_program_id;
ncm::ProgramId m_owner_id;
Path m_path;
RedirectionAttributes m_attr;
u32 m_flags;
public:
Redirection(ncm::ProgramId program_id, ncm::ProgramId owner_id, const Path &path, const RedirectionAttributes &attr, u32 flags) :
m_program_id(program_id), m_owner_id(owner_id), m_path(path), m_attr(attr), m_flags(flags) { /* ... */ }
ncm::ProgramId GetProgramId() const {
return m_program_id;
}
ncm::ProgramId GetOwnerProgramId() const {
return m_owner_id;
}
void GetPath(Path *out) const {
*out = m_path;
}
void GetAttributes(RedirectionAttributes *out) const {
*out = m_attr;
}
u32 GetFlags() const {
return m_flags;
}
void SetFlags(u32 flags) {
m_flags = flags;
}
};
bool LocationRedirector::FindRedirection(Path *out, RedirectionAttributes *out_attr, ncm::ProgramId program_id) const {
/* Obtain the path of a matching redirection. */
for (const auto &redirection : m_redirection_list) {
if (redirection.GetProgramId() == program_id) {
redirection.GetPath(out);
redirection.GetAttributes(out_attr);
return true;
}
}
return false;
}
void LocationRedirector::SetRedirection(ncm::ProgramId program_id, const Path &path, const RedirectionAttributes &attr, u32 flags) {
this->SetRedirection(program_id, ncm::InvalidProgramId, path, attr, flags);
}
void LocationRedirector::SetRedirection(ncm::ProgramId program_id, ncm::ProgramId owner_id, const Path &path, const RedirectionAttributes &attr, u32 flags) {
/* Remove any existing redirections for this program id. */
this->EraseRedirection(program_id);
/* Insert a new redirection into the list. */
m_redirection_list.push_back(*(new Redirection(program_id, owner_id, path, attr, flags)));
}
void LocationRedirector::EraseRedirection(ncm::ProgramId program_id) {
/* Remove any redirections with a matching program id. */
for (auto it = m_redirection_list.begin(); it != m_redirection_list.end(); /* ... */) {
if (it->GetProgramId() == program_id) {
auto *redirection = std::addressof(*it);
it = m_redirection_list.erase(it);
delete redirection;
break;
} else {
++it;
}
}
}
void LocationRedirector::ClearRedirections(u32 flags) {
/* Remove any redirections with matching flags. */
for (auto it = m_redirection_list.begin(); it != m_redirection_list.end(); /* ... */) {
if ((it->GetFlags() & flags) == flags) {
auto *redirection = std::addressof(*it);
it = m_redirection_list.erase(it);
delete redirection;
} else {
++it;
}
}
}
void LocationRedirector::ClearRedirectionsExcludingOwners(const ncm::ProgramId *excluding_ids, size_t num_ids) {
for (auto it = m_redirection_list.begin(); it != m_redirection_list.end();) {
/* Skip removal if the redirection has an excluded owner program id. */
if (this->IsExcluded(it->GetOwnerProgramId(), excluding_ids, num_ids)) {
it++;
continue;
}
/* Remove the redirection. */
auto *redirection = std::addressof(*it);
it = m_redirection_list.erase(it);
delete redirection;
}
}
}
| 4,728
|
C++
|
.cpp
| 108
| 33.638889
| 161
| 0.597436
|
Atmosphere-NX/Atmosphere
| 14,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,799
|
lr_redirect_only_location_resolver_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/lr/lr_redirect_only_location_resolver_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 "lr_redirect_only_location_resolver_impl.hpp"
namespace ams::lr {
RedirectOnlyLocationResolverImpl::~RedirectOnlyLocationResolverImpl() {
/* Ensure entries are deallocated */
this->ClearRedirections();
}
Result RedirectOnlyLocationResolverImpl::ResolveProgramPath(sf::Out<Path> out, ncm::ProgramId id) {
RedirectionAttributes attr;
R_UNLESS(m_program_redirector.FindRedirection(out.GetPointer(), std::addressof(attr), id), lr::ResultProgramNotFound());
R_SUCCEED();
}
Result RedirectOnlyLocationResolverImpl::RedirectProgramPath(const Path &path, ncm::ProgramId id) {
m_program_redirector.SetRedirection(id, path, DefaultRedirectionAttributes);
R_SUCCEED();
}
Result RedirectOnlyLocationResolverImpl::ResolveApplicationControlPath(sf::Out<Path> out, ncm::ProgramId id) {
RedirectionAttributes attr;
R_UNLESS(m_app_control_redirector.FindRedirection(out.GetPointer(), std::addressof(attr), id), lr::ResultControlNotFound());
R_SUCCEED();
}
Result RedirectOnlyLocationResolverImpl::ResolveApplicationHtmlDocumentPath(sf::Out<Path> out, ncm::ProgramId id) {
RedirectionAttributes attr;
R_UNLESS(m_html_docs_redirector.FindRedirection(out.GetPointer(), std::addressof(attr), id), lr::ResultHtmlDocumentNotFound());
R_SUCCEED();
}
Result RedirectOnlyLocationResolverImpl::ResolveDataPath(sf::Out<Path> out, ncm::DataId id) {
AMS_UNUSED(out, id);
R_THROW(lr::ResultDataNotFound());
}
Result RedirectOnlyLocationResolverImpl::RedirectApplicationControlPathDeprecated(const Path &path, ncm::ProgramId id) {
m_app_control_redirector.SetRedirection(id, path, DefaultRedirectionAttributes, RedirectionFlags_Application);
R_SUCCEED();
}
Result RedirectOnlyLocationResolverImpl::RedirectApplicationControlPath(const Path &path, ncm::ProgramId id, ncm::ProgramId owner_id) {
m_app_control_redirector.SetRedirection(id, owner_id, path, DefaultRedirectionAttributes, RedirectionFlags_Application);
R_SUCCEED();
}
Result RedirectOnlyLocationResolverImpl::RedirectApplicationHtmlDocumentPathDeprecated(const Path &path, ncm::ProgramId id) {
m_html_docs_redirector.SetRedirection(id, path, DefaultRedirectionAttributes, RedirectionFlags_Application);
R_SUCCEED();
}
Result RedirectOnlyLocationResolverImpl::RedirectApplicationHtmlDocumentPath(const Path &path, ncm::ProgramId id, ncm::ProgramId owner_id) {
m_html_docs_redirector.SetRedirection(id, owner_id, path, DefaultRedirectionAttributes, RedirectionFlags_Application);
R_SUCCEED();
}
Result RedirectOnlyLocationResolverImpl::ResolveApplicationLegalInformationPath(sf::Out<Path> out, ncm::ProgramId id) {
RedirectionAttributes attr;
R_UNLESS(m_legal_info_redirector.FindRedirection(out.GetPointer(), std::addressof(attr), id), lr::ResultLegalInformationNotFound());
R_SUCCEED();
}
Result RedirectOnlyLocationResolverImpl::RedirectApplicationLegalInformationPathDeprecated(const Path &path, ncm::ProgramId id) {
m_legal_info_redirector.SetRedirection(id, path, DefaultRedirectionAttributes, RedirectionFlags_Application);
R_SUCCEED();
}
Result RedirectOnlyLocationResolverImpl::RedirectApplicationLegalInformationPath(const Path &path, ncm::ProgramId id, ncm::ProgramId owner_id) {
m_legal_info_redirector.SetRedirection(id, owner_id, path, DefaultRedirectionAttributes, RedirectionFlags_Application);
R_SUCCEED();
}
Result RedirectOnlyLocationResolverImpl::Refresh() {
this->ClearRedirections();
R_SUCCEED();
}
Result RedirectOnlyLocationResolverImpl::RedirectApplicationProgramPathDeprecated(const Path &path, ncm::ProgramId id) {
m_program_redirector.SetRedirection(id, path, DefaultRedirectionAttributes, RedirectionFlags_Application);
R_SUCCEED();
}
Result RedirectOnlyLocationResolverImpl::RedirectApplicationProgramPath(const Path &path, ncm::ProgramId id, ncm::ProgramId owner_id) {
m_program_redirector.SetRedirection(id, owner_id, path, DefaultRedirectionAttributes, RedirectionFlags_Application);
R_SUCCEED();
}
Result RedirectOnlyLocationResolverImpl::ClearApplicationRedirectionDeprecated() {
this->ClearRedirections(RedirectionFlags_Application);
R_SUCCEED();
}
Result RedirectOnlyLocationResolverImpl::ClearApplicationRedirection(const sf::InArray<ncm::ProgramId> &excluding_ids) {
this->ClearRedirections(excluding_ids.GetPointer(), excluding_ids.GetSize());
R_SUCCEED();
}
Result RedirectOnlyLocationResolverImpl::EraseProgramRedirection(ncm::ProgramId id) {
m_program_redirector.EraseRedirection(id);
R_SUCCEED();
}
Result RedirectOnlyLocationResolverImpl::EraseApplicationControlRedirection(ncm::ProgramId id) {
m_app_control_redirector.EraseRedirection(id);
R_SUCCEED();
}
Result RedirectOnlyLocationResolverImpl::EraseApplicationHtmlDocumentRedirection(ncm::ProgramId id) {
m_html_docs_redirector.EraseRedirection(id);
R_SUCCEED();
}
Result RedirectOnlyLocationResolverImpl::EraseApplicationLegalInformationRedirection(ncm::ProgramId id) {
m_legal_info_redirector.EraseRedirection(id);
R_SUCCEED();
}
Result RedirectOnlyLocationResolverImpl::ResolveProgramPathForDebug(sf::Out<Path> out, ncm::ProgramId id) {
/* If a debug program redirection is present, use it. */
RedirectionAttributes attr;
R_SUCCEED_IF(m_debug_program_redirector.FindRedirection(out.GetPointer(), std::addressof(attr), id));
/* Otherwise, try to find a normal program redirection. */
R_UNLESS(m_program_redirector.FindRedirection(out.GetPointer(), std::addressof(attr), id), lr::ResultDebugProgramNotFound());
R_SUCCEED();
}
Result RedirectOnlyLocationResolverImpl::RedirectProgramPathForDebug(const Path &path, ncm::ProgramId id) {
m_debug_program_redirector.SetRedirection(id, path, DefaultRedirectionAttributes);
R_SUCCEED();
}
Result RedirectOnlyLocationResolverImpl::RedirectApplicationProgramPathForDebugDeprecated(const Path &path, ncm::ProgramId id) {
m_debug_program_redirector.SetRedirection(id, path, DefaultRedirectionAttributes, RedirectionFlags_Application);
R_SUCCEED();
}
Result RedirectOnlyLocationResolverImpl::RedirectApplicationProgramPathForDebug(const Path &path, ncm::ProgramId id, ncm::ProgramId owner_id) {
m_debug_program_redirector.SetRedirection(id, owner_id, path, DefaultRedirectionAttributes, RedirectionFlags_Application);
R_SUCCEED();
}
Result RedirectOnlyLocationResolverImpl::EraseProgramRedirectionForDebug(ncm::ProgramId id) {
m_debug_program_redirector.EraseRedirection(id);
R_SUCCEED();
}
Result RedirectOnlyLocationResolverImpl::Disable() {
R_SUCCEED();
}
}
| 7,758
|
C++
|
.cpp
| 138
| 49.608696
| 148
| 0.75
|
Atmosphere-NX/Atmosphere
| 14,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,800
|
lr_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/lr/lr_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 "lr_location_resolver_manager_factory.hpp"
namespace ams::lr {
namespace {
constinit sf::SharedPointer<ILocationResolverManager> g_location_resolver_manager;
}
void Initialize() {
AMS_ASSERT(g_location_resolver_manager == nullptr);
g_location_resolver_manager = GetLocationResolverManagerService();
}
void Finalize() {
AMS_ASSERT(g_location_resolver_manager != nullptr);
g_location_resolver_manager = nullptr;
}
Result OpenLocationResolver(LocationResolver *out, ncm::StorageId storage_id) {
sf::SharedPointer<lr::ILocationResolver> lr;
R_TRY(g_location_resolver_manager->OpenLocationResolver(std::addressof(lr), storage_id));
*out = LocationResolver(std::move(lr));
R_SUCCEED();
}
Result OpenRegisteredLocationResolver(RegisteredLocationResolver *out) {
sf::SharedPointer<lr::IRegisteredLocationResolver> lr;
R_TRY(g_location_resolver_manager->OpenRegisteredLocationResolver(std::addressof(lr)));
*out = RegisteredLocationResolver(std::move(lr));
R_SUCCEED();
}
Result OpenAddOnContentLocationResolver(AddOnContentLocationResolver *out) {
sf::SharedPointer<lr::IAddOnContentLocationResolver> lr;
R_TRY(g_location_resolver_manager->OpenAddOnContentLocationResolver(std::addressof(lr)));
*out = AddOnContentLocationResolver(std::move(lr));
R_SUCCEED();
}
Result RefreshLocationResolver(ncm::StorageId storage_id) {
R_RETURN(g_location_resolver_manager->RefreshLocationResolver(storage_id));
}
}
| 2,280
|
C++
|
.cpp
| 51
| 39.235294
| 97
| 0.727765
|
Atmosphere-NX/Atmosphere
| 14,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,801
|
lr_registered_location_resolver_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/lr/lr_registered_location_resolver_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 "lr_registered_location_resolver_impl.hpp"
namespace ams::lr {
namespace {
template<size_t N>
bool ResolvePath(Path *out, const LocationRedirector &redirector, const RegisteredLocations<ncm::ProgramId, N> &locations, ncm::ProgramId id) {
/* Attempt to use a redirection if present. */
RedirectionAttributes attr;
if (!redirector.FindRedirection(out, std::addressof(attr), id)) {
/* Otherwise try and use a registered location. */
RedirectionPath redir_path;
if (!locations.Find(std::addressof(redir_path), id)) {
return false;
}
/* Set the output path. */
*out = redir_path.path;
}
return true;
}
template<size_t N>
void RegisterPath(RegisteredLocations<ncm::ProgramId, N> &locations, ncm::ProgramId id, const Path& path, ncm::ProgramId owner_id) {
/* Create a redirection path. */
const RedirectionPath redir_path = { path, DefaultRedirectionAttributes };
/* If we register successfully, we're good. */
if (locations.Register(id, redir_path, owner_id)) {
return;
}
/* Otherwise, clear and register (this should always succeed). */
locations.Clear();
locations.Register(id, redir_path, owner_id);
}
}
RegisteredLocationResolverImpl::~RegisteredLocationResolverImpl() {
/* Ensure entries are deallocated */
this->ClearRedirections();
}
/* Helper function. */
void RegisteredLocationResolverImpl::ClearRedirections(u32 flags) {
m_html_docs_redirector.ClearRedirections(flags);
m_program_redirector.ClearRedirections(flags);
}
Result RegisteredLocationResolverImpl::RefreshImpl(const ncm::ProgramId *excluding_ids, size_t num_ids) {
/* On < 9.0.0, exclusion lists were not supported yet, so simply clear and return. */
if (hos::GetVersion() < hos::Version_9_0_0) {
this->ClearRedirections();
R_SUCCEED();
}
if (num_ids) {
/* If we have exclusion lists, explicitly clear our locations. */
m_registered_program_locations.ClearExcluding(excluding_ids, num_ids);
m_registered_html_docs_locations.ClearExcluding(excluding_ids, num_ids);
} else {
/* If we don't, just perform a general clear (as pre 9.0.0 did). */
this->ClearRedirections();
}
/* Clear redirectors using exclusion lists. */
m_program_redirector.ClearRedirectionsExcludingOwners(excluding_ids, num_ids);
m_html_docs_redirector.ClearRedirectionsExcludingOwners(excluding_ids, num_ids);
R_SUCCEED();
}
Result RegisteredLocationResolverImpl::ResolveProgramPath(sf::Out<Path> out, ncm::ProgramId id) {
R_UNLESS(ResolvePath(out.GetPointer(), m_program_redirector, m_registered_program_locations, id), lr::ResultProgramNotFound());
R_SUCCEED();
}
Result RegisteredLocationResolverImpl::RegisterProgramPathDeprecated(const Path &path, ncm::ProgramId id) {
RegisterPath(m_registered_program_locations, id, path, ncm::InvalidProgramId);
R_SUCCEED();
}
Result RegisteredLocationResolverImpl::RegisterProgramPath(const Path &path, ncm::ProgramId id, ncm::ProgramId owner_id) {
RegisterPath(m_registered_program_locations, id, path, owner_id);
R_SUCCEED();
}
Result RegisteredLocationResolverImpl::UnregisterProgramPath(ncm::ProgramId id) {
m_registered_program_locations.Unregister(id);
R_SUCCEED();
}
Result RegisteredLocationResolverImpl::RedirectProgramPathDeprecated(const Path &path, ncm::ProgramId id) {
m_program_redirector.SetRedirection(id, path, DefaultRedirectionAttributes);
R_SUCCEED();
}
Result RegisteredLocationResolverImpl::RedirectProgramPath(const Path &path, ncm::ProgramId id, ncm::ProgramId owner_id) {
m_program_redirector.SetRedirection(id, owner_id, path, DefaultRedirectionAttributes);
R_SUCCEED();
}
Result RegisteredLocationResolverImpl::ResolveHtmlDocumentPath(sf::Out<Path> out, ncm::ProgramId id) {
R_UNLESS(ResolvePath(out.GetPointer(), m_html_docs_redirector, m_registered_html_docs_locations, id), lr::ResultHtmlDocumentNotFound());
R_SUCCEED();
}
Result RegisteredLocationResolverImpl::RegisterHtmlDocumentPathDeprecated(const Path &path, ncm::ProgramId id) {
RegisterPath(m_registered_html_docs_locations, id, path, ncm::InvalidProgramId);
R_SUCCEED();
}
Result RegisteredLocationResolverImpl::RegisterHtmlDocumentPath(const Path &path, ncm::ProgramId id, ncm::ProgramId owner_id) {
RegisterPath(m_registered_html_docs_locations, id, path, owner_id);
R_SUCCEED();
}
Result RegisteredLocationResolverImpl::UnregisterHtmlDocumentPath(ncm::ProgramId id) {
m_registered_html_docs_locations.Unregister(id);
R_SUCCEED();
}
Result RegisteredLocationResolverImpl::RedirectHtmlDocumentPathDeprecated(const Path &path, ncm::ProgramId id) {
m_html_docs_redirector.SetRedirection(id, path, DefaultRedirectionAttributes);
R_SUCCEED();
}
Result RegisteredLocationResolverImpl::RedirectHtmlDocumentPath(const Path &path, ncm::ProgramId id, ncm::ProgramId owner_id) {
m_html_docs_redirector.SetRedirection(id, owner_id, path, DefaultRedirectionAttributes);
R_SUCCEED();
}
Result RegisteredLocationResolverImpl::Refresh() {
R_RETURN(this->RefreshImpl(nullptr, 0));
}
Result RegisteredLocationResolverImpl::RefreshExcluding(const sf::InArray<ncm::ProgramId> &ids) {
R_RETURN(this->RefreshImpl(ids.GetPointer(), ids.GetSize()));
}
}
| 6,584
|
C++
|
.cpp
| 130
| 42.492308
| 151
| 0.685652
|
Atmosphere-NX/Atmosphere
| 14,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,802
|
lr_content_location_resolver_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/lr/lr_content_location_resolver_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 "lr_content_location_resolver_impl.hpp"
namespace ams::lr {
ContentLocationResolverImpl::~ContentLocationResolverImpl() {
this->ClearRedirections();
}
/* Helper function. */
void ContentLocationResolverImpl::GetContentStoragePath(Path *out, ncm::ContentId content_id) {
static_assert(sizeof(lr::Path) == sizeof(ncm::Path));
m_content_storage.GetPath(reinterpret_cast<ncm::Path *>(out), content_id);
}
Result ContentLocationResolverImpl::ResolveProgramPath(Path *out, RedirectionAttributes *out_attr, ncm::ProgramId id) {
/* Use a redirection if present. */
R_SUCCEED_IF(m_program_redirector.FindRedirection(out, out_attr, id));
/* If we're not enabled, we can't resolve a program. */
R_UNLESS(m_enabled, lr::ResultProgramNotFound())
/* Find the latest program content for the program id. */
ncm::ContentInfo program_content_info;
R_TRY_CATCH(m_content_meta_database.GetLatestProgram(std::addressof(program_content_info), id)) {
R_CONVERT(ncm::ResultContentMetaNotFound, lr::ResultProgramNotFound())
} R_END_TRY_CATCH;
/* Obtain the content path and attributes. */
this->GetContentStoragePath(out, program_content_info.GetId());
*out_attr = RedirectionAttributes::Make(program_content_info.GetContentAttributes());
R_SUCCEED();
}
Result ContentLocationResolverImpl::ResolveProgramPath(sf::Out<Path> out, ncm::ProgramId id) {
RedirectionAttributes attr;
R_RETURN(this->ResolveProgramPath(out.GetPointer(), std::addressof(attr), id));
}
Result ContentLocationResolverImpl::RedirectProgramPath(const Path &path, ncm::ProgramId id) {
m_program_redirector.SetRedirection(id, path, DefaultRedirectionAttributes);
R_SUCCEED();
}
Result ContentLocationResolverImpl::ResolveApplicationControlPath(sf::Out<Path> out, ncm::ProgramId id) {
RedirectionAttributes attr;
R_UNLESS(m_app_control_redirector.FindRedirection(out.GetPointer(), std::addressof(attr), id), lr::ResultControlNotFound());
R_SUCCEED();
}
Result ContentLocationResolverImpl::ResolveApplicationHtmlDocumentPath(sf::Out<Path> out, ncm::ProgramId id) {
RedirectionAttributes attr;
R_UNLESS(m_html_docs_redirector.FindRedirection(out.GetPointer(), std::addressof(attr), id), lr::ResultHtmlDocumentNotFound());
R_SUCCEED();
}
Result ContentLocationResolverImpl::ResolveDataPath(sf::Out<Path> out, ncm::DataId id) {
/* If we're not enabled, we can't resolve data. */
R_UNLESS(m_enabled, lr::ResultDataNotFound())
/* Find the latest data content info for the program id. */
ncm::ContentInfo data_content_info;
R_TRY(m_content_meta_database.GetLatestData(std::addressof(data_content_info), id));
/* Obtain the content path. */
this->GetContentStoragePath(out.GetPointer(), data_content_info.GetId());
R_SUCCEED();
}
Result ContentLocationResolverImpl::RedirectApplicationControlPathDeprecated(const Path &path, ncm::ProgramId id) {
m_app_control_redirector.SetRedirection(id, path, DefaultRedirectionAttributes, RedirectionFlags_Application);
R_SUCCEED();
}
Result ContentLocationResolverImpl::RedirectApplicationControlPath(const Path &path, ncm::ProgramId id, ncm::ProgramId owner_id) {
m_app_control_redirector.SetRedirection(id, owner_id, path, DefaultRedirectionAttributes, RedirectionFlags_Application);
R_SUCCEED();
}
Result ContentLocationResolverImpl::RedirectApplicationHtmlDocumentPathDeprecated(const Path &path, ncm::ProgramId id) {
m_html_docs_redirector.SetRedirection(id, path, DefaultRedirectionAttributes, RedirectionFlags_Application);
R_SUCCEED();
}
Result ContentLocationResolverImpl::RedirectApplicationHtmlDocumentPath(const Path &path, ncm::ProgramId id, ncm::ProgramId owner_id) {
m_html_docs_redirector.SetRedirection(id, owner_id, path, DefaultRedirectionAttributes, RedirectionFlags_Application);
R_SUCCEED();
}
Result ContentLocationResolverImpl::ResolveApplicationLegalInformationPath(sf::Out<Path> out, ncm::ProgramId id) {
RedirectionAttributes attr;
R_UNLESS(m_legal_info_redirector.FindRedirection(out.GetPointer(), std::addressof(attr), id), lr::ResultLegalInformationNotFound());
R_SUCCEED();
}
Result ContentLocationResolverImpl::RedirectApplicationLegalInformationPathDeprecated(const Path &path, ncm::ProgramId id) {
m_legal_info_redirector.SetRedirection(id, path, DefaultRedirectionAttributes, RedirectionFlags_Application);
R_SUCCEED();
}
Result ContentLocationResolverImpl::RedirectApplicationLegalInformationPath(const Path &path, ncm::ProgramId id, ncm::ProgramId owner_id) {
m_legal_info_redirector.SetRedirection(id, owner_id, path, DefaultRedirectionAttributes, RedirectionFlags_Application);
R_SUCCEED();
}
Result ContentLocationResolverImpl::Refresh() {
/* Obtain content meta database and content storage objects for this resolver's storage. */
ncm::ContentMetaDatabase meta_db;
ncm::ContentStorage storage;
R_TRY(ncm::OpenContentMetaDatabase(std::addressof(meta_db), m_storage_id));
R_TRY(ncm::OpenContentStorage(std::addressof(storage), m_storage_id));
/* Store the acquired objects. */
m_content_meta_database = std::move(meta_db);
m_content_storage = std::move(storage);
/* Remove any existing redirections. */
this->ClearRedirections();
R_SUCCEED();
}
Result ContentLocationResolverImpl::RedirectApplicationProgramPathDeprecated(const Path &path, ncm::ProgramId id) {
m_program_redirector.SetRedirection(id, path, DefaultRedirectionAttributes, RedirectionFlags_Application);
R_SUCCEED();
}
Result ContentLocationResolverImpl::RedirectApplicationProgramPath(const Path &path, ncm::ProgramId id, ncm::ProgramId owner_id) {
m_program_redirector.SetRedirection(id, owner_id, path, DefaultRedirectionAttributes, RedirectionFlags_Application);
R_SUCCEED();
}
Result ContentLocationResolverImpl::ClearApplicationRedirectionDeprecated() {
this->ClearRedirections(RedirectionFlags_Application);
R_SUCCEED();
}
Result ContentLocationResolverImpl::ClearApplicationRedirection(const sf::InArray<ncm::ProgramId> &excluding_ids) {
this->ClearRedirections(excluding_ids.GetPointer(), excluding_ids.GetSize());
R_SUCCEED();
}
Result ContentLocationResolverImpl::EraseProgramRedirection(ncm::ProgramId id) {
m_program_redirector.EraseRedirection(id);
R_SUCCEED();
}
Result ContentLocationResolverImpl::EraseApplicationControlRedirection(ncm::ProgramId id) {
m_app_control_redirector.EraseRedirection(id);
R_SUCCEED();
}
Result ContentLocationResolverImpl::EraseApplicationHtmlDocumentRedirection(ncm::ProgramId id) {
m_html_docs_redirector.EraseRedirection(id);
R_SUCCEED();
}
Result ContentLocationResolverImpl::EraseApplicationLegalInformationRedirection(ncm::ProgramId id) {
m_legal_info_redirector.EraseRedirection(id);
R_SUCCEED();
}
Result ContentLocationResolverImpl::ResolveProgramPathForDebug(sf::Out<Path> out, ncm::ProgramId id) {
/* Use a redirection if present. */
RedirectionAttributes attr;
R_SUCCEED_IF(m_debug_program_redirector.FindRedirection(out.GetPointer(), std::addressof(attr), id));
/* If we're not enabled, we can't resolve a program. */
R_UNLESS(m_enabled, lr::ResultDebugProgramNotFound())
/* Otherwise find the path for the program id. */
R_TRY_CATCH(this->ResolveProgramPath(out.GetPointer(), std::addressof(attr), id)) {
R_CONVERT(lr::ResultProgramNotFound, lr::ResultDebugProgramNotFound())
} R_END_TRY_CATCH;
R_SUCCEED();
}
Result ContentLocationResolverImpl::RedirectProgramPathForDebug(const Path &path, ncm::ProgramId id) {
m_debug_program_redirector.SetRedirection(id, path, DefaultRedirectionAttributes);
R_SUCCEED();
}
Result ContentLocationResolverImpl::RedirectApplicationProgramPathForDebugDeprecated(const Path &path, ncm::ProgramId id) {
m_debug_program_redirector.SetRedirection(id, path, DefaultRedirectionAttributes, RedirectionFlags_Application);
R_SUCCEED();
}
Result ContentLocationResolverImpl::RedirectApplicationProgramPathForDebug(const Path &path, ncm::ProgramId id, ncm::ProgramId owner_id) {
m_debug_program_redirector.SetRedirection(id, owner_id, path, DefaultRedirectionAttributes, RedirectionFlags_Application);
R_SUCCEED();
}
Result ContentLocationResolverImpl::EraseProgramRedirectionForDebug(ncm::ProgramId id) {
m_debug_program_redirector.EraseRedirection(id);
R_SUCCEED();
}
Result ContentLocationResolverImpl::Disable() {
m_enabled = false;
R_SUCCEED();
}
}
| 9,854
|
C++
|
.cpp
| 176
| 48.857955
| 143
| 0.726876
|
Atmosphere-NX/Atmosphere
| 14,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,803
|
lr_add_on_content_location_resolver_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/lr/lr_add_on_content_location_resolver_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 "lr_add_on_content_location_resolver_impl.hpp"
namespace ams::lr {
namespace {
constexpr const lr::Path EmptyPath = {};
template<size_t N>
Result ResolveAddOnContentPathImpl(Path *out, RedirectionAttributes *out_attr, const RegisteredStorages<ncm::DataId, N> &storages, ncm::DataId id) {
/* Find a storage that contains the given program id. */
ncm::StorageId storage_id = ncm::StorageId::None;
R_UNLESS(storages.Find(std::addressof(storage_id), id), lr::ResultAddOnContentNotFound());
/* Obtain a content meta database for the storage id. */
ncm::ContentMetaDatabase content_meta_database;
R_TRY(ncm::OpenContentMetaDatabase(std::addressof(content_meta_database), storage_id));
/* Find the latest data content info for the given program id. */
ncm::ContentInfo data_content_info;
R_TRY(content_meta_database.GetLatestData(std::addressof(data_content_info), id));
/* Obtain a content storage for the storage id. */
ncm::ContentStorage content_storage;
R_TRY(ncm::OpenContentStorage(std::addressof(content_storage), storage_id));
/* Get the path of the data content. */
static_assert(sizeof(lr::Path) == sizeof(ncm::Path));
content_storage.GetPath(reinterpret_cast<ncm::Path *>(out), data_content_info.GetId());
/* Get the redirection attributes. */
*out_attr = RedirectionAttributes::Make(data_content_info.GetContentAttributes());
R_SUCCEED();
}
}
Result AddOnContentLocationResolverImpl::ResolveAddOnContentPath(Path *out, RedirectionAttributes *out_attr, ncm::DataId id) {
/* Try to resolve using our registered storages. */
if (const auto result = ResolveAddOnContentPathImpl(out, out_attr, m_registered_storages, id); R_SUCCEEDED(result) || !lr::ResultAddOnContentNotFound::Includes(result)) {
R_RETURN(result);
}
/* If we failed to find the add-on content by storage, we should check if there's a registered path. */
auto * const found = m_registered_paths.Find(id);
R_UNLESS(found != nullptr, lr::ResultAddOnContentNotFound());
/* Set the output path. */
*out = found->redir_path.path;
*out_attr = found->redir_path.attributes;
R_SUCCEED();
}
Result AddOnContentLocationResolverImpl::ResolveAddOnContentPath(sf::Out<Path> out, ncm::DataId id) {
RedirectionAttributes attr;
R_RETURN(this->ResolveAddOnContentPath(out.GetPointer(), std::addressof(attr), id));
}
Result AddOnContentLocationResolverImpl::RegisterAddOnContentStorageDeprecated(ncm::DataId id, ncm::StorageId storage_id) {
/* Register storage for the given program id. 2.0.0-8.1.0 did not require an owner application id. */
R_UNLESS(m_registered_storages.Register(id, storage_id, ncm::InvalidApplicationId), lr::ResultTooManyRegisteredPaths());
R_SUCCEED();
}
Result AddOnContentLocationResolverImpl::RegisterAddOnContentStorage(ncm::DataId id, ncm::ApplicationId application_id, ncm::StorageId storage_id) {
/* Register storage for the given program id and owner application. */
R_UNLESS(m_registered_storages.Register(id, storage_id, application_id), lr::ResultTooManyRegisteredPaths());
R_SUCCEED();
}
Result AddOnContentLocationResolverImpl::UnregisterAllAddOnContentPath() {
m_registered_storages.Clear();
m_registered_paths.RemoveAll();
m_registered_other_paths.RemoveAll();
R_SUCCEED();
}
Result AddOnContentLocationResolverImpl::RefreshApplicationAddOnContent(const sf::InArray<ncm::ApplicationId> &ids) {
/* Clear all registered storages excluding the provided program ids. */
m_registered_storages.ClearExcluding(reinterpret_cast<const ncm::ProgramId *>(ids.GetPointer()), ids.GetSize());
auto ShouldRefresh = [&ids](const ncm::DataId &, const OwnedPath &owned_path) {
for (size_t i = 0; i < ids.GetSize(); ++i) {
if (owned_path.owner_id == ids[i]) {
return false;
}
}
return true;
};
m_registered_paths.RemoveIf(ShouldRefresh);
m_registered_other_paths.RemoveIf(ShouldRefresh);
R_SUCCEED();
}
Result AddOnContentLocationResolverImpl::UnregisterApplicationAddOnContent(ncm::ApplicationId id) {
/* Remove entries belonging to the provided application. */
m_registered_storages.UnregisterOwnerProgram(id);
auto ShouldRefresh = [&id](const ncm::DataId &, const OwnedPath &owned_path) {
return owned_path.owner_id == id;
};
m_registered_paths.RemoveIf(ShouldRefresh);
m_registered_other_paths.RemoveIf(ShouldRefresh);
R_SUCCEED();
}
Result AddOnContentLocationResolverImpl::GetRegisteredAddOnContentPaths(Path *out, RedirectionAttributes *out_attr, Path *out2, RedirectionAttributes *out_attr2, ncm::DataId id) {
/* Find a registered path. */
auto * const found = m_registered_paths.Find(id);
if (found == nullptr) {
/* We have no registered path, so perform a normal resolution. */
R_TRY(ResolveAddOnContentPathImpl(out, out_attr, m_registered_storages, id));
/* Clear the second output path. */
*out2 = {};
*out_attr2 = {};
R_SUCCEED();
}
/* Set the output path. */
*out = found->redir_path.path;
*out_attr = found->redir_path.attributes;
/* If we have a second path, set it to output. */
if (auto * const found2 = m_registered_other_paths.Find(id); found2 != nullptr) {
*out2 = found2->redir_path.path;
*out_attr2 = found2->redir_path.attributes;
} else {
*out2 = {};
*out_attr2 = {};
}
R_SUCCEED();
}
Result AddOnContentLocationResolverImpl::GetRegisteredAddOnContentPaths(sf::Out<PathByMapAlias> out, sf::Out<PathByMapAlias> out2, ncm::DataId id) {
RedirectionAttributes attr, attr2;
R_RETURN(this->GetRegisteredAddOnContentPaths(out.GetPointer(), std::addressof(attr), out2.GetPointer(), std::addressof(attr2), id));
}
Result AddOnContentLocationResolverImpl::RegisterAddOnContentPath(ncm::DataId id, ncm::ApplicationId application_id, const lr::PathByMapAlias &path) {
R_RETURN(this->RegisterAddOnContentPaths(id, application_id, path, DefaultRedirectionAttributes, EmptyPath, DefaultRedirectionAttributes));
}
Result AddOnContentLocationResolverImpl::RegisterAddOnContentPaths(ncm::DataId id, ncm::ApplicationId application_id, const lr::PathByMapAlias &path, const lr::PathByMapAlias &path2) {
R_RETURN(this->RegisterAddOnContentPaths(id, application_id, path, DefaultRedirectionAttributes, path2, DefaultRedirectionAttributes));
}
Result AddOnContentLocationResolverImpl::RegisterAddOnContentPaths(ncm::DataId id, ncm::ApplicationId application_id, const Path &path, const RedirectionAttributes &attr, const Path &path2, const RedirectionAttributes &attr2) {
/* Check that it's possible for us to register the path. */
/* NOTE: This check is technically incorrect, if the id is already registered. */
R_UNLESS(!m_registered_paths.IsFull(), lr::ResultTooManyRegisteredPaths());
/* Check that the input path isn't empty. */
R_UNLESS(path.str[0] != '\x00', lr::ResultInvalidPath());
/* Insert the path. */
m_registered_paths.InsertOrAssign(id, OwnedPath{ { path, attr }, application_id });
/* If we have a second path, insert it. */
if (path2.str[0] != '\x00') {
m_registered_other_paths.InsertOrAssign(id, OwnedPath { { path2, attr2 }, application_id });
} else {
m_registered_other_paths.Remove(id);
}
R_SUCCEED();
}
}
| 8,762
|
C++
|
.cpp
| 151
| 49.238411
| 231
| 0.673124
|
Atmosphere-NX/Atmosphere
| 14,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,804
|
patcher_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/patcher/patcher_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>
/* IPS Patching adapted from Luma3DS (https://github.com/AuroraWright/Luma3DS/blob/master/sysmodules/loader/source/patcher.c) */
namespace ams::patcher {
namespace {
/* Convenience definitions. */
constexpr const char IpsHeadMagic[5] = {'P', 'A', 'T', 'C', 'H'};
constexpr const char IpsTailMagic[3] = {'E', 'O', 'F'};
constexpr const char Ips32HeadMagic[5] = {'I', 'P', 'S', '3', '2'};
constexpr const char Ips32TailMagic[4] = {'E', 'E', 'O', 'F'};
constexpr const char *IpsFileExtension = ".ips";
constexpr size_t IpsFileExtensionLength = util::Strlen(IpsFileExtension);
constexpr size_t ModuleIpsPatchLength = 2 * sizeof(ro::ModuleId) + IpsFileExtensionLength;
/* Global data. */
constinit os::SdkMutex g_apply_patch_lock;
constinit u8 g_patch_read_buffer[os::MemoryPageSize];
/* Helpers. */
inline u8 ConvertHexNybble(const char nybble) {
if ('0' <= nybble && nybble <= '9') {
return nybble - '0';
} else if ('a' <= nybble && nybble <= 'f') {
return nybble - 'a' + 0xa;
} else {
return nybble - 'A' + 0xA;
}
}
bool ParseModuleIdFromPath(ro::ModuleId *out_module_id, const char *name, size_t name_len, size_t extension_len) {
/* Validate name is hex module id. */
for (unsigned int i = 0; i < name_len - extension_len; i++) {
if (!std::isxdigit(static_cast<unsigned char>(name[i]))) {
return false;
}
}
/* Read module id from name. */
std::memset(out_module_id, 0, sizeof(*out_module_id));
for (unsigned int name_ofs = 0, id_ofs = 0; name_ofs < name_len - extension_len && id_ofs < sizeof(*out_module_id); id_ofs++) {
out_module_id->data[id_ofs] |= ConvertHexNybble(name[name_ofs++]) << 4;
out_module_id->data[id_ofs] |= ConvertHexNybble(name[name_ofs++]);
}
return true;
}
bool MatchesModuleId(const char *name, size_t name_len, size_t extension_len, const ro::ModuleId *module_id) {
/* Get module id. */
ro::ModuleId module_id_from_name;
if (!ParseModuleIdFromPath(std::addressof(module_id_from_name), name, name_len, extension_len)) {
return false;
}
return std::memcmp(std::addressof(module_id_from_name), module_id, sizeof(*module_id)) == 0;
}
bool IsIpsFileForModule(const char *name, const ro::ModuleId *module_id) {
const size_t name_len = std::strlen(name);
/* The path must be correct size for a module id (with trailing zeroes optionally trimmed) + ".ips". */
if (!(IpsFileExtensionLength < name_len && name_len <= ModuleIpsPatchLength)) {
return false;
}
/* The path must be an even number of characters to conform. */
if (!util::IsAligned(name_len, 2)) {
return false;
}
/* The path needs to end with .ips. */
if (std::strcmp(name + name_len - IpsFileExtensionLength, IpsFileExtension) != 0) {
return false;
}
/* The path needs to match the module id. */
return MatchesModuleId(name, name_len, IpsFileExtensionLength, module_id);
}
inline bool IsIpsTail(bool is_ips32, u8 *buffer) {
if (is_ips32) {
return std::memcmp(buffer, Ips32TailMagic, sizeof(Ips32TailMagic)) == 0;
} else {
return std::memcmp(buffer, IpsTailMagic, sizeof(IpsTailMagic)) == 0;
}
}
inline u32 GetIpsPatchOffset(bool is_ips32, u8 *buffer) {
if (is_ips32) {
return (buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | (buffer[3]);
} else {
return (buffer[0] << 16) | (buffer[1] << 8) | (buffer[2]);
}
}
inline u32 GetIpsPatchSize(bool is_ips32, u8 *buffer) {
AMS_UNUSED(is_ips32);
return (buffer[0] << 8) | (buffer[1]);
}
void ApplyIpsPatch(u8 *mapped_module, size_t mapped_size, size_t protected_size, size_t offset, bool is_ips32, fs::FileHandle file) {
/* Validate offset/protected size. */
AMS_ABORT_UNLESS(offset <= protected_size);
s64 file_offset = sizeof(IpsHeadMagic);
auto ReadData = [&](void *dst, size_t size) ALWAYS_INLINE_LAMBDA {
R_ABORT_UNLESS(fs::ReadFile(file, file_offset, dst, size));
file_offset += size;
};
u8 buffer[sizeof(Ips32TailMagic)];
while (true) {
ReadData(buffer, is_ips32 ? sizeof(Ips32TailMagic) : sizeof(IpsTailMagic));
if (IsIpsTail(is_ips32, buffer)) {
break;
}
/* Offset of patch. */
u32 patch_offset = GetIpsPatchOffset(is_ips32, buffer);
/* Size of patch. */
ReadData(buffer, 2);
u32 patch_size = GetIpsPatchSize(is_ips32, buffer);
/* Check for RLE encoding. */
if (patch_size == 0) {
/* Size of RLE. */
ReadData(buffer, 2);
u32 rle_size = (buffer[0] << 8) | (buffer[1]);
/* Value for RLE. */
ReadData(buffer, 1);
/* Ensure we don't write to protected region. */
if (patch_offset < protected_size) {
if (patch_offset + rle_size > protected_size) {
const u32 diff = protected_size - patch_offset;
patch_offset += diff;
rle_size -= diff;
} else {
continue;
}
}
/* Adjust offset, if relevant. */
patch_offset -= offset;
/* Apply patch. */
if (patch_offset + rle_size > mapped_size) {
AMS_ABORT_UNLESS(patch_offset <= mapped_size);
rle_size = mapped_size - patch_offset;
}
std::memset(mapped_module + patch_offset, buffer[0], rle_size);
} else {
/* Ensure we don't write to protected region. */
if (patch_offset < protected_size) {
if (patch_offset + patch_size > protected_size) {
const u32 diff = protected_size - patch_offset;
patch_offset += diff;
patch_size -= diff;
file_offset += diff;
} else {
file_offset += patch_size;
continue;
}
}
/* Adjust offset, if relevant. */
patch_offset -= offset;
/* Apply patch. */
u32 read_size = patch_size;
if (patch_offset + read_size > mapped_size) {
AMS_ABORT_UNLESS(patch_offset <= mapped_size);
read_size = mapped_size - patch_offset;
}
{
size_t remaining = read_size;
size_t copy_offset = patch_offset;
while (remaining > 0) {
const size_t cur_read = std::min(remaining, sizeof(g_patch_read_buffer));
ReadData(g_patch_read_buffer, cur_read);
std::memcpy(mapped_module + copy_offset, g_patch_read_buffer, cur_read);
remaining -= cur_read;
copy_offset += cur_read;
}
}
if (patch_size > read_size) {
file_offset += patch_size - read_size;
}
}
}
}
}
void LocateAndApplyIpsPatchesToModule(const char *mount_name, const char *patch_dir_name, size_t protected_size, size_t offset, const ro::ModuleId *module_id, u8 *mapped_module, size_t mapped_size) {
/* Ensure only one thread tries to apply patches at a time. */
std::scoped_lock lk(g_apply_patch_lock);
/* Inspect all patches from /atmosphere/<patch_dir>/<*>/<*>.ips */
char path[fs::EntryNameLengthMax + 1];
util::SNPrintf(path, sizeof(path), "%s:/atmosphere/%s", mount_name, patch_dir_name);
const size_t patches_dir_path_len = std::strlen(path);
/* Open the patch directory. */
fs::DirectoryHandle patches_dir;
if (R_FAILED(fs::OpenDirectory(std::addressof(patches_dir), path, fs::OpenDirectoryMode_Directory))) {
return;
}
ON_SCOPE_EXIT { fs::CloseDirectory(patches_dir); };
/* Iterate over the patches directory to find patch subdirectories. */
while (true) {
/* Read the next entry. */
s64 count;
fs::DirectoryEntry entry;
if (R_FAILED(fs::ReadDirectory(std::addressof(count), std::addressof(entry), patches_dir, 1)) || count == 0) {
break;
}
/* Print the path for this directory. */
util::SNPrintf(path + patches_dir_path_len, sizeof(path) - patches_dir_path_len, "/%s", entry.name);
const size_t patch_dir_path_len = patches_dir_path_len + 1 + std::strlen(entry.name);
/* Open the patch directory. */
fs::DirectoryHandle patch_dir;
if (R_FAILED(fs::OpenDirectory(std::addressof(patch_dir), path, fs::OpenDirectoryMode_File))) {
continue;
}
ON_SCOPE_EXIT { fs::CloseDirectory(patch_dir); };
/* Iterate over files in the patch directory. */
while (true) {
if (R_FAILED(fs::ReadDirectory(std::addressof(count), std::addressof(entry), patch_dir, 1)) || count == 0) {
break;
}
/* Check if this file is an ips. */
if (!IsIpsFileForModule(entry.name, module_id)) {
continue;
}
/* Print the path for this file. */
util::SNPrintf(path + patch_dir_path_len, sizeof(path) - patch_dir_path_len, "/%s", entry.name);
/* Open the file. */
fs::FileHandle file;
if (R_FAILED(fs::OpenFile(std::addressof(file), path, fs::OpenMode_Read))) {
continue;
}
ON_SCOPE_EXIT { fs::CloseFile(file); };
/* Read the header. */
u8 header[sizeof(IpsHeadMagic)];
if (R_SUCCEEDED(fs::ReadFile(file, 0, header, sizeof(header)))) {
if (std::memcmp(header, IpsHeadMagic, sizeof(header)) == 0) {
ApplyIpsPatch(mapped_module, mapped_size, protected_size, offset, false, file);
} else if (std::memcmp(header, Ips32HeadMagic, sizeof(header)) == 0) {
ApplyIpsPatch(mapped_module, mapped_size, protected_size, offset, true, file);
}
}
}
}
}
}
| 12,319
|
C++
|
.cpp
| 241
| 35.858921
| 203
| 0.514212
|
Atmosphere-NX/Atmosphere
| 14,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,805
|
erpt_srv_cipher.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/erpt/srv/erpt_srv_cipher.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 "erpt_srv_cipher.hpp"
namespace ams::erpt::srv {
constinit u8 Cipher::s_key[crypto::Aes128CtrEncryptor::KeySize + crypto::Aes128CtrEncryptor::IvSize + crypto::Aes128CtrEncryptor::BlockSize];
constinit bool Cipher::s_need_to_store_cipher = false;
}
| 931
|
C++
|
.cpp
| 21
| 42.142857
| 145
| 0.76075
|
Atmosphere-NX/Atmosphere
| 14,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,806
|
erpt_srv_manager_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/erpt/srv/erpt_srv_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 "erpt_srv_manager_impl.hpp"
#include "erpt_srv_journal.hpp"
namespace ams::erpt::srv {
namespace {
using ManagerList = util::IntrusiveListBaseTraits<ManagerImpl>::ListType;
constinit ManagerList g_manager_list;
}
ManagerImpl::ManagerImpl() : m_system_event(os::EventClearMode_AutoClear, true) {
g_manager_list.push_front(*this);
}
ManagerImpl::~ManagerImpl() {
g_manager_list.erase(g_manager_list.iterator_to(*this));
}
void ManagerImpl::NotifyOne() {
m_system_event.Signal();
}
Result ManagerImpl::NotifyAll() {
for (auto &manager : g_manager_list) {
manager.NotifyOne();
}
R_SUCCEED();
}
Result ManagerImpl::GetReportList(const ams::sf::OutBuffer &out_list, ReportType type_filter) {
R_UNLESS(out_list.GetSize() == sizeof(ReportList), erpt::ResultInvalidArgument());
R_RETURN(Journal::GetReportList(reinterpret_cast<ReportList *>(out_list.GetPointer()), type_filter));
}
Result ManagerImpl::GetEvent(ams::sf::OutCopyHandle out) {
out.SetValue(m_system_event.GetReadableHandle(), false);
R_SUCCEED();
}
Result ManagerImpl::CleanupReports() {
Journal::CleanupReports();
Journal::CleanupAttachments();
R_RETURN(Journal::Commit());
}
Result ManagerImpl::DeleteReport(const ReportId &report_id) {
R_TRY(Journal::Delete(report_id));
R_RETURN(Journal::Commit());
}
Result ManagerImpl::GetStorageUsageStatistics(ams::sf::Out<StorageUsageStatistics> out) {
StorageUsageStatistics stats = {};
stats.journal_uuid = Journal::GetJournalId();
stats.used_storage_size = Journal::GetUsedStorage();
stats.max_report_size = Journal::GetMaxReportSize();
for (int i = ReportType_Start; i < ReportType_End; i++) {
const auto type = static_cast<ReportType>(i);
stats.report_count[i] = Journal::GetStoredReportCount(type);
stats.transmitted_count[i] = Journal::GetTransmittedCount(type);
stats.untransmitted_count[i] = Journal::GetUntransmittedCount(type);
}
out.SetValue(stats);
R_SUCCEED();
}
Result ManagerImpl::GetAttachmentList(const ams::sf::OutBuffer &out_list, const ReportId &report_id) {
R_UNLESS(out_list.GetSize() == sizeof(AttachmentList), erpt::ResultInvalidArgument());
R_RETURN(Journal::GetAttachmentList(reinterpret_cast<AttachmentList *>(out_list.GetPointer()), report_id));
}
}
| 3,245
|
C++
|
.cpp
| 74
| 37.459459
| 115
| 0.68127
|
Atmosphere-NX/Atmosphere
| 14,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,807
|
erpt_srv_stream.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/erpt/srv/erpt_srv_stream.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 "erpt_srv_allocator.hpp"
#include "erpt_srv_stream.hpp"
namespace ams::erpt::srv {
constinit bool Stream::s_can_access_fs = true;
constinit os::SdkMutex Stream::s_fs_commit_mutex;
void Stream::EnableFsAccess(bool en) {
s_can_access_fs = en;
}
Result Stream::DeleteStream(const char *path) {
R_UNLESS(s_can_access_fs, erpt::ResultInvalidPowerState());
R_RETURN(fs::DeleteFile(path));
}
Result Stream::CommitStream() {
R_UNLESS(s_can_access_fs, erpt::ResultInvalidPowerState());
std::scoped_lock lk(s_fs_commit_mutex);
fs::CommitSaveData(ReportStoragePath);
R_SUCCEED();
}
Result Stream::GetStreamSize(s64 *out, const char *path) {
R_UNLESS(s_can_access_fs, erpt::ResultInvalidPowerState());
fs::FileHandle file;
R_TRY(fs::OpenFile(std::addressof(file), path, fs::OpenMode_Read));
ON_SCOPE_EXIT { fs::CloseFile(file); };
R_RETURN(fs::GetFileSize(out, file));
}
Stream::Stream() : m_buffer_size(0), m_file_position(0), m_buffer_count(0), m_buffer(nullptr), m_stream_mode(StreamMode_Invalid), m_initialized(false) {
/* ... */
}
Stream::~Stream() {
this->CloseStream();
AMS_ASSERT(!s_fs_commit_mutex.IsLockedByCurrentThread());
}
Result Stream::OpenStream(const char *path, StreamMode mode, u32 buffer_size) {
R_UNLESS(s_can_access_fs, erpt::ResultInvalidPowerState());
R_UNLESS(!m_initialized, erpt::ResultAlreadyInitialized());
auto lock_guard = SCOPE_GUARD {
if (s_fs_commit_mutex.IsLockedByCurrentThread()) {
s_fs_commit_mutex.Unlock();
}
};
if (mode == StreamMode_Write) {
s_fs_commit_mutex.Lock();
while (true) {
R_TRY_CATCH(fs::OpenFile(std::addressof(m_file_handle), path, fs::OpenMode_Write | fs::OpenMode_AllowAppend)) {
R_CATCH(fs::ResultPathNotFound) {
R_TRY(fs::CreateFile(path, 0));
continue;
}
} R_END_TRY_CATCH;
break;
}
fs::SetFileSize(m_file_handle, 0);
} else {
R_UNLESS(mode == StreamMode_Read, erpt::ResultInvalidArgument());
R_TRY(fs::OpenFile(std::addressof(m_file_handle), path, fs::OpenMode_Read));
}
auto file_guard = SCOPE_GUARD { fs::CloseFile(m_file_handle); };
std::strncpy(m_file_name, path, sizeof(m_file_name));
m_file_name[sizeof(m_file_name) - 1] = '\x00';
if (buffer_size > 0) {
m_buffer = reinterpret_cast<u8 *>(Allocate(buffer_size));
AMS_ASSERT(m_buffer != nullptr);
} else {
m_buffer = nullptr;
}
m_buffer_size = m_buffer != nullptr ? buffer_size : 0;
m_buffer_count = 0;
m_buffer_position = 0;
m_file_position = 0;
m_stream_mode = mode;
m_initialized = true;
file_guard.Cancel();
lock_guard.Cancel();
R_SUCCEED();
}
Result Stream::ReadStream(u32 *out, u8 *dst, u32 dst_size) {
R_UNLESS(s_can_access_fs, erpt::ResultInvalidPowerState());
R_UNLESS(m_initialized, erpt::ResultNotInitialized());
R_UNLESS(m_stream_mode == StreamMode_Read, erpt::ResultNotInitialized());
R_UNLESS(out != nullptr, erpt::ResultInvalidArgument());
R_UNLESS(dst != nullptr, erpt::ResultInvalidArgument());
size_t fs_read_size;
u32 read_count = 0;
ON_SCOPE_EXIT {
*out = read_count;
};
if (m_buffer != nullptr) {
while (dst_size > 0) {
if (u32 cur = std::min<u32>(m_buffer_count - m_buffer_position, dst_size); cur > 0) {
std::memcpy(dst, m_buffer + m_buffer_position, cur);
m_buffer_position += cur;
dst += cur;
dst_size -= cur;
read_count += cur;
} else {
R_TRY(fs::ReadFile(std::addressof(fs_read_size), m_file_handle, m_file_position, m_buffer, m_buffer_size));
m_buffer_position = 0;
m_file_position += static_cast<u32>(fs_read_size);
m_buffer_count = static_cast<u32>(fs_read_size);
if (m_buffer_count == 0) {
break;
}
}
}
} else {
R_TRY(fs::ReadFile(std::addressof(fs_read_size), m_file_handle, m_file_position, dst, dst_size));
m_file_position += static_cast<u32>(fs_read_size);
read_count = static_cast<u32>(fs_read_size);
}
R_SUCCEED();
}
Result Stream::WriteStream(const u8 *src, u32 src_size) {
R_UNLESS(s_can_access_fs, erpt::ResultInvalidPowerState());
R_UNLESS(m_initialized, erpt::ResultNotInitialized());
R_UNLESS(m_stream_mode == StreamMode_Write, erpt::ResultNotInitialized());
R_UNLESS(src != nullptr || src_size == 0, erpt::ResultInvalidArgument());
if (m_buffer != nullptr) {
while (src_size > 0) {
if (u32 cur = std::min<u32>(m_buffer_size - m_buffer_count, src_size); cur > 0) {
std::memcpy(m_buffer + m_buffer_count, src, cur);
m_buffer_count += cur;
src += cur;
src_size -= cur;
}
if (m_buffer_count == m_buffer_size) {
R_TRY(this->Flush());
}
}
} else {
R_TRY(fs::WriteFile(m_file_handle, m_file_position, src, src_size, fs::WriteOption::None));
m_file_position += src_size;
}
R_SUCCEED();
}
void Stream::CloseStream() {
if (m_initialized) {
if (s_can_access_fs) {
if (m_stream_mode == StreamMode_Write) {
this->Flush();
fs::FlushFile(m_file_handle);
}
fs::CloseFile(m_file_handle);
}
if (m_buffer != nullptr) {
Deallocate(m_buffer);
}
m_initialized = false;
if (s_fs_commit_mutex.IsLockedByCurrentThread()) {
s_fs_commit_mutex.Unlock();
}
}
}
Result Stream::GetStreamSize(s64 *out) const {
R_RETURN(GetStreamSize(out, m_file_name));
}
Result Stream::Flush() {
AMS_ASSERT(s_fs_commit_mutex.IsLockedByCurrentThread());
R_SUCCEED_IF(m_buffer_count == 0);
R_TRY(fs::WriteFile(m_file_handle, m_file_position, m_buffer, m_buffer_count, fs::WriteOption::None));
m_file_position += m_buffer_count;
m_buffer_count = 0;
R_SUCCEED();
}
}
| 7,801
|
C++
|
.cpp
| 180
| 32.555556
| 156
| 0.541568
|
Atmosphere-NX/Atmosphere
| 14,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,808
|
erpt_srv_attachment.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/erpt/srv/erpt_srv_attachment.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 "erpt_srv_attachment_impl.hpp"
#include "erpt_srv_attachment.hpp"
namespace ams::erpt::srv {
AttachmentFileName Attachment::FileName(AttachmentId attachment_id) {
char uuid_str[AttachmentFileNameLength];
attachment_id.uuid.ToString(uuid_str, sizeof(uuid_str));
AttachmentFileName attachment_name;
util::SNPrintf(attachment_name.name, sizeof(attachment_name.name), "%s:/%s.att", ReportStoragePath, uuid_str);
return attachment_name;
}
Attachment::Attachment(JournalRecord<AttachmentInfo> *r) : m_record(r) {
m_record->AddReference();
}
Attachment::~Attachment() {
this->CloseStream();
if (m_record->RemoveReference()) {
this->DeleteStream(this->FileName().name);
delete m_record;
}
}
AttachmentFileName Attachment::FileName() const {
return FileName(m_record->m_info.attachment_id);
}
Result Attachment::Open(AttachmentOpenType type) {
switch (type) {
case AttachmentOpenType_Create: R_RETURN(this->OpenStream(this->FileName().name, StreamMode_Write, AttachmentStreamBufferSize));
case AttachmentOpenType_Read: R_RETURN(this->OpenStream(this->FileName().name, StreamMode_Read, AttachmentStreamBufferSize));
default: R_THROW(erpt::ResultInvalidArgument());
}
}
Result Attachment::Read(u32 *out_read_count, u8 *dst, u32 dst_size) {
R_RETURN(this->ReadStream(out_read_count, dst, dst_size));
}
Result Attachment::Delete() {
R_RETURN(this->DeleteStream(this->FileName().name));
}
void Attachment::Close() {
return this->CloseStream();
}
Result Attachment::GetFlags(AttachmentFlagSet *out) const {
*out = m_record->m_info.flags;
R_SUCCEED();
}
Result Attachment::SetFlags(AttachmentFlagSet flags) {
if (((~m_record->m_info.flags) & flags).IsAnySet()) {
m_record->m_info.flags |= flags;
R_RETURN(Journal::Commit());
}
R_SUCCEED();
}
Result Attachment::GetSize(s64 *out) const {
R_RETURN(this->GetStreamSize(out));
}
}
| 2,863
|
C++
|
.cpp
| 70
| 34.642857
| 140
| 0.668946
|
Atmosphere-NX/Atmosphere
| 14,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,809
|
erpt_srv_service.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/erpt/srv/erpt_srv_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 "erpt_srv_service.hpp"
#include "erpt_srv_context_impl.hpp"
#include "erpt_srv_session_impl.hpp"
#include "erpt_srv_stream.hpp"
#include "erpt_srv_forced_shutdown.hpp"
namespace ams::erpt::srv {
extern ams::sf::ExpHeapAllocator g_sf_allocator;
namespace {
struct ErrorReportServerOptions {
static constexpr size_t PointerBufferSize = 0;
static constexpr size_t MaxDomains = 64;
static constexpr size_t MaxDomainObjects = 2 * ReportCountMax + 5 + 2;
static constexpr bool CanDeferInvokeRequest = false;
static constexpr bool CanManageMitmServers = false;
};
constexpr inline size_t ErrorReportNumServers = 2;
constexpr inline size_t ErrorReportReportSessions = 5;
constexpr inline size_t ErrorReportContextSessions = 10;
constexpr inline size_t ErrorReportMaxSessions = ErrorReportReportSessions + ErrorReportContextSessions;
constexpr inline sm::ServiceName ErrorReportContextServiceName = sm::ServiceName::Encode("erpt:c");
constexpr inline sm::ServiceName ErrorReportReportServiceName = sm::ServiceName::Encode("erpt:r");
alignas(os::ThreadStackAlignment) constinit u8 g_server_thread_stack[16_KB];
enum PortIndex {
PortIndex_Report,
PortIndex_Context,
};
class ErrorReportServiceManager : public ams::sf::hipc::ServerManager<ErrorReportNumServers, ErrorReportServerOptions, ErrorReportMaxSessions> {
private:
os::ThreadType m_thread;
ams::sf::UnmanagedServiceObject<erpt::sf::IContext, erpt::srv::ContextImpl> m_context_session_object;
private:
static void ThreadFunction(void *_this) {
reinterpret_cast<ErrorReportServiceManager *>(_this)->SetupAndLoopProcess();
}
void SetupAndLoopProcess();
virtual Result OnNeedsToAccept(int port_index, Server *server) override {
switch (port_index) {
case PortIndex_Report:
{
auto intf = ams::sf::ObjectFactory<ams::sf::ExpHeapAllocator::Policy>::CreateSharedEmplaced<erpt::sf::ISession, erpt::srv::SessionImpl>(std::addressof(g_sf_allocator));
AMS_ABORT_UNLESS(intf != nullptr);
R_RETURN(this->AcceptImpl(server, intf));
}
case PortIndex_Context:
R_RETURN(AcceptImpl(server, m_context_session_object.GetShared()));
default:
R_THROW(erpt::ResultNotSupported());
}
}
public:
Result Initialize() {
R_ABORT_UNLESS(this->RegisterServer(PortIndex_Context, ErrorReportContextServiceName, ErrorReportContextSessions));
R_ABORT_UNLESS(this->RegisterServer(PortIndex_Report, ErrorReportReportServiceName, ErrorReportReportSessions));
this->ResumeProcessing();
R_ABORT_UNLESS(os::CreateThread(std::addressof(m_thread), ThreadFunction, this, g_server_thread_stack, sizeof(g_server_thread_stack), AMS_GET_SYSTEM_THREAD_PRIORITY(erpt, IpcServer)));
os::SetThreadNamePointer(std::addressof(m_thread), AMS_GET_SYSTEM_THREAD_NAME(erpt, IpcServer));
os::StartThread(std::addressof(m_thread));
R_SUCCEED();
}
void Wait() {
os::WaitThread(std::addressof(m_thread));
}
};
void ErrorReportServiceManager::SetupAndLoopProcess() {
const psc::PmModuleId dependencies[] = { psc::PmModuleId_Fs };
psc::PmModule pm_module;
psc::PmState pm_state;
psc::PmFlagSet pm_flags;
os::MultiWaitHolderType module_event_holder;
R_ABORT_UNLESS(pm_module.Initialize(psc::PmModuleId_Erpt, dependencies, util::size(dependencies), os::EventClearMode_ManualClear));
os::InitializeMultiWaitHolder(std::addressof(module_event_holder), pm_module.GetEventPointer()->GetBase());
os::SetMultiWaitHolderUserData(std::addressof(module_event_holder), static_cast<uintptr_t>(psc::PmModuleId_Erpt));
this->AddUserMultiWaitHolder(std::addressof(module_event_holder));
while (true) {
/* NOTE: Nintendo checks the user holder data to determine what's signaled, we will prefer to just check the address. */
auto *signaled_holder = this->WaitSignaled();
if (signaled_holder != std::addressof(module_event_holder)) {
R_ABORT_UNLESS(this->Process(signaled_holder));
} else {
pm_module.GetEventPointer()->Clear();
if (R_SUCCEEDED(pm_module.GetRequest(std::addressof(pm_state), std::addressof(pm_flags)))) {
switch (pm_state) {
case psc::PmState_FullAwake:
case psc::PmState_MinimumAwake:
Stream::EnableFsAccess(true);
break;
case psc::PmState_ShutdownReady:
FinalizeForcedShutdownDetection();
[[fallthrough]];
case psc::PmState_SleepReady:
Stream::EnableFsAccess(false);
break;
default:
break;
}
R_ABORT_UNLESS(pm_module.Acknowledge(pm_state, ResultSuccess()));
} else {
AMS_ASSERT(false);
}
this->AddUserMultiWaitHolder(signaled_holder);
}
}
}
constinit util::TypedStorage<ErrorReportServiceManager> g_erpt_server_manager = {};
}
Result InitializeService() {
util::ConstructAt(g_erpt_server_manager);
R_RETURN(util::GetReference(g_erpt_server_manager).Initialize());
}
void WaitService() {
return util::GetReference(g_erpt_server_manager).Wait();
}
}
| 7,125
|
C++
|
.cpp
| 129
| 40.224806
| 204
| 0.591594
|
Atmosphere-NX/Atmosphere
| 14,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,810
|
erpt_srv_journal_for_meta.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/erpt/srv/erpt_srv_journal_for_meta.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "erpt_srv_journal.hpp"
namespace ams::erpt::srv {
constinit JournalMeta JournalForMeta::s_journal_meta = {};
void JournalForMeta::InitializeJournal() {
std::memset(std::addressof(s_journal_meta), 0, sizeof(s_journal_meta));
s_journal_meta.journal_id = util::GenerateUuid();
s_journal_meta.version = JournalVersion;
}
Result JournalForMeta::CommitJournal(Stream *stream) {
R_RETURN(stream->WriteStream(reinterpret_cast<const u8 *>(std::addressof(s_journal_meta)), sizeof(s_journal_meta)));
}
Result JournalForMeta::RestoreJournal(Stream *stream) {
u32 size;
if (R_FAILED(stream->ReadStream(std::addressof(size), reinterpret_cast<u8 *>(std::addressof(s_journal_meta)), sizeof(s_journal_meta))) || size != sizeof(s_journal_meta)) {
InitializeJournal();
}
R_SUCCEED();
}
u32 JournalForMeta::GetTransmittedCount(ReportType type) {
if (ReportType_Start <= type && type < ReportType_End) {
return s_journal_meta.transmitted_count[type];
} else {
return 0;
}
}
u32 JournalForMeta::GetUntransmittedCount(ReportType type) {
if (ReportType_Start <= type && type < ReportType_End) {
return s_journal_meta.untransmitted_count[type];
} else {
return 0;
}
}
void JournalForMeta::IncrementCount(bool transmitted, ReportType type) {
if (ReportType_Start <= type && type < ReportType_End) {
if (transmitted) {
s_journal_meta.transmitted_count[type]++;
} else {
s_journal_meta.untransmitted_count[type]++;
}
}
}
util::Uuid JournalForMeta::GetJournalId() {
return s_journal_meta.journal_id;
}
}
| 2,484
|
C++
|
.cpp
| 61
| 34.016393
| 179
| 0.659345
|
Atmosphere-NX/Atmosphere
| 14,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,811
|
erpt_srv_context.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/erpt/srv/erpt_srv_context.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "erpt_srv_context.hpp"
#include "erpt_srv_cipher.hpp"
#include "erpt_srv_context_record.hpp"
#include "erpt_srv_report.hpp"
namespace ams::erpt::srv {
namespace {
using ContextList = util::IntrusiveListBaseTraits<Context>::ListType;
constinit ContextList g_category_list;
}
Context::Context(CategoryId cat) : m_category(cat) {
g_category_list.push_front(*this);
}
Context::~Context() {
g_category_list.erase(g_category_list.iterator_to(*this));
}
Result Context::AddCategoryToReport(Report *report) {
if (m_record != nullptr) {
const auto *entry = m_record->GetContextEntryPtr();
for (u32 i = 0; i < entry->field_count; i++) {
auto *field = std::addressof(entry->fields[i]);
u8 *arr_buf = entry->array_buffer;
switch (field->type) {
case FieldType_Bool: R_TRY(Cipher::AddField(report, field->id, field->value_bool)); break;
case FieldType_NumericU8: R_TRY(Cipher::AddField(report, field->id, field->value_u8)); break;
case FieldType_NumericU16: R_TRY(Cipher::AddField(report, field->id, field->value_u16)); break;
case FieldType_NumericU32: R_TRY(Cipher::AddField(report, field->id, field->value_u32)); break;
case FieldType_NumericU64: R_TRY(Cipher::AddField(report, field->id, field->value_u64)); break;
case FieldType_NumericI8: R_TRY(Cipher::AddField(report, field->id, field->value_i8)); break;
case FieldType_NumericI16: R_TRY(Cipher::AddField(report, field->id, field->value_i16)); break;
case FieldType_NumericI32: R_TRY(Cipher::AddField(report, field->id, field->value_i32)); break;
case FieldType_NumericI64: R_TRY(Cipher::AddField(report, field->id, field->value_i64)); break;
case FieldType_String: R_TRY(Cipher::AddField(report, field->id, reinterpret_cast<char *>(arr_buf + field->value_array.start_idx), field->value_array.size / sizeof(char))); break;
case FieldType_U8Array: R_TRY(Cipher::AddField(report, field->id, reinterpret_cast< u8 *>(arr_buf + field->value_array.start_idx), field->value_array.size / sizeof(u8))); break;
case FieldType_U32Array: R_TRY(Cipher::AddField(report, field->id, reinterpret_cast< u32 *>(arr_buf + field->value_array.start_idx), field->value_array.size / sizeof(u32))); break;
case FieldType_U64Array: R_TRY(Cipher::AddField(report, field->id, reinterpret_cast< u64 *>(arr_buf + field->value_array.start_idx), field->value_array.size / sizeof(u64))); break;
case FieldType_I8Array: R_TRY(Cipher::AddField(report, field->id, reinterpret_cast< s8 *>(arr_buf + field->value_array.start_idx), field->value_array.size / sizeof(s8))); break;
case FieldType_I32Array: R_TRY(Cipher::AddField(report, field->id, reinterpret_cast< s32 *>(arr_buf + field->value_array.start_idx), field->value_array.size / sizeof(s32))); break;
case FieldType_I64Array: R_TRY(Cipher::AddField(report, field->id, reinterpret_cast< s64 *>(arr_buf + field->value_array.start_idx), field->value_array.size / sizeof(s64))); break;
default: R_THROW(erpt::ResultInvalidArgument());
}
}
}
R_SUCCEED();
}
Result Context::SubmitContext(const ContextEntry *entry, const u8 *data, u32 data_size) {
auto record = std::make_unique<ContextRecord>();
R_UNLESS(record != nullptr, erpt::ResultOutOfMemory());
R_TRY(record->Initialize(entry, data, data_size));
R_RETURN(SubmitContextRecord(std::move(record)));
}
Result Context::SubmitContextRecord(std::unique_ptr<ContextRecord> record) {
auto it = util::range::find_if(g_category_list, [&](const Context &cur) {
return cur.m_category == record->GetContextEntryPtr()->category;
});
R_UNLESS(it != g_category_list.end(), erpt::ResultCategoryNotFound());
it->m_record = std::move(record);
R_SUCCEED();
}
Result Context::WriteContextsToReport(Report *report) {
R_TRY(report->Open(ReportOpenType_Create));
R_TRY(Cipher::Begin(report, ContextRecord::GetRecordCount()));
for (auto it = g_category_list.begin(); it != g_category_list.end(); it++) {
R_TRY(it->AddCategoryToReport(report));
}
Cipher::End(report);
report->Close();
R_SUCCEED();
}
Result Context::ClearContext(CategoryId cat) {
/* Make an empty record for the category. */
auto record = std::make_unique<ContextRecord>(cat);
R_UNLESS(record != nullptr, erpt::ResultOutOfMemory());
/* Submit the context record. */
R_RETURN(SubmitContextRecord(std::move(record)));
}
}
| 5,697
|
C++
|
.cpp
| 92
| 52.358696
| 203
| 0.63568
|
Atmosphere-NX/Atmosphere
| 14,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,812
|
erpt_srv_report_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/erpt/srv/erpt_srv_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 "erpt_srv_report_impl.hpp"
#include "erpt_srv_report.hpp"
namespace ams::erpt::srv {
ReportImpl::ReportImpl() : m_report(nullptr) {
/* ... */
}
ReportImpl::~ReportImpl() {
R_ABORT_UNLESS(this->Close());
}
Result ReportImpl::Open(const ReportId &report_id) {
R_UNLESS(m_report == nullptr, erpt::ResultAlreadyInitialized());
JournalRecord<ReportInfo> *record = Journal::Retrieve(report_id);
R_UNLESS(record != nullptr, erpt::ResultNotFound());
m_report = new Report(record, false);
R_UNLESS(m_report != nullptr, erpt::ResultOutOfMemory());
auto report_guard = SCOPE_GUARD { delete m_report; m_report = nullptr; };
R_TRY(m_report->Open(ReportOpenType_Read));
report_guard.Cancel();
R_SUCCEED();
}
Result ReportImpl::Read(ams::sf::Out<u32> out_count, const ams::sf::OutBuffer &out_buffer) {
R_UNLESS(m_report != nullptr, erpt::ResultNotInitialized());
R_RETURN(m_report->Read(out_count.GetPointer(), static_cast<u8 *>(out_buffer.GetPointer()), static_cast<u32>(out_buffer.GetSize())));
}
Result ReportImpl::SetFlags(ReportFlagSet flags) {
R_UNLESS(m_report != nullptr, erpt::ResultNotInitialized());
R_RETURN(m_report->SetFlags(flags));
}
Result ReportImpl::GetFlags(ams::sf::Out<ReportFlagSet> out) {
R_UNLESS(m_report != nullptr, erpt::ResultNotInitialized());
R_RETURN(m_report->GetFlags(out.GetPointer()));
}
Result ReportImpl::Close() {
if (m_report != nullptr) {
m_report->Close();
delete m_report;
m_report = nullptr;
}
R_SUCCEED();
}
Result ReportImpl::GetSize(ams::sf::Out<s64> out) {
R_UNLESS(m_report != nullptr, erpt::ResultNotInitialized());
R_RETURN(m_report->GetSize(out.GetPointer()));
}
}
| 2,573
|
C++
|
.cpp
| 61
| 36.131148
| 141
| 0.659182
|
Atmosphere-NX/Atmosphere
| 14,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,813
|
erpt_srv_fs_info.os.horizon.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/erpt/srv/erpt_srv_fs_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>
#include "erpt_srv_fs_info.hpp"
#include "erpt_srv_context_record.hpp"
#include "erpt_srv_context.hpp"
namespace ams::erpt::srv {
namespace {
Result SubmitMmcDetailInfo() {
/* Submit the mmc cid. */
{
u8 mmc_cid[fs::MmcCidSize] = {};
if (R_SUCCEEDED(fs::GetMmcCid(mmc_cid, sizeof(mmc_cid)))) {
/* Clear the serial number from the cid. */
fs::ClearMmcCidSerialNumber(mmc_cid);
/* Create a record. */
auto record = std::make_unique<ContextRecord>(CategoryId_NANDTypeInfo, sizeof(mmc_cid));
R_UNLESS(record != nullptr, erpt::ResultOutOfMemory());
/* Add the cid. */
R_ABORT_UNLESS(record->Add(FieldId_NANDType, mmc_cid, sizeof(mmc_cid)));
/* Submit the record. */
R_ABORT_UNLESS(Context::SubmitContextRecord(std::move(record)));
}
}
/* Submit the mmc speed mode. */
{
/* Create a record. */
auto record = std::make_unique<ContextRecord>(CategoryId_NANDSpeedModeInfo, 0x20);
R_UNLESS(record != nullptr, erpt::ResultOutOfMemory());
/* Get the speed mode. */
fs::MmcSpeedMode speed_mode{};
const auto res = fs::GetMmcSpeedMode(std::addressof(speed_mode));
if (R_SUCCEEDED(res)) {
const char *speed_mode_name = "None";
switch (speed_mode) {
case fs::MmcSpeedMode_Identification:
speed_mode_name = "Identification";
break;
case fs::MmcSpeedMode_LegacySpeed:
speed_mode_name = "LegacySpeed";
break;
case fs::MmcSpeedMode_HighSpeed:
speed_mode_name = "HighSpeed";
break;
case fs::MmcSpeedMode_Hs200:
speed_mode_name = "Hs200";
break;
case fs::MmcSpeedMode_Hs400:
speed_mode_name = "Hs400";
break;
case fs::MmcSpeedMode_Unknown:
speed_mode_name = "Unknown";
break;
default:
speed_mode_name = "UnDefined";
break;
}
R_ABORT_UNLESS(record->Add(FieldId_NANDSpeedMode, speed_mode_name, std::strlen(speed_mode_name)));
} else {
/* Getting speed mode failed, so add the result. */
char res_str[0x20];
util::SNPrintf(res_str, sizeof(res_str), "0x%08X", res.GetValue());
R_ABORT_UNLESS(record->Add(FieldId_NANDSpeedMode, res_str, std::strlen(res_str)));
}
/* Submit the record. */
R_ABORT_UNLESS(Context::SubmitContextRecord(std::move(record)));
}
/* Submit the mmc extended csd. */
{
u8 mmc_csd[fs::MmcExtendedCsdSize] = {};
if (R_SUCCEEDED(fs::GetMmcExtendedCsd(mmc_csd, sizeof(mmc_csd)))) {
/* Create a record. */
auto record = std::make_unique<ContextRecord>(CategoryId_NANDExtendedCsd, 0);
R_UNLESS(record != nullptr, erpt::ResultOutOfMemory());
/* Add fields from the csd. */
R_ABORT_UNLESS(record->Add(FieldId_NANDPreEolInfo, static_cast<u32>(mmc_csd[fs::MmcExtendedCsdOffsetReEolInfo])));
R_ABORT_UNLESS(record->Add(FieldId_NANDDeviceLifeTimeEstTypA, static_cast<u32>(mmc_csd[fs::MmcExtendedCsdOffsetDeviceLifeTimeEstTypA])));
R_ABORT_UNLESS(record->Add(FieldId_NANDDeviceLifeTimeEstTypB, static_cast<u32>(mmc_csd[fs::MmcExtendedCsdOffsetDeviceLifeTimeEstTypB])));
/* Submit the record. */
R_ABORT_UNLESS(Context::SubmitContextRecord(std::move(record)));
}
}
/* Submit the mmc patrol count. */
{
u32 count = 0;
if (R_SUCCEEDED(fs::GetMmcPatrolCount(std::addressof(count)))) {
/* Create a record. */
auto record = std::make_unique<ContextRecord>(CategoryId_NANDPatrolInfo, 0);
R_UNLESS(record != nullptr, erpt::ResultOutOfMemory());
/* Add the count. */
R_ABORT_UNLESS(record->Add(FieldId_NANDPatrolCount, count));
/* Submit the record. */
R_ABORT_UNLESS(Context::SubmitContextRecord(std::move(record)));
}
}
R_SUCCEED();
}
Result SubmitMmcErrorInfo() {
/* Get the mmc error info. */
fs::StorageErrorInfo sei = {};
char log_buffer[erpt::ArrayBufferSizeDefault] = {};
size_t log_size = 0;
if (R_SUCCEEDED(fs::GetAndClearMmcErrorInfo(std::addressof(sei), std::addressof(log_size), log_buffer, sizeof(log_buffer)))) {
/* Submit the error info. */
{
/* Create a record. */
auto record = std::make_unique<ContextRecord>(CategoryId_NANDErrorInfo, 0);
R_UNLESS(record != nullptr, erpt::ResultOutOfMemory());
/* Add fields. */
R_ABORT_UNLESS(record->Add(FieldId_NANDNumActivationFailures, sei.num_activation_failures));
R_ABORT_UNLESS(record->Add(FieldId_NANDNumActivationErrorCorrections, sei.num_activation_error_corrections));
R_ABORT_UNLESS(record->Add(FieldId_NANDNumReadWriteFailures, sei.num_read_write_failures));
R_ABORT_UNLESS(record->Add(FieldId_NANDNumReadWriteErrorCorrections, sei.num_read_write_error_corrections));
/* Submit the record. */
R_ABORT_UNLESS(Context::SubmitContextRecord(std::move(record)));
}
/* If we have a log, submit it. */
if (log_size > 0) {
/* Create a record. */
auto record = std::make_unique<ContextRecord>(CategoryId_NANDDriverLog, log_size);
R_UNLESS(record != nullptr, erpt::ResultOutOfMemory());
/* Add fields. */
R_ABORT_UNLESS(record->Add(FieldId_NANDErrorLog, log_buffer, log_size));
/* Submit the record. */
R_ABORT_UNLESS(Context::SubmitContextRecord(std::move(record)));
}
}
R_SUCCEED();
}
Result SubmitSdCardDetailInfo() {
/* Submit the sd card cid. */
{
u8 sd_cid[fs::SdCardCidSize] = {};
if (R_SUCCEEDED(fs::GetSdCardCid(sd_cid, sizeof(sd_cid)))) {
/* Clear the serial number from the cid. */
fs::ClearSdCardCidSerialNumber(sd_cid);
/* Create a record. */
auto record = std::make_unique<ContextRecord>(CategoryId_MicroSDTypeInfo, sizeof(sd_cid));
R_UNLESS(record != nullptr, erpt::ResultOutOfMemory());
/* Add the cid. */
R_ABORT_UNLESS(record->Add(FieldId_MicroSDType, sd_cid, sizeof(sd_cid)));
/* Submit the record. */
R_ABORT_UNLESS(Context::SubmitContextRecord(std::move(record)));
}
}
/* Submit the sd card speed mode. */
{
/* Create a record. */
auto record = std::make_unique<ContextRecord>(CategoryId_MicroSDSpeedModeInfo, 0x20);
R_UNLESS(record != nullptr, erpt::ResultOutOfMemory());
/* Get the speed mode. */
fs::SdCardSpeedMode speed_mode{};
const auto res = fs::GetSdCardSpeedMode(std::addressof(speed_mode));
if (R_SUCCEEDED(res)) {
const char *speed_mode_name = "None";
switch (speed_mode) {
case fs::SdCardSpeedMode_Identification:
speed_mode_name = "Identification";
break;
case fs::SdCardSpeedMode_DefaultSpeed:
speed_mode_name = "DefaultSpeed";
break;
case fs::SdCardSpeedMode_HighSpeed:
speed_mode_name = "HighSpeed";
break;
case fs::SdCardSpeedMode_Sdr12:
speed_mode_name = "Sdr12";
break;
case fs::SdCardSpeedMode_Sdr25:
speed_mode_name = "Sdr25";
break;
case fs::SdCardSpeedMode_Sdr50:
speed_mode_name = "Sdr50";
break;
case fs::SdCardSpeedMode_Sdr104:
speed_mode_name = "Sdr104";
break;
case fs::SdCardSpeedMode_Ddr50:
speed_mode_name = "Ddr50";
break;
case fs::SdCardSpeedMode_Unknown:
speed_mode_name = "Unknown";
break;
default:
speed_mode_name = "UnDefined";
break;
}
R_ABORT_UNLESS(record->Add(FieldId_MicroSDSpeedMode, speed_mode_name, std::strlen(speed_mode_name)));
} else {
/* Getting speed mode failed, so add the result. */
char res_str[0x20];
util::SNPrintf(res_str, sizeof(res_str), "0x%08X", res.GetValue());
R_ABORT_UNLESS(record->Add(FieldId_MicroSDSpeedMode, res_str, std::strlen(res_str)));
}
/* Submit the record. */
R_ABORT_UNLESS(Context::SubmitContextRecord(std::move(record)));
}
/* Submit the area sizes. */
{
s64 user_area_size = 0;
s64 prot_area_size = 0;
const Result res_user = fs::GetSdCardUserAreaSize(std::addressof(user_area_size));
const Result res_prot = fs::GetSdCardProtectedAreaSize(std::addressof(prot_area_size));
if (R_SUCCEEDED(res_user) || R_SUCCEEDED(res_prot)) {
/* Create a record. */
auto record = std::make_unique<ContextRecord>(CategoryId_SdCardSizeSpec, 0);
R_UNLESS(record != nullptr, erpt::ResultOutOfMemory());
/* Add sizes. */
if (R_SUCCEEDED(res_user)) {
R_ABORT_UNLESS(record->Add(FieldId_SdCardUserAreaSize, user_area_size));
}
if (R_SUCCEEDED(res_prot)) {
R_ABORT_UNLESS(record->Add(FieldId_SdCardProtectedAreaSize, prot_area_size));
}
/* Submit the record. */
R_ABORT_UNLESS(Context::SubmitContextRecord(std::move(record)));
}
}
R_SUCCEED();
}
Result SubmitSdCardErrorInfo() {
/* Get the sd card error info. */
fs::StorageErrorInfo sei = {};
char log_buffer[erpt::ArrayBufferSizeDefault] = {};
size_t log_size = 0;
if (R_SUCCEEDED(fs::GetAndClearSdCardErrorInfo(std::addressof(sei), std::addressof(log_size), log_buffer, sizeof(log_buffer)))) {
/* Submit the error info. */
{
/* Create a record. */
auto record = std::make_unique<ContextRecord>(CategoryId_SdCardErrorInfo, 0);
R_UNLESS(record != nullptr, erpt::ResultOutOfMemory());
/* Add fields. */
R_ABORT_UNLESS(record->Add(FieldId_SdCardNumActivationFailures, sei.num_activation_failures));
R_ABORT_UNLESS(record->Add(FieldId_SdCardNumActivationErrorCorrections, sei.num_activation_error_corrections));
R_ABORT_UNLESS(record->Add(FieldId_SdCardNumReadWriteFailures, sei.num_read_write_failures));
R_ABORT_UNLESS(record->Add(FieldId_SdCardNumReadWriteErrorCorrections, sei.num_read_write_error_corrections));
/* Submit the record. */
R_ABORT_UNLESS(Context::SubmitContextRecord(std::move(record)));
}
/* If we have a log, submit it. */
if (log_size > 0) {
/* Create a record. */
auto record = std::make_unique<ContextRecord>(CategoryId_SdCardDriverLog, log_size);
R_UNLESS(record != nullptr, erpt::ResultOutOfMemory());
/* Add fields. */
R_ABORT_UNLESS(record->Add(FieldId_SdCardErrorLog, log_buffer, log_size));
/* Submit the record. */
R_ABORT_UNLESS(Context::SubmitContextRecord(std::move(record)));
}
}
R_SUCCEED();
}
Result SubmitGameCardDetailInfo() {
/* Create a record. */
auto record = std::make_unique<ContextRecord>(CategoryId_GameCardCIDInfo, fs::GameCardCidSize + fs::GameCardDeviceIdSize);
R_UNLESS(record != nullptr, erpt::ResultOutOfMemory());
/* Add the game card cid. */
{
u8 gc_cid[fs::GameCardCidSize] = {};
if (fs::IsGameCardInserted() && R_SUCCEEDED(fs::GetGameCardCid(gc_cid, sizeof(gc_cid)))) {
/* Add the cid. */
R_ABORT_UNLESS(record->Add(FieldId_GameCardCID, gc_cid, sizeof(gc_cid)));
}
}
/* Add the game card device id. */
{
u8 gc_device_id[fs::GameCardDeviceIdSize] = {};
if (fs::IsGameCardInserted() && R_SUCCEEDED(fs::GetGameCardDeviceId(gc_device_id, sizeof(gc_device_id)))) {
/* Add the cid. */
R_ABORT_UNLESS(record->Add(FieldId_GameCardDeviceId, gc_device_id, sizeof(gc_device_id)));
}
}
/* Submit the record. */
R_ABORT_UNLESS(Context::SubmitContextRecord(std::move(record)));
R_SUCCEED();
}
Result SubmitGameCardErrorInfo() {
/* Get the game card error info. */
fs::GameCardErrorReportInfo ei = {};
if (R_SUCCEEDED(fs::GetGameCardErrorReportInfo(std::addressof(ei)))) {
/* Create a record. */
auto record = std::make_unique<ContextRecord>(CategoryId_GameCardErrorInfo, 0);
R_UNLESS(record != nullptr, erpt::ResultOutOfMemory());
/* Add fields. */
R_ABORT_UNLESS(record->Add(FieldId_GameCardCrcErrorCount, static_cast<u32>(ei.game_card_crc_error_num)));
R_ABORT_UNLESS(record->Add(FieldId_GameCardAsicCrcErrorCount, static_cast<u32>(ei.asic_crc_error_num)));
R_ABORT_UNLESS(record->Add(FieldId_GameCardRefreshCount, static_cast<u32>(ei.refresh_num)));
R_ABORT_UNLESS(record->Add(FieldId_GameCardReadRetryCount, static_cast<u32>(ei.retry_limit_out_num)));
R_ABORT_UNLESS(record->Add(FieldId_GameCardTimeoutRetryErrorCount, static_cast<u32>(ei.timeout_retry_num)));
R_ABORT_UNLESS(record->Add(FieldId_GameCardInsertionCount, static_cast<u32>(ei.insertion_count)));
R_ABORT_UNLESS(record->Add(FieldId_GameCardRemovalCount, static_cast<u32>(ei.removal_count)));
R_ABORT_UNLESS(record->Add(FieldId_GameCardAsicInitializeCount, ei.initialize_count));
R_ABORT_UNLESS(record->Add(FieldId_GameCardAsicReinitializeCount, ei.asic_reinitialize_num));
R_ABORT_UNLESS(record->Add(FieldId_GameCardAsicReinitializeFailureCount, ei.asic_reinitialize_failure_num));
R_ABORT_UNLESS(record->Add(FieldId_GameCardAsicReinitializeFailureDetail, ei.asic_reinitialize_failure_detail));
R_ABORT_UNLESS(record->Add(FieldId_GameCardRefreshSuccessCount, ei.refresh_succeeded_count));
R_ABORT_UNLESS(record->Add(FieldId_GameCardAwakenCount, ei.awaken_count));
R_ABORT_UNLESS(record->Add(FieldId_GameCardAwakenFailureCount, ei.awaken_failure_num));
R_ABORT_UNLESS(record->Add(FieldId_GameCardReadCountFromInsert, ei.read_count_from_insert));
R_ABORT_UNLESS(record->Add(FieldId_GameCardReadCountFromAwaken, ei.read_count_from_awaken));
R_ABORT_UNLESS(record->Add(FieldId_GameCardLastReadErrorPageAddress, ei.last_read_error_page_address));
R_ABORT_UNLESS(record->Add(FieldId_GameCardLastReadErrorPageCount, ei.last_read_error_page_count));
/* Submit the record. */
R_ABORT_UNLESS(Context::SubmitContextRecord(std::move(record)));
}
R_SUCCEED();
}
Result SubmitFileSystemErrorInfo() {
/* Get the fsp error info. */
fs::FileSystemProxyErrorInfo ei = {};
if (R_SUCCEEDED(fs::GetAndClearFileSystemProxyErrorInfo(std::addressof(ei)))) {
/* Submit FsProxyErrorInfo. */
{
/* Create a record. */
auto record = std::make_unique<ContextRecord>(CategoryId_FsProxyErrorInfo, fat::FatErrorNameMaxLength);
R_UNLESS(record != nullptr, erpt::ResultOutOfMemory());
/* Add fields. */
R_ABORT_UNLESS(record->Add(FieldId_FsRemountForDataCorruptCount, ei.rom_fs_remount_for_data_corruption_count));
R_ABORT_UNLESS(record->Add(FieldId_FsRemountForDataCorruptRetryOutCount, ei.rom_fs_unrecoverable_data_corruption_by_remount_count));
R_ABORT_UNLESS(record->Add(FieldId_FatFsError, ei.fat_fs_error.error));
R_ABORT_UNLESS(record->Add(FieldId_FatFsExtraError, ei.fat_fs_error.extra_error));
R_ABORT_UNLESS(record->Add(FieldId_FatFsErrorDrive, ei.fat_fs_error.drive_id));
R_ABORT_UNLESS(record->Add(FieldId_FatFsErrorName, ei.fat_fs_error.name, fat::FatErrorNameMaxLength));
R_ABORT_UNLESS(record->Add(FieldId_FsRecoveredByInvalidateCacheCount, ei.rom_fs_recovered_by_invalidate_cache_count));
R_ABORT_UNLESS(record->Add(FieldId_FsSaveDataIndexCount, ei.save_data_index_count));
R_ABORT_UNLESS(record->Add(FieldId_FatFsBisSystemFilePeakOpenCount, ei.bis_system_fat_report_info_1.open_file_peak_count));
R_ABORT_UNLESS(record->Add(FieldId_FatFsBisSystemDirectoryPeakOpenCount, ei.bis_system_fat_report_info_1.open_directory_peak_count));
R_ABORT_UNLESS(record->Add(FieldId_FatFsBisUserFilePeakOpenCount, ei.bis_user_fat_report_info_1.open_file_peak_count));
R_ABORT_UNLESS(record->Add(FieldId_FatFsBisUserDirectoryPeakOpenCount, ei.bis_user_fat_report_info_1.open_directory_peak_count));
R_ABORT_UNLESS(record->Add(FieldId_FatFsSdCardFilePeakOpenCount, ei.sd_card_fat_report_info_1.open_file_peak_count));
R_ABORT_UNLESS(record->Add(FieldId_FatFsSdCardDirectoryPeakOpenCount, ei.sd_card_fat_report_info_1.open_directory_peak_count));
R_ABORT_UNLESS(record->Add(FieldId_FatFsBisSystemUniqueFileEntryPeakOpenCount, ei.bis_system_fat_report_info_2.open_unique_file_entry_peak_count));
R_ABORT_UNLESS(record->Add(FieldId_FatFsBisSystemUniqueDirectoryEntryPeakOpenCount, ei.bis_system_fat_report_info_2.open_unique_directory_entry_peak_count));
R_ABORT_UNLESS(record->Add(FieldId_FatFsBisUserUniqueFileEntryPeakOpenCount, ei.bis_user_fat_report_info_2.open_unique_file_entry_peak_count));
R_ABORT_UNLESS(record->Add(FieldId_FatFsBisUserUniqueDirectoryEntryPeakOpenCount, ei.bis_user_fat_report_info_2.open_unique_directory_entry_peak_count));
R_ABORT_UNLESS(record->Add(FieldId_FatFsSdCardUniqueFileEntryPeakOpenCount, ei.sd_card_fat_report_info_2.open_unique_file_entry_peak_count));
R_ABORT_UNLESS(record->Add(FieldId_FatFsSdCardUniqueDirectoryEntryPeakOpenCount, ei.sd_card_fat_report_info_2.open_unique_directory_entry_peak_count));
/* Submit the record. */
R_ABORT_UNLESS(Context::SubmitContextRecord(std::move(record)));
}
/* Submit FsProxyErrorInfo2. */
{
/* Create a record. */
auto record = std::make_unique<ContextRecord>(CategoryId_FsProxyErrorInfo2, 0);
R_UNLESS(record != nullptr, erpt::ResultOutOfMemory());
/* Add fields. */
R_ABORT_UNLESS(record->Add(FieldId_FsDeepRetryStartCount, ei.rom_fs_deep_retry_start_count));
R_ABORT_UNLESS(record->Add(FieldId_FsUnrecoverableByGameCardAccessFailedCount, ei.rom_fs_unrecoverable_by_game_card_access_failed_count));
R_ABORT_UNLESS(record->Add(FieldId_FatFsBisSystemFatSafeControlResult, static_cast<u8>(ei.bis_system_fat_safe_info.result)));
R_ABORT_UNLESS(record->Add(FieldId_FatFsBisSystemFatErrorNumber, ei.bis_system_fat_safe_info.error_number));
R_ABORT_UNLESS(record->Add(FieldId_FatFsBisSystemFatSafeErrorNumber, ei.bis_system_fat_safe_info.safe_error_number));
R_ABORT_UNLESS(record->Add(FieldId_FatFsBisUserFatSafeControlResult, static_cast<u8>(ei.bis_user_fat_safe_info.result)));
R_ABORT_UNLESS(record->Add(FieldId_FatFsBisUserFatErrorNumber, ei.bis_user_fat_safe_info.error_number));
R_ABORT_UNLESS(record->Add(FieldId_FatFsBisUserFatSafeErrorNumber, ei.bis_user_fat_safe_info.safe_error_number));
/* Submit the record. */
R_ABORT_UNLESS(Context::SubmitContextRecord(std::move(record)));
}
}
R_SUCCEED();
}
Result SubmitMemoryReportInfo() {
/* Get the memory report info. */
fs::MemoryReportInfo mri = {};
if (R_SUCCEEDED(fs::GetAndClearMemoryReportInfo(std::addressof(mri)))) {
/* Create a record. */
auto record = std::make_unique<ContextRecord>(CategoryId_FsMemoryInfo, 0);
R_UNLESS(record != nullptr, erpt::ResultOutOfMemory());
/* Add fields. */
R_ABORT_UNLESS(record->Add(FieldId_FsPooledBufferPeakFreeSize, mri.pooled_buffer_peak_free_size));
R_ABORT_UNLESS(record->Add(FieldId_FsPooledBufferRetriedCount, mri.pooled_buffer_retried_count));
R_ABORT_UNLESS(record->Add(FieldId_FsPooledBufferReduceAllocationCount, mri.pooled_buffer_reduce_allocation_count));
R_ABORT_UNLESS(record->Add(FieldId_FsBufferManagerPeakFreeSize, mri.buffer_manager_peak_free_size));
R_ABORT_UNLESS(record->Add(FieldId_FsBufferManagerRetriedCount, mri.buffer_manager_retried_count));
R_ABORT_UNLESS(record->Add(FieldId_FsExpHeapPeakFreeSize, mri.exp_heap_peak_free_size));
R_ABORT_UNLESS(record->Add(FieldId_FsBufferPoolPeakFreeSize, mri.buffer_pool_peak_free_size));
R_ABORT_UNLESS(record->Add(FieldId_FsPatrolReadAllocateBufferSuccessCount, mri.patrol_read_allocate_buffer_success_count));
R_ABORT_UNLESS(record->Add(FieldId_FsPatrolReadAllocateBufferFailureCount, mri.patrol_read_allocate_buffer_failure_count));
R_ABORT_UNLESS(record->Add(FieldId_FsBufferManagerPeakTotalAllocatableSize, mri.buffer_manager_peak_total_allocatable_size));
R_ABORT_UNLESS(record->Add(FieldId_FsBufferPoolMaxAllocateSize, mri.buffer_pool_max_allocate_size));
R_ABORT_UNLESS(record->Add(FieldId_FsPooledBufferFailedIdealAllocationCountOnAsyncAccess, mri.pooled_buffer_failed_ideal_allocation_count_on_async_access));
/* Submit the record. */
R_ABORT_UNLESS(Context::SubmitContextRecord(std::move(record)));
}
R_SUCCEED();
}
}
Result SubmitFsInfo() {
/* Temporarily disable auto-abort. */
fs::ScopedAutoAbortDisabler aad;
/* Submit various FS info. */
R_TRY(SubmitMmcDetailInfo());
R_TRY(SubmitMmcErrorInfo());
R_TRY(SubmitSdCardDetailInfo());
R_TRY(SubmitSdCardErrorInfo());
R_TRY(SubmitGameCardDetailInfo());
R_TRY(SubmitGameCardErrorInfo());
R_TRY(SubmitFileSystemErrorInfo());
R_TRY(SubmitMemoryReportInfo());
R_SUCCEED();
}
}
| 26,573
|
C++
|
.cpp
| 414
| 46.347826
| 177
| 0.561709
|
Atmosphere-NX/Atmosphere
| 14,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,814
|
erpt_srv_attachment_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/erpt/srv/erpt_srv_attachment_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 "erpt_srv_attachment_impl.hpp"
#include "erpt_srv_attachment.hpp"
namespace ams::erpt::srv {
AttachmentImpl::AttachmentImpl() : m_attachment(nullptr) {
/* ... */
}
AttachmentImpl::~AttachmentImpl() {
R_ABORT_UNLESS(this->Close());
}
Result AttachmentImpl::Open(const AttachmentId &attachment_id) {
R_UNLESS(m_attachment == nullptr, erpt::ResultAlreadyInitialized());
JournalRecord<AttachmentInfo> *record = Journal::Retrieve(attachment_id);
R_UNLESS(record != nullptr, erpt::ResultNotFound());
m_attachment = new Attachment(record);
R_UNLESS(m_attachment != nullptr, erpt::ResultOutOfMemory());
auto attachment_guard = SCOPE_GUARD { delete m_attachment; m_attachment = nullptr; };
R_TRY(m_attachment->Open(AttachmentOpenType_Read));
attachment_guard.Cancel();
R_SUCCEED();
}
Result AttachmentImpl::Read(ams::sf::Out<u32> out_count, const ams::sf::OutBuffer &out_buffer) {
R_UNLESS(m_attachment != nullptr, erpt::ResultNotInitialized());
R_RETURN(m_attachment->Read(out_count.GetPointer(), static_cast<u8 *>(out_buffer.GetPointer()), static_cast<u32>(out_buffer.GetSize())));
}
Result AttachmentImpl::SetFlags(AttachmentFlagSet flags) {
R_UNLESS(m_attachment != nullptr, erpt::ResultNotInitialized());
R_RETURN(m_attachment->SetFlags(flags));
}
Result AttachmentImpl::GetFlags(ams::sf::Out<AttachmentFlagSet> out) {
R_UNLESS(m_attachment != nullptr, erpt::ResultNotInitialized());
R_RETURN(m_attachment->GetFlags(out.GetPointer()));
}
Result AttachmentImpl::Close() {
if (m_attachment != nullptr) {
m_attachment->Close();
delete m_attachment;
m_attachment = nullptr;
}
R_SUCCEED();
}
Result AttachmentImpl::GetSize(ams::sf::Out<s64> out) {
R_UNLESS(m_attachment != nullptr, erpt::ResultNotInitialized());
R_RETURN(m_attachment->GetSize(out.GetPointer()));
}
}
| 2,730
|
C++
|
.cpp
| 61
| 38.704918
| 145
| 0.680121
|
Atmosphere-NX/Atmosphere
| 14,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,815
|
erpt_srv_report.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/erpt/srv/erpt_srv_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 "erpt_srv_report_impl.hpp"
#include "erpt_srv_report.hpp"
namespace ams::erpt::srv {
ReportFileName Report::FileName(ReportId report_id, bool redirect_to_sd) {
ReportFileName report_name;
util::SNPrintf(report_name.name, sizeof(report_name.name),
"%s:/%08x-%04x-%04x-%02x%02x-%04x%08x",
(redirect_to_sd ? ReportOnSdStoragePath : ReportStoragePath),
report_id.uuid_data.time_low,
report_id.uuid_data.time_mid,
report_id.uuid_data.time_high_and_version,
report_id.uuid_data.clock_high,
report_id.uuid_data.clock_low,
static_cast<u32>((report_id.uuid_data.node >> BITSIZEOF(u32)) & 0x0000FFFF),
static_cast<u32>((report_id.uuid_data.node >> 0) & 0xFFFFFFFF));
return report_name;
}
Report::Report(JournalRecord<ReportInfo> *r, bool redirect_to_sd) : m_record(r), m_redirect_to_sd_card(redirect_to_sd) {
m_record->AddReference();
}
Report::~Report() {
this->CloseStream();
if (m_record->RemoveReference()) {
this->DeleteStream(this->FileName().name);
delete m_record;
}
}
ReportFileName Report::FileName() const {
return FileName(m_record->m_info.id, m_redirect_to_sd_card);
}
Result Report::Open(ReportOpenType type) {
switch (type) {
case ReportOpenType_Create: R_RETURN(this->OpenStream(this->FileName().name, StreamMode_Write, ReportStreamBufferSize));
case ReportOpenType_Read: R_RETURN(this->OpenStream(this->FileName().name, StreamMode_Read, ReportStreamBufferSize));
default: R_THROW(erpt::ResultInvalidArgument());
}
}
Result Report::Read(u32 *out_read_count, u8 *dst, u32 dst_size) {
R_RETURN(this->ReadStream(out_read_count, dst, dst_size));
}
Result Report::Delete() {
R_RETURN(this->DeleteStream(this->FileName().name));
}
void Report::Close() {
return this->CloseStream();
}
Result Report::GetFlags(ReportFlagSet *out) const {
*out = m_record->m_info.flags;
R_SUCCEED();
}
Result Report::SetFlags(ReportFlagSet flags) {
if (((~m_record->m_info.flags) & flags).IsAnySet()) {
m_record->m_info.flags |= flags;
R_RETURN(Journal::Commit());
}
R_SUCCEED();
}
Result Report::GetSize(s64 *out) const {
R_RETURN(this->GetStreamSize(out));
}
}
| 3,286
|
C++
|
.cpp
| 77
| 34.545455
| 132
| 0.622966
|
Atmosphere-NX/Atmosphere
| 14,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,816
|
erpt_srv_journal_for_reports.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/erpt/srv/erpt_srv_journal_for_reports.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 "erpt_srv_journal.hpp"
#include "erpt_srv_report.hpp"
namespace ams::erpt::srv {
constinit util::IntrusiveListBaseTraits<JournalRecord<ReportInfo>>::ListType JournalForReports::s_record_list;
constinit u32 JournalForReports::s_record_count = 0;
constinit u32 JournalForReports::s_record_count_by_type[ReportType_Count] = {};
constinit u32 JournalForReports::s_used_storage = 0;
void JournalForReports::CleanupReports() {
for (auto it = s_record_list.begin(); it != s_record_list.end(); /* ... */) {
auto *record = std::addressof(*it);
it = s_record_list.erase(s_record_list.iterator_to(*record));
if (record->RemoveReference()) {
Stream::DeleteStream(Report::FileName(record->m_info.id, false).name);
delete record;
}
}
AMS_ASSERT(s_record_list.empty());
s_record_count = 0;
s_used_storage = 0;
std::memset(s_record_count_by_type, 0, sizeof(s_record_count_by_type));
}
Result JournalForReports::CommitJournal(Stream *stream) {
R_TRY(stream->WriteStream(reinterpret_cast<const u8 *>(std::addressof(s_record_count)), sizeof(s_record_count)));
for (auto it = s_record_list.crbegin(); it != s_record_list.crend(); it++) {
R_TRY(stream->WriteStream(reinterpret_cast<const u8 *>(std::addressof(it->m_info)), sizeof(it->m_info)));
}
R_SUCCEED();
}
void JournalForReports::EraseReportImpl(JournalRecord<ReportInfo> *record, bool increment_count, bool force_delete_attachments) {
/* Erase from the list. */
s_record_list.erase(s_record_list.iterator_to(*record));
/* Update storage tracking counts. */
--s_record_count;
--s_record_count_by_type[record->m_info.type];
s_used_storage -= static_cast<u32>(record->m_info.report_size);
/* If we should increment count, do so. */
if (increment_count) {
JournalForMeta::IncrementCount(record->m_info.flags.Test<ReportFlag::Transmitted>(), record->m_info.type);
}
/* Delete any attachments. */
if (force_delete_attachments || record->m_info.flags.Test<ReportFlag::HasAttachment>()) {
JournalForAttachments::DeleteAttachments(record->m_info.id);
}
/* Delete the object, if we should. */
if (record->RemoveReference()) {
Stream::DeleteStream(Report::FileName(record->m_info.id, false).name);
delete record;
}
}
Result JournalForReports::DeleteReport(ReportId report_id) {
for (auto it = s_record_list.begin(); it != s_record_list.end(); it++) {
auto *record = std::addressof(*it);
if (record->m_info.id == report_id) {
EraseReportImpl(record, false, false);
R_SUCCEED();
}
}
R_THROW(erpt::ResultInvalidArgument());
}
Result JournalForReports::DeleteReportWithAttachments() {
for (auto it = s_record_list.rbegin(); it != s_record_list.rend(); it++) {
auto *record = std::addressof(*it);
if (record->m_info.flags.Test<ReportFlag::HasAttachment>()) {
EraseReportImpl(record, true, true);
R_SUCCEED();
}
}
R_THROW(erpt::ResultNotFound());
}
s64 JournalForReports::GetMaxReportSize() {
s64 max_size = 0;
for (auto it = s_record_list.begin(); it != s_record_list.end(); it++) {
max_size = std::max(max_size, it->m_info.report_size);
}
return max_size;
}
Result JournalForReports::GetReportList(ReportList *out, ReportType type_filter) {
u32 count = 0;
for (auto it = s_record_list.cbegin(); it != s_record_list.cend() && count < util::size(out->reports); it++) {
if (type_filter == ReportType_Any || type_filter == it->m_info.type) {
out->reports[count++] = it->m_info;
}
}
out->report_count = count;
R_SUCCEED();
}
u32 JournalForReports::GetStoredReportCount(ReportType type) {
if (ReportType_Start <= type && type < ReportType_End) {
return s_record_count_by_type[type];
} else {
return 0;
}
}
u32 JournalForReports::GetUsedStorage() {
return s_used_storage;
}
Result JournalForReports::RestoreJournal(Stream *stream) {
/* Clear the used storage. */
s_used_storage = 0;
/* Read the count from storage. */
u32 read_size;
u32 count;
R_TRY(stream->ReadStream(std::addressof(read_size), reinterpret_cast<u8 *>(std::addressof(count)), sizeof(count)));
R_UNLESS(read_size == sizeof(count), erpt::ResultCorruptJournal());
R_UNLESS(count <= ReportCountMax, erpt::ResultCorruptJournal());
/* If we fail in the middle of reading reports, we want to do cleanup. */
auto cleanup_guard = SCOPE_GUARD { CleanupReports(); };
ReportInfo info;
for (u32 i = 0; i < count; i++) {
R_TRY(stream->ReadStream(std::addressof(read_size), reinterpret_cast<u8 *>(std::addressof(info)), sizeof(info)));
R_UNLESS(read_size == sizeof(info), erpt::ResultCorruptJournal());
R_UNLESS(ReportType_Start <= info.type, erpt::ResultCorruptJournal());
R_UNLESS(info.type < ReportType_End, erpt::ResultCorruptJournal());
auto *record = new JournalRecord<ReportInfo>(info);
R_UNLESS(record != nullptr, erpt::ResultOutOfMemory());
/* NOTE: Nintendo does not ensure that the newly allocated record does not leak in the failure case. */
/* We will ensure it is freed if we early error. */
auto record_guard = SCOPE_GUARD { delete record; };
if (record->m_info.report_size == 0) {
R_UNLESS(R_SUCCEEDED(Stream::GetStreamSize(std::addressof(record->m_info.report_size), Report::FileName(record->m_info.id, false).name)), erpt::ResultCorruptJournal());
}
record_guard.Cancel();
/* NOTE: Nintendo does not check the result of storing the new record... */
StoreRecord(record);
}
cleanup_guard.Cancel();
R_SUCCEED();
}
JournalRecord<ReportInfo> *JournalForReports::RetrieveRecord(ReportId report_id) {
for (auto it = s_record_list.begin(); it != s_record_list.end(); it++) {
if (auto *record = std::addressof(*it); record->m_info.id == report_id) {
return record;
}
}
return nullptr;
}
Result JournalForReports::StoreRecord(JournalRecord<ReportInfo> *record) {
/* Check if the record already exists. */
for (auto it = s_record_list.begin(); it != s_record_list.end(); it++) {
R_UNLESS(it->m_info.id != record->m_info.id, erpt::ResultAlreadyExists());
}
/* Delete an older report if we need to. */
if (s_record_count >= ReportCountMax) {
/* Nintendo deletes the oldest report from the type with the most reports. */
/* This is an approximation of FIFO. */
ReportType most_used_type = record->m_info.type;
u32 most_used_count = s_record_count_by_type[most_used_type];
for (int i = ReportType_Start; i < ReportType_End; i++) {
if (s_record_count_by_type[i] > most_used_count) {
most_used_type = static_cast<ReportType>(i);
most_used_count = s_record_count_by_type[i];
}
}
for (auto it = s_record_list.rbegin(); it != s_record_list.rend(); it++) {
if (it->m_info.type != most_used_type) {
continue;
}
EraseReportImpl(std::addressof(*it), true, false);
break;
}
}
AMS_ASSERT(s_record_count < ReportCountMax);
/* Add a reference to the new record. */
record->AddReference();
/* Push the record into the list. */
s_record_list.push_front(*record);
s_record_count++;
s_record_count_by_type[record->m_info.type]++;
s_used_storage += static_cast<u32>(record->m_info.report_size);
R_SUCCEED();
}
}
| 9,062
|
C++
|
.cpp
| 188
| 38.574468
| 184
| 0.60154
|
Atmosphere-NX/Atmosphere
| 14,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,817
|
erpt_srv_main.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/erpt/srv/erpt_srv_main.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 "erpt_srv_allocator.hpp"
#include "erpt_srv_context_record.hpp"
#include "erpt_srv_context.hpp"
#include "erpt_srv_reporter.hpp"
#include "erpt_srv_journal.hpp"
#include "erpt_srv_service.hpp"
#include "erpt_srv_forced_shutdown.hpp"
namespace ams::erpt::srv {
constinit lmem::HeapHandle g_heap_handle;
constinit ams::sf::ExpHeapAllocator g_sf_allocator = {};
namespace {
constexpr fs::SystemSaveDataId SystemSaveDataId = 0x80000000000000D1;
constexpr u32 SystemSaveDataFlags = fs::SaveDataFlags_KeepAfterResettingSystemSaveDataWithoutUserSaveData;
constexpr s64 SystemSaveDataSize = 11_MB;
constexpr s64 SystemSaveDataJournalSize = 2720_KB;
constinit bool g_automatic_report_cleanup_enabled = true;
Result ExtendSystemSaveData() {
s64 cur_journal_size;
s64 cur_savedata_size;
R_TRY(fs::GetSaveDataJournalSize(std::addressof(cur_journal_size), SystemSaveDataId));
R_TRY(fs::GetSaveDataAvailableSize(std::addressof(cur_savedata_size), SystemSaveDataId));
if (cur_journal_size < SystemSaveDataJournalSize || cur_savedata_size < SystemSaveDataSize) {
if (hos::GetVersion() >= hos::Version_3_0_0) {
R_TRY(fs::ExtendSaveData(fs::SaveDataSpaceId::System, SystemSaveDataId, SystemSaveDataSize, SystemSaveDataJournalSize));
}
}
R_SUCCEED();
}
Result MountSystemSaveData() {
fs::DisableAutoSaveDataCreation();
/* Extend the system save data. */
/* NOTE: Nintendo does not check result of this. */
ExtendSystemSaveData();
R_TRY_CATCH(fs::MountSystemSaveData(ReportStoragePath, SystemSaveDataId)) {
R_CATCH(fs::ResultTargetNotFound) {
R_TRY(fs::CreateSystemSaveData(SystemSaveDataId, SystemSaveDataSize, SystemSaveDataJournalSize, SystemSaveDataFlags));
R_TRY(fs::MountSystemSaveData(ReportStoragePath, SystemSaveDataId));
}
} R_END_TRY_CATCH;
R_SUCCEED();
}
}
Result Initialize(u8 *mem, size_t mem_size) {
R_ABORT_UNLESS(time::Initialize());
g_heap_handle = lmem::CreateExpHeap(mem, mem_size, lmem::CreateOption_ThreadSafe);
AMS_ABORT_UNLESS(g_heap_handle != nullptr);
fs::InitializeForSystem();
fs::SetAllocator(Allocate, DeallocateWithSize);
fs::SetEnabledAutoAbort(false);
R_ABORT_UNLESS(fs::MountSdCardErrorReportDirectoryForAtmosphere(ReportOnSdStoragePath));
if (g_automatic_report_cleanup_enabled) {
constexpr s64 MinimumReportCountForCleanup = 1000;
s64 report_count = MinimumReportCountForCleanup;
fs::DirectoryHandle dir;
if (R_SUCCEEDED(fs::OpenDirectory(std::addressof(dir), ReportOnSdStorageRootDirectoryPath, fs::OpenDirectoryMode_All))) {
ON_SCOPE_EXIT { fs::CloseDirectory(dir); };
if (R_FAILED(fs::GetDirectoryEntryCount(std::addressof(report_count), dir))) {
report_count = MinimumReportCountForCleanup;
}
}
if (report_count >= MinimumReportCountForCleanup) {
fs::CleanDirectoryRecursively(ReportOnSdStorageRootDirectoryPath);
}
}
R_ABORT_UNLESS(MountSystemSaveData());
g_sf_allocator.Attach(g_heap_handle);
for (const auto category_id : CategoryIndexToCategoryIdMap) {
Context *ctx = new Context(category_id);
AMS_ABORT_UNLESS(ctx != nullptr);
}
Journal::Restore();
Reporter::UpdatePowerOnTime();
Reporter::UpdateAwakeTime();
R_SUCCEED();
}
Result InitializeAndStartService() {
/* Initialize forced shutdown detection. */
/* NOTE: Nintendo does not check error code here. */
InitializeForcedShutdownDetection();
R_RETURN(InitializeService());
}
Result SetSerialNumberAndOsVersion(const char *sn, u32 sn_len, const char *os, u32 os_len, const char *os_priv, u32 os_priv_len) {
R_RETURN(Reporter::SetSerialNumberAndOsVersion(sn, sn_len, os, os_len, os_priv, os_priv_len));
}
Result SetProductModel(const char *model, u32 model_len) {
/* NOTE: Nintendo does not check that this allocation succeeds. */
auto record = std::make_unique<ContextRecord>(CategoryId_ProductModelInfo);
R_UNLESS(record != nullptr, erpt::ResultOutOfMemory());
R_TRY(record->Add(FieldId_ProductModel, model, model_len));
R_TRY(Context::SubmitContextRecord(std::move(record)));
R_SUCCEED();
}
Result SetRegionSetting(const char *region, u32 region_len) {
/* NOTE: Nintendo does not check that this allocation succeeds. */
auto record = std::make_unique<ContextRecord>(CategoryId_RegionSettingInfo);
R_UNLESS(record != nullptr, erpt::ResultOutOfMemory());
R_TRY(record->Add(FieldId_RegionSetting, region, region_len));
R_TRY(Context::SubmitContextRecord(std::move(record)));
R_SUCCEED();
}
Result SetRedirectNewReportsToSdCard(bool redirect) {
Reporter::SetRedirectNewReportsToSdCard(redirect);
R_SUCCEED();
}
Result SetEnabledAutomaticReportCleanup(bool en) {
g_automatic_report_cleanup_enabled = en;
R_SUCCEED();
}
void Wait() {
/* Get the update event. */
os::Event *event = GetForcedShutdownUpdateEvent();
/* Forever wait, saving any updates. */
while (true) {
event->Wait();
event->Clear();
SaveForcedShutdownContext();
}
}
}
| 6,514
|
C++
|
.cpp
| 135
| 39.303704
| 140
| 0.656092
|
Atmosphere-NX/Atmosphere
| 14,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,818
|
erpt_srv_journal.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/erpt/srv/erpt_srv_journal.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 "erpt_srv_journal.hpp"
namespace ams::erpt::srv {
void Journal::CleanupAttachments() {
return JournalForAttachments::CleanupAttachments();
}
void Journal::CleanupReports() {
return JournalForReports::CleanupReports();
}
Result Journal::Commit() {
/* Open the stream. */
Stream stream;
R_TRY(stream.OpenStream(JournalFileName, StreamMode_Write, JournalStreamBufferSize));
/* Commit the reports. */
R_TRY(JournalForReports::CommitJournal(std::addressof(stream)));
/* Commit the meta. */
R_TRY(JournalForMeta::CommitJournal(std::addressof(stream)));
/* Commit the attachments. */
R_TRY(JournalForAttachments::CommitJournal(std::addressof(stream)));
/* Close and commit the stream. */
stream.CloseStream();
stream.CommitStream();
R_SUCCEED();
}
Result Journal::Delete(ReportId report_id) {
R_RETURN(JournalForReports::DeleteReport(report_id));
}
Result Journal::GetAttachmentList(AttachmentList *out, ReportId report_id) {
R_RETURN(JournalForAttachments::GetAttachmentList(out, report_id));
}
util::Uuid Journal::GetJournalId() {
return JournalForMeta::GetJournalId();
}
s64 Journal::GetMaxReportSize() {
return JournalForReports::GetMaxReportSize();
}
Result Journal::GetReportList(ReportList *out, ReportType type_filter) {
R_RETURN(JournalForReports::GetReportList(out, type_filter));
}
u32 Journal::GetStoredReportCount(ReportType type) {
return JournalForReports::GetStoredReportCount(type);
}
u32 Journal::GetTransmittedCount(ReportType type) {
return JournalForMeta::GetTransmittedCount(type);
}
u32 Journal::GetUntransmittedCount(ReportType type) {
return JournalForMeta::GetUntransmittedCount(type);
}
u32 Journal::GetUsedStorage() {
return JournalForReports::GetUsedStorage() + JournalForAttachments::GetUsedStorage();
}
Result Journal::Restore() {
/* Open the stream. */
Stream stream;
R_TRY(stream.OpenStream(JournalFileName, StreamMode_Read, JournalStreamBufferSize));
/* Restore the reports. */
R_TRY(JournalForReports::RestoreJournal(std::addressof(stream)));
/* Restore the meta. */
R_TRY(JournalForMeta::RestoreJournal(std::addressof(stream)));
/* Restore the attachments. */
R_TRY(JournalForAttachments::RestoreJournal(std::addressof(stream)));
R_SUCCEED();
}
JournalRecord<ReportInfo> *Journal::Retrieve(ReportId report_id) {
return JournalForReports::RetrieveRecord(report_id);
}
JournalRecord<AttachmentInfo> *Journal::Retrieve(AttachmentId attachment_id) {
return JournalForAttachments::RetrieveRecord(attachment_id);
}
Result Journal::Store(JournalRecord<ReportInfo> *record) {
R_RETURN(JournalForReports::StoreRecord(record));
}
Result Journal::Store(JournalRecord<AttachmentInfo> *record) {
R_RETURN(JournalForAttachments::StoreRecord(record));
}
}
| 3,810
|
C++
|
.cpp
| 91
| 35.571429
| 93
| 0.702249
|
Atmosphere-NX/Atmosphere
| 14,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,819
|
erpt_srv_context_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/erpt/srv/erpt_srv_context_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 "erpt_srv_context_impl.hpp"
#include "erpt_srv_manager_impl.hpp"
#include "erpt_srv_context.hpp"
#include "erpt_srv_reporter.hpp"
#include "erpt_srv_journal.hpp"
#include "erpt_srv_forced_shutdown.hpp"
namespace ams::erpt::srv {
Result ContextImpl::SubmitContext(const ams::sf::InBuffer &ctx_buffer, const ams::sf::InBuffer &data_buffer) {
const ContextEntry *ctx = reinterpret_cast<const ContextEntry *>( ctx_buffer.GetPointer());
const u8 *data = reinterpret_cast<const u8 *>(data_buffer.GetPointer());
const u32 ctx_size = static_cast<u32>(ctx_buffer.GetSize());
const u32 data_size = static_cast<u32>(data_buffer.GetSize());
R_UNLESS(ctx_size == sizeof(ContextEntry), erpt::ResultInvalidArgument());
R_UNLESS(data_size <= ArrayBufferSizeMax, erpt::ResultInvalidArgument());
SubmitContextForForcedShutdownDetection(ctx, data, data_size);
R_RETURN(Context::SubmitContext(ctx, data, data_size));
}
Result ContextImpl::CreateReport(ReportType report_type, const ams::sf::InBuffer &ctx_buffer, const ams::sf::InBuffer &data_buffer, const ams::sf::InBuffer &meta_buffer, Result result, erpt::CreateReportOptionFlagSet flags) {
const ContextEntry *ctx = reinterpret_cast<const ContextEntry *>( ctx_buffer.GetPointer());
const u8 *data = reinterpret_cast<const u8 *>(data_buffer.GetPointer());
const ReportMetaData *meta = reinterpret_cast<const ReportMetaData *>(meta_buffer.GetPointer());
const u32 ctx_size = static_cast<u32>(ctx_buffer.GetSize());
const u32 data_size = static_cast<u32>(data_buffer.GetSize());
const u32 meta_size = static_cast<u32>(meta_buffer.GetSize());
R_UNLESS(ctx_size == sizeof(ContextEntry), erpt::ResultInvalidArgument());
R_UNLESS(meta_size == 0 || meta_size == sizeof(ReportMetaData), erpt::ResultInvalidArgument());
R_TRY(Reporter::CreateReport(report_type, result, ctx, data, data_size, meta_size != 0 ? meta : nullptr, nullptr, 0, flags));
ManagerImpl::NotifyAll();
R_SUCCEED();
}
Result ContextImpl::CreateReportV1(ReportType report_type, const ams::sf::InBuffer &ctx_buffer, const ams::sf::InBuffer &data_buffer, const ams::sf::InBuffer &meta_buffer, Result result) {
R_RETURN(this->CreateReport(report_type, ctx_buffer, data_buffer, meta_buffer, result, erpt::srv::MakeNoCreateReportOptionFlags()));
}
Result ContextImpl::CreateReportV0(ReportType report_type, const ams::sf::InBuffer &ctx_buffer, const ams::sf::InBuffer &data_buffer, const ams::sf::InBuffer &meta_buffer) {
R_RETURN(this->CreateReportV1(report_type, ctx_buffer, data_buffer, meta_buffer, ResultSuccess()));
}
Result ContextImpl::SetInitialLaunchSettingsCompletionTime(const time::SteadyClockTimePoint &time_point) {
Reporter::SetInitialLaunchSettingsCompletionTime(time_point);
R_SUCCEED();
}
Result ContextImpl::ClearInitialLaunchSettingsCompletionTime() {
Reporter::ClearInitialLaunchSettingsCompletionTime();
R_SUCCEED();
}
Result ContextImpl::UpdatePowerOnTime() {
/* NOTE: Prior to 12.0.0, this set the power on time, but now erpt does it during initialization. */
R_SUCCEED();
}
Result ContextImpl::UpdateAwakeTime() {
/* NOTE: Prior to 12.0.0, this set the power on time, but now erpt does it during initialization. */
R_SUCCEED();
}
Result ContextImpl::SubmitMultipleCategoryContext(const MultipleCategoryContextEntry &ctx_entry, const ams::sf::InBuffer &str_buffer) {
R_UNLESS(ctx_entry.category_count <= CategoriesPerMultipleCategoryContext, erpt::ResultInvalidArgument());
const u8 *str = reinterpret_cast<const u8 *>(str_buffer.GetPointer());
const u32 str_size = static_cast<u32>(str_buffer.GetSize());
u32 total_field_count = 0, total_arr_count = 0;
for (u32 i = 0; i < ctx_entry.category_count; i++) {
ContextEntry entry = {
.version = ctx_entry.version,
.field_count = ctx_entry.field_counts[i],
.category = ctx_entry.categories[i],
};
R_UNLESS(entry.field_count <= erpt::FieldsPerContext, erpt::ResultInvalidArgument());
R_UNLESS(entry.field_count + total_field_count <= erpt::FieldsPerMultipleCategoryContext, erpt::ResultInvalidArgument());
R_UNLESS(ctx_entry.array_buf_counts[i] <= ArrayBufferSizeMax, erpt::ResultInvalidArgument());
R_UNLESS(ctx_entry.array_buf_counts[i] + total_arr_count <= str_size, erpt::ResultInvalidArgument());
std::memcpy(entry.fields, ctx_entry.fields + total_field_count, entry.field_count * sizeof(FieldEntry));
R_TRY(Context::SubmitContext(std::addressof(entry), str + total_arr_count, ctx_entry.array_buf_counts[i]));
total_field_count += entry.field_count;
total_arr_count += ctx_entry.array_buf_counts[i];
}
R_SUCCEED();
}
Result ContextImpl::UpdateApplicationLaunchTime() {
Reporter::UpdateApplicationLaunchTime();
R_SUCCEED();
}
Result ContextImpl::ClearApplicationLaunchTime() {
Reporter::ClearApplicationLaunchTime();
R_SUCCEED();
}
Result ContextImpl::SubmitAttachment(ams::sf::Out<AttachmentId> out, const ams::sf::InBuffer &attachment_name, const ams::sf::InBuffer &attachment_data) {
const char *name = reinterpret_cast<const char *>(attachment_name.GetPointer());
const u8 *data = reinterpret_cast<const u8 *>(attachment_data.GetPointer());
const u32 name_size = static_cast<u32>(attachment_name.GetSize());
const u32 data_size = static_cast<u32>(attachment_data.GetSize());
R_UNLESS(data != nullptr, erpt::ResultInvalidArgument());
R_UNLESS(data_size <= AttachmentSizeMax, erpt::ResultInvalidArgument());
R_UNLESS(name != nullptr, erpt::ResultInvalidArgument());
R_UNLESS(name_size <= AttachmentNameSizeMax, erpt::ResultInvalidArgument());
char name_safe[AttachmentNameSizeMax];
util::Strlcpy(name_safe, name, sizeof(name_safe));
R_RETURN(JournalForAttachments::SubmitAttachment(out.GetPointer(), name_safe, data, data_size));
}
Result ContextImpl::CreateReportWithAttachments(ReportType report_type, const ams::sf::InBuffer &ctx_buffer, const ams::sf::InBuffer &data_buffer, const ams::sf::InBuffer &attachment_ids_buffer, Result result, erpt::CreateReportOptionFlagSet flags) {
const ContextEntry *ctx = reinterpret_cast<const ContextEntry *>( ctx_buffer.GetPointer());
const u8 *data = reinterpret_cast<const u8 *>(data_buffer.GetPointer());
const u32 ctx_size = static_cast<u32>(ctx_buffer.GetSize());
const u32 data_size = static_cast<u32>(data_buffer.GetSize());
const AttachmentId *attachments = reinterpret_cast<const AttachmentId *>(attachment_ids_buffer.GetPointer());
const u32 num_attachments = attachment_ids_buffer.GetSize() / sizeof(*attachments);
R_UNLESS(ctx_size == sizeof(ContextEntry), erpt::ResultInvalidArgument());
R_UNLESS(num_attachments <= AttachmentsPerReportMax, erpt::ResultInvalidArgument());
R_TRY(Reporter::CreateReport(report_type, result, ctx, data, data_size, nullptr, attachments, num_attachments, flags));
ManagerImpl::NotifyAll();
R_SUCCEED();
}
Result ContextImpl::CreateReportWithAttachmentsDeprecated2(ReportType report_type, const ams::sf::InBuffer &ctx_buffer, const ams::sf::InBuffer &data_buffer, const ams::sf::InBuffer &attachment_ids_buffer, Result result) {
R_RETURN(this->CreateReportWithAttachments(report_type, ctx_buffer, data_buffer, attachment_ids_buffer, result, erpt::srv::MakeNoCreateReportOptionFlags()));
}
Result ContextImpl::CreateReportWithAttachmentsDeprecated(ReportType report_type, const ams::sf::InBuffer &ctx_buffer, const ams::sf::InBuffer &data_buffer, const ams::sf::InBuffer &attachment_ids_buffer) {
R_RETURN(this->CreateReportWithAttachmentsDeprecated2(report_type, ctx_buffer, data_buffer, attachment_ids_buffer, ResultSuccess()));
}
Result ContextImpl::RegisterRunningApplet(ncm::ProgramId program_id) {
R_RETURN(Reporter::RegisterRunningApplet(program_id));
}
Result ContextImpl::UnregisterRunningApplet(ncm::ProgramId program_id) {
R_RETURN(Reporter::UnregisterRunningApplet(program_id));
}
Result ContextImpl::UpdateAppletSuspendedDuration(ncm::ProgramId program_id, TimeSpanType duration) {
R_RETURN(Reporter::UpdateAppletSuspendedDuration(program_id, duration));
}
Result ContextImpl::InvalidateForcedShutdownDetection() {
/* NOTE: Nintendo does not check the result here. */
erpt::srv::InvalidateForcedShutdownDetection();
R_SUCCEED();
}
}
| 9,836
|
C++
|
.cpp
| 145
| 60.358621
| 254
| 0.689716
|
Atmosphere-NX/Atmosphere
| 14,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,820
|
erpt_srv_session_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/erpt/srv/erpt_srv_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>
#include "erpt_srv_session_impl.hpp"
#include "erpt_srv_report_impl.hpp"
#include "erpt_srv_manager_impl.hpp"
#include "erpt_srv_attachment_impl.hpp"
namespace ams::erpt::srv {
extern ams::sf::ExpHeapAllocator g_sf_allocator;
namespace {
template<typename Interface, typename Impl>
ALWAYS_INLINE Result OpenInterface(ams::sf::Out<ams::sf::SharedPointer<Interface>> &out) {
/* Create an interface holder. */
auto intf = ams::sf::ObjectFactory<ams::sf::ExpHeapAllocator::Policy>::CreateSharedEmplaced<Interface, Impl>(std::addressof(g_sf_allocator));
R_UNLESS(intf != nullptr, erpt::ResultOutOfMemory());
/* Return it. */
out.SetValue(intf);
R_SUCCEED();
}
}
Result SessionImpl::OpenReport(ams::sf::Out<ams::sf::SharedPointer<erpt::sf::IReport>> out) {
R_RETURN((OpenInterface<erpt::sf::IReport, ReportImpl>(out)));
}
Result SessionImpl::OpenManager(ams::sf::Out<ams::sf::SharedPointer<erpt::sf::IManager>> out) {
R_RETURN((OpenInterface<erpt::sf::IManager, ManagerImpl>(out)));
}
Result SessionImpl::OpenAttachment(ams::sf::Out<ams::sf::SharedPointer<erpt::sf::IAttachment>> out) {
R_RETURN((OpenInterface<erpt::sf::IAttachment, AttachmentImpl>(out)));
}
}
| 1,985
|
C++
|
.cpp
| 43
| 40.976744
| 153
| 0.696687
|
Atmosphere-NX/Atmosphere
| 14,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,821
|
erpt_srv_journal_for_attachments.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/erpt/srv/erpt_srv_journal_for_attachments.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 "erpt_srv_journal.hpp"
#include "erpt_srv_attachment.hpp"
namespace ams::erpt::srv {
constinit util::IntrusiveListBaseTraits<JournalRecord<AttachmentInfo>>::ListType JournalForAttachments::s_attachment_list;
constinit u32 JournalForAttachments::s_attachment_count = 0;
constinit u32 JournalForAttachments::s_used_storage = 0;
namespace {
constexpr inline u32 AttachmentUsedStorageMax = 4_MB;
}
void JournalForAttachments::CleanupAttachments() {
for (auto it = s_attachment_list.begin(); it != s_attachment_list.end(); /* ... */) {
auto *record = std::addressof(*it);
it = s_attachment_list.erase(s_attachment_list.iterator_to(*record));
if (record->RemoveReference()) {
Stream::DeleteStream(Attachment::FileName(record->m_info.attachment_id).name);
delete record;
}
}
AMS_ASSERT(s_attachment_list.empty());
s_attachment_count = 0;
s_used_storage = 0;
}
Result JournalForAttachments::CommitJournal(Stream *stream) {
R_TRY(stream->WriteStream(reinterpret_cast<const u8 *>(std::addressof(s_attachment_count)), sizeof(s_attachment_count)));
for (auto it = s_attachment_list.crbegin(); it != s_attachment_list.crend(); it++) {
R_TRY(stream->WriteStream(reinterpret_cast<const u8 *>(std::addressof(it->m_info)), sizeof(it->m_info)));
}
R_SUCCEED();
}
Result JournalForAttachments::DeleteAttachments(ReportId report_id) {
for (auto it = s_attachment_list.begin(); it != s_attachment_list.end(); /* ... */) {
auto *record = std::addressof(*it);
if (record->m_info.owner_report_id == report_id) {
/* Erase from the list. */
it = s_attachment_list.erase(s_attachment_list.iterator_to(*record));
/* Update storage tracking counts. */
--s_attachment_count;
s_used_storage -= static_cast<u32>(record->m_info.attachment_size);
/* Delete the object, if we should. */
if (record->RemoveReference()) {
Stream::DeleteStream(Attachment::FileName(record->m_info.attachment_id).name);
delete record;
}
} else {
/* Not attached, just advance. */
it++;
}
}
R_SUCCEED();
}
Result JournalForAttachments::GetAttachmentList(AttachmentList *out, ReportId report_id) {
u32 count = 0;
for (auto it = s_attachment_list.cbegin(); it != s_attachment_list.cend() && count < util::size(out->attachments); it++) {
if (report_id == it->m_info.owner_report_id) {
out->attachments[count++] = it->m_info;
}
}
out->attachment_count = count;
R_SUCCEED();
}
u32 JournalForAttachments::GetUsedStorage() {
return s_used_storage;
}
Result JournalForAttachments::RestoreJournal(Stream *stream) {
/* Clear the used storage. */
s_used_storage = 0;
/* Read the count from storage. */
u32 read_size;
u32 count;
R_TRY(stream->ReadStream(std::addressof(read_size), reinterpret_cast<u8 *>(std::addressof(count)), sizeof(count)));
R_UNLESS(read_size == sizeof(count), erpt::ResultCorruptJournal());
R_UNLESS(count <= AttachmentCountMax, erpt::ResultCorruptJournal());
/* If we fail in the middle of reading reports, we want to do cleanup. */
auto cleanup_guard = SCOPE_GUARD { CleanupAttachments(); };
AttachmentInfo info;
for (u32 i = 0; i < count; i++) {
R_TRY(stream->ReadStream(std::addressof(read_size), reinterpret_cast<u8 *>(std::addressof(info)), sizeof(info)));
R_UNLESS(read_size == sizeof(info), erpt::ResultCorruptJournal());
auto *record = new JournalRecord<AttachmentInfo>(info);
R_UNLESS(record != nullptr, erpt::ResultOutOfMemory());
auto record_guard = SCOPE_GUARD { delete record; };
if (R_FAILED(Stream::GetStreamSize(std::addressof(record->m_info.attachment_size), Attachment::FileName(record->m_info.attachment_id).name))) {
continue;
}
if (record->m_info.flags.Test<AttachmentFlag::HasOwner>() && JournalForReports::RetrieveRecord(record->m_info.owner_report_id) != nullptr) {
/* NOTE: Nintendo does not check the result of storing the new record... */
record_guard.Cancel();
StoreRecord(record);
} else {
/* If the attachment has no owner (or we deleted the report), delete the file associated with it. */
Stream::DeleteStream(Attachment::FileName(record->m_info.attachment_id).name);
}
}
cleanup_guard.Cancel();
R_SUCCEED();
}
JournalRecord<AttachmentInfo> *JournalForAttachments::RetrieveRecord(AttachmentId attachment_id) {
for (auto it = s_attachment_list.begin(); it != s_attachment_list.end(); it++) {
if (auto *record = std::addressof(*it); record->m_info.attachment_id == attachment_id) {
return record;
}
}
return nullptr;
}
Result JournalForAttachments::SetOwner(AttachmentId attachment_id, ReportId report_id) {
for (auto it = s_attachment_list.begin(); it != s_attachment_list.end(); it++) {
auto *record = std::addressof(*it);
if (record->m_info.attachment_id == attachment_id) {
R_UNLESS(!record->m_info.flags.Test<AttachmentFlag::HasOwner>(), erpt::ResultAlreadyOwned());
record->m_info.owner_report_id = report_id;
record->m_info.flags.Set<AttachmentFlag::HasOwner>();
R_SUCCEED();
}
}
R_THROW(erpt::ResultInvalidArgument());
}
Result JournalForAttachments::StoreRecord(JournalRecord<AttachmentInfo> *record) {
/* Check if the record already exists. */
for (auto it = s_attachment_list.begin(); it != s_attachment_list.end(); it++) {
R_UNLESS(it->m_info.attachment_id != record->m_info.attachment_id, erpt::ResultAlreadyExists());
}
/* Add a reference to the new record. */
record->AddReference();
/* Push the record into the list. */
s_attachment_list.push_front(*record);
s_attachment_count++;
s_used_storage += static_cast<u32>(record->m_info.attachment_size);
R_SUCCEED();
}
Result JournalForAttachments::SubmitAttachment(AttachmentId *out, char *name, const u8 *data, u32 data_size) {
R_UNLESS(data_size > 0, erpt::ResultInvalidArgument());
R_UNLESS(data_size < AttachmentSizeMax, erpt::ResultInvalidArgument());
const auto name_len = std::strlen(name);
R_UNLESS(name_len < AttachmentNameSizeMax, erpt::ResultInvalidArgument());
/* Ensure that we have free space. */
while (s_used_storage > AttachmentUsedStorageMax) {
R_TRY(JournalForReports::DeleteReportWithAttachments());
}
AttachmentInfo info;
info.attachment_id.uuid = util::GenerateUuid();
info.flags = erpt::srv::MakeNoAttachmentFlags();
info.attachment_size = data_size;
util::Strlcpy(info.attachment_name, name, sizeof(info.attachment_name));
auto *record = new JournalRecord<AttachmentInfo>(info);
R_UNLESS(record != nullptr, erpt::ResultOutOfMemory());
record->AddReference();
ON_SCOPE_EXIT {
if (record->RemoveReference()) {
delete record;
}
};
{
auto attachment = std::make_unique<Attachment>(record);
R_UNLESS(attachment != nullptr, erpt::ResultOutOfMemory());
R_TRY(attachment->Open(AttachmentOpenType_Create));
ON_SCOPE_EXIT { attachment->Close(); };
R_TRY(attachment->Write(data, data_size));
R_TRY(StoreRecord(record));
}
*out = info.attachment_id;
R_SUCCEED();
}
}
| 8,921
|
C++
|
.cpp
| 179
| 39.910615
| 155
| 0.613704
|
Atmosphere-NX/Atmosphere
| 14,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,822
|
erpt_srv_reporter.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/erpt/srv/erpt_srv_reporter.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 "erpt_srv_reporter.hpp"
#include "erpt_srv_report.hpp"
#include "erpt_srv_journal.hpp"
#include "erpt_srv_context_record.hpp"
#include "erpt_srv_context.hpp"
#include "erpt_srv_fs_info.hpp"
namespace ams::erpt::srv {
constinit bool Reporter::s_redirect_new_reports = true;
constinit char Reporter::s_serial_number[24] = "Unknown";
constinit char Reporter::s_os_version[24] = "Unknown";
constinit char Reporter::s_private_os_version[96] = "Unknown";
constinit util::optional<os::Tick> Reporter::s_application_launch_time;
constinit util::optional<os::Tick> Reporter::s_awake_time;
constinit util::optional<os::Tick> Reporter::s_power_on_time;
constinit util::optional<time::SteadyClockTimePoint> Reporter::s_initial_launch_settings_completion_time;
namespace {
class AppletActiveTimeInfoList {
private:
struct AppletActiveTimeInfo {
ncm::ProgramId program_id;
os::Tick register_tick;
TimeSpan suspended_duration;
};
static constexpr AppletActiveTimeInfo InvalidAppletActiveTimeInfo = { ncm::InvalidProgramId, os::Tick{}, TimeSpan::FromNanoSeconds(0) };
private:
std::array<AppletActiveTimeInfo, 8> m_list;
public:
constexpr AppletActiveTimeInfoList() : m_list{InvalidAppletActiveTimeInfo, InvalidAppletActiveTimeInfo, InvalidAppletActiveTimeInfo, InvalidAppletActiveTimeInfo, InvalidAppletActiveTimeInfo, InvalidAppletActiveTimeInfo, InvalidAppletActiveTimeInfo, InvalidAppletActiveTimeInfo} {
m_list.fill(InvalidAppletActiveTimeInfo);
}
public:
void Register(ncm::ProgramId program_id) {
/* Find an unused entry. */
auto entry = util::range::find_if(m_list, [](const AppletActiveTimeInfo &info) { return info.program_id == ncm::InvalidProgramId; });
AMS_ASSERT(entry != m_list.end());
/* Create the entry. */
*entry = { program_id, os::GetSystemTick(), TimeSpan::FromNanoSeconds(0) };
}
void Unregister(ncm::ProgramId program_id) {
/* Find a matching entry. */
auto entry = util::range::find_if(m_list, [&](const AppletActiveTimeInfo &info) { return info.program_id == program_id; });
AMS_ASSERT(entry != m_list.end());
/* Clear the entry. */
*entry = InvalidAppletActiveTimeInfo;
}
void UpdateSuspendedDuration(ncm::ProgramId program_id, TimeSpan suspended_duration) {
/* Find a matching entry. */
auto entry = util::range::find_if(m_list, [&](const AppletActiveTimeInfo &info) { return info.program_id == program_id; });
AMS_ASSERT(entry != m_list.end());
/* Set the suspended duration. */
entry->suspended_duration = suspended_duration;
}
util::optional<TimeSpan> GetActiveDuration(ncm::ProgramId program_id) const {
/* Try to find a matching entry. */
const auto entry = util::range::find_if(m_list, [&](const AppletActiveTimeInfo &info) { return info.program_id == program_id; });
if (entry != m_list.end()) {
return (os::GetSystemTick() - entry->register_tick).ToTimeSpan() - entry->suspended_duration;
} else {
return util::nullopt;
}
}
};
constinit AppletActiveTimeInfoList g_applet_active_time_info_list;
#if defined(ATMOSPHERE_OS_HORIZON)
Result PullErrorContext(size_t *out_total_size, size_t *out_size, void *dst, size_t dst_size, const err::ContextDescriptor &descriptor, Result result) {
s32 unk0;
u32 total_size, size;
R_TRY(::ectxrPullContext(std::addressof(unk0), std::addressof(total_size), std::addressof(size), dst, dst_size, descriptor.value, result.GetValue()));
*out_total_size = total_size;
*out_size = size;
R_SUCCEED();
}
void SubmitErrorContext(ContextRecord *record, Result result) {
/* Only support submitting context on 11.x. */
if (hos::GetVersion() < hos::Version_11_0_0) {
return;
}
/* Get the context descriptor. */
const auto descriptor = err::GetContextDescriptorFromResult(result);
if (descriptor == err::InvalidContextDescriptor) {
return;
}
/* Pull the error context. */
u8 error_context[0x200];
size_t error_context_total_size;
size_t error_context_size;
if (R_FAILED(PullErrorContext(std::addressof(error_context_total_size), std::addressof(error_context_size), error_context, util::size(error_context), descriptor, result))) {
return;
}
/* Set the total size. */
if (error_context_total_size == 0) {
return;
}
record->Add(FieldId_ErrorContextTotalSize, error_context_total_size);
/* Set the context. */
if (error_context_size == 0) {
return;
}
record->Add(FieldId_ErrorContextSize, error_context_size);
record->Add(FieldId_ErrorContext, error_context, error_context_size);
}
constinit os::SdkMutex g_limit_mutex;
constinit bool g_submitted_limit = false;
void SubmitResourceLimitLimitContext() {
std::scoped_lock lk(g_limit_mutex);
if (g_submitted_limit) {
return;
}
ON_SCOPE_EXIT { g_submitted_limit = true; };
/* Create and populate the record. */
auto record = std::make_unique<ContextRecord>(CategoryId_ResourceLimitLimitInfo);
if (record == nullptr) {
return;
}
u64 reslimit_handle_value;
if (R_FAILED(svc::GetInfo(std::addressof(reslimit_handle_value), svc::InfoType_ResourceLimit, svc::InvalidHandle, 0))) {
return;
}
const auto handle = static_cast<svc::Handle>(reslimit_handle_value);
ON_SCOPE_EXIT { R_ABORT_UNLESS(svc::CloseHandle(handle)); };
#define ADD_RESOURCE(__RESOURCE__) \
do { \
s64 limit_value; \
if (R_FAILED(svc::GetResourceLimitLimitValue(std::addressof(limit_value), handle, svc::LimitableResource_##__RESOURCE__##Max))) { \
return; \
} \
if (R_FAILED(record->Add(FieldId_System##__RESOURCE__##Limit, limit_value))) { \
return; \
} \
} while (0)
ADD_RESOURCE(PhysicalMemory);
ADD_RESOURCE(ThreadCount);
ADD_RESOURCE(EventCount);
ADD_RESOURCE(TransferMemoryCount);
ADD_RESOURCE(SessionCount);
#undef ADD_RESOURCE
Context::SubmitContextRecord(std::move(record));
g_submitted_limit = true;
}
void SubmitResourceLimitPeakContext() {
/* Create and populate the record. */
auto record = std::make_unique<ContextRecord>(CategoryId_ResourceLimitPeakInfo);
if (record == nullptr) {
return;
}
u64 reslimit_handle_value;
if (R_FAILED(svc::GetInfo(std::addressof(reslimit_handle_value), svc::InfoType_ResourceLimit, svc::InvalidHandle, 0))) {
return;
}
const auto handle = static_cast<svc::Handle>(reslimit_handle_value);
ON_SCOPE_EXIT { R_ABORT_UNLESS(svc::CloseHandle(handle)); };
#define ADD_RESOURCE(__RESOURCE__) \
do { \
s64 peak_value; \
if (R_FAILED(svc::GetResourceLimitPeakValue(std::addressof(peak_value), handle, svc::LimitableResource_##__RESOURCE__##Max))) { \
return; \
} \
if (R_FAILED(record->Add(FieldId_System##__RESOURCE__##Peak, peak_value))) { \
return; \
} \
} while (0)
ADD_RESOURCE(PhysicalMemory);
ADD_RESOURCE(ThreadCount);
ADD_RESOURCE(EventCount);
ADD_RESOURCE(TransferMemoryCount);
ADD_RESOURCE(SessionCount);
#undef ADD_RESOURCE
Context::SubmitContextRecord(std::move(record));
}
void SubmitResourceLimitContexts() {
SubmitResourceLimitLimitContext();
SubmitResourceLimitPeakContext();
}
#else
void SubmitErrorContext(ContextRecord *record, Result result) {
AMS_UNUSED(record, result);
}
#endif
Result ValidateCreateReportContext(const ContextEntry *ctx) {
R_UNLESS(ctx->category == CategoryId_ErrorInfo, erpt::ResultRequiredContextMissing());
R_UNLESS(ctx->field_count <= FieldsPerContext, erpt::ResultInvalidArgument());
const bool found_error_code = util::range::any_of(MakeSpan(ctx->fields, ctx->field_count), [] (const FieldEntry &entry) {
return entry.id == FieldId_ErrorCode;
});
R_UNLESS(found_error_code, erpt::ResultRequiredFieldMissing());
R_SUCCEED();
}
Result SubmitReportDefaults(const ContextEntry *ctx) {
AMS_ASSERT(ctx->category == CategoryId_ErrorInfo);
auto record = std::make_unique<ContextRecord>(CategoryId_ErrorInfoDefaults);
R_UNLESS(record != nullptr, erpt::ResultOutOfMemory());
bool found_abort_flag = false, found_syslog_flag = false;
for (u32 i = 0; i < ctx->field_count; i++) {
if (ctx->fields[i].id == FieldId_AbortFlag) {
found_abort_flag = true;
}
if (ctx->fields[i].id == FieldId_HasSyslogFlag) {
found_syslog_flag = true;
}
if (found_abort_flag && found_syslog_flag) {
break;
}
}
if (!found_abort_flag) {
record->Add(FieldId_AbortFlag, false);
}
if (!found_syslog_flag) {
record->Add(FieldId_HasSyslogFlag, true);
}
R_TRY(Context::SubmitContextRecord(std::move(record)));
R_SUCCEED();
}
void SaveSyslogReportIfRequired(const ContextEntry *ctx, const ReportId &report_id) {
bool needs_save_syslog = true;
for (u32 i = 0; i < ctx->field_count; i++) {
static_assert(FieldIndexToTypeMap[*FindFieldIndex(FieldId_HasSyslogFlag)] == FieldType_Bool);
if (ctx->fields[i].id == FieldId_HasSyslogFlag && !ctx->fields[i].value_bool) {
needs_save_syslog = false;
break;
}
}
if (needs_save_syslog) {
/* Here nintendo sends a report to srepo:u (vtable offset 0xE8) with data report_id. */
/* We will not send report ids to srepo:u. */
AMS_UNUSED(report_id);
}
}
void SubmitAppletActiveDurationForCrashReport(const ContextEntry *error_info_ctx, const void *data, u32 data_size, ContextRecord *error_info_auto_record) {
/* Check pre-conditions. */
AMS_ASSERT(error_info_ctx != nullptr);
AMS_ASSERT(error_info_ctx->category == CategoryId_ErrorInfo);
AMS_ASSERT(data != nullptr);
AMS_ASSERT(error_info_auto_record != nullptr);
/* Find the program id entry. */
const auto fields_span = MakeSpan(error_info_ctx->fields, error_info_ctx->field_count);
const auto program_id_entry = util::range::find_if(fields_span, [](const FieldEntry &entry) { return entry.id == FieldId_ProgramId; });
if (program_id_entry == fields_span.end()) {
return;
}
/* Check that the report has abort flag set. */
AMS_ASSERT(util::range::any_of(fields_span, [](const FieldEntry &entry) { return entry.id == FieldId_AbortFlag && entry.value_bool; }));
/* Check that the program id's value is a string. */
AMS_ASSERT(program_id_entry->type == FieldType_String);
/* Check that the program id's length is valid/in bounds. */
const auto program_id_ofs = program_id_entry->value_array.start_idx;
const auto program_id_len = program_id_entry->value_array.size;
AMS_ASSERT(16 <= program_id_len && program_id_len <= 17);
AMS_ASSERT(program_id_ofs + program_id_len <= data_size);
AMS_UNUSED(data_size);
/* Get the program id string. */
char program_id_str[17];
std::memcpy(program_id_str, static_cast<const u8 *>(data) + program_id_ofs, std::min<size_t>(program_id_len, sizeof(program_id_str)));
program_id_str[sizeof(program_id_str) - 1] = '\x00';
/* Convert the string to an integer. */
char *end_ptr = nullptr;
const ncm::ProgramId program_id = { std::strtoull(program_id_str, std::addressof(end_ptr), 16) };
AMS_ASSERT(*end_ptr == '\x00');
/* Get the active duration. */
const auto active_duration = g_applet_active_time_info_list.GetActiveDuration(program_id);
if (!active_duration.has_value()) {
return;
}
/* Add the active applet time. */
const auto result = error_info_auto_record->Add(FieldId_AppletTotalActiveTime, (*active_duration).GetSeconds());
R_ASSERT(result);
}
Result LinkAttachments(const ReportId &report_id, const AttachmentId *attachments, u32 num_attachments) {
for (u32 i = 0; i < num_attachments; i++) {
R_TRY(JournalForAttachments::SetOwner(attachments[i], report_id));
}
R_SUCCEED();
}
Result CreateReportFile(const ReportId &report_id, ReportType type, const ReportMetaData *meta, u32 num_attachments, const time::PosixTime ×tamp_user, const time::PosixTime ×tamp_network, bool redirect_new_reports) {
/* Define journal record deleter. */
struct JournalRecordDeleter {
void operator()(JournalRecord<ReportInfo> *record) {
if (record != nullptr) {
if (record->RemoveReference()) {
delete record;
}
}
}
};
/* Make a journal record. */
auto record = std::unique_ptr<JournalRecord<ReportInfo>, JournalRecordDeleter>{new JournalRecord<ReportInfo>, JournalRecordDeleter{}};
R_UNLESS(record != nullptr, erpt::ResultOutOfMemory());
record->AddReference();
record->m_info.type = type;
record->m_info.id = report_id;
record->m_info.flags = erpt::srv::MakeNoReportFlags();
record->m_info.timestamp_user = timestamp_user;
record->m_info.timestamp_network = timestamp_network;
if (meta != nullptr) {
record->m_info.meta_data = *meta;
}
if (num_attachments > 0) {
record->m_info.flags.Set<ReportFlag::HasAttachment>();
}
auto report = std::make_unique<Report>(record.get(), redirect_new_reports);
R_UNLESS(report != nullptr, erpt::ResultOutOfMemory());
auto report_guard = SCOPE_GUARD { report->Delete(); };
R_TRY(Context::WriteContextsToReport(report.get()));
R_TRY(report->GetSize(std::addressof(record->m_info.report_size)));
if (!redirect_new_reports) {
/* If we're not redirecting new reports, then we want to store the report in the journal. */
R_TRY(Journal::Store(record.get()));
} else {
/* If we are redirecting new reports, we don't want to store the report in the journal. */
/* We should take this opportunity to delete any attachments associated with the report. */
R_ABORT_UNLESS(JournalForAttachments::DeleteAttachments(report_id));
}
R_TRY(Journal::Commit());
report_guard.Cancel();
R_SUCCEED();
}
}
Result Reporter::RegisterRunningApplet(ncm::ProgramId program_id) {
g_applet_active_time_info_list.Register(program_id);
R_SUCCEED();
}
Result Reporter::UnregisterRunningApplet(ncm::ProgramId program_id) {
g_applet_active_time_info_list.Unregister(program_id);
R_SUCCEED();
}
Result Reporter::UpdateAppletSuspendedDuration(ncm::ProgramId program_id, TimeSpan duration) {
g_applet_active_time_info_list.UpdateSuspendedDuration(program_id, duration);
R_SUCCEED();
}
Result Reporter::CreateReport(ReportType type, Result ctx_result, const ContextEntry *ctx, const u8 *data, u32 data_size, const ReportMetaData *meta, const AttachmentId *attachments, u32 num_attachments, erpt::CreateReportOptionFlagSet flags) {
/* Create a context record for the report. */
auto record = std::make_unique<ContextRecord>();
R_UNLESS(record != nullptr, erpt::ResultOutOfMemory());
/* Initialize the record. */
R_TRY(record->Initialize(ctx, data, data_size));
/* Create the report. */
R_RETURN(CreateReport(type, ctx_result, std::move(record), meta, attachments, num_attachments, flags));
}
Result Reporter::CreateReport(ReportType type, Result ctx_result, std::unique_ptr<ContextRecord> record, const ReportMetaData *meta, const AttachmentId *attachments, u32 num_attachments, erpt::CreateReportOptionFlagSet flags) {
/* Clear the automatic categories, when we're done with our report. */
ON_SCOPE_EXIT {
Context::ClearContext(CategoryId_ErrorInfo);
Context::ClearContext(CategoryId_ErrorInfoAuto);
Context::ClearContext(CategoryId_ErrorInfoDefaults);
};
/* Get the context entry pointer. */
const ContextEntry *ctx = record->GetContextEntryPtr();
/* Validate the context. */
R_TRY(ValidateCreateReportContext(ctx));
/* Submit report defaults. */
R_TRY(SubmitReportDefaults(ctx));
/* Generate report id. */
const ReportId report_id = { .uuid = util::GenerateUuid() };
/* Get posix timestamps. */
time::PosixTime timestamp_user;
time::PosixTime timestamp_network;
R_TRY(time::StandardUserSystemClock::GetCurrentTime(std::addressof(timestamp_user)));
if (R_FAILED(time::StandardNetworkSystemClock::GetCurrentTime(std::addressof(timestamp_network)))) {
timestamp_network = {};
}
/* Save syslog report, if required. */
SaveSyslogReportIfRequired(ctx, report_id);
/* Submit report contexts. */
R_TRY(SubmitReportContexts(report_id, type, ctx_result, std::move(record), timestamp_user, timestamp_network, flags));
/* Link attachments to the report. */
R_TRY(LinkAttachments(report_id, attachments, num_attachments));
/* Create the report file. */
R_TRY(CreateReportFile(report_id, type, meta, num_attachments, timestamp_user, timestamp_network, s_redirect_new_reports));
R_SUCCEED();
}
Result Reporter::SubmitReportContexts(const ReportId &report_id, ReportType type, Result ctx_result, std::unique_ptr<ContextRecord> record, const time::PosixTime ×tamp_user, const time::PosixTime ×tamp_network, erpt::CreateReportOptionFlagSet flags) {
/* Create automatic record. */
auto auto_record = std::make_unique<ContextRecord>(CategoryId_ErrorInfoAuto, 0x300);
R_UNLESS(auto_record != nullptr, erpt::ResultOutOfMemory());
/* Handle error context. */
if (R_FAILED(ctx_result)) {
SubmitErrorContext(auto_record.get(), ctx_result);
}
/* Collect unique report fields. */
char identifier_str[0x40];
report_id.uuid.ToString(identifier_str, sizeof(identifier_str));
const auto occurrence_tick = os::GetSystemTick();
const s64 steady_clock_internal_offset_seconds = (hos::GetVersion() >= hos::Version_5_0_0) ? time::GetStandardSteadyClockInternalOffset().GetSeconds() : 0;
time::SteadyClockTimePoint steady_clock_current_timepoint;
R_ABORT_UNLESS(time::GetStandardSteadyClockCurrentTimePoint(std::addressof(steady_clock_current_timepoint)));
/* Add automatic fields. */
auto_record->Add(FieldId_OsVersion, s_os_version, util::Strnlen(s_os_version, sizeof(s_os_version)));
auto_record->Add(FieldId_PrivateOsVersion, s_private_os_version, util::Strnlen(s_private_os_version, sizeof(s_private_os_version)));
auto_record->Add(FieldId_SerialNumber, s_serial_number, util::Strnlen(s_serial_number, sizeof(s_serial_number)));
auto_record->Add(FieldId_ReportIdentifier, identifier_str, util::Strnlen(identifier_str, sizeof(identifier_str)));
auto_record->Add(FieldId_OccurrenceTimestamp, timestamp_user.value);
auto_record->Add(FieldId_OccurrenceTimestampNet, timestamp_network.value);
auto_record->Add(FieldId_ReportVisibilityFlag, type == ReportType_Visible);
auto_record->Add(FieldId_OccurrenceTick, occurrence_tick.GetInt64Value());
auto_record->Add(FieldId_SteadyClockInternalOffset, steady_clock_internal_offset_seconds);
auto_record->Add(FieldId_SteadyClockCurrentTimePointValue, steady_clock_current_timepoint.value);
auto_record->Add(FieldId_ElapsedTimeSincePowerOn, (occurrence_tick - *s_power_on_time).ToTimeSpan().GetSeconds());
auto_record->Add(FieldId_ElapsedTimeSinceLastAwake, (occurrence_tick - *s_awake_time).ToTimeSpan().GetSeconds());
if (s_initial_launch_settings_completion_time) {
s64 elapsed_seconds;
if (R_SUCCEEDED(time::GetElapsedSecondsBetween(std::addressof(elapsed_seconds), *s_initial_launch_settings_completion_time, steady_clock_current_timepoint))) {
auto_record->Add(FieldId_ElapsedTimeSinceInitialLaunch, elapsed_seconds);
}
}
if (s_application_launch_time) {
auto_record->Add(FieldId_ApplicationAliveTime, (occurrence_tick - *s_application_launch_time).ToTimeSpan().GetSeconds());
}
/* Submit applet active duration information. */
{
const auto *error_info_ctx = record->GetContextEntryPtr();
SubmitAppletActiveDurationForCrashReport(error_info_ctx, error_info_ctx->array_buffer, error_info_ctx->array_buffer_size - error_info_ctx->array_free_count, auto_record.get());
}
/* Submit the auto record. */
R_TRY(Context::SubmitContextRecord(std::move(auto_record)));
/* Submit the info record. */
R_TRY(Context::SubmitContextRecord(std::move(record)));
/* Submit context for resource limits. */
#if defined(ATMOSPHERE_OS_HORIZON)
SubmitResourceLimitContexts();
#endif
/* If we should, submit fs info. */
#if defined(ATMOSPHERE_OS_HORIZON)
if (hos::GetVersion() >= hos::Version_17_0_0 && flags.Test<CreateReportOptionFlag::SubmitFsInfo>()) {
/* NOTE: Nintendo ignores the result of this call. */
SubmitFsInfo();
}
#else
AMS_UNUSED(flags);
#endif
R_SUCCEED();
}
}
| 26,903
|
C++
|
.cpp
| 447
| 47.55481
| 295
| 0.558414
|
Atmosphere-NX/Atmosphere
| 14,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.