stratosphere: use SdkMutex/SdkRecursiveMutex over Mutex

This commit is contained in:
Michael Scire
2021-09-29 22:52:50 -07:00
parent a4fe1bb5d8
commit 41ab4c2c68
70 changed files with 188 additions and 645 deletions

View File

@@ -501,18 +501,18 @@ namespace ams::mitm {
crypto::EncryptAes128Ctr(dst, dst_size, entropy.data, crypto::Aes128CtrEncryptor::KeySize, entropy.data + crypto::Aes128CtrEncryptor::KeySize, crypto::Aes128CtrEncryptor::IvSize, dst, dst_size);
}
alignas(os::MemoryPageSize) CalibrationInfo g_calibration_info = {};
alignas(os::MemoryPageSize) CalibrationInfo g_blank_calibration_info = {};
alignas(os::MemoryPageSize) SecureCalibrationInfoBackup g_secure_calibration_info_backup = {};
alignas(os::MemoryPageSize) constinit CalibrationInfo g_calibration_info = {};
alignas(os::MemoryPageSize) constinit CalibrationInfo g_blank_calibration_info = {};
alignas(os::MemoryPageSize) constinit SecureCalibrationInfoBackup g_secure_calibration_info_backup = {};
util::optional<ams::fs::FileStorage> g_prodinfo_backup_file;
util::optional<ams::fs::MemoryStorage> g_blank_prodinfo_storage;
util::optional<ams::fs::MemoryStorage> g_fake_secure_backup_storage;
constinit util::optional<ams::fs::FileStorage> g_prodinfo_backup_file;
constinit util::optional<ams::fs::MemoryStorage> g_blank_prodinfo_storage;
constinit util::optional<ams::fs::MemoryStorage> g_fake_secure_backup_storage;
bool g_allow_writes = false;
bool g_has_secure_backup = false;
constinit bool g_allow_writes = false;
constinit bool g_has_secure_backup = false;
os::Mutex g_prodinfo_management_lock(false);
constinit os::SdkMutex g_prodinfo_management_lock;
}

View File

@@ -22,7 +22,7 @@ namespace ams::mitm::fs {
namespace {
os::Mutex g_cal0_access_mutex(false);
constinit os::SdkMutex g_cal0_access_mutex;
}
Result CalibrationBinaryStorage::Read(s64 offset, void *_buffer, size_t size) {

View File

@@ -22,9 +22,9 @@ namespace ams::mitm::fs {
namespace {
os::Mutex g_mq_lock(false);
bool g_started_req_thread;
uintptr_t g_mq_storage[2];
constinit os::SdkMutex g_mq_lock;
constinit bool g_started_req_thread;
constinit uintptr_t g_mq_storage[2];
os::MessageQueue g_req_mq(g_mq_storage + 0, 1);
os::MessageQueue g_ack_mq(g_mq_storage + 1, 1);

View File

@@ -258,8 +258,8 @@ namespace ams::mitm::fs {
}
}
os::Mutex g_fs_romfs_path_lock(false);
char g_fs_romfs_path_buffer[fs::EntryNameLengthMax + 1];
constinit os::SdkMutex g_fs_romfs_path_lock;
constinit char g_fs_romfs_path_buffer[fs::EntryNameLengthMax + 1];
NOINLINE void OpenFileSystemRomfsDirectory(FsDir *out, ncm::ProgramId program_id, BuildDirectoryContext *parent, fs::OpenDirectoryMode mode, FsFileSystem *fs) {
std::scoped_lock lk(g_fs_romfs_path_lock);

View File

@@ -23,15 +23,19 @@ namespace ams::mitm::settings {
namespace {
os::Mutex g_firmware_version_lock(false);
bool g_cached_firmware_version;
settings::FirmwareVersion g_firmware_version;
settings::FirmwareVersion g_ams_firmware_version;
constinit os::SdkMutex g_firmware_version_lock;
constinit bool g_cached_firmware_version;
constinit settings::FirmwareVersion g_firmware_version;
constinit settings::FirmwareVersion g_ams_firmware_version;
void CacheFirmwareVersion() {
if (AMS_LIKELY(g_cached_firmware_version)) {
return;
}
std::scoped_lock lk(g_firmware_version_lock);
if (AMS_LIKELY(g_cached_firmware_version)) {
if (AMS_UNLIKELY(g_cached_firmware_version)) {
return;
}

View File

@@ -20,9 +20,9 @@ namespace ams::mitm::sysupdater {
class SystemUpdateApplyManager {
private:
os::Mutex apply_mutex;
os::SdkMutex apply_mutex;
public:
constexpr SystemUpdateApplyManager() : apply_mutex(false) { /* ... */ }
constexpr SystemUpdateApplyManager() : apply_mutex() { /* ... */ }
Result ApplyPackageTask(ncm::PackageSystemDowngradeTask *task);
};

View File

@@ -23,8 +23,8 @@ namespace ams::creport {
/* Convenience definitions. */
constexpr size_t MaximumLineLength = 0x20;
os::Mutex g_format_lock(false);
char g_format_buffer[2 * os::MemoryPageSize];
constinit os::SdkMutex g_format_lock;
constinit char g_format_buffer[2 * os::MemoryPageSize];
}

View File

@@ -83,7 +83,7 @@ namespace ams::dmnt::cheat::impl {
private:
static constexpr size_t ThreadStackSize = 0x4000;
private:
os::Mutex cheat_lock;
os::SdkMutex cheat_lock;
os::Event unsafe_break_event;
os::Event debug_events_event; /* Autoclear. */
os::ThreadType detect_thread, debug_events_thread;
@@ -250,7 +250,7 @@ namespace ams::dmnt::cheat::impl {
}
public:
CheatProcessManager() : cheat_lock(false), unsafe_break_event(os::EventClearMode_ManualClear), debug_events_event(os::EventClearMode_AutoClear), cheat_process_event(os::EventClearMode_AutoClear, true) {
CheatProcessManager() : cheat_lock(), unsafe_break_event(os::EventClearMode_ManualClear), debug_events_event(os::EventClearMode_AutoClear), cheat_process_event(os::EventClearMode_AutoClear, true) {
/* Learn whether we should enable cheats by default. */
{
u8 en = 0;

View File

@@ -14,7 +14,6 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "dmnt_service.hpp"
#include "cheat/dmnt_cheat_service.hpp"
#include "cheat/impl/dmnt_cheat_api.hpp"
@@ -189,8 +188,6 @@ int main(int argc, char **argv)
ams::dmnt::cheat::impl::InitializeCheatManager();
/* Create services. */
/* TODO: Implement rest of dmnt:- in ams.tma development branch. */
/* TODO: register debug service */
R_ABORT_UNLESS(g_server_manager.RegisterObjectForServer(g_cheat_service.GetShared(), CheatServiceName, CheatMaxSessions));
/* Loop forever, servicing our services. */

View File

@@ -1,137 +0,0 @@
/*
* Copyright (c) 2018-2020 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <stratosphere.hpp>
namespace ams::dmnt {
/* TODO: Move into libstratosphere, eventually. */
struct TargetIOFileHandle : sf::LargeData, sf::PrefersMapAliasTransferMode {
u64 value;
constexpr u64 GetValue() const {
return this->value;
}
constexpr explicit operator u64() const {
return this->value;
}
inline constexpr bool operator==(const TargetIOFileHandle &rhs) const {
return this->value == rhs.value;
}
inline constexpr bool operator!=(const TargetIOFileHandle &rhs) const {
return this->value != rhs.value;
}
inline constexpr bool operator<(const TargetIOFileHandle &rhs) const {
return this->value < rhs.value;
}
inline constexpr bool operator<=(const TargetIOFileHandle &rhs) const {
return this->value <= rhs.value;
}
inline constexpr bool operator>(const TargetIOFileHandle &rhs) const {
return this->value > rhs.value;
}
inline constexpr bool operator>=(const TargetIOFileHandle &rhs) const {
return this->value >= rhs.value;
}
};
static_assert(util::is_pod<TargetIOFileHandle>::value && sizeof(TargetIOFileHandle) == sizeof(u64), "TargetIOFileHandle");
/* TODO: Convert to new sf format in the future. */
class DebugMonitorService final {
private:
enum class CommandId {
BreakDebugProcess = 0,
TerminateDebugProcess = 1,
CloseHandle = 2,
LoadImage = 3,
GetProcessId = 4,
GetProcessHandle = 5,
WaitSynchronization = 6,
GetDebugEvent = 7,
GetProcessModuleInfo = 8,
GetProcessList = 9,
GetThreadList = 10,
GetDebugThreadContext = 11,
ContinueDebugEvent = 12,
ReadDebugProcessMemory = 13,
WriteDebugProcessMemory = 14,
SetDebugThreadContext = 15,
GetDebugThreadParam = 16,
InitializeThreadInfo = 17,
SetHardwareBreakPoint = 18,
QueryDebugProcessMemory = 19,
GetProcessMemoryDetails = 20,
AttachByProgramId = 21,
AttachOnLaunch = 22,
GetDebugMonitorProcessId = 23,
GetJitDebugProcessList = 25,
CreateCoreDump = 26,
GetAllDebugThreadInfo = 27,
TargetIO_FileOpen = 29,
TargetIO_FileClose = 30,
TargetIO_FileRead = 31,
TargetIO_FileWrite = 32,
TargetIO_FileSetAttributes = 33,
TargetIO_FileGetInformation = 34,
TargetIO_FileSetTime = 35,
TargetIO_FileSetSize = 36,
TargetIO_FileDelete = 37,
TargetIO_FileMove = 38,
TargetIO_DirectoryCreate = 39,
TargetIO_DirectoryDelete = 40,
TargetIO_DirectoryRename = 41,
TargetIO_DirectoryGetCount = 42,
TargetIO_DirectoryOpen = 43,
TargetIO_DirectoryGetNext = 44,
TargetIO_DirectoryClose = 45,
TargetIO_GetFreeSpace = 46,
TargetIO_GetVolumeInformation = 47,
InitiateCoreDump = 48,
ContinueCoreDump = 49,
AddTTYToCoreDump = 50,
AddImageToCoreDump = 51,
CloseCoreDump = 52,
CancelAttach = 53,
};
private:
Result BreakDebugProcess(Handle debug_hnd);
Result TerminateDebugProcess(Handle debug_hnd);
Result CloseHandle(Handle debug_hnd);
Result GetProcessId(sf::Out<os::ProcessId> out_pid, Handle hnd);
Result GetProcessHandle(sf::Out<Handle> out_hnd, os::ProcessId pid);
Result WaitSynchronization(Handle hnd, u64 ns);
Result TargetIO_FileOpen(sf::Out<TargetIOFileHandle> out_hnd, const sf::InBuffer &path, int open_mode, u32 create_mode);
Result TargetIO_FileClose(TargetIOFileHandle hnd);
Result TargetIO_FileRead(TargetIOFileHandle hnd, const sf::OutNonSecureBuffer &out_data, sf::Out<u32> out_read, s64 offset);
Result TargetIO_FileWrite(TargetIOFileHandle hnd, const sf::InNonSecureBuffer &data, sf::Out<u32> out_written, s64 offset);
Result TargetIO_FileSetAttributes(const sf::InBuffer &path, const sf::InBuffer &attributes);
Result TargetIO_FileGetInformation(const sf::InBuffer &path, const sf::OutArray<u64> &out_info, sf::Out<int> is_directory);
Result TargetIO_FileSetTime(const sf::InBuffer &path, u64 create, u64 access, u64 modify);
Result TargetIO_FileSetSize(const sf::InBuffer &input, s64 size);
Result TargetIO_FileDelete(const sf::InBuffer &path);
Result TargetIO_FileMove(const sf::InBuffer &src_path, const sf::InBuffer &dst_path);
};
}

View File

@@ -1,55 +0,0 @@
/*
* Copyright (c) 2018-2020 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "dmnt_service.hpp"
namespace ams::dmnt {
Result DebugMonitorService::BreakDebugProcess(Handle debug_hnd) {
/* Nintendo discards the output of this command, but we will return it. */
return svcBreakDebugProcess(debug_hnd);
}
Result DebugMonitorService::TerminateDebugProcess(Handle debug_hnd) {
/* Nintendo discards the output of this command, but we will return it. */
return svcTerminateDebugProcess(debug_hnd);
}
Result DebugMonitorService::CloseHandle(Handle debug_hnd) {
/* Nintendo discards the output of this command, but we will return it. */
/* This command is, entertainingly, also pretty unsafe in general... */
return svcCloseHandle(debug_hnd);
}
Result DebugMonitorService::GetProcessId(sf::Out<os::ProcessId> out_pid, Handle hnd) {
/* Nintendo discards the output of this command, but we will return it. */
return os::TryGetProcessId(out_pid.GetPointer(), hnd);
}
Result DebugMonitorService::GetProcessHandle(sf::Out<Handle> out_hnd, os::ProcessId pid) {
R_TRY_CATCH(svcDebugActiveProcess(out_hnd.GetPointer(), static_cast<u64>(pid))) {
R_CONVERT(svc::ResultBusy, dbg::ResultAlreadyAttached());
} R_END_TRY_CATCH;
return ResultSuccess();
}
Result DebugMonitorService::WaitSynchronization(Handle hnd, u64 ns) {
/* Nintendo discards the output of this command, but we will return it. */
return svcWaitSynchronizationSingle(hnd, ns);
}
}

View File

@@ -1,259 +0,0 @@
/*
* Copyright (c) 2018-2020 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "dmnt_service.hpp"
namespace std {
template<>
struct hash<ams::dmnt::TargetIOFileHandle> {
u64 operator()(ams::dmnt::TargetIOFileHandle const &handle) const noexcept {
return handle.GetValue();
}
};
}
namespace ams::dmnt {
namespace {
enum TIOCreateOption : u32 {
TIOCreateOption_CreateNew = 1,
TIOCreateOption_CreateAlways = 2,
TIOCreateOption_OpenExisting = 3,
TIOCreateOption_OpenAlways = 4,
TIOCreateOption_ResetSize = 5,
};
/* Nintendo uses actual pointers as file handles. We'll add a layer of indirection... */
bool g_sd_initialized = false;
os::Mutex g_sd_lock(false);
FsFileSystem g_sd_fs;
os::Mutex g_file_handle_lock(false);
u64 g_cur_fd;
std::unordered_map<TargetIOFileHandle, FsFile> g_file_handles;
Result EnsureSdInitialized() {
std::scoped_lock lk(g_sd_lock);
R_SUCCEED_IF(g_sd_initialized);
R_TRY(fsOpenSdCardFileSystem(&g_sd_fs));
g_sd_initialized = true;
return ResultSuccess();
}
TargetIOFileHandle GetNewFileHandle(FsFile f) {
std::scoped_lock lk(g_file_handle_lock);
TargetIOFileHandle fd = { .value = g_cur_fd++ };
g_file_handles[fd] = f;
return fd;
}
Result GetFileByHandle(FsFile *out, TargetIOFileHandle handle) {
std::scoped_lock lk(g_file_handle_lock);
if (g_file_handles.find(handle) != g_file_handles.end()) {
*out = g_file_handles[handle];
return ResultSuccess();
}
return fs::ResultInvalidArgument();
}
Result CloseFileByHandle(TargetIOFileHandle handle) {
std::scoped_lock lk(g_file_handle_lock);
if (g_file_handles.find(handle) != g_file_handles.end()) {
fsFileClose(&g_file_handles[handle]);
g_file_handles.erase(handle);
return ResultSuccess();
}
return fs::ResultInvalidArgument();
}
void FixPath(char *dst, size_t dst_size, const sf::InBuffer &path) {
dst[dst_size - 1] = 0;
strncpy(dst, "/", dst_size - 1);
const char *src = reinterpret_cast<const char *>(path.GetPointer());
size_t src_idx = 0;
size_t dst_idx = 1;
while (src_idx < path.GetSize() && (src[src_idx] == '/' || src[src_idx] == '\\')) {
src_idx++;
}
while (src_idx < path.GetSize() && dst_idx < dst_size - 1 && src[src_idx] != 0) {
if (src[src_idx] == '\\') {
dst[dst_idx] = '/';
} else {
dst[dst_idx] = src[src_idx];
}
src_idx++;
dst_idx++;
}
if (dst_idx < dst_size) {
dst[dst_idx] = 0;
}
}
}
Result DebugMonitorService::TargetIO_FileOpen(sf::Out<TargetIOFileHandle> out_hnd, const sf::InBuffer &path, int open_mode, u32 create_mode) {
R_TRY(EnsureSdInitialized());
char fs_path[FS_MAX_PATH];
FixPath(fs_path, sizeof(fs_path), path);
/* Create file as required by mode. */
if (create_mode == TIOCreateOption_CreateAlways) {
fsFsDeleteFile(&g_sd_fs, fs_path);
R_TRY(fsFsCreateFile(&g_sd_fs, fs_path, 0, 0));
} else if (create_mode == TIOCreateOption_CreateNew) {
R_TRY(fsFsCreateFile(&g_sd_fs, fs_path, 0, 0));
} else if (create_mode == TIOCreateOption_OpenAlways) {
fsFsCreateFile(&g_sd_fs, fs_path, 0, 0);
}
/* Open the file, guard to prevent failure to close. */
FsFile f;
R_TRY(fsFsOpenFile(&g_sd_fs, fs_path, open_mode, &f));
auto file_guard = SCOPE_GUARD { fsFileClose(&f); };
/* Set size if needed. */
if (create_mode == TIOCreateOption_ResetSize) {
R_TRY(fsFileSetSize(&f, 0));
}
/* Cancel guard, output file handle. */
file_guard.Cancel();
out_hnd.SetValue(GetNewFileHandle(f));
return ResultSuccess();
}
Result DebugMonitorService::TargetIO_FileClose(TargetIOFileHandle hnd) {
return CloseFileByHandle(hnd);
}
Result DebugMonitorService::TargetIO_FileRead(TargetIOFileHandle hnd, const sf::OutNonSecureBuffer &out_data, sf::Out<u32> out_read, s64 offset) {
FsFile f;
size_t read = 0;
R_TRY(GetFileByHandle(&f, hnd));
R_TRY(fsFileRead(&f, offset, out_data.GetPointer(), out_data.GetSize(), FsReadOption_None, &read));
out_read.SetValue(static_cast<u32>(read));
return ResultSuccess();
}
Result DebugMonitorService::TargetIO_FileWrite(TargetIOFileHandle hnd, const sf::InNonSecureBuffer &data, sf::Out<u32> out_written, s64 offset) {
FsFile f;
R_TRY(GetFileByHandle(&f, hnd));
R_TRY(fsFileWrite(&f, offset, data.GetPointer(), data.GetSize(), FsWriteOption_None));
out_written.SetValue(data.GetSize());
return ResultSuccess();
}
Result DebugMonitorService::TargetIO_FileSetAttributes(const sf::InBuffer &path, const sf::InBuffer &attributes) {
/* I don't really know why this command exists, Horizon doesn't allow you to set any attributes. */
/* N just returns ResultSuccess unconditionally here. */
return ResultSuccess();
}
Result DebugMonitorService::TargetIO_FileGetInformation(const sf::InBuffer &path, const sf::OutArray<u64> &out_info, sf::Out<int> is_directory) {
R_TRY(EnsureSdInitialized());
char fs_path[FS_MAX_PATH];
FixPath(fs_path, sizeof(fs_path), path);
for (size_t i = 0; i < out_info.GetSize(); i++) {
out_info[i] = 0;
}
is_directory.SetValue(0);
FsFile f;
if (R_SUCCEEDED(fsFsOpenFile(&g_sd_fs, fs_path, FsOpenMode_Read, &f))) {
ON_SCOPE_EXIT { fsFileClose(&f); };
/* N doesn't check this return code. */
if (out_info.GetSize() > 0) {
fsFileGetSize(&f, reinterpret_cast<s64 *>(&out_info[0]));
}
/* TODO: N does not call fsFsGetFileTimestampRaw here, but we possibly could. */
} else {
FsDir dir;
R_TRY(fsFsOpenDirectory(&g_sd_fs, fs_path, FsDirOpenMode_ReadFiles | FsDirOpenMode_ReadDirs, &dir));
fsDirClose(&dir);
is_directory.SetValue(1);
}
return ResultSuccess();
}
Result DebugMonitorService::TargetIO_FileSetTime(const sf::InBuffer &path, u64 create, u64 access, u64 modify) {
/* This is another function that doesn't really need to exist, because Horizon doesn't let you set anything. */
return ResultSuccess();
}
Result DebugMonitorService::TargetIO_FileSetSize(const sf::InBuffer &input, s64 size) {
/* Why does this function take in a path and not a file handle? */
R_TRY(EnsureSdInitialized());
/* We will try to be better than N, here. N only treats input as a path. */
FsFile f;
if (input.GetSize() == sizeof(TargetIOFileHandle)) {
R_UNLESS(R_FAILED(GetFileByHandle(&f, *reinterpret_cast<const TargetIOFileHandle *>(input.GetPointer()))), fsFileSetSize(&f, size));
}
char fs_path[FS_MAX_PATH];
FixPath(fs_path, sizeof(fs_path), input);
R_TRY(fsFsOpenFile(&g_sd_fs, fs_path, FsOpenMode_Write, &f));
ON_SCOPE_EXIT { fsFileClose(&f); };
return fsFileSetSize(&f, size);
}
Result DebugMonitorService::TargetIO_FileDelete(const sf::InBuffer &path) {
R_TRY(EnsureSdInitialized());
char fs_path[FS_MAX_PATH];
FixPath(fs_path, sizeof(fs_path), path);
return fsFsDeleteFile(&g_sd_fs, fs_path);
}
Result DebugMonitorService::TargetIO_FileMove(const sf::InBuffer &src_path, const sf::InBuffer &dst_path) {
R_TRY(EnsureSdInitialized());
char fs_src_path[FS_MAX_PATH];
char fs_dst_path[FS_MAX_PATH];
FixPath(fs_src_path, sizeof(fs_src_path), src_path);
FixPath(fs_dst_path, sizeof(fs_dst_path), dst_path);
return fsFsRenameFile(&g_sd_fs, fs_src_path, fs_dst_path);
}
}

View File

@@ -18,7 +18,7 @@
namespace ams::fatal::srv {
FatalEventManager::FatalEventManager() : lock(false) {
FatalEventManager::FatalEventManager() : lock() {
/* Just create all the events. */
for (size_t i = 0; i < FatalEventManager::NumFatalEvents; i++) {
R_ABORT_UNLESS(os::CreateSystemEvent(std::addressof(this->events[i]), os::EventClearMode_AutoClear, true));

View File

@@ -24,7 +24,7 @@ namespace ams::fatal::srv {
public:
static constexpr size_t NumFatalEvents = 3;
private:
os::Mutex lock;
os::SdkMutex lock;
size_t num_events_gotten = 0;
os::SystemEventType events[NumFatalEvents];
public:

View File

@@ -23,8 +23,8 @@ namespace ams::fatal::srv {
/* Convenience definitions. */
constexpr size_t MaximumLineLength = 0x20;
os::Mutex g_format_lock(false);
char g_format_buffer[2 * os::MemoryPageSize];
constinit os::SdkMutex g_format_lock;
constinit char g_format_buffer[2 * os::MemoryPageSize];
}

View File

@@ -20,7 +20,7 @@ namespace ams::ldr {
namespace {
os::Mutex g_scoped_code_mount_lock(false);
constinit os::SdkMutex g_scoped_code_mount_lock;
}

View File

@@ -23,7 +23,7 @@ namespace ams::ldr {
NON_COPYABLE(ScopedCodeMount);
NON_MOVEABLE(ScopedCodeMount);
private:
std::scoped_lock<os::Mutex> lk;
std::scoped_lock<os::SdkMutex> lk;
cfg::OverrideStatus override_status;
fs::CodeVerificationData ams_code_verification_data;
fs::CodeVerificationData sd_or_base_code_verification_data;

View File

@@ -167,9 +167,9 @@ namespace ams::pm::impl {
class ProcessList final : public util::IntrusiveListMemberTraits<&ProcessInfo::list_node>::ListType {
private:
os::Mutex lock;
os::SdkMutex lock;
public:
constexpr ProcessList() : lock(false) { /* ... */ }
constexpr ProcessList() : lock() { /* ... */ }
void Lock() {
this->lock.Lock();

View File

@@ -78,18 +78,15 @@ namespace ams::pm::impl {
NON_MOVEABLE(ProcessInfoAllocator);
static_assert(MaxProcessInfos >= 0x40, "MaxProcessInfos is too small.");
private:
util::TypedStorage<ProcessInfo> process_info_storages[MaxProcessInfos];
bool process_info_allocated[MaxProcessInfos];
os::Mutex lock;
util::TypedStorage<ProcessInfo> process_info_storages[MaxProcessInfos]{};
bool process_info_allocated[MaxProcessInfos]{};
os::SdkMutex lock{};
private:
constexpr inline size_t GetProcessInfoIndex(ProcessInfo *process_info) const {
return process_info - GetPointer(this->process_info_storages[0]);
}
public:
constexpr ProcessInfoAllocator() : lock(false) {
std::memset(this->process_info_storages, 0, sizeof(this->process_info_storages));
std::memset(this->process_info_allocated, 0, sizeof(this->process_info_allocated));
}
constexpr ProcessInfoAllocator() = default;
template<typename... Args>
ProcessInfo *AllocateProcessInfo(Args &&... args) {
@@ -123,34 +120,34 @@ namespace ams::pm::impl {
/* Process Tracking globals. */
void ProcessTrackingMain(void *arg);
os::ThreadType g_process_track_thread;
alignas(os::ThreadStackAlignment) u8 g_process_track_thread_stack[16_KB];
constinit os::ThreadType g_process_track_thread;
alignas(os::ThreadStackAlignment) constinit u8 g_process_track_thread_stack[16_KB];
/* Process lists. */
ProcessList g_process_list;
ProcessList g_dead_process_list;
constinit ProcessList g_process_list;
constinit ProcessList g_dead_process_list;
/* Process Info Allocation. */
/* Note: The kernel slabheap is size 0x50 -- we allow slightly larger to account for the dead process list. */
constexpr size_t MaxProcessCount = 0x60;
ProcessInfoAllocator<MaxProcessCount> g_process_info_allocator;
constinit ProcessInfoAllocator<MaxProcessCount> g_process_info_allocator;
/* Global events. */
os::SystemEventType g_process_event;
os::SystemEventType g_hook_to_create_process_event;
os::SystemEventType g_hook_to_create_application_process_event;
os::SystemEventType g_boot_finished_event;
constinit os::SystemEventType g_process_event;
constinit os::SystemEventType g_hook_to_create_process_event;
constinit os::SystemEventType g_hook_to_create_application_process_event;
constinit os::SystemEventType g_boot_finished_event;
/* Process Launch synchronization globals. */
os::Mutex g_launch_program_lock(false);
constinit os::SdkMutex g_launch_program_lock;
os::Event g_process_launch_start_event(os::EventClearMode_AutoClear);
os::Event g_process_launch_finish_event(os::EventClearMode_AutoClear);
Result g_process_launch_result = ResultSuccess();
LaunchProcessArgs g_process_launch_args = {};
constinit Result g_process_launch_result = ResultSuccess();
constinit LaunchProcessArgs g_process_launch_args = {};
/* Hook globals. */
std::atomic<ncm::ProgramId> g_program_id_hook;
std::atomic<bool> g_application_hook;
constinit std::atomic<ncm::ProgramId> g_program_id_hook;
constinit std::atomic<bool> g_application_hook;
/* Forward declarations. */
Result LaunchProcess(os::WaitableManagerType &waitable_manager, const LaunchProcessArgs &args);

View File

@@ -44,13 +44,13 @@ namespace ams::pm::resource {
constexpr size_t ExtraSystemMemorySizeAtmosphere500 = 33_MB; /* Applet pool is 0x20100000 */
/* Globals. */
os::Mutex g_resource_limit_lock(false);
Handle g_resource_limit_handles[ResourceLimitGroup_Count];
spl::MemoryArrangement g_memory_arrangement = spl::MemoryArrangement_Standard;
u64 g_system_memory_boost_size = 0;
u64 g_extra_application_threads_available = 0;
constinit os::SdkMutex g_resource_limit_lock;
constinit Handle g_resource_limit_handles[ResourceLimitGroup_Count];
constinit spl::MemoryArrangement g_memory_arrangement = spl::MemoryArrangement_Standard;
constinit u64 g_system_memory_boost_size = 0;
constinit u64 g_extra_application_threads_available = 0;
u64 g_resource_limits[ResourceLimitGroup_Count][svc::LimitableResource_Count] = {
constinit u64 g_resource_limits[ResourceLimitGroup_Count][svc::LimitableResource_Count] = {
[ResourceLimitGroup_System] = {
[svc::LimitableResource_PhysicalMemoryMax] = 0, /* Initialized by more complicated logic later. */
[svc::LimitableResource_ThreadCountMax] = 508,
@@ -74,7 +74,7 @@ namespace ams::pm::resource {
},
};
u64 g_memory_resource_limits[spl::MemoryArrangement_Count][ResourceLimitGroup_Count] = {
constinit u64 g_memory_resource_limits[spl::MemoryArrangement_Count][ResourceLimitGroup_Count] = {
[spl::MemoryArrangement_Standard] = {
[ResourceLimitGroup_System] = 269_MB,
[ResourceLimitGroup_Application] = 3285_MB,

View File

@@ -145,7 +145,7 @@ namespace ams::sm::impl {
/* any kind of mutual exclusivity when accessing (and modifying) global state. Previously, this was */
/* not a problem, because sm was strictly single-threaded, and so two threads could not race eachother. */
/* We will add a mutex (and perform locking) in order to prevent simultaneous access to global state. */
constinit os::Mutex g_mutex{true};
constinit os::SdkRecursiveMutex g_mutex;
constinit std::array<ProcessInfo, ProcessCountMax> g_process_list = [] {
std::array<ProcessInfo, ProcessCountMax> list = {};

View File

@@ -41,8 +41,8 @@ namespace ams::spl::impl {
constexpr s32 MaxVirtualAesKeySlots = 9;
/* KeySlot management. */
KeySlotCache g_keyslot_cache;
util::optional<KeySlotCacheEntry> g_keyslot_cache_entry[MaxPhysicalAesKeySlots];
constinit KeySlotCache g_keyslot_cache;
constinit util::optional<KeySlotCacheEntry> g_keyslot_cache_entry[MaxPhysicalAesKeySlots];
inline s32 GetMaxPhysicalKeySlots() {
return (hos::GetVersion() >= hos::Version_6_0_0) ? MaxPhysicalAesKeySlots : MaxPhysicalAesKeySlotsDeprecated;
@@ -96,9 +96,9 @@ namespace ams::spl::impl {
};
};
const void *g_keyslot_owners[MaxVirtualAesKeySlots];
KeySlotContents g_keyslot_contents[MaxVirtualAesKeySlots];
KeySlotContents g_physical_keyslot_contents_for_backwards_compatibility[MaxPhysicalAesKeySlots];
constinit const void *g_keyslot_owners[MaxVirtualAesKeySlots];
constinit KeySlotContents g_keyslot_contents[MaxVirtualAesKeySlots];
constinit KeySlotContents g_physical_keyslot_contents_for_backwards_compatibility[MaxPhysicalAesKeySlots];
void ClearPhysicalKeySlot(s32 keyslot) {
AMS_ASSERT(IsPhysicalKeySlot(keyslot));
@@ -237,18 +237,18 @@ namespace ams::spl::impl {
};
/* Global variables. */
CtrDrbg g_drbg;
os::InterruptEventType g_se_event;
os::SystemEventType g_se_keyslot_available_event;
constinit CtrDrbg g_drbg;
constinit os::InterruptEventType g_se_event;
constinit os::SystemEventType g_se_keyslot_available_event;
Handle g_se_das_hnd;
u32 g_se_mapped_work_buffer_addr;
alignas(os::MemoryPageSize) u8 g_work_buffer[2 * WorkBufferSizeMax];
constinit Handle g_se_das_hnd;
constinit u32 g_se_mapped_work_buffer_addr;
alignas(os::MemoryPageSize) constinit u8 g_work_buffer[2 * WorkBufferSizeMax];
os::Mutex g_async_op_lock(false);
constinit os::SdkMutex g_async_op_lock;
BootReasonValue g_boot_reason;
bool g_boot_reason_set;
constinit BootReasonValue g_boot_reason;
constinit bool g_boot_reason_set;
/* Boot Reason accessors. */
BootReasonValue GetBootReason() {
@@ -505,10 +505,13 @@ namespace ams::spl::impl {
void Initialize() {
/* Initialize the Drbg. */
InitializeCtrDrbg();
/* Initialize SE interrupt + keyslot events. */
InitializeSeEvents();
/* Initialize DAS for the SE. */
InitializeDeviceAddressSpace();
/* Initialize the keyslot cache. */
InitializeKeySlotCache();
}