id
int64
0
755k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
7,124
ldr_development_manager.cpp
Atmosphere-NX_Atmosphere/stratosphere/loader/source/ldr_development_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 "ldr_launch_record.hpp" namespace ams::ldr { namespace { bool g_development_for_acid_production_check = false; bool g_development_for_anti_downgrade_check = false; bool g_development_for_acid_signature_check = false; bool g_enabled_program_verification = true; } void SetDevelopmentForAcidProductionCheck(bool development) { g_development_for_acid_production_check = development; } void SetDevelopmentForAntiDowngradeCheck(bool development) { g_development_for_anti_downgrade_check = development; } void SetDevelopmentForAcidSignatureCheck(bool development) { g_development_for_acid_signature_check = development; } void SetEnabledProgramVerification(bool enabled) { if (g_development_for_acid_signature_check) { g_enabled_program_verification = enabled; } } bool IsDevelopmentForAcidProductionCheck() { return g_development_for_acid_production_check; } bool IsDevelopmentForAntiDowngradeCheck() { return g_development_for_anti_downgrade_check; } bool IsDevelopmentForAcidSignatureCheck() { return g_development_for_acid_signature_check; } bool IsEnabledProgramVerification() { return g_enabled_program_verification; } }
2,005
C++
.cpp
51
34.098039
76
0.725914
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,125
ldr_patcher.cpp
Atmosphere-NX_Atmosphere/stratosphere/loader/source/ldr_patcher.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "ldr_patcher.hpp" namespace ams::ldr { namespace { constexpr const char *NsoPatchesDirectory = "exefs_patches"; /* Exefs patches want to prevent modification of header, */ /* and also want to adjust offset relative to mapped location. */ constexpr size_t NsoPatchesProtectedSize = sizeof(NsoHeader); constexpr size_t NsoPatchesProtectedOffset = sizeof(NsoHeader); constexpr const char * const LoaderSdMountName = "#amsldr-sdpatch"; static_assert(sizeof(LoaderSdMountName) <= fs::MountNameLengthMax); constinit os::SdkMutex g_ldr_sd_lock; constinit bool g_mounted_sd; constinit os::SdkMutex g_embedded_patch_lock; constinit bool g_got_embedded_patch_settings; constinit bool g_force_enable_usb30; bool EnsureSdCardMounted() { std::scoped_lock lk(g_ldr_sd_lock); if (g_mounted_sd) { return true; } if (!cfg::IsSdCardInitialized()) { return false; } if (R_FAILED(fs::MountSdCard(LoaderSdMountName))) { return false; } return (g_mounted_sd = true); } bool IsUsb30ForceEnabled() { std::scoped_lock lk(g_embedded_patch_lock); if (!g_got_embedded_patch_settings) { g_force_enable_usb30 = spl::IsUsb30ForceEnabled(); g_got_embedded_patch_settings = true; } return g_force_enable_usb30; } consteval u8 ParseNybble(char c) { AMS_ASSUME(('0' <= c && c <= '9') || ('A' <= c && c <= 'F') || ('a' <= c && c <= 'f')); if ('0' <= c && c <= '9') { return c - '0' + 0x0; } else if ('A' <= c && c <= 'F') { return c - 'A' + 0xA; } else /* if ('a' <= c && c <= 'f') */ { return c - 'a' + 0xa; } } consteval ro::ModuleId ParseModuleId(const char *str) { /* Parse a static module id. */ ro::ModuleId module_id = {}; size_t ofs = 0; while (str[0] != 0) { AMS_ASSUME(ofs < sizeof(module_id)); AMS_ASSUME(str[1] != 0); module_id.data[ofs] = (ParseNybble(str[0]) << 4) | (ParseNybble(str[1]) << 0); str += 2; ofs++; } return module_id; } struct EmbeddedPatchEntry { uintptr_t offset; const void * const data; size_t size; }; struct EmbeddedPatch { ro::ModuleId module_id; size_t num_entries; const EmbeddedPatchEntry *entries; }; #include "ldr_embedded_usb_patches.inc" } /* Apply IPS patches. */ void LocateAndApplyIpsPatchesToModule(const u8 *module_id_data, uintptr_t mapped_nso, size_t mapped_size) { if (!EnsureSdCardMounted()) { return; } ro::ModuleId module_id; std::memcpy(std::addressof(module_id.data), module_id_data, sizeof(module_id.data)); ams::patcher::LocateAndApplyIpsPatchesToModule(LoaderSdMountName, NsoPatchesDirectory, NsoPatchesProtectedSize, NsoPatchesProtectedOffset, std::addressof(module_id), reinterpret_cast<u8 *>(mapped_nso), mapped_size); } /* Apply embedded patches. */ void ApplyEmbeddedPatchesToModule(const u8 *module_id_data, uintptr_t mapped_nso, size_t mapped_size) { /* Make module id. */ ro::ModuleId module_id; std::memcpy(std::addressof(module_id.data), module_id_data, sizeof(module_id.data)); if (IsUsb30ForceEnabled()) { for (const auto &patch : Usb30ForceEnablePatches) { if (std::memcmp(std::addressof(patch.module_id), std::addressof(module_id), sizeof(module_id)) == 0) { for (size_t i = 0; i < patch.num_entries; ++i) { const auto &entry = patch.entries[i]; if (entry.offset + entry.size <= mapped_size) { std::memcpy(reinterpret_cast<void *>(mapped_nso + entry.offset), entry.data, entry.size); } } } } } } }
5,013
C++
.cpp
115
32.86087
223
0.567673
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,126
ldr_launch_record.cpp
Atmosphere-NX_Atmosphere/stratosphere/loader/source/ldr_launch_record.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "ldr_launch_record.hpp" namespace ams::ldr { namespace { static constexpr size_t MaxBootPrograms = 0x50; constinit std::array<ncm::ProgramId, MaxBootPrograms> g_launched_boot_programs = [] { std::array<ncm::ProgramId, MaxBootPrograms> arr = {}; for (size_t i = 0; i < MaxBootPrograms; ++i) { arr[i] = ncm::InvalidProgramId; } return arr; }(); constinit bool g_boot_programs_done = false; bool HasLaunchedBootProgramImpl(ncm::ProgramId program_id) { for (const auto &launched : g_launched_boot_programs) { if (launched == program_id) { return true; } } return false; } void SetLaunchedBootProgramImpl(ncm::ProgramId program_id) { for (size_t i = 0; i < MaxBootPrograms; ++i) { if (g_launched_boot_programs[i] == ncm::InvalidProgramId) { g_launched_boot_programs[i] = program_id; return; } } AMS_ABORT("Too many boot programs"); } } /* Launch Record API. */ bool HasLaunchedBootProgram(ncm::ProgramId program_id) { return HasLaunchedBootProgramImpl(program_id); } void SetLaunchedBootProgram(ncm::ProgramId program_id) { if (!g_boot_programs_done) { SetLaunchedBootProgramImpl(program_id); if (program_id == ncm::SystemAppletId::Qlaunch) { g_boot_programs_done = true; } } } } /* Loader wants to override this libstratosphere function, which is weakly linked. */ /* This is necessary to prevent circular dependencies. */ namespace ams::pm::info { Result HasLaunchedBootProgram(bool *out, ncm::ProgramId program_id) { *out = ldr::HasLaunchedBootProgram(program_id); R_SUCCEED(); } }
2,617
C++
.cpp
67
30.910448
93
0.623965
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,127
ldr_process_creation.cpp
Atmosphere-NX_Atmosphere/stratosphere/loader/source/ldr_process_creation.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "ldr_capabilities.hpp" #include "ldr_content_management.hpp" #include "ldr_development_manager.hpp" #include "ldr_launch_record.hpp" #include "ldr_meta.hpp" #include "ldr_patcher.hpp" #include "ldr_process_creation.hpp" #include "ldr_ro_manager.hpp" namespace ams::ldr { namespace { /* Convenience defines. */ constexpr size_t SystemResourceSizeMax = 0x1FE00000; /* Types. */ enum NsoIndex { Nso_Rtld = 0, Nso_Main = 1, Nso_Compat0 = 2, Nso_Compat1 = 3, Nso_Compat2 = 4, Nso_Compat3 = 5, Nso_Compat4 = 6, Nso_Compat5 = 7, Nso_Compat6 = 8, Nso_Compat7 = 9, Nso_Compat8 = 10, Nso_Compat9 = 11, Nso_SubSdk0 = 12, Nso_SubSdk1 = 13, Nso_SubSdk2 = 14, Nso_SubSdk3 = 15, Nso_SubSdk4 = 16, Nso_SubSdk5 = 17, Nso_SubSdk6 = 18, Nso_SubSdk7 = 19, Nso_SubSdk8 = 20, Nso_SubSdk9 = 21, Nso_Sdk = 22, Nso_Count, }; constexpr inline const char *NsoPaths[Nso_Count] = { ENCODE_ATMOSPHERE_CODE_PATH("/rtld"), ENCODE_ATMOSPHERE_CODE_PATH("/main"), ENCODE_ATMOSPHERE_CMPT_PATH("/compat0"), ENCODE_ATMOSPHERE_CMPT_PATH("/compat1"), ENCODE_ATMOSPHERE_CMPT_PATH("/compat2"), ENCODE_ATMOSPHERE_CMPT_PATH("/compat3"), ENCODE_ATMOSPHERE_CMPT_PATH("/compat4"), ENCODE_ATMOSPHERE_CMPT_PATH("/compat5"), ENCODE_ATMOSPHERE_CMPT_PATH("/compat6"), ENCODE_ATMOSPHERE_CMPT_PATH("/compat7"), ENCODE_ATMOSPHERE_CMPT_PATH("/compat8"), ENCODE_ATMOSPHERE_CMPT_PATH("/compat9"), ENCODE_ATMOSPHERE_CODE_PATH("/subsdk0"), ENCODE_ATMOSPHERE_CODE_PATH("/subsdk1"), ENCODE_ATMOSPHERE_CODE_PATH("/subsdk2"), ENCODE_ATMOSPHERE_CODE_PATH("/subsdk3"), ENCODE_ATMOSPHERE_CODE_PATH("/subsdk4"), ENCODE_ATMOSPHERE_CODE_PATH("/subsdk5"), ENCODE_ATMOSPHERE_CODE_PATH("/subsdk6"), ENCODE_ATMOSPHERE_CODE_PATH("/subsdk7"), ENCODE_ATMOSPHERE_CODE_PATH("/subsdk8"), ENCODE_ATMOSPHERE_CODE_PATH("/subsdk9"), ENCODE_ATMOSPHERE_CODE_PATH("/sdk"), }; constexpr const char *GetNsoPath(size_t idx) { AMS_ABORT_UNLESS(idx < Nso_Count); return NsoPaths[idx]; } struct ProcessInfo { os::NativeHandle process_handle; uintptr_t args_address; size_t args_size; uintptr_t nso_address[Nso_Count]; size_t nso_size[Nso_Count]; }; /* Global NSO header cache. */ bool g_has_nso[Nso_Count]; NsoHeader g_nso_headers[Nso_Count]; Result ValidateProgramVersion(ncm::ProgramId program_id, u32 version) { /* No version verification is done before 8.1.0. */ R_SUCCEED_IF(hos::GetVersion() < hos::Version_8_1_0); /* No verification is done if development. */ R_SUCCEED_IF(IsDevelopmentForAntiDowngradeCheck()); /* TODO: Anti-downgrade checking does not make very much sense for us. Should we do anything? */ AMS_UNUSED(program_id, version); R_SUCCEED(); } /* Helpers. */ Result GetProgramInfoFromMeta(ProgramInfo *out, const Meta *meta) { /* Copy basic info. */ out->main_thread_priority = meta->npdm->main_thread_priority; out->default_cpu_id = meta->npdm->default_cpu_id; out->main_thread_stack_size = meta->npdm->main_thread_stack_size; out->program_id = meta->aci->program_id; /* Copy access controls. */ size_t offset = 0; #define COPY_ACCESS_CONTROL(source, which) \ ({ \ const size_t size = meta->source->which##_size; \ R_UNLESS(offset + size <= sizeof(out->ac_buffer), ldr::ResultInternalError()); \ out->source##_##which##_size = size; \ std::memcpy(out->ac_buffer + offset, meta->source##_##which, size); \ offset += size; \ }) /* Copy all access controls to buffer. */ COPY_ACCESS_CONTROL(acid, sac); COPY_ACCESS_CONTROL(aci, sac); COPY_ACCESS_CONTROL(acid, fac); COPY_ACCESS_CONTROL(aci, fah); #undef COPY_ACCESS_CONTROL /* Copy flags. */ out->flags = MakeProgramInfoFlag(static_cast<const util::BitPack32 *>(meta->aci_kac), meta->aci->kac_size / sizeof(util::BitPack32)); R_SUCCEED(); } bool IsApplet(const Meta *meta) { return (MakeProgramInfoFlag(static_cast<const util::BitPack32 *>(meta->aci_kac), meta->aci->kac_size / sizeof(util::BitPack32)) & ProgramInfoFlag_ApplicationTypeMask) == ProgramInfoFlag_Applet; } bool IsApplication(const Meta *meta) { return (MakeProgramInfoFlag(static_cast<const util::BitPack32 *>(meta->aci_kac), meta->aci->kac_size / sizeof(util::BitPack32)) & ProgramInfoFlag_ApplicationTypeMask) == ProgramInfoFlag_Application; } Npdm::AddressSpaceType GetAddressSpaceType(const Meta *meta) { return static_cast<Npdm::AddressSpaceType>((meta->npdm->flags & Npdm::MetaFlag_AddressSpaceTypeMask) >> Npdm::MetaFlag_AddressSpaceTypeShift); } Acid::PoolPartition GetPoolPartition(const Meta *meta) { return static_cast<Acid::PoolPartition>((meta->acid->flags & Acid::AcidFlag_PoolPartitionMask) >> Acid::AcidFlag_PoolPartitionShift); } Result LoadAutoLoadHeaders(NsoHeader *nso_headers, bool *has_nso) { /* Clear NSOs. */ std::memset(nso_headers, 0, sizeof(*nso_headers) * Nso_Count); std::memset(has_nso, 0, sizeof(*has_nso) * Nso_Count); for (size_t i = 0; i < Nso_Count; i++) { fs::FileHandle file; if (R_SUCCEEDED(fs::OpenFile(std::addressof(file), GetNsoPath(i), fs::OpenMode_Read))) { ON_SCOPE_EXIT { fs::CloseFile(file); }; /* Read NSO header. */ size_t read_size; R_TRY(fs::ReadFile(std::addressof(read_size), file, 0, nso_headers + i, sizeof(*nso_headers))); R_UNLESS(read_size == sizeof(*nso_headers), ldr::ResultInvalidNso()); has_nso[i] = true; } } R_SUCCEED(); } Result CheckAutoLoad(const NsoHeader *nso_headers, const bool *has_nso) { /* We must always have a main. */ R_UNLESS(has_nso[Nso_Main], ldr::ResultInvalidNso()); /* If we don't have an RTLD, we must only have a main. */ if (!has_nso[Nso_Rtld]) { for (size_t i = Nso_Main + 1; i < Nso_Count; i++) { R_UNLESS(!has_nso[i], ldr::ResultInvalidNso()); } } /* All NSOs must have zero text offset. */ for (size_t i = 0; i < Nso_Count; i++) { R_UNLESS(nso_headers[i].text_dst_offset == 0, ldr::ResultInvalidNso()); } R_SUCCEED(); } constexpr const ncm::ProgramId UnqualifiedApprovalProgramIds[] = { { 0x010003F003A34000 }, /* Pokemon: Let's Go, Pikachu! */ { 0x0100152000022000 }, /* Mario Kart 8 Deluxe */ { 0x0100165003504000 }, /* Nintendo Labo Toy-Con 04: VR Kit */ { 0x0100187003A36000 }, /* Pokemon: Let's Go, Eevee! */ { 0x01002E5008C56000 }, /* Pokemon Sword [Live Tournament] */ { 0x01002FF008C24000 }, /* Ring Fit Adventure */ { 0x010049900F546001 }, /* Super Mario 3D All-Stars: Super Mario 64 */ { 0x010057D00ECE4000 }, /* Nintendo Switch Online (Nintendo 64) [for Japan] */ { 0x01006F8002326000 }, /* Animal Crossing: New Horizons */ { 0x01006FB00F50E000 }, /* [???] */ { 0x010070300F50C000 }, /* [???] */ { 0x010075100E8EC000 }, /* 马力欧卡丁车8 豪华版 [Mario Kart 8 Deluxe for China] */ { 0x01008DB008C2C000 }, /* Pokemon Shield */ { 0x01009AD008C4C000 }, /* Pokemon: Let's Go, Pikachu! [Kiosk] */ { 0x0100A66003384000 }, /* Hulu */ { 0x0100ABF008968000 }, /* Pokemon Sword */ { 0x0100C9A00ECE6000 }, /* Nintendo Switch Online (Nintendo 64) [for America] */ { 0x0100ED100BA3A000 }, /* Mario Kart Live: Home Circuit */ { 0x0100F38011CFE000 }, /* Animal Crossing: New Horizons Island Transfer Tool */ { 0x0100F6B011028000 }, /* 健身环大冒险 [Ring Fit Adventure for China] */ }; /* Check that the unqualified approval programs are sorted. */ static_assert([]() -> bool { for (size_t i = 0; i < util::size(UnqualifiedApprovalProgramIds) - 1; ++i) { if (UnqualifiedApprovalProgramIds[i].value >= UnqualifiedApprovalProgramIds[i + 1].value) { return false; } } return true; }()); bool IsUnqualifiedApprovalProgramId(ncm::ProgramId program_id) { /* Check if the program id is one with unqualified approval. */ return std::binary_search(std::begin(UnqualifiedApprovalProgramIds), std::end(UnqualifiedApprovalProgramIds), program_id); } bool IsUnqualifiedApproval(const Meta *meta) { /* If the meta has unqualified approval flag, it's unqualified approval. */ if (meta->acid->flags & ldr::Acid::AcidFlag_UnqualifiedApproval) { return true; } /* If the unqualified approval flag is not set, the program must be an application. */ if (!IsApplication(meta)) { return false; } /* The program id must be a force unqualified approval program id. */ return IsUnqualifiedApprovalProgramId(meta->acid->program_id_min) && meta->acid->program_id_min == meta->acid->program_id_max; } Result ValidateMeta(const Meta *meta, const ncm::ProgramLocation &loc, const fs::CodeVerificationData &code_verification_data) { /* Validate version. */ R_TRY(ValidateProgramVersion(loc.program_id, meta->npdm->version)); /* Validate program id. */ R_UNLESS(meta->aci->program_id >= meta->acid->program_id_min, ldr::ResultInvalidProgramId()); R_UNLESS(meta->aci->program_id <= meta->acid->program_id_max, ldr::ResultInvalidProgramId()); /* Validate the kernel capabilities. */ R_TRY(TestCapability(static_cast<const util::BitPack32 *>(meta->acid_kac), meta->acid->kac_size / sizeof(util::BitPack32), static_cast<const util::BitPack32 *>(meta->aci_kac), meta->aci->kac_size / sizeof(util::BitPack32))); /* If we have data to validate, validate it. */ if (meta->check_verification_data) { const u8 *sig = code_verification_data.signature; const size_t sig_size = sizeof(code_verification_data.signature); const u8 *mod = static_cast<u8 *>(meta->modulus); const size_t mod_size = crypto::Rsa2048PssSha256Verifier::ModulusSize; const u8 *exp = fssystem::GetAcidSignatureKeyPublicExponent(); const size_t exp_size = fssystem::AcidSignatureKeyPublicExponentSize; const u8 *hsh = code_verification_data.target_hash; const size_t hsh_size = sizeof(code_verification_data.target_hash); const bool is_signature_valid = crypto::VerifyRsa2048PssSha256WithHash(sig, sig_size, mod, mod_size, exp, exp_size, hsh, hsh_size); /* If the signature check fails, we need to check if this is allowable. */ if (!is_signature_valid) { /* We have to enforce signature checks on prod and when we have a signature to check on dev. */ R_UNLESS(IsDevelopmentForAcidProductionCheck(), ldr::ResultInvalidNcaSignature()); R_UNLESS(!code_verification_data.has_data, ldr::ResultInvalidNcaSignature()); /* There was no signature to check on dev. Check if this is acceptable. */ R_UNLESS(IsUnqualifiedApproval(meta), ldr::ResultInvalidNcaSignature()); } } /* All good. */ R_SUCCEED(); } Result GetCreateProcessFlags(u32 *out, const Meta *meta, const u32 ldr_flags) { const u8 meta_flags = meta->npdm->flags; u32 flags = 0; /* Set Is64Bit. */ if (meta_flags & Npdm::MetaFlag_Is64Bit) { flags |= svc::CreateProcessFlag_Is64Bit; } /* Set AddressSpaceType. */ switch (GetAddressSpaceType(meta)) { case Npdm::AddressSpaceType_32Bit: flags |= svc::CreateProcessFlag_AddressSpace32Bit; break; case Npdm::AddressSpaceType_64BitDeprecated: flags |= svc::CreateProcessFlag_AddressSpace64BitDeprecated; break; case Npdm::AddressSpaceType_32BitWithoutAlias: flags |= svc::CreateProcessFlag_AddressSpace32BitWithoutAlias; break; case Npdm::AddressSpaceType_64Bit: flags |= svc::CreateProcessFlag_AddressSpace64Bit; break; default: R_THROW(ldr::ResultInvalidMeta()); } /* Set Enable Debug. */ if (ldr_flags & CreateProcessFlag_EnableDebug) { flags |= svc::CreateProcessFlag_EnableDebug; } /* Set Enable ASLR. */ if (!(ldr_flags & CreateProcessFlag_DisableAslr)) { flags |= svc::CreateProcessFlag_EnableAslr; } /* Set Is Application. */ if (IsApplication(meta)) { flags |= svc::CreateProcessFlag_IsApplication; /* 7.0.0+: Set OptimizeMemoryAllocation if relevant. */ if (hos::GetVersion() >= hos::Version_7_0_0) { if (meta_flags & Npdm::MetaFlag_OptimizeMemoryAllocation) { flags |= svc::CreateProcessFlag_OptimizeMemoryAllocation; } } } /* 5.0.0+ Set Pool Partition. */ if (hos::GetVersion() >= hos::Version_5_0_0) { /* TODO: Nintendo no longer accepts Applet when pool partition == application. Would this break hbl/anything else in the hb ecosystem? */ /* TODO: Nintendo uses a helper bool MakeSvcPoolPartitionFlag(u32 *out, Acid::PoolPartition partition); */ switch (GetPoolPartition(meta)) { case Acid::PoolPartition_Application: if (IsApplet(meta)) { flags |= svc::CreateProcessFlag_PoolPartitionApplet; } else { flags |= svc::CreateProcessFlag_PoolPartitionApplication; } break; case Acid::PoolPartition_Applet: flags |= svc::CreateProcessFlag_PoolPartitionApplet; break; case Acid::PoolPartition_System: flags |= svc::CreateProcessFlag_PoolPartitionSystem; break; case Acid::PoolPartition_SystemNonSecure: flags |= svc::CreateProcessFlag_PoolPartitionSystemNonSecure; break; default: R_THROW(ldr::ResultInvalidMeta()); } } else if (hos::GetVersion() >= hos::Version_4_0_0) { /* On 4.0.0+, the corresponding bit was simply "UseSecureMemory". */ if (meta->acid->flags & Acid::AcidFlag_DeprecatedUseSecureMemory) { flags |= svc::CreateProcessFlag_DeprecatedUseSecureMemory; } } /* 11.0.0+/meso Set Disable DAS merge. */ if (meta_flags & Npdm::MetaFlag_DisableDeviceAddressSpaceMerge) { flags |= svc::CreateProcessFlag_DisableDeviceAddressSpaceMerge; } /* 18.0.0+/meso Set Alias region extra size. */ if (meta_flags & Npdm::MetaFlag_EnableAliasRegionExtraSize) { flags |= svc::CreateProcessFlag_EnableAliasRegionExtraSize; } *out = flags; R_SUCCEED(); } Result GetCreateProcessParameter(svc::CreateProcessParameter *out, const Meta *meta, u32 flags, os::NativeHandle resource_limit) { /* Clear output. */ std::memset(out, 0, sizeof(*out)); /* Set name, version, program id, resource limit handle. */ std::memcpy(out->name, meta->npdm->program_name, sizeof(out->name) - 1); out->version = meta->npdm->version; out->program_id = meta->aci->program_id.value; out->reslimit = resource_limit; /* Set flags. */ R_TRY(GetCreateProcessFlags(std::addressof(out->flags), meta, flags)); /* 3.0.0+ System Resource Size. */ if (hos::GetVersion() >= hos::Version_3_0_0) { /* Validate size is aligned. */ R_UNLESS(util::IsAligned(meta->npdm->system_resource_size, os::MemoryBlockUnitSize), ldr::ResultInvalidSize()); /* Validate system resource usage. */ if (meta->npdm->system_resource_size) { /* Process must be 64-bit. */ R_UNLESS((out->flags & svc::CreateProcessFlag_AddressSpace64Bit), ldr::ResultInvalidMeta()); /* Process must be application or applet. */ R_UNLESS(IsApplication(meta) || IsApplet(meta), ldr::ResultInvalidMeta()); /* Size must be less than or equal to max. */ R_UNLESS(meta->npdm->system_resource_size <= SystemResourceSizeMax, ldr::ResultInvalidMeta()); } out->system_resource_num_pages = meta->npdm->system_resource_size >> 12; } R_SUCCEED(); } u64 GenerateSecureRandom(u64 max) { /* Generate a cryptographically random number. */ u64 rand; crypto::GenerateCryptographicallyRandomBytes(std::addressof(rand), sizeof(rand)); /* Coerce into range. */ return rand % (max + 1); } Result DecideAddressSpaceLayout(ProcessInfo *out, svc::CreateProcessParameter *out_param, const NsoHeader *nso_headers, const bool *has_nso, const ArgumentStore::Entry *argument) { /* Clear output. */ out->args_address = 0; out->args_size = 0; std::memset(out->nso_address, 0, sizeof(out->nso_address)); std::memset(out->nso_size, 0, sizeof(out->nso_size)); size_t total_size = 0; bool argument_allocated = false; /* Calculate base offsets. */ for (size_t i = 0; i < Nso_Count; i++) { if (has_nso[i]) { out->nso_address[i] = total_size; const size_t text_end = nso_headers[i].text_dst_offset + nso_headers[i].text_size; const size_t ro_end = nso_headers[i].ro_dst_offset + nso_headers[i].ro_size; const size_t rw_end = nso_headers[i].rw_dst_offset + nso_headers[i].rw_size + nso_headers[i].bss_size; out->nso_size[i] = text_end; out->nso_size[i] = std::max(out->nso_size[i], ro_end); out->nso_size[i] = std::max(out->nso_size[i], rw_end); out->nso_size[i] = util::AlignUp(out->nso_size[i], os::MemoryPageSize); total_size += out->nso_size[i]; if (!argument_allocated && argument != nullptr) { out->args_address = total_size; out->args_size = util::AlignUp(2 * sizeof(u32) + argument->argument_size * 2 + ArgumentStore::ArgumentBufferSize, os::MemoryPageSize); total_size += out->args_size; argument_allocated = true; } } } /* Calculate ASLR. */ uintptr_t aslr_start = 0; size_t aslr_size = 0; if (hos::GetVersion() >= hos::Version_2_0_0) { switch (out_param->flags & svc::CreateProcessFlag_AddressSpaceMask) { case svc::CreateProcessFlag_AddressSpace32Bit: case svc::CreateProcessFlag_AddressSpace32BitWithoutAlias: aslr_start = svc::AddressSmallMap32Start; aslr_size = svc::AddressSmallMap32Size; break; case svc::CreateProcessFlag_AddressSpace64BitDeprecated: aslr_start = svc::AddressSmallMap36Start; aslr_size = svc::AddressSmallMap36Size; break; case svc::CreateProcessFlag_AddressSpace64Bit: aslr_start = svc::AddressMap39Start; aslr_size = svc::AddressMap39Size; break; AMS_UNREACHABLE_DEFAULT_CASE(); } } else { /* On 1.0.0, only 2 address space types existed. */ if (out_param->flags & svc::CreateProcessFlag_AddressSpace64BitDeprecated) { aslr_start = svc::AddressSmallMap36Start; aslr_size = svc::AddressSmallMap36Size; } else { aslr_start = svc::AddressSmallMap32Start; aslr_size = svc::AddressSmallMap32Size; } } R_UNLESS(total_size <= aslr_size, svc::ResultOutOfMemory()); /* Set Create Process output. */ uintptr_t aslr_slide = 0; size_t free_size = (aslr_size - total_size); if (out_param->flags & svc::CreateProcessFlag_EnableAslr) { aslr_slide = GenerateSecureRandom(free_size / os::MemoryBlockUnitSize) * os::MemoryBlockUnitSize; } /* Set out. */ aslr_start += aslr_slide; for (size_t i = 0; i < Nso_Count; i++) { if (has_nso[i]) { out->nso_address[i] += aslr_start; } } if (out->args_address) { out->args_address += aslr_start; } out_param->code_address = aslr_start; out_param->code_num_pages = total_size >> 12; R_SUCCEED(); } Result LoadAutoLoadModuleSegment(fs::FileHandle file, const NsoHeader::SegmentInfo *segment, size_t file_size, const u8 *file_hash, bool is_compressed, bool check_hash, uintptr_t map_base, uintptr_t map_end) { /* Select read size based on compression. */ if (!is_compressed) { file_size = segment->size; } /* Validate size. */ R_UNLESS(file_size <= segment->size, ldr::ResultInvalidNso()); R_UNLESS(segment->size <= std::numeric_limits<s32>::max(), ldr::ResultInvalidNso()); /* Load data from file. */ uintptr_t load_address = is_compressed ? map_end - file_size : map_base; size_t read_size; R_TRY(fs::ReadFile(std::addressof(read_size), file, segment->file_offset, reinterpret_cast<void *>(load_address), file_size)); R_UNLESS(read_size == file_size, ldr::ResultInvalidNso()); /* Uncompress if necessary. */ if (is_compressed) { bool decompressed = (util::DecompressLZ4(reinterpret_cast<void *>(map_base), segment->size, reinterpret_cast<const void *>(load_address), file_size) == static_cast<int>(segment->size)); R_UNLESS(decompressed, ldr::ResultInvalidNso()); } /* Check hash if necessary. */ if (check_hash) { u8 hash[crypto::Sha256Generator::HashSize]; crypto::GenerateSha256(hash, sizeof(hash), reinterpret_cast<void *>(map_base), segment->size); R_UNLESS(std::memcmp(hash, file_hash, sizeof(hash)) == 0, ldr::ResultInvalidNso()); } R_SUCCEED(); } Result LoadAutoLoadModule(os::NativeHandle process_handle, fs::FileHandle file, const NsoHeader *nso_header, uintptr_t nso_address, size_t nso_size, bool prevent_code_reads) { /* Map and read data from file. */ { /* Map the process memory. */ void *mapped_memory = nullptr; R_TRY(os::MapProcessMemory(std::addressof(mapped_memory), process_handle, nso_address, nso_size, GenerateSecureRandom)); ON_SCOPE_EXIT { os::UnmapProcessMemory(mapped_memory, process_handle, nso_address, nso_size); }; const uintptr_t map_address = reinterpret_cast<uintptr_t>(mapped_memory); /* Load NSO segments. */ R_TRY(LoadAutoLoadModuleSegment(file, std::addressof(nso_header->segments[NsoHeader::Segment_Text]), nso_header->text_compressed_size, nso_header->text_hash, (nso_header->flags & NsoHeader::Flag_CompressedText) != 0, (nso_header->flags & NsoHeader::Flag_CheckHashText) != 0, map_address + nso_header->text_dst_offset, map_address + nso_size)); R_TRY(LoadAutoLoadModuleSegment(file, std::addressof(nso_header->segments[NsoHeader::Segment_Ro]), nso_header->ro_compressed_size, nso_header->ro_hash, (nso_header->flags & NsoHeader::Flag_CompressedRo) != 0, (nso_header->flags & NsoHeader::Flag_CheckHashRo) != 0, map_address + nso_header->ro_dst_offset, map_address + nso_size)); R_TRY(LoadAutoLoadModuleSegment(file, std::addressof(nso_header->segments[NsoHeader::Segment_Rw]), nso_header->rw_compressed_size, nso_header->rw_hash, (nso_header->flags & NsoHeader::Flag_CompressedRw) != 0, (nso_header->flags & NsoHeader::Flag_CheckHashRw) != 0, map_address + nso_header->rw_dst_offset, map_address + nso_size)); /* Clear unused space to zero. */ const size_t text_end = nso_header->text_dst_offset + nso_header->text_size; const size_t ro_end = nso_header->ro_dst_offset + nso_header->ro_size; const size_t rw_end = nso_header->rw_dst_offset + nso_header->rw_size; std::memset(reinterpret_cast<void *>(map_address + 0), 0, nso_header->text_dst_offset); std::memset(reinterpret_cast<void *>(map_address + text_end), 0, nso_header->ro_dst_offset - text_end); std::memset(reinterpret_cast<void *>(map_address + ro_end), 0, nso_header->rw_dst_offset - ro_end); std::memset(reinterpret_cast<void *>(map_address + rw_end), 0, nso_header->bss_size); /* Apply embedded patches. */ ApplyEmbeddedPatchesToModule(nso_header->module_id, map_address, nso_size); /* Apply IPS patches. */ LocateAndApplyIpsPatchesToModule(nso_header->module_id, map_address, nso_size); } /* Set permissions. */ const size_t text_size = util::AlignUp(nso_header->text_size, os::MemoryPageSize); const size_t ro_size = util::AlignUp(nso_header->ro_size, os::MemoryPageSize); const size_t rw_size = util::AlignUp(nso_header->rw_size + nso_header->bss_size, os::MemoryPageSize); if (text_size) { R_TRY(os::SetProcessMemoryPermission(process_handle, nso_address + nso_header->text_dst_offset, text_size, prevent_code_reads ? os::MemoryPermission_ExecuteOnly : os::MemoryPermission_ReadExecute)); } if (ro_size) { R_TRY(os::SetProcessMemoryPermission(process_handle, nso_address + nso_header->ro_dst_offset, ro_size, os::MemoryPermission_ReadOnly)); } if (rw_size) { R_TRY(os::SetProcessMemoryPermission(process_handle, nso_address + nso_header->rw_dst_offset, rw_size, os::MemoryPermission_ReadWrite)); } R_SUCCEED(); } Result LoadAutoLoadModules(const ProcessInfo *process_info, const NsoHeader *nso_headers, const bool *has_nso, const ArgumentStore::Entry *argument, bool prevent_code_reads) { /* Load each NSO. */ for (size_t i = 0; i < Nso_Count; i++) { if (has_nso[i]) { fs::FileHandle file; R_TRY(fs::OpenFile(std::addressof(file), GetNsoPath(i), fs::OpenMode_Read)); ON_SCOPE_EXIT { fs::CloseFile(file); }; R_TRY(LoadAutoLoadModule(process_info->process_handle, file, nso_headers + i, process_info->nso_address[i], process_info->nso_size[i], prevent_code_reads)); } } /* Load arguments, if present. */ if (argument != nullptr) { /* Write argument data into memory. */ { void *map_address = nullptr; R_TRY(os::MapProcessMemory(std::addressof(map_address), process_info->process_handle, process_info->args_address, process_info->args_size, GenerateSecureRandom)); ON_SCOPE_EXIT { os::UnmapProcessMemory(map_address, process_info->process_handle, process_info->args_address, process_info->args_size); }; ProgramArguments *args = static_cast<ProgramArguments *>(map_address); std::memset(args, 0, sizeof(*args)); args->allocated_size = process_info->args_size; args->arguments_size = argument->argument_size; std::memcpy(args->arguments, argument->argument, argument->argument_size); } /* Set argument region permissions. */ /* NOTE: Nintendo uses svc::SetProcessMemoryPermission directly here. */ R_TRY(os::SetProcessMemoryPermission(process_info->process_handle, process_info->args_address, process_info->args_size, os::MemoryPermission_ReadWrite)); } R_SUCCEED(); } Result CreateProcessAndLoadAutoLoadModules(ProcessInfo *out, const Meta *meta, const NsoHeader *nso_headers, const bool *has_nso, const ArgumentStore::Entry *argument, u32 flags, os::NativeHandle resource_limit) { /* Get CreateProcessParameter. */ svc::CreateProcessParameter param; R_TRY(GetCreateProcessParameter(std::addressof(param), meta, flags, resource_limit)); /* Decide on an NSO layout. */ R_TRY(DecideAddressSpaceLayout(out, std::addressof(param), nso_headers, has_nso, argument)); /* Actually create process. */ svc::Handle process_handle; R_TRY(svc::CreateProcess(std::addressof(process_handle), std::addressof(param), static_cast<const u32 *>(meta->aci_kac), meta->aci->kac_size / sizeof(u32))); /* Set the output handle, and ensure that if we fail after this point we clean it up. */ out->process_handle = process_handle; ON_RESULT_FAILURE { svc::CloseHandle(process_handle); }; /* Load all auto load modules. */ R_RETURN(LoadAutoLoadModules(out, nso_headers, has_nso, argument, (meta->npdm->flags & ldr::Npdm::MetaFlag_PreventCodeReads) != 0)); } } /* Process Creation API. */ Result CreateProcess(os::NativeHandle *out, PinId pin_id, const ncm::ProgramLocation &loc, const cfg::OverrideStatus &override_status, const char *path, const ArgumentStore::Entry *argument, u32 flags, os::NativeHandle resource_limit, ncm::ContentMetaPlatform platform) { /* Mount code. */ AMS_UNUSED(path); ScopedCodeMount mount(loc, override_status, platform); R_TRY(mount.GetResult()); /* Load meta, possibly from cache. */ Meta meta; R_TRY(LoadMetaFromCache(std::addressof(meta), loc, override_status, platform)); /* Validate meta. */ R_TRY(ValidateMeta(std::addressof(meta), loc, mount.GetCodeVerificationData())); /* Load, validate NSO headers. */ R_TRY(LoadAutoLoadHeaders(g_nso_headers, g_has_nso)); R_TRY(CheckAutoLoad(g_nso_headers, g_has_nso)); /* Actually create the process and load NSOs into process memory. */ ProcessInfo info; R_TRY(CreateProcessAndLoadAutoLoadModules(std::addressof(info), std::addressof(meta), g_nso_headers, g_has_nso, argument, flags, resource_limit)); /* Register NSOs with the RoManager. */ { /* Nintendo doesn't validate this get, but we do. */ os::ProcessId process_id = os::GetProcessId(info.process_handle); /* Register new process. */ const auto as_type = GetAddressSpaceType(std::addressof(meta)); RoManager::GetInstance().RegisterProcess(pin_id, process_id, meta.aci->program_id, as_type == Npdm::AddressSpaceType_64Bit || as_type == Npdm::AddressSpaceType_64BitDeprecated); /* Register all NSOs. */ for (size_t i = 0; i < Nso_Count; i++) { if (g_has_nso[i]) { RoManager::GetInstance().AddNso(pin_id, g_nso_headers[i].module_id, info.nso_address[i], info.nso_size[i]); } } } /* If we're overriding for HBL, perform HTML document redirection. */ if (override_status.IsHbl()) { /* Don't validate result, failure is okay. */ RedirectHtmlDocumentPathForHbl(loc); } /* Clear the external code for the program. */ fssystem::DestroyExternalCode(loc.program_id); /* Note that we've created the program. */ SetLaunchedBootProgram(loc.program_id); /* Move the process handle to output. */ *out = info.process_handle; R_SUCCEED(); } Result GetProgramInfo(ProgramInfo *out, cfg::OverrideStatus *out_status, const ncm::ProgramLocation &loc, const char *path, ncm::ContentMetaPlatform platform) { Meta meta; /* Load Meta. */ { AMS_UNUSED(path); ScopedCodeMount mount(loc, platform); R_TRY(mount.GetResult()); R_TRY(LoadMeta(std::addressof(meta), loc, mount.GetOverrideStatus(), platform, false)); if (out_status != nullptr) { *out_status = mount.GetOverrideStatus(); } } return GetProgramInfoFromMeta(out, std::addressof(meta)); } Result PinProgram(PinId *out_id, const ncm::ProgramLocation &loc, const cfg::OverrideStatus &override_status) { R_UNLESS(RoManager::GetInstance().Allocate(out_id, loc, override_status), ldr::ResultMaxProcess()); R_SUCCEED(); } Result UnpinProgram(PinId id) { R_UNLESS(RoManager::GetInstance().Free(id), ldr::ResultNotPinned()); R_SUCCEED(); } Result GetProcessModuleInfo(u32 *out_count, ldr::ModuleInfo *out, size_t max_out_count, os::ProcessId process_id) { R_UNLESS(RoManager::GetInstance().GetProcessModuleInfo(out_count, out, max_out_count, process_id), ldr::ResultNotPinned()); R_SUCCEED(); } Result GetProgramLocationAndOverrideStatusFromPinId(ncm::ProgramLocation *out, cfg::OverrideStatus *out_status, PinId pin_id) { R_UNLESS(RoManager::GetInstance().GetProgramLocationAndStatus(out, out_status, pin_id), ldr::ResultNotPinned()); R_SUCCEED(); } }
37,192
C++
.cpp
637
44.188383
275
0.575742
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,128
ldr_ro_manager.cpp
Atmosphere-NX_Atmosphere/stratosphere/loader/source/ldr_ro_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 "ldr_ro_manager.hpp" namespace ams::ldr { bool RoManager::Allocate(PinId *out, const ncm::ProgramLocation &loc, const cfg::OverrideStatus &status) { /* Ensure that output pin id is set. */ *out = InvalidPinId; /* Allocate a process info. */ auto *found = this->AllocateProcessInfo(); if (found == nullptr) { return false; } /* Setup the process info. */ std::memset(found, 0, sizeof(*found)); found->pin_id = { ++m_pin_id }; found->program_location = loc; found->override_status = status; found->in_use = true; /* Set the output pin id. */ *out = found->pin_id; return true; } bool RoManager::Free(PinId pin_id) { /* Find the process. */ auto *found = this->FindProcessInfo(pin_id); if (found == nullptr) { return false; } /* Set the process as not in use. */ found->in_use = false; /* Set all the process's nsos as not in use. */ for (auto i = 0; i < NsoCount; ++i) { found->nso_infos[i].in_use = false; } return true; } void RoManager::RegisterProcess(PinId pin_id, os::ProcessId process_id, ncm::ProgramId program_id, bool is_64_bit_address_space) { /* Find the process. */ auto *found = this->FindProcessInfo(pin_id); if (found == nullptr) { return; } /* Set the process id and program id. */ found->process_id = process_id; found->program_id = program_id; AMS_UNUSED(is_64_bit_address_space); } bool RoManager::GetProgramLocationAndStatus(ncm::ProgramLocation *out, cfg::OverrideStatus *out_status, PinId pin_id) { /* Find the process. */ auto *found = this->FindProcessInfo(pin_id); if (found == nullptr) { return false; } /* Set the output location/status. */ *out = found->program_location; *out_status = found->override_status; return true; } void RoManager::AddNso(PinId pin_id, const u8 *module_id, u64 address, u64 size) { /* Find the process. */ auto *found = this->FindProcessInfo(pin_id); if (found == nullptr) { return; } /* Allocate an nso. */ auto *info = this->AllocateNsoInfo(found); if (info == nullptr) { return; } /* Copy the information into the nso info. */ std::memcpy(info->module_info.module_id, module_id, sizeof(info->module_info.module_id)); info->module_info.address = address; info->module_info.size = size; info->in_use = true; } bool RoManager::GetProcessModuleInfo(u32 *out_count, ModuleInfo *out, size_t max_out_count, os::ProcessId process_id) { /* Find the process. */ auto *found = this->FindProcessInfo(process_id); if (found == nullptr) { return false; } /* Copy allocated nso module infos. */ size_t count = 0; for (auto i = 0; i < NsoCount && count < max_out_count; ++i) { /* Skip unallocated nsos. */ if (!found->nso_infos[i].in_use) { continue; } /* Copy out the module info. */ out[count++] = found->nso_infos[i].module_info; } /* Set the output count. */ *out_count = count; return true; } RoManager::ProcessInfo *RoManager::AllocateProcessInfo() { for (auto i = 0; i < ProcessCount; ++i) { if (!m_processes[i].in_use) { return m_processes + i; } } return nullptr; } RoManager::ProcessInfo *RoManager::FindProcessInfo(PinId pin_id) { for (auto i = 0; i < ProcessCount; ++i) { if (m_processes[i].in_use && m_processes[i].pin_id == pin_id) { return m_processes + i; } } return nullptr; } RoManager::ProcessInfo *RoManager::FindProcessInfo(os::ProcessId process_id) { for (auto i = 0; i < ProcessCount; ++i) { if (m_processes[i].in_use && m_processes[i].process_id == process_id) { return m_processes + i; } } return nullptr; } RoManager::ProcessInfo *RoManager::FindProcessInfo(ncm::ProgramId program_id) { for (auto i = 0; i < ProcessCount; ++i) { if (m_processes[i].in_use && m_processes[i].program_id == program_id) { return m_processes + i; } } return nullptr; } RoManager::NsoInfo *RoManager::AllocateNsoInfo(ProcessInfo *info) { for (auto i = 0; i < NsoCount; ++i) { if (!info->nso_infos[i].in_use) { return info->nso_infos + i; } } return nullptr; } }
5,652
C++
.cpp
150
29.046667
134
0.56571
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,129
ldr_main.cpp
Atmosphere-NX_Atmosphere/stratosphere/loader/source/ldr_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 "ldr_development_manager.hpp" #include "ldr_loader_service.hpp" namespace ams { namespace ldr { namespace { constinit u8 g_heap_memory[16_KB]; lmem::HeapHandle g_server_heap_handle; constinit ams::sf::ExpHeapAllocator g_server_allocator; void *Allocate(size_t size) { return lmem::AllocateFromExpHeap(g_server_heap_handle, size); } void Deallocate(void *p, size_t size) { AMS_UNUSED(size); return lmem::FreeToExpHeap(g_server_heap_handle, p); } void InitializeHeap() { g_server_heap_handle = lmem::CreateExpHeap(g_heap_memory, sizeof(g_heap_memory), lmem::CreateOption_None); g_server_allocator.Attach(g_server_heap_handle); } } namespace { struct ServerOptions { static constexpr size_t PointerBufferSize = 0x420; static constexpr size_t MaxDomains = 0; static constexpr size_t MaxDomainObjects = 0; static constexpr bool CanDeferInvokeRequest = false; static constexpr bool CanManageMitmServers = false; }; /* ldr:pm, ldr:shel, ldr:dmnt. */ enum PortIndex { PortIndex_ProcessManager, PortIndex_Shell, PortIndex_DebugMonitor, PortIndex_Count, }; constexpr sm::ServiceName ProcessManagerServiceName = sm::ServiceName::Encode("ldr:pm"); constexpr size_t ProcessManagerMaxSessions = 1; constexpr sm::ServiceName ShellServiceName = sm::ServiceName::Encode("ldr:shel"); constexpr size_t ShellMaxSessions = 3; constexpr sm::ServiceName DebugMonitorServiceName = sm::ServiceName::Encode("ldr:dmnt"); constexpr size_t DebugMonitorMaxSessions = 3; constinit sf::UnmanagedServiceObject<impl::IProcessManagerInterface, LoaderService> g_pm_service; constinit sf::UnmanagedServiceObject<impl::IShellInterface, LoaderService> g_shell_service; constinit sf::UnmanagedServiceObject<impl::IDebugMonitorInterface, LoaderService> g_dmnt_service; constexpr size_t MaxSessions = ProcessManagerMaxSessions + ShellMaxSessions + DebugMonitorMaxSessions + 1; using ServerManager = ams::sf::hipc::ServerManager<PortIndex_Count, ServerOptions, MaxSessions>; ServerManager g_server_manager; void RegisterServiceSessions() { R_ABORT_UNLESS(g_server_manager.RegisterObjectForServer(g_pm_service.GetShared(), ProcessManagerServiceName, ProcessManagerMaxSessions)); R_ABORT_UNLESS(g_server_manager.RegisterObjectForServer(g_shell_service.GetShared(), ShellServiceName, ShellMaxSessions)); R_ABORT_UNLESS(g_server_manager.RegisterObjectForServer(g_dmnt_service.GetShared(), DebugMonitorServiceName, DebugMonitorMaxSessions)); } void LoopProcess() { g_server_manager.LoopProcess(); } } } namespace init { void InitializeSystemModule() { /* Initialize heap. */ ldr::InitializeHeap(); /* Set fs allocator. */ fs::SetAllocator(ldr::Allocate, ldr::Deallocate); /* Initialize services we need. */ R_ABORT_UNLESS(sm::Initialize()); fs::InitializeForSystem(); lr::Initialize(); R_ABORT_UNLESS(fsldrInitialize()); spl::Initialize(); /* Verify that we can sanely execute. */ ams::CheckApiVersion(); } void FinalizeSystemModule() { /* ... */ } void Startup() { /* ... */ } } void NORETURN Exit(int rc) { AMS_UNUSED(rc); AMS_ABORT("Exit called by immortal process"); } void Main() { /* Disable auto-abort in fs operations. */ fs::SetEnabledAutoAbort(false); /* Set thread name. */ os::SetThreadNamePointer(os::GetCurrentThread(), AMS_GET_SYSTEM_THREAD_NAME(ldr, Main)); AMS_ASSERT(os::GetThreadPriority(os::GetCurrentThread()) == AMS_GET_SYSTEM_THREAD_PRIORITY(ldr, Main)); /* Configure development. */ /* NOTE: Nintendo really does call the getter function three times instead of caching the value. */ ldr::SetDevelopmentForAcidProductionCheck(spl::IsDevelopment()); ldr::SetDevelopmentForAntiDowngradeCheck(spl::IsDevelopment()); ldr::SetDevelopmentForAcidSignatureCheck(spl::IsDevelopment()); /* Register the loader services. */ ldr::RegisterServiceSessions(); /* Loop forever, servicing our services. */ ldr::LoopProcess(); /* This can never be reached. */ AMS_ASSUME(false); } } /* Override operator new. */ void *operator new(size_t size) { return ams::ldr::Allocate(size); } void *operator new(size_t size, const std::nothrow_t &) { return ams::ldr::Allocate(size); } void operator delete(void *p) { return ams::ldr::Deallocate(p, 0); } void operator delete(void *p, size_t size) { return ams::ldr::Deallocate(p, size); }
5,990
C++
.cpp
127
37.464567
153
0.637629
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,130
ldr_content_management.cpp
Atmosphere-NX_Atmosphere/stratosphere/loader/source/ldr_content_management.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "ldr_content_management.hpp" namespace ams::ldr { namespace { constinit os::SdkMutex g_scoped_code_mount_lock; } /* ScopedCodeMount functionality. */ ScopedCodeMount::ScopedCodeMount(const ncm::ProgramLocation &loc, ncm::ContentMetaPlatform platform) : m_lk(g_scoped_code_mount_lock), m_has_status(false), m_mounted_ams(false), m_mounted_sd_or_code(false), m_mounted_code(false) { m_result = this->Initialize(loc, platform); } ScopedCodeMount::ScopedCodeMount(const ncm::ProgramLocation &loc, const cfg::OverrideStatus &o, ncm::ContentMetaPlatform platform) : m_lk(g_scoped_code_mount_lock), m_override_status(o), m_has_status(true), m_mounted_ams(false), m_mounted_sd_or_code(false), m_mounted_code(false) { m_result = this->Initialize(loc, platform); } ScopedCodeMount::~ScopedCodeMount() { /* Unmount filesystems. */ if (m_mounted_ams) { fs::Unmount(AtmosphereCodeMountName); } if (m_mounted_sd_or_code) { fs::Unmount(SdOrCodeMountName); } if (m_mounted_code) { fs::Unmount(CodeMountName); } } Result ScopedCodeMount::Initialize(const ncm::ProgramLocation &loc, ncm::ContentMetaPlatform platform) { /* Capture override status, if necessary. */ this->EnsureOverrideStatus(loc); AMS_ABORT_UNLESS(m_has_status); /* Get the content path. */ char content_path[fs::EntryNameLengthMax + 1]; R_TRY(GetProgramPath(content_path, sizeof(content_path), loc, platform)); /* Get the content attributes. */ const auto content_attributes = GetPlatformContentAttributes(platform); /* Mount the atmosphere code file system. */ R_TRY(fs::MountCodeForAtmosphereWithRedirection(std::addressof(m_ams_code_verification_data), AtmosphereCodeMountName, content_path, content_attributes, loc.program_id, m_override_status.IsHbl(), m_override_status.IsProgramSpecific())); m_mounted_ams = true; /* Mount the sd or base code file system. */ R_TRY(fs::MountCodeForAtmosphere(std::addressof(m_sd_or_base_code_verification_data), SdOrCodeMountName, content_path, content_attributes, loc.program_id)); m_mounted_sd_or_code = true; /* Mount the base code file system. */ if (R_SUCCEEDED(fs::MountCode(std::addressof(m_base_code_verification_data), CodeMountName, content_path, content_attributes, loc.program_id))) { m_mounted_code = true; } R_SUCCEED(); } void ScopedCodeMount::EnsureOverrideStatus(const ncm::ProgramLocation &loc) { if (m_has_status) { return; } m_override_status = cfg::CaptureOverrideStatus(loc.program_id); m_has_status = true; } /* Redirection API. */ Result GetProgramPath(char *out_path, size_t out_size, const ncm::ProgramLocation &loc, ncm::ContentMetaPlatform platform) { /* Check for storage id none. */ if (static_cast<ncm::StorageId>(loc.storage_id) == ncm::StorageId::None) { std::memset(out_path, 0, out_size); std::memcpy(out_path, "/", std::min<size_t>(out_size, 2)); R_SUCCEED(); } /* Get the content attributes. */ const auto content_attributes = GetPlatformContentAttributes(platform); AMS_UNUSED(content_attributes); lr::Path path; /* Check that path registration is allowable. */ if (static_cast<ncm::StorageId>(loc.storage_id) == ncm::StorageId::Host) { AMS_ABORT_UNLESS(spl::IsDevelopment()); } /* Try to get the path from the registered resolver. */ lr::RegisteredLocationResolver reg; R_TRY(lr::OpenRegisteredLocationResolver(std::addressof(reg))); R_TRY_CATCH(reg.ResolveProgramPath(std::addressof(path), loc.program_id)) { R_CATCH(lr::ResultProgramNotFound) { /* Program wasn't found via registered resolver, fall back to the normal resolver. */ lr::LocationResolver lr; R_TRY(lr::OpenLocationResolver(std::addressof(lr), static_cast<ncm::StorageId>(loc.storage_id))); R_TRY(lr.ResolveProgramPath(std::addressof(path), loc.program_id)); } } R_END_TRY_CATCH; /* Fix directory separators in path. */ fs::Replace(path.str, sizeof(path.str), fs::StringTraits::AlternateDirectorySeparator, fs::StringTraits::DirectorySeparator); /* Check that the path is valid. */ AMS_ABORT_UNLESS(path.IsValid()); /* Copy the output path. */ std::memset(out_path, 0, out_size); std::memcpy(out_path, path.str, std::min(out_size, sizeof(path))); R_SUCCEED(); } Result RedirectProgramPath(const char *path, size_t size, const ncm::ProgramLocation &loc) { /* Check for storage id none. */ if (static_cast<ncm::StorageId>(loc.storage_id) == ncm::StorageId::None) { R_SUCCEED(); } /* Open location resolver. */ lr::LocationResolver lr; R_TRY(lr::OpenLocationResolver(std::addressof(lr), static_cast<ncm::StorageId>(loc.storage_id))); /* Copy in path. */ lr::Path lr_path; std::memcpy(lr_path.str, path, std::min(size, sizeof(lr_path.str))); lr_path.str[sizeof(lr_path.str) - 1] = '\x00'; /* Redirect the path. */ lr.RedirectProgramPath(lr_path, loc.program_id); R_SUCCEED(); } Result RedirectHtmlDocumentPathForHbl(const ncm::ProgramLocation &loc) { lr::Path path; /* Open a location resolver. */ lr::LocationResolver lr; R_TRY(lr::OpenLocationResolver(std::addressof(lr), static_cast<ncm::StorageId>(loc.storage_id))); /* If there's already a Html Document path, we don't need to set one. */ R_SUCCEED_IF(R_SUCCEEDED(lr.ResolveApplicationHtmlDocumentPath(std::addressof(path), loc.program_id))); /* We just need to set this to any valid NCA path. Let's use the executable path. */ R_TRY(lr.ResolveProgramPath(std::addressof(path), loc.program_id)); lr.RedirectApplicationHtmlDocumentPath(path, loc.program_id, loc.program_id); R_SUCCEED(); } fs::ContentAttributes GetPlatformContentAttributes(ncm::ContentMetaPlatform platform) { switch (platform) { case ncm::ContentMetaPlatform::Nx: return fs::ContentAttributes_None; AMS_UNREACHABLE_DEFAULT_CASE(); } } }
7,237
C++
.cpp
140
43.357143
285
0.657082
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,131
ldr_loader_service.cpp
Atmosphere-NX_Atmosphere/stratosphere/loader/source/ldr_loader_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 "ldr_argument_store.hpp" #include "ldr_content_management.hpp" #include "ldr_development_manager.hpp" #include "ldr_process_creation.hpp" #include "ldr_launch_record.hpp" #include "ldr_loader_service.hpp" namespace ams::ldr { namespace { constinit ArgumentStore g_argument_store; bool IsValidPlatform(ncm::ContentMetaPlatform platform) { return platform == ncm::ContentMetaPlatform::Nx; } Result CreateProcessByPlatform(os::NativeHandle *out, PinId pin_id, u32 flags, os::NativeHandle resource_limit, ncm::ContentMetaPlatform platform) { /* Check that the platform is valid. */ R_UNLESS(IsValidPlatform(platform), ldr::ResultInvalidPlatformId()); /* Get the location and override status. */ ncm::ProgramLocation loc; cfg::OverrideStatus override_status; R_TRY(ldr::GetProgramLocationAndOverrideStatusFromPinId(std::addressof(loc), std::addressof(override_status), pin_id)); /* Get the program path. */ char path[fs::EntryNameLengthMax]; R_TRY(GetProgramPath(path, sizeof(path), loc, platform)); path[sizeof(path) - 1] = '\x00'; /* Create the process. */ R_RETURN(ldr::CreateProcess(out, pin_id, loc, override_status, path, g_argument_store.Get(loc.program_id), flags, resource_limit, platform)); } Result GetProgramInfoByPlatform(ProgramInfo *out, cfg::OverrideStatus *out_status, const ncm::ProgramLocation &loc, ncm::ContentMetaPlatform platform) { /* Check that the platform is valid. */ R_UNLESS(IsValidPlatform(platform), ldr::ResultInvalidPlatformId()); /* Zero output. */ std::memset(out, 0, sizeof(*out)); /* Get the program path. */ char path[fs::EntryNameLengthMax]; R_TRY(GetProgramPath(path, sizeof(path), loc, platform)); path[sizeof(path) - 1] = '\x00'; /* Get the program info. */ cfg::OverrideStatus status; R_TRY(ldr::GetProgramInfo(out, std::addressof(status), loc, path, platform)); if (loc.program_id != out->program_id) { /* Redirect the program path. */ const ncm::ProgramLocation new_loc = ncm::ProgramLocation::Make(out->program_id, static_cast<ncm::StorageId>(loc.storage_id)); R_TRY(RedirectProgramPath(path, sizeof(path), new_loc)); /* Update the arguments, as needed. */ if (const auto *entry = g_argument_store.Get(loc.program_id); entry != nullptr) { R_TRY(g_argument_store.Set(new_loc.program_id, entry->argument, entry->argument_size)); } } /* If we should, set the output status. */ if (out_status != nullptr) { *out_status = status; } R_SUCCEED(); } } Result LoaderService::CreateProcess(os::NativeHandle *out, PinId pin_id, u32 flags, os::NativeHandle resource_limit) { R_RETURN(CreateProcessByPlatform(out, pin_id, flags, resource_limit, ncm::ContentMetaPlatform::Nx)); } Result LoaderService::GetProgramInfo(ProgramInfo *out, cfg::OverrideStatus *out_status, const ncm::ProgramLocation &loc) { R_RETURN(GetProgramInfoByPlatform(out, out_status, loc, ncm::ContentMetaPlatform::Nx)); } Result LoaderService::PinProgram(PinId *out, const ncm::ProgramLocation &loc, const cfg::OverrideStatus &status) { *out = {}; R_RETURN(ldr::PinProgram(out, loc, status)); } Result LoaderService::UnpinProgram(PinId id) { R_RETURN(ldr::UnpinProgram(id)); } Result LoaderService::SetProgramArgument(ncm::ProgramId program_id, const void *argument, size_t size) { R_RETURN(g_argument_store.Set(program_id, argument, size)); } Result LoaderService::FlushArguments() { R_RETURN(g_argument_store.Flush()); } Result LoaderService::GetProcessModuleInfo(u32 *out_count, ModuleInfo *out, size_t max_out_count, os::ProcessId process_id) { *out_count = 0; std::memset(out, 0, max_out_count * sizeof(*out)); R_RETURN(ldr::GetProcessModuleInfo(out_count, out, max_out_count, process_id)); } Result LoaderService::RegisterExternalCode(os::NativeHandle *out, ncm::ProgramId program_id) { R_RETURN(fssystem::CreateExternalCode(out, program_id)); } void LoaderService::UnregisterExternalCode(ncm::ProgramId program_id) { fssystem::DestroyExternalCode(program_id); } void LoaderService::HasLaunchedBootProgram(bool *out, ncm::ProgramId program_id) { *out = ldr::HasLaunchedBootProgram(program_id); } Result LoaderService::SetEnabledProgramVerification(bool enabled) { ldr::SetEnabledProgramVerification(enabled); R_SUCCEED(); } }
5,597
C++
.cpp
108
43.342593
160
0.662392
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,132
dmnt_main.cpp
Atmosphere-NX_Atmosphere/stratosphere/dmnt/source/dmnt_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 "cheat/dmnt_cheat_service.hpp" #include "cheat/impl/dmnt_cheat_api.hpp" namespace ams { namespace dmnt { namespace { constinit u8 g_fs_heap_memory[4_KB]; lmem::HeapHandle g_fs_heap_handle; void *AllocateForFs(size_t size) { return lmem::AllocateFromExpHeap(g_fs_heap_handle, size); } void DeallocateForFs(void *p, size_t size) { AMS_UNUSED(size); return lmem::FreeToExpHeap(g_fs_heap_handle, p); } void InitializeFsHeap() { g_fs_heap_handle = lmem::CreateExpHeap(g_fs_heap_memory, sizeof(g_fs_heap_memory), lmem::CreateOption_None); } } namespace { using ServerOptions = sf::hipc::DefaultServerManagerOptions; constexpr sm::ServiceName DebugMonitorServiceName = sm::ServiceName::Encode("dmnt:-"); constexpr size_t DebugMonitorMaxSessions = 4; constexpr sm::ServiceName CheatServiceName = sm::ServiceName::Encode("dmnt:cht"); constexpr size_t CheatMaxSessions = 2; /* dmnt:-, dmnt:cht. */ constexpr size_t NumServers = 2; constexpr size_t NumSessions = DebugMonitorMaxSessions + CheatMaxSessions; sf::hipc::ServerManager<NumServers, ServerOptions, NumSessions> g_server_manager; constinit sf::UnmanagedServiceObject<dmnt::cheat::impl::ICheatInterface, dmnt::cheat::CheatService> g_cheat_service; void LoopServerThread(void *) { g_server_manager.LoopProcess(); } /* NOTE: Nintendo loops four threads processing on the manager -- we'll loop an extra fifth for our cheat service. */ constexpr size_t TotalThreads = DebugMonitorMaxSessions + 1; static_assert(TotalThreads >= 1, "TotalThreads"); constexpr size_t NumExtraThreads = TotalThreads - 1; constexpr size_t ThreadStackSize = 0x4000; alignas(os::MemoryPageSize) u8 g_extra_thread_stacks[NumExtraThreads][ThreadStackSize]; os::ThreadType g_extra_threads[NumExtraThreads]; void InitializeIpcServer() { /* Create services. */ R_ABORT_UNLESS(g_server_manager.RegisterObjectForServer(g_cheat_service.GetShared(), CheatServiceName, CheatMaxSessions)); } void LoopProcessIpcServer() { /* Initialize threads. */ if constexpr (NumExtraThreads > 0) { static_assert(AMS_GET_SYSTEM_THREAD_PRIORITY(dmnt, Main) == AMS_GET_SYSTEM_THREAD_PRIORITY(dmnt, Ipc)); for (size_t i = 0; i < NumExtraThreads; i++) { R_ABORT_UNLESS(os::CreateThread(std::addressof(g_extra_threads[i]), LoopServerThread, nullptr, g_extra_thread_stacks[i], ThreadStackSize, AMS_GET_SYSTEM_THREAD_PRIORITY(dmnt, Ipc))); os::SetThreadNamePointer(std::addressof(g_extra_threads[i]), AMS_GET_SYSTEM_THREAD_NAME(dmnt, Ipc)); } } /* Start extra threads. */ if constexpr (NumExtraThreads > 0) { for (size_t i = 0; i < NumExtraThreads; i++) { os::StartThread(std::addressof(g_extra_threads[i])); } } /* Loop this thread. */ LoopServerThread(nullptr); /* Wait for extra threads to finish. */ if constexpr (NumExtraThreads > 0) { for (size_t i = 0; i < NumExtraThreads; i++) { os::WaitThread(std::addressof(g_extra_threads[i])); } } } } } namespace init { void InitializeSystemModule() { /* Initialize heap. */ dmnt::InitializeFsHeap(); /* Initialize our connection to sm. */ R_ABORT_UNLESS(sm::Initialize()); /* Initialize fs. */ fs::InitializeForSystem(); fs::SetAllocator(dmnt::AllocateForFs, dmnt::DeallocateForFs); fs::SetEnabledAutoAbort(false); /* Initialize other services we need. */ R_ABORT_UNLESS(pmdmntInitialize()); R_ABORT_UNLESS(pminfoInitialize()); R_ABORT_UNLESS(ldrDmntInitialize()); R_ABORT_UNLESS(roDmntInitialize()); R_ABORT_UNLESS(nsdevInitialize()); lr::Initialize(); R_ABORT_UNLESS(setInitialize()); R_ABORT_UNLESS(setsysInitialize()); R_ABORT_UNLESS(hidInitialize()); /* Mount the SD card. */ R_ABORT_UNLESS(fs::MountSdCard("sdmc")); /* Verify that we can sanely execute. */ ams::CheckApiVersion(); } void FinalizeSystemModule() { /* ... */ } void Startup() { /* ... */ } } void Main() { /* Set thread name. */ os::SetThreadNamePointer(os::GetCurrentThread(), AMS_GET_SYSTEM_THREAD_NAME(dmnt, Main)); AMS_ASSERT(os::GetThreadPriority(os::GetCurrentThread()) == AMS_GET_SYSTEM_THREAD_PRIORITY(dmnt, Main)); /* Initialize the cheat manager. */ dmnt::cheat::impl::InitializeCheatManager(); /* Initialize ipc server. */ dmnt::InitializeIpcServer(); /* Loop processing ipc server. */ dmnt::LoopProcessIpcServer(); } }
6,187
C++
.cpp
125
37.504
206
0.592826
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,133
dmnt_cheat_service.cpp
Atmosphere-NX_Atmosphere/stratosphere/dmnt/source/cheat/dmnt_cheat_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 "dmnt_cheat_service.hpp" #include "impl/dmnt_cheat_api.hpp" namespace ams::dmnt::cheat { /* ========================================================================================= */ /* ==================================== Meta Commands ==================================== */ /* ========================================================================================= */ void CheatService::HasCheatProcess(sf::Out<bool> out) { out.SetValue(dmnt::cheat::impl::GetHasActiveCheatProcess()); } void CheatService::GetCheatProcessEvent(sf::OutCopyHandle out_event) { out_event.SetValue(dmnt::cheat::impl::GetCheatProcessEventHandle(), false); } Result CheatService::GetCheatProcessMetadata(sf::Out<CheatProcessMetadata> out_metadata) { R_RETURN(dmnt::cheat::impl::GetCheatProcessMetadata(out_metadata.GetPointer())); } Result CheatService::ForceOpenCheatProcess() { R_UNLESS(R_SUCCEEDED(dmnt::cheat::impl::ForceOpenCheatProcess()), dmnt::cheat::ResultCheatNotAttached()); R_SUCCEED(); } Result CheatService::PauseCheatProcess() { R_RETURN(dmnt::cheat::impl::PauseCheatProcess()); } Result CheatService::ResumeCheatProcess() { R_RETURN(dmnt::cheat::impl::ResumeCheatProcess()); } Result CheatService::ForceCloseCheatProcess() { R_RETURN(dmnt::cheat::impl::ForceCloseCheatProcess()); } /* ========================================================================================= */ /* =================================== Memory Commands =================================== */ /* ========================================================================================= */ Result CheatService::GetCheatProcessMappingCount(sf::Out<u64> out_count) { R_RETURN(dmnt::cheat::impl::GetCheatProcessMappingCount(out_count.GetPointer())); } Result CheatService::GetCheatProcessMappings(const sf::OutArray<svc::MemoryInfo> &mappings, sf::Out<u64> out_count, u64 offset) { R_UNLESS(mappings.GetPointer() != nullptr, dmnt::cheat::ResultCheatNullBuffer()); R_RETURN(dmnt::cheat::impl::GetCheatProcessMappings(mappings.GetPointer(), mappings.GetSize(), out_count.GetPointer(), offset)); } Result CheatService::ReadCheatProcessMemory(const sf::OutBuffer &buffer, u64 address, u64 out_size) { R_UNLESS(buffer.GetPointer() != nullptr, dmnt::cheat::ResultCheatNullBuffer()); R_RETURN(dmnt::cheat::impl::ReadCheatProcessMemory(address, buffer.GetPointer(), std::min(out_size, buffer.GetSize()))); } Result CheatService::WriteCheatProcessMemory(const sf::InBuffer &buffer, u64 address, u64 in_size) { R_UNLESS(buffer.GetPointer() != nullptr, dmnt::cheat::ResultCheatNullBuffer()); R_RETURN(dmnt::cheat::impl::WriteCheatProcessMemory(address, buffer.GetPointer(), std::min(in_size, buffer.GetSize()))); } Result CheatService::QueryCheatProcessMemory(sf::Out<svc::MemoryInfo> mapping, u64 address) { R_RETURN(dmnt::cheat::impl::QueryCheatProcessMemory(mapping.GetPointer(), address)); } /* ========================================================================================= */ /* =================================== Cheat Commands ==================================== */ /* ========================================================================================= */ Result CheatService::GetCheatCount(sf::Out<u64> out_count) { R_RETURN(dmnt::cheat::impl::GetCheatCount(out_count.GetPointer())); } Result CheatService::GetCheats(const sf::OutArray<CheatEntry> &cheats, sf::Out<u64> out_count, u64 offset) { R_UNLESS(cheats.GetPointer() != nullptr, dmnt::cheat::ResultCheatNullBuffer()); R_RETURN(dmnt::cheat::impl::GetCheats(cheats.GetPointer(), cheats.GetSize(), out_count.GetPointer(), offset)); } Result CheatService::GetCheatById(sf::Out<CheatEntry> cheat, u32 cheat_id) { R_RETURN(dmnt::cheat::impl::GetCheatById(cheat.GetPointer(), cheat_id)); } Result CheatService::ToggleCheat(u32 cheat_id) { R_RETURN(dmnt::cheat::impl::ToggleCheat(cheat_id)); } Result CheatService::AddCheat(const CheatDefinition &cheat, sf::Out<u32> out_cheat_id, bool enabled) { R_RETURN(dmnt::cheat::impl::AddCheat(out_cheat_id.GetPointer(), cheat, enabled)); } Result CheatService::RemoveCheat(u32 cheat_id) { R_RETURN(dmnt::cheat::impl::RemoveCheat(cheat_id)); } Result CheatService::ReadStaticRegister(sf::Out<u64> out, u8 which) { R_RETURN(dmnt::cheat::impl::ReadStaticRegister(out.GetPointer(), which)); } Result CheatService::WriteStaticRegister(u8 which, u64 value) { R_RETURN(dmnt::cheat::impl::WriteStaticRegister(which, value)); } Result CheatService::ResetStaticRegisters() { R_RETURN(dmnt::cheat::impl::ResetStaticRegisters()); } Result CheatService::SetMasterCheat(const CheatDefinition &cheat) { R_RETURN(dmnt::cheat::impl::SetMasterCheat(cheat)); } /* ========================================================================================= */ /* =================================== Address Commands ================================== */ /* ========================================================================================= */ Result CheatService::GetFrozenAddressCount(sf::Out<u64> out_count) { R_RETURN(dmnt::cheat::impl::GetFrozenAddressCount(out_count.GetPointer())); } Result CheatService::GetFrozenAddresses(const sf::OutArray<FrozenAddressEntry> &addresses, sf::Out<u64> out_count, u64 offset) { R_UNLESS(addresses.GetPointer() != nullptr, dmnt::cheat::ResultCheatNullBuffer()); R_RETURN(dmnt::cheat::impl::GetFrozenAddresses(addresses.GetPointer(), addresses.GetSize(), out_count.GetPointer(), offset)); } Result CheatService::GetFrozenAddress(sf::Out<FrozenAddressEntry> entry, u64 address) { R_RETURN(dmnt::cheat::impl::GetFrozenAddress(entry.GetPointer(), address)); } Result CheatService::EnableFrozenAddress(sf::Out<u64> out_value, u64 address, u64 width) { /* Width needs to be a power of two <= 8. */ R_UNLESS(width > 0, dmnt::cheat::ResultFrozenAddressInvalidWidth()); R_UNLESS(width <= sizeof(u64), dmnt::cheat::ResultFrozenAddressInvalidWidth()); R_UNLESS((width & (width - 1)) == 0, dmnt::cheat::ResultFrozenAddressInvalidWidth()); R_RETURN(dmnt::cheat::impl::EnableFrozenAddress(out_value.GetPointer(), address, width)); } Result CheatService::DisableFrozenAddress(u64 address) { R_RETURN(dmnt::cheat::impl::DisableFrozenAddress(address)); } }
7,442
C++
.cpp
123
54.569106
136
0.60129
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,134
dmnt_cheat_vm.cpp
Atmosphere-NX_Atmosphere/stratosphere/dmnt/source/cheat/impl/dmnt_cheat_vm.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have 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_cheat_vm.hpp" #include "dmnt_cheat_api.hpp" namespace ams::dmnt::cheat::impl { void CheatVirtualMachine::DebugLog(u32 log_id, u64 value) { /* Just unconditionally try to create the log folder. */ fs::EnsureDirectory("sdmc:/atmosphere/cheat_vm_logs"); fs::FileHandle log_file; { char log_path[fs::EntryNameLengthMax + 1]; util::SNPrintf(log_path, sizeof(log_path), "sdmc:/atmosphere/cheat_vm_logs/%08x.log", log_id); if (R_FAILED(fs::OpenFile(std::addressof(log_file), log_path, fs::OpenMode_Write | fs::OpenMode_AllowAppend))) { return; } } ON_SCOPE_EXIT { fs::CloseFile(log_file); }; s64 log_offset; if (R_FAILED(fs::GetFileSize(std::addressof(log_offset), log_file))) { return; } char log_value[18]; util::SNPrintf(log_value, sizeof(log_value), "%016lx\n", value); fs::WriteFile(log_file, log_offset, log_value, std::strlen(log_value), fs::WriteOption::Flush); } void CheatVirtualMachine::OpenDebugLogFile() { #ifdef DMNT_CHEAT_VM_DEBUG_LOG CloseDebugLogFile(); fs::EnsureDirectory("sdmc:/atmosphere/cheat_vm_logs"); fs::CreateFile("sdmc:/atmosphere/cheat_vm_logs/debug_log.txt", 0); R_ABORT_UNLESS(fs::OpenFile(std::addressof(m_debug_log_file), "sdmc:/atmosphere/cheat_vm_logs/debug_log.txt", fs::OpenMode_Write | fs::OpenMode_AllowAppend)); m_debug_log_file_offset = 0; m_has_debug_log_file = true; #endif } void CheatVirtualMachine::CloseDebugLogFile() { #ifdef DMNT_CHEAT_VM_DEBUG_LOG if (m_has_debug_log_file) { fs::CloseFile(m_debug_log_file); } m_has_debug_log_file = false; #endif } void CheatVirtualMachine::LogToDebugFile(const char *format, ...) { #ifdef DMNT_CHEAT_VM_DEBUG_LOG if (!m_has_debug_log_file) { return; } { std::va_list vl; va_start(vl, format); util::VSNPrintf(m_debug_log_format_buf, sizeof(m_debug_log_format_buf) - 1, format, vl); va_end(vl); } size_t fmt_len = std::strlen(m_debug_log_format_buf); if (m_debug_log_format_buf[fmt_len - 1] != '\n') { m_debug_log_format_buf[fmt_len + 0] = '\n'; m_debug_log_format_buf[fmt_len + 1] = '\x00'; fmt_len += 1; } fs::WriteFile(m_debug_log_file, m_debug_log_file_offset, m_debug_log_format_buf, fmt_len, fs::WriteOption::Flush); m_debug_log_file_offset += fmt_len; #else AMS_UNUSED(format); #endif } void CheatVirtualMachine::LogOpcode(const CheatVmOpcode *opcode) { #ifndef DMNT_CHEAT_VM_DEBUG_LOG return; #endif switch (opcode->opcode) { case CheatVmOpcodeType_StoreStatic: this->LogToDebugFile("Opcode: Store Static\n"); this->LogToDebugFile("Bit Width: %x\n", opcode->store_static.bit_width); this->LogToDebugFile("Mem Type: %x\n", opcode->store_static.mem_type); this->LogToDebugFile("Reg Idx: %x\n", opcode->store_static.offset_register); this->LogToDebugFile("Rel Addr: %lx\n", opcode->store_static.rel_address); this->LogToDebugFile("Value: %lx\n", opcode->store_static.value.bit64); break; case CheatVmOpcodeType_BeginConditionalBlock: this->LogToDebugFile("Opcode: Begin Conditional\n"); this->LogToDebugFile("Bit Width: %x\n", opcode->begin_cond.bit_width); this->LogToDebugFile("Mem Type: %x\n", opcode->begin_cond.mem_type); this->LogToDebugFile("Cond Type: %x\n", opcode->begin_cond.cond_type); this->LogToDebugFile("Rel Addr: %lx\n", opcode->begin_cond.rel_address); this->LogToDebugFile("Value: %lx\n", opcode->begin_cond.value.bit64); break; case CheatVmOpcodeType_EndConditionalBlock: this->LogToDebugFile("Opcode: End Conditional\n"); break; case CheatVmOpcodeType_ControlLoop: if (opcode->ctrl_loop.start_loop) { this->LogToDebugFile("Opcode: Start Loop\n"); this->LogToDebugFile("Reg Idx: %x\n", opcode->ctrl_loop.reg_index); this->LogToDebugFile("Num Iters: %x\n", opcode->ctrl_loop.num_iters); } else { this->LogToDebugFile("Opcode: End Loop\n"); this->LogToDebugFile("Reg Idx: %x\n", opcode->ctrl_loop.reg_index); } break; case CheatVmOpcodeType_LoadRegisterStatic: this->LogToDebugFile("Opcode: Load Register Static\n"); this->LogToDebugFile("Reg Idx: %x\n", opcode->ldr_static.reg_index); this->LogToDebugFile("Value: %lx\n", opcode->ldr_static.value); break; case CheatVmOpcodeType_LoadRegisterMemory: this->LogToDebugFile("Opcode: Load Register Memory\n"); this->LogToDebugFile("Bit Width: %x\n", opcode->ldr_memory.bit_width); this->LogToDebugFile("Reg Idx: %x\n", opcode->ldr_memory.reg_index); this->LogToDebugFile("Mem Type: %x\n", opcode->ldr_memory.mem_type); this->LogToDebugFile("From Reg: %d\n", opcode->ldr_memory.load_from_reg); this->LogToDebugFile("Rel Addr: %lx\n", opcode->ldr_memory.rel_address); break; case CheatVmOpcodeType_StoreStaticToAddress: this->LogToDebugFile("Opcode: Store Static to Address\n"); this->LogToDebugFile("Bit Width: %x\n", opcode->str_static.bit_width); this->LogToDebugFile("Reg Idx: %x\n", opcode->str_static.reg_index); if (opcode->str_static.add_offset_reg) { this->LogToDebugFile("O Reg Idx: %x\n", opcode->str_static.offset_reg_index); } this->LogToDebugFile("Incr Reg: %d\n", opcode->str_static.increment_reg); this->LogToDebugFile("Value: %lx\n", opcode->str_static.value); break; case CheatVmOpcodeType_PerformArithmeticStatic: this->LogToDebugFile("Opcode: Perform Static Arithmetic\n"); this->LogToDebugFile("Bit Width: %x\n", opcode->perform_math_static.bit_width); this->LogToDebugFile("Reg Idx: %x\n", opcode->perform_math_static.reg_index); this->LogToDebugFile("Math Type: %x\n", opcode->perform_math_static.math_type); this->LogToDebugFile("Value: %lx\n", opcode->perform_math_static.value); break; case CheatVmOpcodeType_BeginKeypressConditionalBlock: this->LogToDebugFile("Opcode: Begin Keypress Conditional\n"); this->LogToDebugFile("Key Mask: %x\n", opcode->begin_keypress_cond.key_mask); break; case CheatVmOpcodeType_PerformArithmeticRegister: this->LogToDebugFile("Opcode: Perform Register Arithmetic\n"); this->LogToDebugFile("Bit Width: %x\n", opcode->perform_math_reg.bit_width); this->LogToDebugFile("Dst Idx: %x\n", opcode->perform_math_reg.dst_reg_index); this->LogToDebugFile("Src1 Idx: %x\n", opcode->perform_math_reg.src_reg_1_index); if (opcode->perform_math_reg.has_immediate) { this->LogToDebugFile("Value: %lx\n", opcode->perform_math_reg.value.bit64); } else { this->LogToDebugFile("Src2 Idx: %x\n", opcode->perform_math_reg.src_reg_2_index); } break; case CheatVmOpcodeType_StoreRegisterToAddress: this->LogToDebugFile("Opcode: Store Register to Address\n"); this->LogToDebugFile("Bit Width: %x\n", opcode->str_register.bit_width); this->LogToDebugFile("S Reg Idx: %x\n", opcode->str_register.str_reg_index); this->LogToDebugFile("A Reg Idx: %x\n", opcode->str_register.addr_reg_index); this->LogToDebugFile("Incr Reg: %d\n", opcode->str_register.increment_reg); switch (opcode->str_register.ofs_type) { case StoreRegisterOffsetType_None: break; case StoreRegisterOffsetType_Reg: this->LogToDebugFile("O Reg Idx: %x\n", opcode->str_register.ofs_reg_index); break; case StoreRegisterOffsetType_Imm: this->LogToDebugFile("Rel Addr: %lx\n", opcode->str_register.rel_address); break; case StoreRegisterOffsetType_MemReg: this->LogToDebugFile("Mem Type: %x\n", opcode->str_register.mem_type); break; case StoreRegisterOffsetType_MemImm: case StoreRegisterOffsetType_MemImmReg: this->LogToDebugFile("Mem Type: %x\n", opcode->str_register.mem_type); this->LogToDebugFile("Rel Addr: %lx\n", opcode->str_register.rel_address); break; } break; case CheatVmOpcodeType_BeginRegisterConditionalBlock: this->LogToDebugFile("Opcode: Begin Register Conditional\n"); this->LogToDebugFile("Bit Width: %x\n", opcode->begin_reg_cond.bit_width); this->LogToDebugFile("Cond Type: %x\n", opcode->begin_reg_cond.cond_type); this->LogToDebugFile("V Reg Idx: %x\n", opcode->begin_reg_cond.val_reg_index); switch (opcode->begin_reg_cond.comp_type) { case CompareRegisterValueType_StaticValue: this->LogToDebugFile("Comp Type: Static Value\n"); this->LogToDebugFile("Value: %lx\n", opcode->begin_reg_cond.value.bit64); break; case CompareRegisterValueType_OtherRegister: this->LogToDebugFile("Comp Type: Other Register\n"); this->LogToDebugFile("X Reg Idx: %x\n", opcode->begin_reg_cond.other_reg_index); break; case CompareRegisterValueType_MemoryRelAddr: this->LogToDebugFile("Comp Type: Memory Relative Address\n"); this->LogToDebugFile("Mem Type: %x\n", opcode->begin_reg_cond.mem_type); this->LogToDebugFile("Rel Addr: %lx\n", opcode->begin_reg_cond.rel_address); break; case CompareRegisterValueType_MemoryOfsReg: this->LogToDebugFile("Comp Type: Memory Offset Register\n"); this->LogToDebugFile("Mem Type: %x\n", opcode->begin_reg_cond.mem_type); this->LogToDebugFile("O Reg Idx: %x\n", opcode->begin_reg_cond.ofs_reg_index); break; case CompareRegisterValueType_RegisterRelAddr: this->LogToDebugFile("Comp Type: Register Relative Address\n"); this->LogToDebugFile("A Reg Idx: %x\n", opcode->begin_reg_cond.addr_reg_index); this->LogToDebugFile("Rel Addr: %lx\n", opcode->begin_reg_cond.rel_address); break; case CompareRegisterValueType_RegisterOfsReg: this->LogToDebugFile("Comp Type: Register Offset Register\n"); this->LogToDebugFile("A Reg Idx: %x\n", opcode->begin_reg_cond.addr_reg_index); this->LogToDebugFile("O Reg Idx: %x\n", opcode->begin_reg_cond.ofs_reg_index); break; } break; case CheatVmOpcodeType_SaveRestoreRegister: this->LogToDebugFile("Opcode: Save or Restore Register\n"); this->LogToDebugFile("Dst Idx: %x\n", opcode->save_restore_reg.dst_index); this->LogToDebugFile("Src Idx: %x\n", opcode->save_restore_reg.src_index); this->LogToDebugFile("Op Type: %d\n", opcode->save_restore_reg.op_type); break; case CheatVmOpcodeType_SaveRestoreRegisterMask: this->LogToDebugFile("Opcode: Save or Restore Register Mask\n"); this->LogToDebugFile("Op Type: %d\n", opcode->save_restore_regmask.op_type); for (size_t i = 0; i < NumRegisters; i++) { this->LogToDebugFile("Act[%02x]: %d\n", i, opcode->save_restore_regmask.should_operate[i]); } break; case CheatVmOpcodeType_ReadWriteStaticRegister: this->LogToDebugFile("Opcode: Read/Write Static Register\n"); if (opcode->rw_static_reg.static_idx < NumReadableStaticRegisters) { this->LogToDebugFile("Op Type: ReadStaticRegister\n"); } else { this->LogToDebugFile("Op Type: WriteStaticRegister\n"); } this->LogToDebugFile("Reg Idx: %x\n", opcode->rw_static_reg.idx); this->LogToDebugFile("Stc Idx: %x\n", opcode->rw_static_reg.static_idx); break; case CheatVmOpcodeType_PauseProcess: this->LogToDebugFile("Opcode: Pause Cheat Process\n"); break; case CheatVmOpcodeType_ResumeProcess: this->LogToDebugFile("Opcode: Resume Cheat Process\n"); break; case CheatVmOpcodeType_DebugLog: this->LogToDebugFile("Opcode: Debug Log\n"); this->LogToDebugFile("Bit Width: %x\n", opcode->debug_log.bit_width); this->LogToDebugFile("Log ID: %x\n", opcode->debug_log.log_id); this->LogToDebugFile("Val Type: %x\n", opcode->debug_log.val_type); switch (opcode->debug_log.val_type) { case DebugLogValueType_RegisterValue: this->LogToDebugFile("Val Type: Register Value\n"); this->LogToDebugFile("X Reg Idx: %x\n", opcode->debug_log.val_reg_index); break; case DebugLogValueType_MemoryRelAddr: this->LogToDebugFile("Val Type: Memory Relative Address\n"); this->LogToDebugFile("Mem Type: %x\n", opcode->debug_log.mem_type); this->LogToDebugFile("Rel Addr: %lx\n", opcode->debug_log.rel_address); break; case DebugLogValueType_MemoryOfsReg: this->LogToDebugFile("Val Type: Memory Offset Register\n"); this->LogToDebugFile("Mem Type: %x\n", opcode->debug_log.mem_type); this->LogToDebugFile("O Reg Idx: %x\n", opcode->debug_log.ofs_reg_index); break; case DebugLogValueType_RegisterRelAddr: this->LogToDebugFile("Val Type: Register Relative Address\n"); this->LogToDebugFile("A Reg Idx: %x\n", opcode->debug_log.addr_reg_index); this->LogToDebugFile("Rel Addr: %lx\n", opcode->debug_log.rel_address); break; case DebugLogValueType_RegisterOfsReg: this->LogToDebugFile("Val Type: Register Offset Register\n"); this->LogToDebugFile("A Reg Idx: %x\n", opcode->debug_log.addr_reg_index); this->LogToDebugFile("O Reg Idx: %x\n", opcode->debug_log.ofs_reg_index); break; } break; default: this->LogToDebugFile("Unknown opcode: %x\n", opcode->opcode); break; } } bool CheatVirtualMachine::DecodeNextOpcode(CheatVmOpcode *out) { /* If we've ever seen a decode failure, return false. */ bool valid = m_decode_success; CheatVmOpcode opcode = {}; ON_SCOPE_EXIT { m_decode_success &= valid; if (valid) { *out = opcode; } }; /* Helper function for getting instruction dwords. */ auto GetNextDword = [&]() { if (m_instruction_ptr >= m_num_opcodes) { valid = false; return static_cast<u32>(0); } return m_program[m_instruction_ptr++]; }; /* Helper function for parsing a VmInt. */ auto GetNextVmInt = [&](const u32 bit_width) { VmInt val = {0}; const u32 first_dword = GetNextDword(); switch (bit_width) { case 1: val.bit8 = (u8)first_dword; break; case 2: val.bit16 = (u16)first_dword; break; case 4: val.bit32 = first_dword; break; case 8: val.bit64 = (((u64)first_dword) << 32ul) | ((u64)GetNextDword()); break; } return val; }; /* Read opcode. */ const u32 first_dword = GetNextDword(); if (!valid) { return valid; } opcode.opcode = (CheatVmOpcodeType)(((first_dword >> 28) & 0xF)); if (opcode.opcode >= CheatVmOpcodeType_ExtendedWidth) { opcode.opcode = (CheatVmOpcodeType)((((u32)opcode.opcode) << 4) | ((first_dword >> 24) & 0xF)); } if (opcode.opcode >= CheatVmOpcodeType_DoubleExtendedWidth) { opcode.opcode = (CheatVmOpcodeType)((((u32)opcode.opcode) << 4) | ((first_dword >> 20) & 0xF)); } /* detect condition start. */ switch (opcode.opcode) { case CheatVmOpcodeType_BeginConditionalBlock: case CheatVmOpcodeType_BeginKeypressConditionalBlock: case CheatVmOpcodeType_BeginRegisterConditionalBlock: opcode.begin_conditional_block = true; break; default: opcode.begin_conditional_block = false; break; } switch (opcode.opcode) { case CheatVmOpcodeType_StoreStatic: { /* 0TMR00AA AAAAAAAA YYYYYYYY (YYYYYYYY) */ /* Read additional words. */ const u32 second_dword = GetNextDword(); opcode.store_static.bit_width = (first_dword >> 24) & 0xF; opcode.store_static.mem_type = (MemoryAccessType)((first_dword >> 20) & 0xF); opcode.store_static.offset_register = ((first_dword >> 16) & 0xF); opcode.store_static.rel_address = ((u64)(first_dword & 0xFF) << 32ul) | ((u64)second_dword); opcode.store_static.value = GetNextVmInt(opcode.store_static.bit_width); } break; case CheatVmOpcodeType_BeginConditionalBlock: { /* 1TMC00AA AAAAAAAA YYYYYYYY (YYYYYYYY) */ /* Read additional words. */ const u32 second_dword = GetNextDword(); opcode.begin_cond.bit_width = (first_dword >> 24) & 0xF; opcode.begin_cond.mem_type = (MemoryAccessType)((first_dword >> 20) & 0xF); opcode.begin_cond.cond_type = (ConditionalComparisonType)((first_dword >> 16) & 0xF); opcode.begin_cond.rel_address = ((u64)(first_dword & 0xFF) << 32ul) | ((u64)second_dword); opcode.begin_cond.value = GetNextVmInt(opcode.begin_cond.bit_width); } break; case CheatVmOpcodeType_EndConditionalBlock: { /* 2X000000 */ opcode.end_cond.is_else = ((first_dword >> 24) & 0xF) == 1; } break; case CheatVmOpcodeType_ControlLoop: { /* 300R0000 VVVVVVVV */ /* 310R0000 */ /* Parse register, whether loop start or loop end. */ opcode.ctrl_loop.start_loop = ((first_dword >> 24) & 0xF) == 0; opcode.ctrl_loop.reg_index = ((first_dword >> 16) & 0xF); /* Read number of iters if loop start. */ if (opcode.ctrl_loop.start_loop) { opcode.ctrl_loop.num_iters = GetNextDword(); } } break; case CheatVmOpcodeType_LoadRegisterStatic: { /* 400R0000 VVVVVVVV VVVVVVVV */ /* Read additional words. */ opcode.ldr_static.reg_index = ((first_dword >> 16) & 0xF); opcode.ldr_static.value = (((u64)GetNextDword()) << 32ul) | ((u64)GetNextDword()); } break; case CheatVmOpcodeType_LoadRegisterMemory: { /* 5TMRI0AA AAAAAAAA */ /* Read additional words. */ const u32 second_dword = GetNextDword(); opcode.ldr_memory.bit_width = (first_dword >> 24) & 0xF; opcode.ldr_memory.mem_type = (MemoryAccessType)((first_dword >> 20) & 0xF); opcode.ldr_memory.reg_index = ((first_dword >> 16) & 0xF); opcode.ldr_memory.load_from_reg = ((first_dword >> 12) & 0xF) != 0; opcode.ldr_memory.rel_address = ((u64)(first_dword & 0xFF) << 32ul) | ((u64)second_dword); } break; case CheatVmOpcodeType_StoreStaticToAddress: { /* 6T0RIor0 VVVVVVVV VVVVVVVV */ /* Read additional words. */ opcode.str_static.bit_width = (first_dword >> 24) & 0xF; opcode.str_static.reg_index = ((first_dword >> 16) & 0xF); opcode.str_static.increment_reg = ((first_dword >> 12) & 0xF) != 0; opcode.str_static.add_offset_reg = ((first_dword >> 8) & 0xF) != 0; opcode.str_static.offset_reg_index = ((first_dword >> 4) & 0xF); opcode.str_static.value = (((u64)GetNextDword()) << 32ul) | ((u64)GetNextDword()); } break; case CheatVmOpcodeType_PerformArithmeticStatic: { /* 7T0RC000 VVVVVVVV */ /* Read additional words. */ opcode.perform_math_static.bit_width = (first_dword >> 24) & 0xF; opcode.perform_math_static.reg_index = ((first_dword >> 16) & 0xF); opcode.perform_math_static.math_type = (RegisterArithmeticType)((first_dword >> 12) & 0xF); opcode.perform_math_static.value = GetNextDword(); } break; case CheatVmOpcodeType_BeginKeypressConditionalBlock: { /* 8kkkkkkk */ /* Just parse the mask. */ opcode.begin_keypress_cond.key_mask = first_dword & 0x0FFFFFFF; } break; case CheatVmOpcodeType_PerformArithmeticRegister: { /* 9TCRSIs0 (VVVVVVVV (VVVVVVVV)) */ opcode.perform_math_reg.bit_width = (first_dword >> 24) & 0xF; opcode.perform_math_reg.math_type = (RegisterArithmeticType)((first_dword >> 20) & 0xF); opcode.perform_math_reg.dst_reg_index = ((first_dword >> 16) & 0xF); opcode.perform_math_reg.src_reg_1_index = ((first_dword >> 12) & 0xF); opcode.perform_math_reg.has_immediate = ((first_dword >> 8) & 0xF) != 0; if (opcode.perform_math_reg.has_immediate) { opcode.perform_math_reg.src_reg_2_index = 0; opcode.perform_math_reg.value = GetNextVmInt(opcode.perform_math_reg.bit_width); } else { opcode.perform_math_reg.src_reg_2_index = ((first_dword >> 4) & 0xF); } } break; case CheatVmOpcodeType_StoreRegisterToAddress: { /* ATSRIOxa (aaaaaaaa) */ /* A = opcode 10 */ /* T = bit width */ /* S = src register index */ /* R = address register index */ /* I = 1 if increment address register, 0 if not increment address register */ /* O = offset type, 0 = None, 1 = Register, 2 = Immediate, 3 = Memory Region, 4 = Memory Region + Relative Address (ignore address register), 5 = Memory Region + Relative Address */ /* x = offset register (for offset type 1), memory type (for offset type 3) */ /* a = relative address (for offset type 2+3) */ opcode.str_register.bit_width = (first_dword >> 24) & 0xF; opcode.str_register.str_reg_index = ((first_dword >> 20) & 0xF); opcode.str_register.addr_reg_index = ((first_dword >> 16) & 0xF); opcode.str_register.increment_reg = ((first_dword >> 12) & 0xF) != 0; opcode.str_register.ofs_type = (StoreRegisterOffsetType)(((first_dword >> 8) & 0xF)); opcode.str_register.ofs_reg_index = ((first_dword >> 4) & 0xF); switch (opcode.str_register.ofs_type) { case StoreRegisterOffsetType_None: case StoreRegisterOffsetType_Reg: /* Nothing more to do */ break; case StoreRegisterOffsetType_Imm: opcode.str_register.rel_address = (((u64)(first_dword & 0xF) << 32ul) | ((u64)GetNextDword())); break; case StoreRegisterOffsetType_MemReg: opcode.str_register.mem_type = (MemoryAccessType)((first_dword >> 4) & 0xF); break; case StoreRegisterOffsetType_MemImm: case StoreRegisterOffsetType_MemImmReg: opcode.str_register.mem_type = (MemoryAccessType)((first_dword >> 4) & 0xF); opcode.str_register.rel_address = (((u64)(first_dword & 0xF) << 32ul) | ((u64)GetNextDword())); break; default: opcode.str_register.ofs_type = StoreRegisterOffsetType_None; break; } } break; case CheatVmOpcodeType_BeginRegisterConditionalBlock: { /* C0TcSX## */ /* C0TcS0Ma aaaaaaaa */ /* C0TcS1Mr */ /* C0TcS2Ra aaaaaaaa */ /* C0TcS3Rr */ /* C0TcS400 VVVVVVVV (VVVVVVVV) */ /* C0TcS5X0 */ /* C0 = opcode 0xC0 */ /* T = bit width */ /* c = condition type. */ /* S = source register. */ /* X = value operand type, 0 = main/heap with relative offset, 1 = main/heap with offset register, */ /* 2 = register with relative offset, 3 = register with offset register, 4 = static value, 5 = other register. */ /* M = memory type. */ /* R = address register. */ /* a = relative address. */ /* r = offset register. */ /* X = other register. */ /* V = value. */ opcode.begin_reg_cond.bit_width = (first_dword >> 20) & 0xF; opcode.begin_reg_cond.cond_type = (ConditionalComparisonType)((first_dword >> 16) & 0xF); opcode.begin_reg_cond.val_reg_index = ((first_dword >> 12) & 0xF); opcode.begin_reg_cond.comp_type = (CompareRegisterValueType)((first_dword >> 8) & 0xF); switch (opcode.begin_reg_cond.comp_type) { case CompareRegisterValueType_StaticValue: opcode.begin_reg_cond.value = GetNextVmInt(opcode.begin_reg_cond.bit_width); break; case CompareRegisterValueType_OtherRegister: opcode.begin_reg_cond.other_reg_index = ((first_dword >> 4) & 0xF); break; case CompareRegisterValueType_MemoryRelAddr: opcode.begin_reg_cond.mem_type = (MemoryAccessType)((first_dword >> 4) & 0xF); opcode.begin_reg_cond.rel_address = (((u64)(first_dword & 0xF) << 32ul) | ((u64)GetNextDword())); break; case CompareRegisterValueType_MemoryOfsReg: opcode.begin_reg_cond.mem_type = (MemoryAccessType)((first_dword >> 4) & 0xF); opcode.begin_reg_cond.ofs_reg_index = (first_dword & 0xF); break; case CompareRegisterValueType_RegisterRelAddr: opcode.begin_reg_cond.addr_reg_index = ((first_dword >> 4) & 0xF); opcode.begin_reg_cond.rel_address = (((u64)(first_dword & 0xF) << 32ul) | ((u64)GetNextDword())); break; case CompareRegisterValueType_RegisterOfsReg: opcode.begin_reg_cond.addr_reg_index = ((first_dword >> 4) & 0xF); opcode.begin_reg_cond.ofs_reg_index = (first_dword & 0xF); break; } } break; case CheatVmOpcodeType_SaveRestoreRegister: { /* C10D0Sx0 */ /* C1 = opcode 0xC1 */ /* D = destination index. */ /* S = source index. */ /* x = 3 if clearing reg, 2 if clearing saved value, 1 if saving a register, 0 if restoring a register. */ /* NOTE: If we add more save slots later, current encoding is backwards compatible. */ opcode.save_restore_reg.dst_index = (first_dword >> 16) & 0xF; opcode.save_restore_reg.src_index = (first_dword >> 8) & 0xF; opcode.save_restore_reg.op_type = (SaveRestoreRegisterOpType)((first_dword >> 4) & 0xF); } break; case CheatVmOpcodeType_SaveRestoreRegisterMask: { /* C2x0XXXX */ /* C2 = opcode 0xC2 */ /* x = 3 if clearing reg, 2 if clearing saved value, 1 if saving, 0 if restoring. */ /* X = 16-bit bitmask, bit i --> save or restore register i. */ opcode.save_restore_regmask.op_type = (SaveRestoreRegisterOpType)((first_dword >> 20) & 0xF); for (size_t i = 0; i < NumRegisters; i++) { opcode.save_restore_regmask.should_operate[i] = (first_dword & (1u << i)) != 0; } } break; case CheatVmOpcodeType_ReadWriteStaticRegister: { /* C3000XXx */ /* C3 = opcode 0xC3. */ /* XX = static register index. */ /* x = register index. */ opcode.rw_static_reg.static_idx = ((first_dword >> 4) & 0xFF); opcode.rw_static_reg.idx = (first_dword & 0xF); } break; case CheatVmOpcodeType_PauseProcess: { /* FF0????? */ /* FF0 = opcode 0xFF0 */ /* Pauses the current process. */ } break; case CheatVmOpcodeType_ResumeProcess: { /* FF1????? */ /* FF1 = opcode 0xFF1 */ /* Resumes the current process. */ } break; case CheatVmOpcodeType_DebugLog: { /* FFFTIX## */ /* FFFTI0Ma aaaaaaaa */ /* FFFTI1Mr */ /* FFFTI2Ra aaaaaaaa */ /* FFFTI3Rr */ /* FFFTI4X0 */ /* FFF = opcode 0xFFF */ /* T = bit width. */ /* I = log id. */ /* X = value operand type, 0 = main/heap with relative offset, 1 = main/heap with offset register, */ /* 2 = register with relative offset, 3 = register with offset register, 4 = register value. */ /* M = memory type. */ /* R = address register. */ /* a = relative address. */ /* r = offset register. */ /* X = value register. */ opcode.debug_log.bit_width = (first_dword >> 16) & 0xF; opcode.debug_log.log_id = ((first_dword >> 12) & 0xF); opcode.debug_log.val_type = (DebugLogValueType)((first_dword >> 8) & 0xF); switch (opcode.debug_log.val_type) { case DebugLogValueType_RegisterValue: opcode.debug_log.val_reg_index = ((first_dword >> 4) & 0xF); break; case DebugLogValueType_MemoryRelAddr: opcode.debug_log.mem_type = (MemoryAccessType)((first_dword >> 4) & 0xF); opcode.debug_log.rel_address = (((u64)(first_dword & 0xF) << 32ul) | ((u64)GetNextDword())); break; case DebugLogValueType_MemoryOfsReg: opcode.debug_log.mem_type = (MemoryAccessType)((first_dword >> 4) & 0xF); opcode.debug_log.ofs_reg_index = (first_dword & 0xF); break; case DebugLogValueType_RegisterRelAddr: opcode.debug_log.addr_reg_index = ((first_dword >> 4) & 0xF); opcode.debug_log.rel_address = (((u64)(first_dword & 0xF) << 32ul) | ((u64)GetNextDword())); break; case DebugLogValueType_RegisterOfsReg: opcode.debug_log.addr_reg_index = ((first_dword >> 4) & 0xF); opcode.debug_log.ofs_reg_index = (first_dword & 0xF); break; } } break; case CheatVmOpcodeType_ExtendedWidth: case CheatVmOpcodeType_DoubleExtendedWidth: default: /* Unrecognized instruction cannot be decoded. */ valid = false; break; } /* End decoding. */ return valid; } void CheatVirtualMachine::SkipConditionalBlock(bool is_if) { if (m_condition_depth > 0) { /* We want to continue until we're out of the current block. */ const size_t desired_depth = m_condition_depth - 1; CheatVmOpcode skip_opcode; while (m_condition_depth > desired_depth && this->DecodeNextOpcode(std::addressof(skip_opcode))) { /* Decode instructions until we see end of the current conditional block. */ /* NOTE: This is broken in gateway's implementation. */ /* Gateway currently checks for "0x2" instead of "0x20000000" */ /* In addition, they do a linear scan instead of correctly decoding opcodes. */ /* This causes issues if "0x2" appears as an immediate in the conditional block... */ /* We also support nesting of conditional blocks, and Gateway does not. */ if (skip_opcode.begin_conditional_block) { m_condition_depth++; } else if (skip_opcode.opcode == CheatVmOpcodeType_EndConditionalBlock) { if (!skip_opcode.end_cond.is_else) { m_condition_depth--; } else if (is_if && m_condition_depth - 1 == desired_depth) { /* An if will continue to an else at the same depth. */ break; } } } } else { /* Skipping, but m_condition_depth = 0. */ /* This is an error condition. */ /* This could occur with a mismatched "else" opcode, for example. */ R_ABORT_UNLESS(ResultVirtualMachineInvalidConditionDepth()); } } u64 CheatVirtualMachine::GetVmInt(VmInt value, u32 bit_width) { switch (bit_width) { case 1: return value.bit8; case 2: return value.bit16; case 4: return value.bit32; case 8: return value.bit64; default: /* Invalid bit width -> return 0. */ return 0; } } u64 CheatVirtualMachine::GetCheatProcessAddress(const CheatProcessMetadata* metadata, MemoryAccessType mem_type, u64 rel_address) { switch (mem_type) { case MemoryAccessType_MainNso: default: return metadata->main_nso_extents.base + rel_address; case MemoryAccessType_Heap: return metadata->heap_extents.base + rel_address; case MemoryAccessType_Alias: return metadata->alias_extents.base + rel_address; case MemoryAccessType_Aslr: return metadata->aslr_extents.base + rel_address; } } void CheatVirtualMachine::ResetState() { for (size_t i = 0; i < CheatVirtualMachine::NumRegisters; i++) { m_registers[i] = 0; m_saved_values[i] = 0; m_loop_tops[i] = 0; } m_instruction_ptr = 0; m_condition_depth = 0; m_decode_success = true; } bool CheatVirtualMachine::LoadProgram(const CheatEntry *cheats, size_t num_cheats) { /* Reset opcode count. */ m_num_opcodes = 0; for (size_t i = 0; i < num_cheats; i++) { if (cheats[i].enabled) { /* Bounds check. */ if (cheats[i].definition.num_opcodes + m_num_opcodes > MaximumProgramOpcodeCount) { m_num_opcodes = 0; return false; } for (size_t n = 0; n < cheats[i].definition.num_opcodes; n++) { m_program[m_num_opcodes++] = cheats[i].definition.opcodes[n]; } } } return true; } void CheatVirtualMachine::Execute(const CheatProcessMetadata *metadata) { CheatVmOpcode cur_opcode; u64 kHeld = 0; /* Get Keys held. */ hid::GetKeysHeld(std::addressof(kHeld)); this->OpenDebugLogFile(); ON_SCOPE_EXIT { this->CloseDebugLogFile(); }; this->LogToDebugFile("Started VM execution.\n"); this->LogToDebugFile("Main NSO: %012lx\n", metadata->main_nso_extents.base); this->LogToDebugFile("Heap: %012lx\n", metadata->main_nso_extents.base); this->LogToDebugFile("Keys Held: %08x\n", (u32)(kHeld & 0x0FFFFFFF)); /* Clear VM state. */ this->ResetState(); /* Loop until program finishes. */ while (this->DecodeNextOpcode(std::addressof(cur_opcode))) { this->LogToDebugFile("Instruction Ptr: %04x\n", (u32)m_instruction_ptr); for (size_t i = 0; i < NumRegisters; i++) { this->LogToDebugFile("Registers[%02x]: %016lx\n", i, m_registers[i]); } for (size_t i = 0; i < NumRegisters; i++) { this->LogToDebugFile("SavedRegs[%02x]: %016lx\n", i, m_saved_values[i]); } this->LogOpcode(std::addressof(cur_opcode)); /* Increment conditional depth, if relevant. */ if (cur_opcode.begin_conditional_block) { m_condition_depth++; } switch (cur_opcode.opcode) { case CheatVmOpcodeType_StoreStatic: { /* Calculate address, write value to memory. */ u64 dst_address = GetCheatProcessAddress(metadata, cur_opcode.store_static.mem_type, cur_opcode.store_static.rel_address + m_registers[cur_opcode.store_static.offset_register]); u64 dst_value = GetVmInt(cur_opcode.store_static.value, cur_opcode.store_static.bit_width); switch (cur_opcode.store_static.bit_width) { case 1: case 2: case 4: case 8: dmnt::cheat::impl::WriteCheatProcessMemoryUnsafe(dst_address, std::addressof(dst_value), cur_opcode.store_static.bit_width); break; } } break; case CheatVmOpcodeType_BeginConditionalBlock: { /* Read value from memory. */ u64 src_address = GetCheatProcessAddress(metadata, cur_opcode.begin_cond.mem_type, cur_opcode.begin_cond.rel_address); u64 src_value = 0; switch (cur_opcode.store_static.bit_width) { case 1: case 2: case 4: case 8: dmnt::cheat::impl::ReadCheatProcessMemoryUnsafe(src_address, std::addressof(src_value), cur_opcode.begin_cond.bit_width); break; } /* Check against condition. */ u64 cond_value = GetVmInt(cur_opcode.begin_cond.value, cur_opcode.begin_cond.bit_width); bool cond_met = false; switch (cur_opcode.begin_cond.cond_type) { case ConditionalComparisonType_GT: cond_met = src_value > cond_value; break; case ConditionalComparisonType_GE: cond_met = src_value >= cond_value; break; case ConditionalComparisonType_LT: cond_met = src_value < cond_value; break; case ConditionalComparisonType_LE: cond_met = src_value <= cond_value; break; case ConditionalComparisonType_EQ: cond_met = src_value == cond_value; break; case ConditionalComparisonType_NE: cond_met = src_value != cond_value; break; } /* Skip conditional block if condition not met. */ if (!cond_met) { this->SkipConditionalBlock(true); } } break; case CheatVmOpcodeType_EndConditionalBlock: if (cur_opcode.end_cond.is_else) { /* Skip to the end of the conditional block. */ this->SkipConditionalBlock(false); } else { /* Decrement the condition depth. */ /* We will assume, graciously, that mismatched conditional block ends are a nop. */ if (m_condition_depth > 0) { m_condition_depth--; } } break; case CheatVmOpcodeType_ControlLoop: if (cur_opcode.ctrl_loop.start_loop) { /* Start a loop. */ m_registers[cur_opcode.ctrl_loop.reg_index] = cur_opcode.ctrl_loop.num_iters; m_loop_tops[cur_opcode.ctrl_loop.reg_index] = m_instruction_ptr; } else { /* End a loop. */ m_registers[cur_opcode.ctrl_loop.reg_index]--; if (m_registers[cur_opcode.ctrl_loop.reg_index] != 0) { m_instruction_ptr = m_loop_tops[cur_opcode.ctrl_loop.reg_index]; } } break; case CheatVmOpcodeType_LoadRegisterStatic: /* Set a register to a static value. */ m_registers[cur_opcode.ldr_static.reg_index] = cur_opcode.ldr_static.value; break; case CheatVmOpcodeType_LoadRegisterMemory: { /* Choose source address. */ u64 src_address; if (cur_opcode.ldr_memory.load_from_reg) { src_address = m_registers[cur_opcode.ldr_memory.reg_index] + cur_opcode.ldr_memory.rel_address; } else { src_address = GetCheatProcessAddress(metadata, cur_opcode.ldr_memory.mem_type, cur_opcode.ldr_memory.rel_address); } /* Read into register. Gateway only reads on valid bitwidth. */ switch (cur_opcode.ldr_memory.bit_width) { case 1: case 2: case 4: case 8: dmnt::cheat::impl::ReadCheatProcessMemoryUnsafe(src_address, std::addressof(m_registers[cur_opcode.ldr_memory.reg_index]), cur_opcode.ldr_memory.bit_width); break; } } break; case CheatVmOpcodeType_StoreStaticToAddress: { /* Calculate address. */ u64 dst_address = m_registers[cur_opcode.str_static.reg_index]; u64 dst_value = cur_opcode.str_static.value; if (cur_opcode.str_static.add_offset_reg) { dst_address += m_registers[cur_opcode.str_static.offset_reg_index]; } /* Write value to memory. Gateway only writes on valid bitwidth. */ switch (cur_opcode.str_static.bit_width) { case 1: case 2: case 4: case 8: dmnt::cheat::impl::WriteCheatProcessMemoryUnsafe(dst_address, std::addressof(dst_value), cur_opcode.str_static.bit_width); break; } /* Increment register if relevant. */ if (cur_opcode.str_static.increment_reg) { m_registers[cur_opcode.str_static.reg_index] += cur_opcode.str_static.bit_width; } } break; case CheatVmOpcodeType_PerformArithmeticStatic: { /* Do requested math. */ switch (cur_opcode.perform_math_static.math_type) { case RegisterArithmeticType_Addition: m_registers[cur_opcode.perform_math_static.reg_index] += (u64)cur_opcode.perform_math_static.value; break; case RegisterArithmeticType_Subtraction: m_registers[cur_opcode.perform_math_static.reg_index] -= (u64)cur_opcode.perform_math_static.value; break; case RegisterArithmeticType_Multiplication: m_registers[cur_opcode.perform_math_static.reg_index] *= (u64)cur_opcode.perform_math_static.value; break; case RegisterArithmeticType_LeftShift: m_registers[cur_opcode.perform_math_static.reg_index] <<= (u64)cur_opcode.perform_math_static.value; break; case RegisterArithmeticType_RightShift: m_registers[cur_opcode.perform_math_static.reg_index] >>= (u64)cur_opcode.perform_math_static.value; break; default: /* Do not handle extensions here. */ break; } /* Apply bit width. */ switch (cur_opcode.perform_math_static.bit_width) { case 1: m_registers[cur_opcode.perform_math_static.reg_index] = static_cast<u8>(m_registers[cur_opcode.perform_math_static.reg_index]); break; case 2: m_registers[cur_opcode.perform_math_static.reg_index] = static_cast<u16>(m_registers[cur_opcode.perform_math_static.reg_index]); break; case 4: m_registers[cur_opcode.perform_math_static.reg_index] = static_cast<u32>(m_registers[cur_opcode.perform_math_static.reg_index]); break; case 8: m_registers[cur_opcode.perform_math_static.reg_index] = static_cast<u64>(m_registers[cur_opcode.perform_math_static.reg_index]); break; } } break; case CheatVmOpcodeType_BeginKeypressConditionalBlock: /* Check for keypress. */ if ((cur_opcode.begin_keypress_cond.key_mask & kHeld) != cur_opcode.begin_keypress_cond.key_mask) { /* Keys not pressed. Skip conditional block. */ this->SkipConditionalBlock(true); } break; case CheatVmOpcodeType_PerformArithmeticRegister: { const u64 operand_1_value = m_registers[cur_opcode.perform_math_reg.src_reg_1_index]; const u64 operand_2_value = cur_opcode.perform_math_reg.has_immediate ? GetVmInt(cur_opcode.perform_math_reg.value, cur_opcode.perform_math_reg.bit_width) : m_registers[cur_opcode.perform_math_reg.src_reg_2_index]; u64 res_val = 0; /* Do requested math. */ switch (cur_opcode.perform_math_reg.math_type) { case RegisterArithmeticType_Addition: res_val = operand_1_value + operand_2_value; break; case RegisterArithmeticType_Subtraction: res_val = operand_1_value - operand_2_value; break; case RegisterArithmeticType_Multiplication: res_val = operand_1_value * operand_2_value; break; case RegisterArithmeticType_LeftShift: res_val = operand_1_value << operand_2_value; break; case RegisterArithmeticType_RightShift: res_val = operand_1_value >> operand_2_value; break; case RegisterArithmeticType_LogicalAnd: res_val = operand_1_value & operand_2_value; break; case RegisterArithmeticType_LogicalOr: res_val = operand_1_value | operand_2_value; break; case RegisterArithmeticType_LogicalNot: res_val = ~operand_1_value; break; case RegisterArithmeticType_LogicalXor: res_val = operand_1_value ^ operand_2_value; break; case RegisterArithmeticType_None: res_val = operand_1_value; break; } /* Apply bit width. */ switch (cur_opcode.perform_math_reg.bit_width) { case 1: res_val = static_cast<u8>(res_val); break; case 2: res_val = static_cast<u16>(res_val); break; case 4: res_val = static_cast<u32>(res_val); break; case 8: res_val = static_cast<u64>(res_val); break; } /* Save to register. */ m_registers[cur_opcode.perform_math_reg.dst_reg_index] = res_val; } break; case CheatVmOpcodeType_StoreRegisterToAddress: { /* Calculate address. */ u64 dst_value = m_registers[cur_opcode.str_register.str_reg_index]; u64 dst_address = m_registers[cur_opcode.str_register.addr_reg_index]; switch (cur_opcode.str_register.ofs_type) { case StoreRegisterOffsetType_None: /* Nothing more to do */ break; case StoreRegisterOffsetType_Reg: dst_address += m_registers[cur_opcode.str_register.ofs_reg_index]; break; case StoreRegisterOffsetType_Imm: dst_address += cur_opcode.str_register.rel_address; break; case StoreRegisterOffsetType_MemReg: dst_address = GetCheatProcessAddress(metadata, cur_opcode.str_register.mem_type, m_registers[cur_opcode.str_register.addr_reg_index]); break; case StoreRegisterOffsetType_MemImm: dst_address = GetCheatProcessAddress(metadata, cur_opcode.str_register.mem_type, cur_opcode.str_register.rel_address); break; case StoreRegisterOffsetType_MemImmReg: dst_address = GetCheatProcessAddress(metadata, cur_opcode.str_register.mem_type, m_registers[cur_opcode.str_register.addr_reg_index] + cur_opcode.str_register.rel_address); break; } /* Write value to memory. Write only on valid bitwidth. */ switch (cur_opcode.str_register.bit_width) { case 1: case 2: case 4: case 8: dmnt::cheat::impl::WriteCheatProcessMemoryUnsafe(dst_address, std::addressof(dst_value), cur_opcode.str_register.bit_width); break; } /* Increment register if relevant. */ if (cur_opcode.str_register.increment_reg) { m_registers[cur_opcode.str_register.addr_reg_index] += cur_opcode.str_register.bit_width; } } break; case CheatVmOpcodeType_BeginRegisterConditionalBlock: { /* Get value from register. */ u64 src_value = 0; switch (cur_opcode.begin_reg_cond.bit_width) { case 1: src_value = static_cast<u8>(m_registers[cur_opcode.begin_reg_cond.val_reg_index] & 0xFFul); break; case 2: src_value = static_cast<u16>(m_registers[cur_opcode.begin_reg_cond.val_reg_index] & 0xFFFFul); break; case 4: src_value = static_cast<u32>(m_registers[cur_opcode.begin_reg_cond.val_reg_index] & 0xFFFFFFFFul); break; case 8: src_value = static_cast<u64>(m_registers[cur_opcode.begin_reg_cond.val_reg_index] & 0xFFFFFFFFFFFFFFFFul); break; } /* Read value from memory. */ u64 cond_value = 0; if (cur_opcode.begin_reg_cond.comp_type == CompareRegisterValueType_StaticValue) { cond_value = GetVmInt(cur_opcode.begin_reg_cond.value, cur_opcode.begin_reg_cond.bit_width); } else if (cur_opcode.begin_reg_cond.comp_type == CompareRegisterValueType_OtherRegister) { switch (cur_opcode.begin_reg_cond.bit_width) { case 1: cond_value = static_cast<u8>(m_registers[cur_opcode.begin_reg_cond.other_reg_index] & 0xFFul); break; case 2: cond_value = static_cast<u16>(m_registers[cur_opcode.begin_reg_cond.other_reg_index] & 0xFFFFul); break; case 4: cond_value = static_cast<u32>(m_registers[cur_opcode.begin_reg_cond.other_reg_index] & 0xFFFFFFFFul); break; case 8: cond_value = static_cast<u64>(m_registers[cur_opcode.begin_reg_cond.other_reg_index] & 0xFFFFFFFFFFFFFFFFul); break; } } else { u64 cond_address = 0; switch (cur_opcode.begin_reg_cond.comp_type) { case CompareRegisterValueType_MemoryRelAddr: cond_address = GetCheatProcessAddress(metadata, cur_opcode.begin_reg_cond.mem_type, cur_opcode.begin_reg_cond.rel_address); break; case CompareRegisterValueType_MemoryOfsReg: cond_address = GetCheatProcessAddress(metadata, cur_opcode.begin_reg_cond.mem_type, m_registers[cur_opcode.begin_reg_cond.ofs_reg_index]); break; case CompareRegisterValueType_RegisterRelAddr: cond_address = m_registers[cur_opcode.begin_reg_cond.addr_reg_index] + cur_opcode.begin_reg_cond.rel_address; break; case CompareRegisterValueType_RegisterOfsReg: cond_address = m_registers[cur_opcode.begin_reg_cond.addr_reg_index] + m_registers[cur_opcode.begin_reg_cond.ofs_reg_index]; break; default: break; } switch (cur_opcode.begin_reg_cond.bit_width) { case 1: case 2: case 4: case 8: dmnt::cheat::impl::ReadCheatProcessMemoryUnsafe(cond_address, std::addressof(cond_value), cur_opcode.begin_reg_cond.bit_width); break; } } /* Check against condition. */ bool cond_met = false; switch (cur_opcode.begin_reg_cond.cond_type) { case ConditionalComparisonType_GT: cond_met = src_value > cond_value; break; case ConditionalComparisonType_GE: cond_met = src_value >= cond_value; break; case ConditionalComparisonType_LT: cond_met = src_value < cond_value; break; case ConditionalComparisonType_LE: cond_met = src_value <= cond_value; break; case ConditionalComparisonType_EQ: cond_met = src_value == cond_value; break; case ConditionalComparisonType_NE: cond_met = src_value != cond_value; break; } /* Skip conditional block if condition not met. */ if (!cond_met) { this->SkipConditionalBlock(true); } } break; case CheatVmOpcodeType_SaveRestoreRegister: /* Save or restore a register. */ switch (cur_opcode.save_restore_reg.op_type) { case SaveRestoreRegisterOpType_ClearRegs: m_registers[cur_opcode.save_restore_reg.dst_index] = 0ul; break; case SaveRestoreRegisterOpType_ClearSaved: m_saved_values[cur_opcode.save_restore_reg.dst_index] = 0ul; break; case SaveRestoreRegisterOpType_Save: m_saved_values[cur_opcode.save_restore_reg.dst_index] = m_registers[cur_opcode.save_restore_reg.src_index]; break; case SaveRestoreRegisterOpType_Restore: default: m_registers[cur_opcode.save_restore_reg.dst_index] = m_saved_values[cur_opcode.save_restore_reg.src_index]; break; } break; case CheatVmOpcodeType_SaveRestoreRegisterMask: /* Save or restore register mask. */ u64 *src; u64 *dst; switch (cur_opcode.save_restore_regmask.op_type) { case SaveRestoreRegisterOpType_ClearSaved: case SaveRestoreRegisterOpType_Save: src = m_registers; dst = m_saved_values; break; case SaveRestoreRegisterOpType_ClearRegs: case SaveRestoreRegisterOpType_Restore: default: src = m_saved_values; dst = m_registers; break; } for (size_t i = 0; i < NumRegisters; i++) { if (cur_opcode.save_restore_regmask.should_operate[i]) { switch (cur_opcode.save_restore_regmask.op_type) { case SaveRestoreRegisterOpType_ClearSaved: case SaveRestoreRegisterOpType_ClearRegs: dst[i] = 0ul; break; case SaveRestoreRegisterOpType_Save: case SaveRestoreRegisterOpType_Restore: default: dst[i] = src[i]; break; } } } break; case CheatVmOpcodeType_ReadWriteStaticRegister: if (cur_opcode.rw_static_reg.static_idx < NumReadableStaticRegisters) { /* Load a register with a static register. */ m_registers[cur_opcode.rw_static_reg.idx] = m_static_registers[cur_opcode.rw_static_reg.static_idx]; } else { /* Store a register to a static register. */ m_static_registers[cur_opcode.rw_static_reg.static_idx] = m_registers[cur_opcode.rw_static_reg.idx]; } break; case CheatVmOpcodeType_PauseProcess: dmnt::cheat::impl::PauseCheatProcessUnsafe(); break; case CheatVmOpcodeType_ResumeProcess: dmnt::cheat::impl::ResumeCheatProcessUnsafe(); break; case CheatVmOpcodeType_DebugLog: { /* Read value from memory. */ u64 log_value = 0; if (cur_opcode.debug_log.val_type == DebugLogValueType_RegisterValue) { switch (cur_opcode.debug_log.bit_width) { case 1: log_value = static_cast<u8>(m_registers[cur_opcode.debug_log.val_reg_index] & 0xFFul); break; case 2: log_value = static_cast<u16>(m_registers[cur_opcode.debug_log.val_reg_index] & 0xFFFFul); break; case 4: log_value = static_cast<u32>(m_registers[cur_opcode.debug_log.val_reg_index] & 0xFFFFFFFFul); break; case 8: log_value = static_cast<u64>(m_registers[cur_opcode.debug_log.val_reg_index] & 0xFFFFFFFFFFFFFFFFul); break; } } else { u64 val_address = 0; switch (cur_opcode.debug_log.val_type) { case DebugLogValueType_MemoryRelAddr: val_address = GetCheatProcessAddress(metadata, cur_opcode.debug_log.mem_type, cur_opcode.debug_log.rel_address); break; case DebugLogValueType_MemoryOfsReg: val_address = GetCheatProcessAddress(metadata, cur_opcode.debug_log.mem_type, m_registers[cur_opcode.debug_log.ofs_reg_index]); break; case DebugLogValueType_RegisterRelAddr: val_address = m_registers[cur_opcode.debug_log.addr_reg_index] + cur_opcode.debug_log.rel_address; break; case DebugLogValueType_RegisterOfsReg: val_address = m_registers[cur_opcode.debug_log.addr_reg_index] + m_registers[cur_opcode.debug_log.ofs_reg_index]; break; default: break; } switch (cur_opcode.debug_log.bit_width) { case 1: case 2: case 4: case 8: dmnt::cheat::impl::ReadCheatProcessMemoryUnsafe(val_address, std::addressof(log_value), cur_opcode.debug_log.bit_width); break; } } /* Log value. */ this->DebugLog(cur_opcode.debug_log.log_id, log_value); } break; default: /* By default, we do a no-op. */ break; } } } }
71,550
C++
.cpp
1,253
35.584198
204
0.479734
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,135
dmnt_cheat_api.cpp
Atmosphere-NX_Atmosphere/stratosphere/dmnt/source/cheat/impl/dmnt_cheat_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 "dmnt_cheat_api.hpp" #include "dmnt_cheat_vm.hpp" #include "dmnt_cheat_debug_events_manager.hpp" namespace ams::dmnt::cheat::impl { namespace { /* Helper definitions. */ constexpr size_t MaxCheatCount = 0x80; constexpr size_t MaxFrozenAddressCount = 0x80; class FrozenAddressMapEntry : public util::IntrusiveRedBlackTreeBaseNode<FrozenAddressMapEntry> { public: using RedBlackKeyType = u64; private: u64 m_address; FrozenAddressValue m_value; public: FrozenAddressMapEntry(u64 address, FrozenAddressValue value) : m_address(address), m_value(value) { /* ... */ } constexpr u64 GetAddress() const { return m_address; } constexpr const FrozenAddressValue &GetValue() const { return m_value; } constexpr FrozenAddressValue &GetValue() { return m_value; } static constexpr ALWAYS_INLINE int Compare(const RedBlackKeyType &lval, const FrozenAddressMapEntry &rhs) { const auto rval = rhs.GetAddress(); if (lval < rval) { return -1; } else if (lval == rval) { return 0; } else { return 1; } } static constexpr ALWAYS_INLINE int Compare(const FrozenAddressMapEntry &lhs, const FrozenAddressMapEntry &rhs) { return Compare(lhs.GetAddress(), rhs); } }; constinit os::SdkMutex g_text_file_buffer_lock; constinit char g_text_file_buffer[64_KB]; constinit u8 g_frozen_address_map_memory[sizeof(FrozenAddressMapEntry) * MaxFrozenAddressCount]; constinit lmem::HeapHandle g_frozen_address_map_heap; FrozenAddressMapEntry *AllocateFrozenAddress(u64 address, FrozenAddressValue value) { FrozenAddressMapEntry *entry = static_cast<FrozenAddressMapEntry *>(lmem::AllocateFromUnitHeap(g_frozen_address_map_heap)); if (entry != nullptr) { std::construct_at(entry, address, value); } return entry; } void DeallocateFrozenAddress(FrozenAddressMapEntry *entry) { std::destroy_at(entry); lmem::FreeToUnitHeap(g_frozen_address_map_heap, entry); } using FrozenAddressMap = typename util::IntrusiveRedBlackTreeBaseTraits<FrozenAddressMapEntry>::TreeType<FrozenAddressMapEntry>; /* Manager class. */ class CheatProcessManager { private: static constexpr size_t ThreadStackSize = 0x4000; private: os::SdkMutex m_cheat_lock; os::Event m_unsafe_break_event; os::Event m_debug_events_event; /* Autoclear. */ os::ThreadType m_detect_thread, m_debug_events_thread; os::SystemEvent m_cheat_process_event; os::NativeHandle m_cheat_process_debug_handle = os::InvalidNativeHandle; CheatProcessMetadata m_cheat_process_metadata = {}; os::ThreadType m_vm_thread; bool m_broken_unsafe = false; bool m_needs_reload_vm = false; CheatVirtualMachine m_cheat_vm; bool m_enable_cheats_by_default = true; bool m_always_save_cheat_toggles = false; bool m_should_save_cheat_toggles = false; CheatEntry m_cheat_entries[MaxCheatCount] = {}; FrozenAddressMap m_frozen_addresses_map = {}; alignas(os::MemoryPageSize) u8 m_detect_thread_stack[ThreadStackSize] = {}; alignas(os::MemoryPageSize) u8 m_debug_events_thread_stack[ThreadStackSize] = {}; alignas(os::MemoryPageSize) u8 m_vm_thread_stack[ThreadStackSize] = {}; private: static void DetectLaunchThread(void *_this); static void VirtualMachineThread(void *_this); static void DebugEventsThread(void *_this); Result AttachToApplicationProcess(bool on_process_launch); bool ParseCheats(const char *s, size_t len); bool LoadCheats(const ncm::ProgramId program_id, const u8 *module_id); bool ParseCheatToggles(const char *s, size_t len); bool LoadCheatToggles(const ncm::ProgramId program_id); void SaveCheatToggles(const ncm::ProgramId program_id); bool GetNeedsReloadVm() const { return m_needs_reload_vm; } void SetNeedsReloadVm(bool reload) { m_needs_reload_vm = reload; } void ResetCheatEntry(size_t i) { if (i < MaxCheatCount) { std::memset(m_cheat_entries + i, 0, sizeof(m_cheat_entries[i])); m_cheat_entries[i].cheat_id = i; this->SetNeedsReloadVm(true); } } void ResetAllCheatEntries() { for (size_t i = 0; i < MaxCheatCount; i++) { this->ResetCheatEntry(i); } m_cheat_vm.ResetStaticRegisters(); } CheatEntry *GetCheatEntryById(size_t i) { if (i < MaxCheatCount) { return m_cheat_entries + i; } return nullptr; } CheatEntry *GetCheatEntryByReadableName(const char *readable_name) { /* Check all non-master cheats for match. */ for (size_t i = 1; i < MaxCheatCount; i++) { if (std::strncmp(m_cheat_entries[i].definition.readable_name, readable_name, sizeof(m_cheat_entries[i].definition.readable_name)) == 0) { return m_cheat_entries + i; } } return nullptr; } CheatEntry *GetFreeCheatEntry() { /* Check all non-master cheats for availability. */ for (size_t i = 1; i < MaxCheatCount; i++) { if (m_cheat_entries[i].definition.num_opcodes == 0) { return m_cheat_entries + i; } } return nullptr; } void CloseActiveCheatProcess() { if (m_cheat_process_debug_handle != os::InvalidNativeHandle) { /* We don't need to do any unsafe brekaing. */ m_broken_unsafe = false; m_unsafe_break_event.Signal(); /* Knock out the debug events thread. */ { std::scoped_lock lk(util::GetReference(m_debug_events_thread.cs_thread)); R_ABORT_UNLESS(svc::CancelSynchronization(m_debug_events_thread.thread_impl->handle)); } /* Close resources. */ R_ABORT_UNLESS(svc::CloseHandle(m_cheat_process_debug_handle)); m_cheat_process_debug_handle = os::InvalidNativeHandle; /* Save cheat toggles. */ if (m_always_save_cheat_toggles || m_should_save_cheat_toggles) { this->SaveCheatToggles(m_cheat_process_metadata.program_id); m_should_save_cheat_toggles = false; } /* Clear metadata. */ static_assert(util::is_pod<decltype(m_cheat_process_metadata)>::value, "CheatProcessMetadata definition!"); std::memset(std::addressof(m_cheat_process_metadata), 0, sizeof(m_cheat_process_metadata)); /* Clear cheat list. */ this->ResetAllCheatEntries(); /* Clear frozen addresses. */ { auto it = m_frozen_addresses_map.begin(); while (it != m_frozen_addresses_map.end()) { FrozenAddressMapEntry *entry = std::addressof(*it); it = m_frozen_addresses_map.erase(it); DeallocateFrozenAddress(entry); } } /* Signal to our fans. */ m_cheat_process_event.Signal(); } } bool HasActiveCheatProcess() { /* Note: This function *MUST* be called only with the cheat lock held. */ os::ProcessId pid; bool has_cheat_process = m_cheat_process_debug_handle != os::InvalidNativeHandle; has_cheat_process &= R_SUCCEEDED(os::GetProcessId(std::addressof(pid), m_cheat_process_debug_handle)); has_cheat_process &= R_SUCCEEDED(pm::dmnt::GetApplicationProcessId(std::addressof(pid))); has_cheat_process &= (pid == m_cheat_process_metadata.process_id); if (!has_cheat_process) { this->CloseActiveCheatProcess(); } return has_cheat_process; } Result EnsureCheatProcess() { R_UNLESS(this->HasActiveCheatProcess(), dmnt::cheat::ResultCheatNotAttached()); R_SUCCEED(); } os::NativeHandle GetCheatProcessHandle() const { return m_cheat_process_debug_handle; } os::NativeHandle HookToCreateApplicationProcess() const { os::NativeHandle h; R_ABORT_UNLESS(pm::dmnt::HookToCreateApplicationProcess(std::addressof(h))); return h; } void StartProcess(os::ProcessId process_id) const { R_ABORT_UNLESS(pm::dmnt::StartProcess(process_id)); } public: CheatProcessManager() : m_cheat_lock(), m_unsafe_break_event(os::EventClearMode_ManualClear), m_debug_events_event(os::EventClearMode_AutoClear), m_cheat_process_event(os::EventClearMode_AutoClear, true) { /* Learn whether we should enable cheats by default. */ { u8 en = 0; if (settings::fwdbg::GetSettingsItemValue(std::addressof(en), sizeof(en), "atmosphere", "dmnt_cheats_enabled_by_default") == sizeof(en)) { m_enable_cheats_by_default = (en != 0); } en = 0; if (settings::fwdbg::GetSettingsItemValue( std::addressof(en), sizeof(en), "atmosphere", "dmnt_always_save_cheat_toggles") == sizeof(en)) { m_always_save_cheat_toggles = (en != 0); } } /* Spawn application detection thread, spawn cheat vm thread. */ R_ABORT_UNLESS(os::CreateThread(std::addressof(m_detect_thread), DetectLaunchThread, this, m_detect_thread_stack, ThreadStackSize, AMS_GET_SYSTEM_THREAD_PRIORITY(dmnt, CheatDetect))); os::SetThreadNamePointer(std::addressof(m_detect_thread), AMS_GET_SYSTEM_THREAD_NAME(dmnt, CheatDetect)); R_ABORT_UNLESS(os::CreateThread(std::addressof(m_vm_thread), VirtualMachineThread, this, m_vm_thread_stack, ThreadStackSize, AMS_GET_SYSTEM_THREAD_PRIORITY(dmnt, CheatVirtualMachine))); os::SetThreadNamePointer(std::addressof(m_vm_thread), AMS_GET_SYSTEM_THREAD_NAME(dmnt, CheatVirtualMachine)); R_ABORT_UNLESS(os::CreateThread(std::addressof(m_debug_events_thread), DebugEventsThread, this, m_debug_events_thread_stack, ThreadStackSize, AMS_GET_SYSTEM_THREAD_PRIORITY(dmnt, CheatDebugEvents))); os::SetThreadNamePointer(std::addressof(m_debug_events_thread), AMS_GET_SYSTEM_THREAD_NAME(dmnt, CheatDebugEvents)); /* Start threads. */ os::StartThread(std::addressof(m_detect_thread)); os::StartThread(std::addressof(m_vm_thread)); os::StartThread(std::addressof(m_debug_events_thread)); } bool GetHasActiveCheatProcess() { std::scoped_lock lk(m_cheat_lock); return this->HasActiveCheatProcess(); } os::NativeHandle GetCheatProcessEventHandle() const { return m_cheat_process_event.GetReadableHandle(); } Result GetCheatProcessMetadata(CheatProcessMetadata *out) { std::scoped_lock lk(m_cheat_lock); R_TRY(this->EnsureCheatProcess()); std::memcpy(out, std::addressof(m_cheat_process_metadata), sizeof(*out)); R_SUCCEED(); } Result ForceOpenCheatProcess() { R_RETURN(this->AttachToApplicationProcess(false)); } Result ForceCloseCheatProcess() { this->CloseActiveCheatProcess(); R_SUCCEED(); } Result ReadCheatProcessMemoryUnsafe(u64 proc_addr, void *out_data, size_t size) { R_RETURN(svc::ReadDebugProcessMemory(reinterpret_cast<uintptr_t>(out_data), this->GetCheatProcessHandle(), proc_addr, size)); } Result WriteCheatProcessMemoryUnsafe(u64 proc_addr, const void *data, size_t size) { R_TRY(svc::WriteDebugProcessMemory(this->GetCheatProcessHandle(), reinterpret_cast<uintptr_t>(data), proc_addr, size)); for (auto &entry : m_frozen_addresses_map) { /* Get address/value. */ const u64 address = entry.GetAddress(); auto &value = entry.GetValue(); /* Map is ordered, so break when we can. */ if (address >= proc_addr + size) { break; } /* Check if we need to write. */ if (proc_addr <= address && address < proc_addr + size) { const size_t offset = (address - proc_addr); const size_t copy_size = std::min(sizeof(value.value), size - offset); std::memcpy(std::addressof(value.value), reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(data) + offset), copy_size); } } R_SUCCEED(); } Result PauseCheatProcessUnsafe() { m_broken_unsafe = true; m_unsafe_break_event.Clear(); R_RETURN(svc::BreakDebugProcess(this->GetCheatProcessHandle())); } Result ResumeCheatProcessUnsafe() { m_broken_unsafe = false; m_unsafe_break_event.Signal(); dmnt::cheat::impl::ContinueCheatProcess(this->GetCheatProcessHandle()); R_SUCCEED(); } Result GetCheatProcessMappingCount(u64 *out_count) { std::scoped_lock lk(m_cheat_lock); R_TRY(this->EnsureCheatProcess()); svc::MemoryInfo mem_info; svc::PageInfo page_info; u64 address = 0, count = 0; do { if (R_FAILED(svc::QueryDebugProcessMemory(std::addressof(mem_info), std::addressof(page_info), this->GetCheatProcessHandle(), address))) { break; } if (mem_info.permission != svc::MemoryPermission_None) { count++; } address = mem_info.base_address + mem_info.size; } while (address != 0); *out_count = count; R_SUCCEED(); } Result GetCheatProcessMappings(svc::MemoryInfo *mappings, size_t max_count, u64 *out_count, u64 offset) { std::scoped_lock lk(m_cheat_lock); R_TRY(this->EnsureCheatProcess()); svc::MemoryInfo mem_info; svc::PageInfo page_info; u64 address = 0, total_count = 0, written_count = 0; do { if (R_FAILED(svc::QueryDebugProcessMemory(std::addressof(mem_info), std::addressof(page_info), this->GetCheatProcessHandle(), address))) { break; } if (mem_info.permission != svc::MemoryPermission_None) { if (offset <= total_count && written_count < max_count) { mappings[written_count++] = mem_info; } total_count++; } address = mem_info.base_address + mem_info.size; } while (address != 0 && written_count < max_count); *out_count = written_count; R_SUCCEED(); } Result ReadCheatProcessMemory(u64 proc_addr, void *out_data, size_t size) { std::scoped_lock lk(m_cheat_lock); R_TRY(this->EnsureCheatProcess()); R_RETURN(this->ReadCheatProcessMemoryUnsafe(proc_addr, out_data, size)); } Result WriteCheatProcessMemory(u64 proc_addr, const void *data, size_t size) { std::scoped_lock lk(m_cheat_lock); R_TRY(this->EnsureCheatProcess()); R_RETURN(this->WriteCheatProcessMemoryUnsafe(proc_addr, data, size)); } Result QueryCheatProcessMemory(svc::MemoryInfo *mapping, u64 address) { std::scoped_lock lk(m_cheat_lock); R_TRY(this->EnsureCheatProcess()); svc::PageInfo page_info; R_RETURN(svc::QueryDebugProcessMemory(mapping, std::addressof(page_info), this->GetCheatProcessHandle(), address)); } Result PauseCheatProcess() { std::scoped_lock lk(m_cheat_lock); R_TRY(this->EnsureCheatProcess()); R_RETURN(this->PauseCheatProcessUnsafe()); } Result ResumeCheatProcess() { std::scoped_lock lk(m_cheat_lock); R_TRY(this->EnsureCheatProcess()); R_RETURN(this->ResumeCheatProcessUnsafe()); } Result GetCheatCount(u64 *out_count) { std::scoped_lock lk(m_cheat_lock); R_TRY(this->EnsureCheatProcess()); size_t count = 0; for (size_t i = 0; i < MaxCheatCount; i++) { if (m_cheat_entries[i].definition.num_opcodes) { count++; } } *out_count = count; R_SUCCEED(); } Result GetCheats(CheatEntry *out_cheats, size_t max_count, u64 *out_count, u64 offset) { std::scoped_lock lk(m_cheat_lock); R_TRY(this->EnsureCheatProcess()); size_t count = 0, total_count = 0; for (size_t i = 0; i < MaxCheatCount && count < max_count; i++) { if (m_cheat_entries[i].definition.num_opcodes) { total_count++; if (total_count > offset) { out_cheats[count++] = m_cheat_entries[i]; } } } *out_count = count; R_SUCCEED(); } Result GetCheatById(CheatEntry *out_cheat, u32 cheat_id) { std::scoped_lock lk(m_cheat_lock); R_TRY(this->EnsureCheatProcess()); const CheatEntry *entry = this->GetCheatEntryById(cheat_id); R_UNLESS(entry != nullptr, dmnt::cheat::ResultCheatUnknownId()); R_UNLESS(entry->definition.num_opcodes != 0, dmnt::cheat::ResultCheatUnknownId()); *out_cheat = *entry; R_SUCCEED(); } Result ToggleCheat(u32 cheat_id) { std::scoped_lock lk(m_cheat_lock); R_TRY(this->EnsureCheatProcess()); CheatEntry *entry = this->GetCheatEntryById(cheat_id); R_UNLESS(entry != nullptr, dmnt::cheat::ResultCheatUnknownId()); R_UNLESS(entry->definition.num_opcodes != 0, dmnt::cheat::ResultCheatUnknownId()); R_UNLESS(cheat_id != 0, dmnt::cheat::ResultCheatCannotDisable()); entry->enabled = !entry->enabled; /* Trigger a VM reload. */ this->SetNeedsReloadVm(true); R_SUCCEED(); } Result AddCheat(u32 *out_id, const CheatDefinition &def, bool enabled) { std::scoped_lock lk(m_cheat_lock); R_TRY(this->EnsureCheatProcess()); R_UNLESS(def.num_opcodes != 0, dmnt::cheat::ResultCheatInvalid()); R_UNLESS(def.num_opcodes <= util::size(def.opcodes), dmnt::cheat::ResultCheatInvalid()); CheatEntry *new_entry = this->GetFreeCheatEntry(); R_UNLESS(new_entry != nullptr, dmnt::cheat::ResultCheatOutOfResource()); new_entry->enabled = enabled; new_entry->definition = def; /* Trigger a VM reload. */ this->SetNeedsReloadVm(true); /* Set output id. */ *out_id = new_entry->cheat_id; R_SUCCEED(); } Result RemoveCheat(u32 cheat_id) { std::scoped_lock lk(m_cheat_lock); R_TRY(this->EnsureCheatProcess()); R_UNLESS(cheat_id < MaxCheatCount, dmnt::cheat::ResultCheatUnknownId()); this->ResetCheatEntry(cheat_id); /* Trigger a VM reload. */ this->SetNeedsReloadVm(true); R_SUCCEED(); } Result SetMasterCheat(const CheatDefinition &def) { std::scoped_lock lk(m_cheat_lock); R_TRY(this->EnsureCheatProcess()); R_UNLESS(def.num_opcodes != 0, dmnt::cheat::ResultCheatInvalid()); R_UNLESS(def.num_opcodes <= util::size(def.opcodes), dmnt::cheat::ResultCheatInvalid()); CheatEntry *master_entry = m_cheat_entries + 0; master_entry->enabled = true; master_entry->definition = def; /* Trigger a VM reload. */ this->SetNeedsReloadVm(true); R_SUCCEED(); } Result ReadStaticRegister(u64 *out, size_t which) { std::scoped_lock lk(m_cheat_lock); R_TRY(this->EnsureCheatProcess()); R_UNLESS(which < CheatVirtualMachine::NumStaticRegisters, dmnt::cheat::ResultCheatInvalid()); *out = m_cheat_vm.GetStaticRegister(which); R_SUCCEED(); } Result WriteStaticRegister(size_t which, u64 value) { std::scoped_lock lk(m_cheat_lock); R_TRY(this->EnsureCheatProcess()); R_UNLESS(which < CheatVirtualMachine::NumStaticRegisters, dmnt::cheat::ResultCheatInvalid()); m_cheat_vm.SetStaticRegister(which, value); R_SUCCEED(); } Result ResetStaticRegisters() { std::scoped_lock lk(m_cheat_lock); R_TRY(this->EnsureCheatProcess()); m_cheat_vm.ResetStaticRegisters(); R_SUCCEED(); } Result GetFrozenAddressCount(u64 *out_count) { std::scoped_lock lk(m_cheat_lock); R_TRY(this->EnsureCheatProcess()); *out_count = std::distance(m_frozen_addresses_map.begin(), m_frozen_addresses_map.end()); R_SUCCEED(); } Result GetFrozenAddresses(FrozenAddressEntry *frz_addrs, size_t max_count, u64 *out_count, u64 offset) { std::scoped_lock lk(m_cheat_lock); R_TRY(this->EnsureCheatProcess()); u64 total_count = 0, written_count = 0; for (const auto &entry : m_frozen_addresses_map) { if (written_count >= max_count) { break; } if (offset <= total_count) { frz_addrs[written_count].address = entry.GetAddress(); frz_addrs[written_count].value = entry.GetValue(); written_count++; } total_count++; } *out_count = written_count; R_SUCCEED(); } Result GetFrozenAddress(FrozenAddressEntry *frz_addr, u64 address) { std::scoped_lock lk(m_cheat_lock); R_TRY(this->EnsureCheatProcess()); const auto it = m_frozen_addresses_map.find_key(address); R_UNLESS(it != m_frozen_addresses_map.end(), dmnt::cheat::ResultFrozenAddressNotFound()); frz_addr->address = it->GetAddress(); frz_addr->value = it->GetValue(); R_SUCCEED(); } Result EnableFrozenAddress(u64 *out_value, u64 address, u64 width) { std::scoped_lock lk(m_cheat_lock); R_TRY(this->EnsureCheatProcess()); const auto it = m_frozen_addresses_map.find_key(address); R_UNLESS(it == m_frozen_addresses_map.end(), dmnt::cheat::ResultFrozenAddressAlreadyExists()); FrozenAddressValue value = {}; value.width = width; R_TRY(this->ReadCheatProcessMemoryUnsafe(address, std::addressof(value.value), width)); FrozenAddressMapEntry *entry = AllocateFrozenAddress(address, value); R_UNLESS(entry != nullptr, dmnt::cheat::ResultFrozenAddressOutOfResource()); m_frozen_addresses_map.insert(*entry); *out_value = value.value; R_SUCCEED(); } Result DisableFrozenAddress(u64 address) { std::scoped_lock lk(m_cheat_lock); R_TRY(this->EnsureCheatProcess()); const auto it = m_frozen_addresses_map.find_key(address); R_UNLESS(it != m_frozen_addresses_map.end(), dmnt::cheat::ResultFrozenAddressNotFound()); FrozenAddressMapEntry *entry = std::addressof(*it); m_frozen_addresses_map.erase(it); DeallocateFrozenAddress(entry); R_SUCCEED(); } }; void CheatProcessManager::DetectLaunchThread(void *_this) { CheatProcessManager *manager = reinterpret_cast<CheatProcessManager *>(_this); Event hook; while (true) { eventLoadRemote(std::addressof(hook), manager->HookToCreateApplicationProcess(), true); if (R_SUCCEEDED(eventWait(std::addressof(hook), std::numeric_limits<u64>::max()))) { manager->AttachToApplicationProcess(true); } eventClose(std::addressof(hook)); } } void CheatProcessManager::DebugEventsThread(void *_this) { CheatProcessManager *manager = reinterpret_cast<CheatProcessManager *>(_this); while (true) { /* Atomically wait (and clear) signal for new process. */ manager->m_debug_events_event.Wait(); while (true) { os::NativeHandle cheat_process_handle = manager->GetCheatProcessHandle(); s32 dummy; while (cheat_process_handle != os::InvalidNativeHandle && R_SUCCEEDED(svc::WaitSynchronization(std::addressof(dummy), std::addressof(cheat_process_handle), 1, std::numeric_limits<u64>::max()))) { manager->m_cheat_lock.Lock(); ON_SCOPE_EXIT { manager->m_cheat_lock.Unlock(); }; { ON_SCOPE_EXIT { cheat_process_handle = manager->GetCheatProcessHandle(); }; /* If we did an unsafe break, wait until we're not broken. */ if (manager->m_broken_unsafe) { manager->m_cheat_lock.Unlock(); manager->m_unsafe_break_event.Wait(); manager->m_cheat_lock.Lock(); if (manager->GetCheatProcessHandle() != os::InvalidNativeHandle) { continue; } else { break; } } /* Handle any pending debug events. */ if (manager->HasActiveCheatProcess()) { R_TRY_CATCH(dmnt::cheat::impl::ContinueCheatProcess(manager->GetCheatProcessHandle())) { R_CATCH(svc::ResultProcessTerminated) { manager->CloseActiveCheatProcess(); break; } } R_END_TRY_CATCH_WITH_ABORT_UNLESS; } } } /* WaitSynchronization failed. This means someone canceled our synchronization, possibly us. */ /* Let's check if we should quit! */ std::scoped_lock lk(manager->m_cheat_lock); if (!manager->HasActiveCheatProcess()) { break; } } } } void CheatProcessManager::VirtualMachineThread(void *_this) { CheatProcessManager *manager = reinterpret_cast<CheatProcessManager *>(_this); while (true) { /* Apply cheats. */ { std::scoped_lock lk(manager->m_cheat_lock); if (manager->HasActiveCheatProcess()) { /* Execute VM. */ if (!manager->GetNeedsReloadVm() || manager->m_cheat_vm.LoadProgram(manager->m_cheat_entries, util::size(manager->m_cheat_entries))) { manager->SetNeedsReloadVm(false); /* Execute program only if it has opcodes. */ if (manager->m_cheat_vm.GetProgramSize()) { manager->m_cheat_vm.Execute(std::addressof(manager->m_cheat_process_metadata)); } } /* Apply frozen addresses. */ for (const auto &entry : manager->m_frozen_addresses_map) { const auto address = entry.GetAddress(); const auto &value = entry.GetValue(); /* Use Write SVC directly, to avoid the usual frozen address update logic. */ svc::WriteDebugProcessMemory(manager->GetCheatProcessHandle(), reinterpret_cast<uintptr_t>(std::addressof(value.value)), address, value.width); } } } /* Sleep until next potential execution. */ constexpr s64 TimesPerSecond = 12; constexpr s64 DelayNanoSeconds = TimeSpan::FromSeconds(1).GetNanoSeconds() / TimesPerSecond; constexpr TimeSpan Delay = TimeSpan::FromNanoSeconds(DelayNanoSeconds); os::SleepThread(Delay); } } #define R_ABORT_UNLESS_IF_NEW_PROCESS(res) \ if (on_process_launch) { \ R_ABORT_UNLESS(res); \ } else { \ R_TRY(res); \ } Result CheatProcessManager::AttachToApplicationProcess(bool on_process_launch) { std::scoped_lock lk(m_cheat_lock); /* Close the active process, if needed. */ { if (this->HasActiveCheatProcess()) { /* When forcing attach, we're done. */ R_SUCCEED_IF(!on_process_launch); } /* Detach from the current process, if it's open. */ this->CloseActiveCheatProcess(); } /* Get the application process's ID. */ R_ABORT_UNLESS_IF_NEW_PROCESS(pm::dmnt::GetApplicationProcessId(std::addressof(m_cheat_process_metadata.process_id))); auto proc_guard = SCOPE_GUARD { if (on_process_launch) { this->StartProcess(m_cheat_process_metadata.process_id); } m_cheat_process_metadata.process_id = os::ProcessId{}; }; /* Get process handle, use it to learn memory extents. */ { os::NativeHandle proc_h = os::InvalidNativeHandle; ncm::ProgramLocation loc = {}; cfg::OverrideStatus status = {}; R_ABORT_UNLESS_IF_NEW_PROCESS(pm::dmnt::AtmosphereGetProcessInfo(std::addressof(proc_h), std::addressof(loc), std::addressof(status), m_cheat_process_metadata.process_id)); ON_SCOPE_EXIT { os::CloseNativeHandle(proc_h); }; m_cheat_process_metadata.program_id = loc.program_id; R_ABORT_UNLESS(svc::GetInfo(std::addressof(m_cheat_process_metadata.heap_extents.base), svc::InfoType_HeapRegionAddress, proc_h, 0)); R_ABORT_UNLESS(svc::GetInfo(std::addressof(m_cheat_process_metadata.heap_extents.size), svc::InfoType_HeapRegionSize, proc_h, 0)); R_ABORT_UNLESS(svc::GetInfo(std::addressof(m_cheat_process_metadata.alias_extents.base), svc::InfoType_AliasRegionAddress, proc_h, 0)); R_ABORT_UNLESS(svc::GetInfo(std::addressof(m_cheat_process_metadata.alias_extents.size), svc::InfoType_AliasRegionSize, proc_h, 0)); R_ABORT_UNLESS(svc::GetInfo(std::addressof(m_cheat_process_metadata.aslr_extents.base), svc::InfoType_AslrRegionAddress, proc_h, 0)); R_ABORT_UNLESS(svc::GetInfo(std::addressof(m_cheat_process_metadata.aslr_extents.size), svc::InfoType_AslrRegionSize, proc_h, 0)); /* If new process launch, we may not want to actually attach. */ if (on_process_launch) { R_UNLESS(status.IsCheatEnabled(), dmnt::cheat::ResultCheatNotAttached()); } } /* Get module information from loader. */ { ldr::ModuleInfo proc_modules[2]; s32 num_modules; /* TODO: ldr::dmnt:: */ R_ABORT_UNLESS_IF_NEW_PROCESS(ldrDmntGetProcessModuleInfo(static_cast<u64>(m_cheat_process_metadata.process_id), reinterpret_cast<LoaderModuleInfo *>(proc_modules), util::size(proc_modules), std::addressof(num_modules))); /* All applications must have two modules. */ /* Only accept one (which means we're attaching to HBL) */ /* if we aren't auto-attaching. */ const ldr::ModuleInfo *proc_module = nullptr; if (num_modules == 2) { proc_module = std::addressof(proc_modules[1]); } else if (num_modules == 1 && !on_process_launch) { proc_module = std::addressof(proc_modules[0]); } else { R_THROW(dmnt::cheat::ResultCheatNotAttached()); } m_cheat_process_metadata.main_nso_extents.base = proc_module->address; m_cheat_process_metadata.main_nso_extents.size = proc_module->size; std::memcpy(m_cheat_process_metadata.main_nso_module_id, proc_module->module_id, sizeof(m_cheat_process_metadata.main_nso_module_id)); } /* Read cheats off the SD. */ if (!this->LoadCheats(m_cheat_process_metadata.program_id, m_cheat_process_metadata.main_nso_module_id) || !this->LoadCheatToggles(m_cheat_process_metadata.program_id)) { /* If new process launch, require success. */ R_UNLESS(!on_process_launch, dmnt::cheat::ResultCheatNotAttached()); } /* Open a debug handle. */ svc::Handle debug_handle = svc::InvalidHandle; R_ABORT_UNLESS_IF_NEW_PROCESS(svc::DebugActiveProcess(std::addressof(debug_handle), m_cheat_process_metadata.process_id.value)); /* Set our debug handle. */ m_cheat_process_debug_handle = debug_handle; /* Cancel process guard. */ proc_guard.Cancel(); /* Reset broken state. */ m_broken_unsafe = false; m_unsafe_break_event.Signal(); /* If new process, start the process. */ if (on_process_launch) { this->StartProcess(m_cheat_process_metadata.process_id); } /* Signal to the debug events thread. */ m_debug_events_event.Signal(); /* Signal to our fans. */ m_cheat_process_event.Signal(); R_SUCCEED(); } #undef R_ABORT_UNLESS_IF_NEW_PROCESS bool CheatProcessManager::ParseCheats(const char *s, size_t len) { /* Trigger a VM reload. */ this->SetNeedsReloadVm(true); /* Parse the input string. */ size_t i = 0; CheatEntry *cur_entry = nullptr; while (i < len) { if (std::isspace(static_cast<unsigned char>(s[i]))) { /* Just ignore whitespace. */ i++; } else if (s[i] == '[') { /* Parse a readable cheat name. */ cur_entry = this->GetFreeCheatEntry(); if (cur_entry == nullptr) { return false; } /* Extract name bounds. */ size_t j = i + 1; while (s[j] != ']') { j++; if (j >= len) { return false; } } /* s[i+1:j] is cheat name. */ const size_t cheat_name_len = std::min(j - i - 1, sizeof(cur_entry->definition.readable_name)); std::memcpy(cur_entry->definition.readable_name, s + (i + 1), cheat_name_len); cur_entry->definition.readable_name[cheat_name_len] = 0; /* Skip onwards. */ i = j + 1; } else if (s[i] == '{') { /* We're parsing a master cheat. */ cur_entry = std::addressof(m_cheat_entries[0]); /* There can only be one master cheat. */ if (cur_entry->definition.num_opcodes > 0) { return false; } /* Extract name bounds */ size_t j = i + 1; while (s[j] != '}') { j++; if (j >= len) { return false; } } /* s[i+1:j] is cheat name. */ const size_t cheat_name_len = std::min(j - i - 1, sizeof(cur_entry->definition.readable_name)); memcpy(cur_entry->definition.readable_name, s + (i + 1), cheat_name_len); cur_entry->definition.readable_name[cheat_name_len] = 0; /* Skip onwards. */ i = j + 1; } else if (std::isxdigit(static_cast<unsigned char>(s[i]))) { /* Make sure that we have a cheat open. */ if (cur_entry == nullptr) { return false; } /* Bounds check the opcode count. */ if (cur_entry->definition.num_opcodes >= util::size(cur_entry->definition.opcodes)) { return false; } /* We're parsing an instruction, so validate it's 8 hex digits. */ for (size_t j = 1; j < 8; j++) { /* Validate 8 hex chars. */ if (i + j >= len || !std::isxdigit(static_cast<unsigned char>(s[i+j]))) { return false; } } /* Parse the new opcode. */ char hex_str[9] = {0}; std::memcpy(hex_str, s + i, 8); cur_entry->definition.opcodes[cur_entry->definition.num_opcodes++] = std::strtoul(hex_str, NULL, 16); /* Skip onwards. */ i += 8; } else { /* Unexpected character encountered. */ return false; } } /* Master cheat can't be disabled. */ if (m_cheat_entries[0].definition.num_opcodes > 0) { m_cheat_entries[0].enabled = true; } /* Enable all entries we parsed. */ for (size_t i = 1; i < MaxCheatCount; i++) { if (m_cheat_entries[i].definition.num_opcodes > 0) { m_cheat_entries[i].enabled = m_enable_cheats_by_default; } } return true; } bool CheatProcessManager::ParseCheatToggles(const char *s, size_t len) { size_t i = 0; char cur_cheat_name[sizeof(CheatEntry::definition.readable_name)]; char toggle[8]; while (i < len) { if (std::isspace(static_cast<unsigned char>(s[i]))) { /* Just ignore whitespace. */ i++; } else if (s[i] == '[') { /* Extract name bounds. */ size_t j = i + 1; while (s[j] != ']') { j++; if (j >= len) { return false; } } /* s[i+1:j] is cheat name. */ const size_t cheat_name_len = std::min(j - i - 1, sizeof(cur_cheat_name)); std::memcpy(cur_cheat_name, s + (i + 1), cheat_name_len); cur_cheat_name[cheat_name_len] = 0; /* Skip onwards. */ i = j + 1; /* Skip whitespace. */ while (std::isspace(static_cast<unsigned char>(s[i]))) { i++; if (i >= len) { return false; } } /* Parse whether to toggle. */ j = i + 1; while (j < len && !std::isspace(static_cast<unsigned char>(s[j]))) { j++; if ((j - i) >= sizeof(toggle)) { return false; } } /* s[i:j] is toggle. */ const size_t toggle_len = (j - i); std::memcpy(toggle, s + i, toggle_len); toggle[toggle_len] = 0; /* Allow specifying toggle for not present cheat. */ CheatEntry *entry = this->GetCheatEntryByReadableName(cur_cheat_name); if (entry != nullptr) { if (strcasecmp(toggle, "1") == 0 || strcasecmp(toggle, "true") == 0 || strcasecmp(toggle, "on") == 0) { entry->enabled = true; } else if (strcasecmp(toggle, "0") == 0 || strcasecmp(toggle, "false") == 0 || strcasecmp(toggle, "off") == 0) { entry->enabled = false; } } /* Skip onwards. */ i = j + 1; } else { /* Unexpected character encountered. */ return false; } } return true; } bool CheatProcessManager::LoadCheats(const ncm::ProgramId program_id, const u8 *module_id) { /* Reset existing entries. */ this->ResetAllCheatEntries(); /* Open the file for program/module_id. */ fs::FileHandle file; { char path[fs::EntryNameLengthMax + 1]; util::SNPrintf(path, sizeof(path), "sdmc:/atmosphere/contents/%016lx/cheats/%02x%02x%02x%02x%02x%02x%02x%02x.txt", program_id.value, module_id[0], module_id[1], module_id[2], module_id[3], module_id[4], module_id[5], module_id[6], module_id[7]); if (R_FAILED(fs::OpenFile(std::addressof(file), path, fs::OpenMode_Read))) { return false; } } ON_SCOPE_EXIT { fs::CloseFile(file); }; /* Get file size. */ s64 file_size; if (R_FAILED(fs::GetFileSize(std::addressof(file_size), file))) { return false; } if (file_size < 0 || file_size >= static_cast<s64>(sizeof(g_text_file_buffer))) { return false; } std::scoped_lock lk(g_text_file_buffer_lock); /* Read cheats into buffer. */ if (R_FAILED(fs::ReadFile(file, 0, g_text_file_buffer, file_size))) { return false; } g_text_file_buffer[file_size] = '\x00'; /* Parse cheat buffer. */ return this->ParseCheats(g_text_file_buffer, std::strlen(g_text_file_buffer)); } bool CheatProcessManager::LoadCheatToggles(const ncm::ProgramId program_id) { /* Unless we successfully parse, don't save toggles on close. */ m_should_save_cheat_toggles = false; /* Open the file for program_id. */ fs::FileHandle file; { char path[fs::EntryNameLengthMax + 1]; util::SNPrintf(path, sizeof(path), "sdmc:/atmosphere/contents/%016lx/cheats/toggles.txt", program_id.value); if (R_FAILED(fs::OpenFile(std::addressof(file), path, fs::OpenMode_Read))) { /* No file presence is allowed. */ return true; } } ON_SCOPE_EXIT { fs::CloseFile(file); }; /* Get file size. */ s64 file_size; if (R_FAILED(fs::GetFileSize(std::addressof(file_size), file))) { return false; } if (file_size < 0 || file_size >= static_cast<s64>(sizeof(g_text_file_buffer))) { return false; } std::scoped_lock lk(g_text_file_buffer_lock); /* Read cheats into buffer. */ if (R_FAILED(fs::ReadFile(file, 0, g_text_file_buffer, file_size))) { return false; } g_text_file_buffer[file_size] = '\x00'; /* Parse toggle buffer. */ m_should_save_cheat_toggles = this->ParseCheatToggles(g_text_file_buffer, std::strlen(g_text_file_buffer)); return m_should_save_cheat_toggles; } void CheatProcessManager::SaveCheatToggles(const ncm::ProgramId program_id) { /* Open the file for program_id. */ fs::FileHandle file; { char path[fs::EntryNameLengthMax + 1]; util::SNPrintf(path, sizeof(path), "sdmc:/atmosphere/contents/%016lx/cheats/toggles.txt", program_id.value); fs::DeleteFile(path); fs::CreateFile(path, 0); if (R_FAILED(fs::OpenFile(std::addressof(file), path, fs::OpenMode_Write | fs::OpenMode_AllowAppend))) { return; } } ON_SCOPE_EXIT { fs::CloseFile(file); }; s64 offset = 0; char buf[0x100]; /* Save all non-master cheats. */ for (size_t i = 1; i < MaxCheatCount; i++) { if (m_cheat_entries[i].definition.num_opcodes != 0) { util::SNPrintf(buf, sizeof(buf), "[%s]\n", m_cheat_entries[i].definition.readable_name); const size_t name_len = std::strlen(buf); if (R_SUCCEEDED(fs::WriteFile(file, offset, buf, name_len, fs::WriteOption::Flush))) { offset += name_len; } const char *entry = m_cheat_entries[i].enabled ? "true\n" : "false\n"; const size_t entry_len = std::strlen(entry); if (R_SUCCEEDED(fs::WriteFile(file, offset, entry, entry_len, fs::WriteOption::Flush))) { offset += entry_len; } } } } /* Manager global. */ util::TypedStorage<CheatProcessManager> g_cheat_process_manager; } void InitializeCheatManager() { /* Initialize the debug events manager (spawning its threads). */ InitializeDebugEventsManager(); /* Initialize the frozen address map heap. */ g_frozen_address_map_heap = lmem::CreateUnitHeap(g_frozen_address_map_memory, sizeof(g_frozen_address_map_memory), sizeof(FrozenAddressMapEntry), lmem::CreateOption_ThreadSafe); /* Create the cheat process manager (spawning its threads). */ util::ConstructAt(g_cheat_process_manager); } bool GetHasActiveCheatProcess() { return GetReference(g_cheat_process_manager).GetHasActiveCheatProcess(); } os::NativeHandle GetCheatProcessEventHandle() { return GetReference(g_cheat_process_manager).GetCheatProcessEventHandle(); } Result GetCheatProcessMetadata(CheatProcessMetadata *out) { R_RETURN(GetReference(g_cheat_process_manager).GetCheatProcessMetadata(out)); } Result ForceOpenCheatProcess() { R_RETURN(GetReference(g_cheat_process_manager).ForceOpenCheatProcess()); } Result PauseCheatProcess() { R_RETURN(GetReference(g_cheat_process_manager).PauseCheatProcess()); } Result ResumeCheatProcess() { R_RETURN(GetReference(g_cheat_process_manager).ResumeCheatProcess()); } Result ForceCloseCheatProcess() { R_RETURN(GetReference(g_cheat_process_manager).ForceCloseCheatProcess()); } Result ReadCheatProcessMemoryUnsafe(u64 process_addr, void *out_data, size_t size) { R_RETURN(GetReference(g_cheat_process_manager).ReadCheatProcessMemoryUnsafe(process_addr, out_data, size)); } Result WriteCheatProcessMemoryUnsafe(u64 process_addr, void *data, size_t size) { R_RETURN(GetReference(g_cheat_process_manager).WriteCheatProcessMemoryUnsafe(process_addr, data, size)); } Result PauseCheatProcessUnsafe() { R_RETURN(GetReference(g_cheat_process_manager).PauseCheatProcessUnsafe()); } Result ResumeCheatProcessUnsafe() { R_RETURN(GetReference(g_cheat_process_manager).ResumeCheatProcessUnsafe()); } Result GetCheatProcessMappingCount(u64 *out_count) { R_RETURN(GetReference(g_cheat_process_manager).GetCheatProcessMappingCount(out_count)); } Result GetCheatProcessMappings(svc::MemoryInfo *mappings, size_t max_count, u64 *out_count, u64 offset) { R_RETURN(GetReference(g_cheat_process_manager).GetCheatProcessMappings(mappings, max_count, out_count, offset)); } Result ReadCheatProcessMemory(u64 proc_addr, void *out_data, size_t size) { R_RETURN(GetReference(g_cheat_process_manager).ReadCheatProcessMemory(proc_addr, out_data, size)); } Result WriteCheatProcessMemory(u64 proc_addr, const void *data, size_t size) { R_RETURN(GetReference(g_cheat_process_manager).WriteCheatProcessMemory(proc_addr, data, size)); } Result QueryCheatProcessMemory(svc::MemoryInfo *mapping, u64 address) { R_RETURN(GetReference(g_cheat_process_manager).QueryCheatProcessMemory(mapping, address)); } Result GetCheatCount(u64 *out_count) { R_RETURN(GetReference(g_cheat_process_manager).GetCheatCount(out_count)); } Result GetCheats(CheatEntry *cheats, size_t max_count, u64 *out_count, u64 offset) { R_RETURN(GetReference(g_cheat_process_manager).GetCheats(cheats, max_count, out_count, offset)); } Result GetCheatById(CheatEntry *out_cheat, u32 cheat_id) { R_RETURN(GetReference(g_cheat_process_manager).GetCheatById(out_cheat, cheat_id)); } Result ToggleCheat(u32 cheat_id) { R_RETURN(GetReference(g_cheat_process_manager).ToggleCheat(cheat_id)); } Result AddCheat(u32 *out_id, const CheatDefinition &def, bool enabled) { R_RETURN(GetReference(g_cheat_process_manager).AddCheat(out_id, def, enabled)); } Result RemoveCheat(u32 cheat_id) { R_RETURN(GetReference(g_cheat_process_manager).RemoveCheat(cheat_id)); } Result SetMasterCheat(const CheatDefinition &def) { R_RETURN(GetReference(g_cheat_process_manager).SetMasterCheat(def)); } Result ReadStaticRegister(u64 *out, size_t which) { R_RETURN(GetReference(g_cheat_process_manager).ReadStaticRegister(out, which)); } Result WriteStaticRegister(size_t which, u64 value) { R_RETURN(GetReference(g_cheat_process_manager).WriteStaticRegister(which, value)); } Result ResetStaticRegisters() { R_RETURN(GetReference(g_cheat_process_manager).ResetStaticRegisters()); } Result GetFrozenAddressCount(u64 *out_count) { R_RETURN(GetReference(g_cheat_process_manager).GetFrozenAddressCount(out_count)); } Result GetFrozenAddresses(FrozenAddressEntry *frz_addrs, size_t max_count, u64 *out_count, u64 offset) { R_RETURN(GetReference(g_cheat_process_manager).GetFrozenAddresses(frz_addrs, max_count, out_count, offset)); } Result GetFrozenAddress(FrozenAddressEntry *frz_addr, u64 address) { R_RETURN(GetReference(g_cheat_process_manager).GetFrozenAddress(frz_addr, address)); } Result EnableFrozenAddress(u64 *out_value, u64 address, u64 width) { R_RETURN(GetReference(g_cheat_process_manager).EnableFrozenAddress(out_value, address, width)); } Result DisableFrozenAddress(u64 address) { R_RETURN(GetReference(g_cheat_process_manager).DisableFrozenAddress(address)); } }
57,455
C++
.cpp
1,037
37.228544
237
0.517226
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,136
dmnt_cheat_debug_events_manager.cpp
Atmosphere-NX_Atmosphere/stratosphere/dmnt/source/cheat/impl/dmnt_cheat_debug_events_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 "dmnt_cheat_debug_events_manager.hpp" /* WORKAROUND: This design prevents a kernel deadlock from occurring on 6.0.0+ */ namespace ams::dmnt::cheat::impl { namespace { class DebugEventsManager { public: static constexpr size_t NumCores = 4; static constexpr size_t ThreadStackSize = os::MemoryPageSize; private: std::array<uintptr_t, NumCores> m_handle_message_queue_buffers; std::array<uintptr_t, NumCores> m_result_message_queue_buffers; std::array<os::MessageQueue, NumCores> m_handle_message_queues; std::array<os::MessageQueue, NumCores> m_result_message_queues; std::array<os::ThreadType, NumCores> m_threads; alignas(os::MemoryPageSize) u8 m_thread_stacks[NumCores][ThreadStackSize]; private: static void PerCoreThreadFunction(void *_this) { /* This thread will wait on the appropriate message queue. */ DebugEventsManager *this_ptr = reinterpret_cast<DebugEventsManager *>(_this); const size_t current_core = svc::GetCurrentProcessorNumber(); while (true) { /* Receive handle. */ os::NativeHandle debug_handle = this_ptr->WaitReceiveHandle(current_core); /* Continue events on the correct core. */ Result result = this_ptr->ContinueDebugEvent(debug_handle); /* Return our result. */ this_ptr->SendContinueResult(current_core, result); } } Result GetTargetCore(size_t *out, const svc::DebugEventInfo &dbg_event, os::NativeHandle debug_handle) { /* If we don't need to continue on a specific core, use the system core. */ size_t target_core = NumCores - 1; /* Retrieve correct core for new thread event. */ if (dbg_event.type == svc::DebugEvent_CreateThread) { u64 out64 = 0; u32 out32 = 0; R_TRY_CATCH(svc::GetDebugThreadParam(&out64, &out32, debug_handle, dbg_event.info.create_thread.thread_id, svc::DebugThreadParam_CurrentCore)) { R_CATCH_RETHROW(svc::ResultProcessTerminated) } R_END_TRY_CATCH_WITH_ABORT_UNLESS; target_core = out32; } /* Set the target core. */ *out = target_core; R_SUCCEED(); } void SendHandle(size_t target_core, os::NativeHandle debug_handle) { m_handle_message_queues[target_core].Send(static_cast<uintptr_t>(debug_handle)); } os::NativeHandle WaitReceiveHandle(size_t core_id) { uintptr_t x = 0; m_handle_message_queues[core_id].Receive(&x); return static_cast<os::NativeHandle>(x); } Result ContinueDebugEvent(os::NativeHandle debug_handle) { if (hos::GetVersion() >= hos::Version_3_0_0) { R_RETURN(svc::ContinueDebugEvent(debug_handle, svc::ContinueFlag_ExceptionHandled | svc::ContinueFlag_ContinueAll, nullptr, 0)); } else { R_RETURN(svc::LegacyContinueDebugEvent(debug_handle, svc::ContinueFlag_ExceptionHandled | svc::ContinueFlag_ContinueAll, 0)); } } void SendContinueResult(size_t target_core, Result result) { m_result_message_queues[target_core].Send(static_cast<uintptr_t>(result.GetValue())); } Result GetContinueResult(size_t core_id) { uintptr_t x = 0; m_result_message_queues[core_id].Receive(&x); return static_cast<Result>(x); } public: DebugEventsManager() : m_handle_message_queues{ os::MessageQueue(std::addressof(m_handle_message_queue_buffers[0]), 1), os::MessageQueue(std::addressof(m_handle_message_queue_buffers[1]), 1), os::MessageQueue(std::addressof(m_handle_message_queue_buffers[2]), 1), os::MessageQueue(std::addressof(m_handle_message_queue_buffers[3]), 1)}, m_result_message_queues{ os::MessageQueue(std::addressof(m_result_message_queue_buffers[0]), 1), os::MessageQueue(std::addressof(m_result_message_queue_buffers[1]), 1), os::MessageQueue(std::addressof(m_result_message_queue_buffers[2]), 1), os::MessageQueue(std::addressof(m_result_message_queue_buffers[3]), 1)}, m_thread_stacks{} { for (size_t i = 0; i < NumCores; i++) { /* Create thread. */ R_ABORT_UNLESS(os::CreateThread(std::addressof(m_threads[i]), PerCoreThreadFunction, this, m_thread_stacks[i], ThreadStackSize, AMS_GET_SYSTEM_THREAD_PRIORITY(dmnt, MultiCoreEventManager), i)); os::SetThreadNamePointer(std::addressof(m_threads[i]), AMS_GET_SYSTEM_THREAD_NAME(dmnt, MultiCoreEventManager)); /* Set core mask. */ os::SetThreadCoreMask(std::addressof(m_threads[i]), i, (1u << i)); /* Start thread. */ os::StartThread(std::addressof(m_threads[i])); } } Result ContinueCheatProcess(os::NativeHandle cheat_dbg_hnd) { /* Loop getting all debug events. */ svc::DebugEventInfo d; size_t target_core = NumCores - 1; while (R_SUCCEEDED(svc::GetDebugEvent(std::addressof(d), cheat_dbg_hnd))) { if (d.type == svc::DebugEvent_CreateThread) { R_TRY(GetTargetCore(std::addressof(target_core), d, cheat_dbg_hnd)); } } /* Send handle to correct core, wait for continue to finish. */ this->SendHandle(target_core, cheat_dbg_hnd); R_RETURN(this->GetContinueResult(target_core)); } }; /* Manager global. */ util::TypedStorage<DebugEventsManager> g_events_manager; } void InitializeDebugEventsManager() { util::ConstructAt(g_events_manager); } Result ContinueCheatProcess(os::NativeHandle cheat_dbg_hnd) { R_RETURN(GetReference(g_events_manager).ContinueCheatProcess(cheat_dbg_hnd)); } }
7,675
C++
.cpp
132
41.143939
217
0.555275
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,137
sm_main.cpp
Atmosphere-NX_Atmosphere/stratosphere/sm/source/sm_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 "sm_tipc_server.hpp" namespace ams { namespace init { void InitializeSystemModule() { /* ... */ } void FinalizeSystemModule() { /* ... */ } void Startup() { /* ... */ } } void NORETURN Exit(int rc) { AMS_UNUSED(rc); AMS_ABORT("Exit called by immortal process"); } void Main() { /* Set thread name. */ os::SetThreadNamePointer(os::GetCurrentThread(), AMS_GET_SYSTEM_THREAD_NAME(sm, Main)); AMS_ASSERT(os::GetThreadPriority(os::GetCurrentThread()) == AMS_GET_SYSTEM_THREAD_PRIORITY(sm, Main)); /* Initialize the server. */ sm::InitializeTipcServer(); /* Loop forever, processing our services. */ sm::LoopProcessTipcServer(); /* This can never be reached. */ AMS_ASSUME(false); } }
1,499
C++
.cpp
39
33.282051
110
0.665746
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,138
sm_user_service.cpp
Atmosphere-NX_Atmosphere/stratosphere/sm/source/sm_user_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 "sm_user_service.hpp" #include "impl/sm_service_manager.hpp" namespace ams::sm { namespace { constexpr const u8 CmifResponseToQueryPointerBufferSize[] = { 0x00, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x53, 0x46, 0x43, 0x4F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; static_assert(CmifCommandType_Request == 4); constexpr const u8 CmifExpectedRequestHeaderForRegisterClientAndDetachClient[] = { 0x04, 0x00, 0x00, 0x00, 0x0A, 0x00, 0x00, 0x80, 0x01, 0x00, 0x00, 0x00, }; constexpr const u8 CmifResponseToRegisterClientAndDetachClient[] = { 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x53, 0x46, 0x43, 0x4F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; constexpr const u8 CmifExpectedRequestHeaderForGetServiceHandleAndUnregisterService[] = { 0x04, 0x00, 0x00, 0x00, 0x0A, 0x00, 0x00, 0x00 }; constexpr const u8 CmifResponseToGetServiceHandleAndRegisterService[] = { 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x80, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x53, 0x46, 0x43, 0x4F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; constexpr const u8 CmifResponseToUnregisterService[] = { 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x53, 0x46, 0x43, 0x4F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; constexpr const u8 CmifExpectedRequestHeaderForRegisterService[] = { 0x04, 0x00, 0x00, 0x00, 0x0C, 0x00, 0x00, 0x00 }; static_assert(tipc::ResultRequestDeferred().GetValue() == 0xC823); constexpr const u8 CmifResponseToForceProcessorDeferral[] = { 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x23, 0xC8, 0x00, 0x00, }; } Result UserService::ProcessDefaultServiceCommand(const svc::ipc::MessageBuffer &message_buffer) { /* Parse the hipc headers. */ const svc::ipc::MessageBuffer::MessageHeader message_header(message_buffer); const svc::ipc::MessageBuffer::SpecialHeader special_header(message_buffer, message_header); /* Get the request tag. */ const auto tag = message_header.GetTag(); /* Handle the case where we received a control request. */ if (tag == CmifCommandType_Control || tag == CmifCommandType_ControlWithContext) { /* The only control/control with context command which we support is QueryPointerBufferSize. */ /* We do not have a pointer buffer, and so our pointer buffer size is zero. */ /* Return the relevant hardcoded response. */ std::memcpy(message_buffer.GetBufferForDebug(), CmifResponseToQueryPointerBufferSize, sizeof(CmifResponseToQueryPointerBufferSize)); R_SUCCEED(); } /* We only support request (with context), from this point forwards. */ R_UNLESS((tag == CmifCommandType_Request || tag == CmifCommandType_RequestWithContext), tipc::ResultInvalidMethod()); /* For ease of parsing, we will alter the tag to be Request when it is RequestWithContext. */ if (tag == CmifCommandType_RequestWithContext) { message_buffer.Set(svc::ipc::MessageBuffer::MessageHeader(CmifCommandType_Request, message_header.GetHasSpecialHeader(), message_header.GetPointerCount(), message_header.GetSendCount(), message_header.GetReceiveCount(), message_header.GetExchangeCount(), message_header.GetRawCount(), message_header.GetReceiveListCount())); } /* NOTE: Nintendo only supports RegisterClient and GetServiceHandle. However, it would break */ /* a substantial amount of homebrew system modules, if we were to not provide shims for some */ /* other commands (RegisterService, and UnregisterService, in particular). As such, we will */ /* do the nice thing, and accommodate this by providing backwards compatibility shims for */ /* those commands. */ /* Please note, though, that the atmosphere extensions are not shimmed, as performing all the required */ /* parsing for that seems unreasonable. Also, if you are using atmosphere extensions, you are probably */ /* used to my breaking shit regularly anyway, and I don't expect much of a fuss to be raised by you. */ /* I invite you to demonstrate to me that this expectation does not reflect reality. */ const u8 * const raw_message_buffer = static_cast<const u8 *>(message_buffer.GetBufferForDebug()); u8 * const out_message_buffer = static_cast<u8 *>(message_buffer.GetBufferForDebug()); if (std::memcmp(raw_message_buffer, CmifExpectedRequestHeaderForRegisterClientAndDetachClient, sizeof(CmifExpectedRequestHeaderForRegisterClientAndDetachClient)) == 0) { /* Get the command id. */ const u32 command_id = *reinterpret_cast<const u32 *>(raw_message_buffer + 0x28); /* Get the client process id. */ u64 client_process_id; std::memcpy(std::addressof(client_process_id), raw_message_buffer + 0xC, sizeof(client_process_id)); if (command_id == 0) { /* Invoke the handler for RegisterClient. */ R_ABORT_UNLESS(this->RegisterClient(tipc::ClientProcessId{ client_process_id })); } else if (command_id == 4) { /* Invoke the handler for DetachClient. */ R_ABORT_UNLESS(this->DetachClient(tipc::ClientProcessId{ client_process_id })); } else { R_THROW(tipc::ResultInvalidMethod()); } /* Serialize output. */ std::memcpy(out_message_buffer, CmifResponseToRegisterClientAndDetachClient, sizeof(CmifResponseToRegisterClientAndDetachClient)); } else if (std::memcmp(raw_message_buffer, CmifExpectedRequestHeaderForGetServiceHandleAndUnregisterService, sizeof(CmifExpectedRequestHeaderForGetServiceHandleAndUnregisterService)) == 0) { /* Get the command id. */ const u32 command_id = *reinterpret_cast<const u32 *>(raw_message_buffer + 0x18); /* Get the service_name. */ sm::ServiceName service_name; std::memcpy(std::addressof(service_name), raw_message_buffer + 0x20, sizeof(service_name)); if (command_id == 1) { /* Invoke the handler for GetServiceHandle. */ svc::Handle out_handle = svc::InvalidHandle; const Result result = this->GetServiceHandle(std::addressof(out_handle), service_name); /* Serialize output. */ if (!tipc::ResultRequestDeferred::Includes(result)) { std::memcpy(out_message_buffer + 0x00, CmifResponseToGetServiceHandleAndRegisterService, sizeof(CmifResponseToGetServiceHandleAndRegisterService)); std::memcpy(out_message_buffer + 0x0C, std::addressof(out_handle), sizeof(out_handle)); std::memcpy(out_message_buffer + 0x18, std::addressof(result), sizeof(result)); } else { std::memcpy(out_message_buffer, CmifResponseToForceProcessorDeferral, sizeof(CmifResponseToForceProcessorDeferral)); } } else if (command_id == 3) { /* Invoke the handler for UnregisterService. */ const Result result = this->UnregisterService(service_name); /* Serialize output. */ std::memcpy(out_message_buffer + 0x00, CmifResponseToUnregisterService, sizeof(CmifResponseToUnregisterService)); std::memcpy(out_message_buffer + 0x18, std::addressof(result), sizeof(result)); } else { R_THROW(tipc::ResultInvalidMethod()); } } else if (std::memcmp(raw_message_buffer, CmifExpectedRequestHeaderForRegisterService, sizeof(CmifExpectedRequestHeaderForRegisterService)) == 0) { /* Get the command id. */ const u32 command_id = *reinterpret_cast<const u32 *>(raw_message_buffer + 0x18); /* Get the service_name. */ sm::ServiceName service_name; std::memcpy(std::addressof(service_name), raw_message_buffer + 0x20, sizeof(service_name)); /* Get "is light". */ bool is_light; is_light = (raw_message_buffer[0x28] & 0x01) != 0; /* Get the max sessions. */ u32 max_sessions; std::memcpy(std::addressof(max_sessions), raw_message_buffer + 0x2C, sizeof(max_sessions)); if (command_id == 2) { /* Invoke the handler for RegisterService. */ svc::Handle out_handle = svc::InvalidHandle; const Result result = this->RegisterService(std::addressof(out_handle), service_name, max_sessions, is_light); /* Serialize output. */ std::memcpy(out_message_buffer + 0x00, CmifResponseToGetServiceHandleAndRegisterService, sizeof(CmifResponseToGetServiceHandleAndRegisterService)); std::memcpy(out_message_buffer + 0x0C, std::addressof(out_handle), sizeof(out_handle)); std::memcpy(out_message_buffer + 0x18, std::addressof(result), sizeof(result)); } else { R_THROW(tipc::ResultInvalidMethod()); } } else { R_THROW(tipc::ResultInvalidMethod()); } R_SUCCEED(); } }
11,025
C++
.cpp
164
53.420732
198
0.621871
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,139
sm_tipc_server.cpp
Atmosphere-NX_Atmosphere/stratosphere/sm/source/sm_tipc_server.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "sm_tipc_server.hpp" #include "sm_user_service.hpp" #include "sm_manager_service.hpp" #include "sm_wait_list.hpp" #include "impl/sm_service_manager.hpp" namespace ams::sm { namespace { /* Server limit definitions. */ enum PortIndex : size_t { PortIndex_Manager, PortIndex_User, PortIndex_Count, }; constexpr inline size_t NumTipcPorts = static_cast<size_t>(PortIndex_Count); constexpr inline size_t MaxSessionsManager = 1; constexpr inline size_t MaxSessionsUser = 0x50 + 8 - MaxSessionsManager; constexpr inline size_t MaxSessionsTotal = MaxSessionsManager + MaxSessionsUser; static_assert(MaxSessionsTotal % NumTipcPorts == 0); /* Define port metadata. */ using UserPortMeta = tipc::PortMeta<MaxSessionsUser, impl::IUserInterface, UserService, tipc::SlabAllocator>; using ManagerPortMeta = tipc::PortMeta<MaxSessionsManager, impl::IManagerInterface, ManagerService, tipc::SingletonAllocator>; /* Define server manager global. */ using ServerManager = tipc::ServerManager<ManagerPortMeta, UserPortMeta>; ServerManager g_server_manager; } void InitializeTipcServer() { /* Initialize the server manager. */ g_server_manager.Initialize(); /* Create the handles for our ports. */ os::NativeHandle user_port_handle, manager_port_handle; { /* Create the user port handle. */ R_ABORT_UNLESS(svc::ManageNamedPort(std::addressof(user_port_handle), "sm:", MaxSessionsUser)); /* Create the manager port handle. */ R_ABORT_UNLESS(impl::RegisterServiceForSelf(std::addressof(manager_port_handle), sm::ServiceName::Encode("sm:m"), MaxSessionsManager)); } /* Register the ports. */ g_server_manager.RegisterPort<PortIndex_Manager>(manager_port_handle); g_server_manager.RegisterPort<PortIndex_User >(user_port_handle); } void LoopProcessTipcServer() { /* Loop processing the server on all threads. */ g_server_manager.LoopAuto(AMS_GET_SYSTEM_THREAD_PRIORITY(sm, DispatcherThread), AMS_GET_SYSTEM_THREAD_NAME(sm, DispatcherThread)); } void TriggerResume(sm::ServiceName service_name) { /* Trigger a resumption. */ g_server_manager.TriggerResume(service_name); } }
3,121
C++
.cpp
65
41.415385
147
0.68499
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,140
sm_service_manager.cpp
Atmosphere-NX_Atmosphere/stratosphere/sm/source/impl/sm_service_manager.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "sm_service_manager.hpp" #include "../sm_wait_list.hpp" namespace ams::hos { void InitializeVersionInternal(bool allow_approximate); } namespace ams::sm::impl { namespace { /* Constexpr definitions. */ static constexpr size_t ProcessCountMax = 0x50; static constexpr size_t ServiceCountMax = 0x180; static constexpr size_t MitmCountMax = 0x20; static constexpr size_t AccessControlSizeMax = 0x200; constexpr const sm::ServiceName InitiallyDeferredServices[] = { ServiceName::Encode("fsp-srv") }; /* Types. */ struct ProcessInfo { os::ProcessId process_id; ncm::ProgramId program_id; cfg::OverrideStatus override_status; size_t access_control_size; u8 access_control[AccessControlSizeMax]; }; constexpr const ProcessInfo InvalidProcessInfo = { .process_id = os::InvalidProcessId, .program_id = ncm::InvalidProgramId, .override_status = {}, .access_control_size = 0, .access_control = {}, }; struct ServiceInfo { ServiceName name; os::ProcessId owner_process_id; os::NativeHandle port_h; bool is_light; u8 max_sessions; u8 mitm_index; }; struct MitmInfo { os::ProcessId process_id; os::ProcessId waiting_ack_process_id; os::NativeHandle port_h; os::NativeHandle query_h; os::NativeHandle fwd_sess_h; bool waiting_ack; }; constexpr const ServiceInfo InvalidServiceInfo = { .name = sm::InvalidServiceName, .owner_process_id = os::InvalidProcessId, .port_h = os::InvalidNativeHandle, .is_light = false, .max_sessions = 0, .mitm_index = MitmCountMax, }; constexpr const MitmInfo InvalidMitmInfo = { .process_id = os::InvalidProcessId, .waiting_ack_process_id = os::InvalidProcessId, .port_h = os::InvalidNativeHandle, .query_h = os::InvalidNativeHandle, .fwd_sess_h = os::InvalidNativeHandle, .waiting_ack = false, }; class AccessControlEntry { private: const u8 *m_entry; size_t m_capacity; public: AccessControlEntry(const void *e, size_t c) : m_entry(static_cast<const u8 *>(e)), m_capacity(c) { /* ... */ } AccessControlEntry GetNextEntry() const { return AccessControlEntry(m_entry + this->GetSize(), m_capacity - this->GetSize()); } size_t GetSize() const { return this->GetServiceNameSize() + 1; } size_t GetServiceNameSize() const { return (m_entry[0] & 7) + 1; } ServiceName GetServiceName() const { return ServiceName::Encode(reinterpret_cast<const char *>(m_entry + 1), this->GetServiceNameSize()); } bool IsHost() const { return (m_entry[0] & 0x80) != 0; } bool IsWildcard() const { return m_entry[this->GetServiceNameSize()] == '*'; } bool IsValid() const { /* Validate that we can access data. */ if (m_entry == nullptr || m_capacity == 0) { return false; } /* Validate that the size is correct. */ return this->GetSize() <= m_capacity; } }; class InitialProcessIdLimits { private: os::ProcessId m_min; os::ProcessId m_max; public: InitialProcessIdLimits() { /* Retrieve process limits. */ R_ABORT_UNLESS(svc::GetSystemInfo(std::addressof(m_min.value), svc::SystemInfoType_InitialProcessIdRange, svc::InvalidHandle, svc::InitialProcessIdRangeInfo_Minimum)); R_ABORT_UNLESS(svc::GetSystemInfo(std::addressof(m_max.value), svc::SystemInfoType_InitialProcessIdRange, svc::InvalidHandle, svc::InitialProcessIdRangeInfo_Maximum)); /* Ensure range is sane. */ AMS_ABORT_UNLESS(m_min <= m_max); } bool IsInitialProcess(os::ProcessId process_id) const { AMS_ABORT_UNLESS(process_id != os::InvalidProcessId); return m_min <= process_id && process_id <= m_max; } }; /* Static members. */ /* NOTE: In 12.0.0, Nintendo added multithreaded processing to sm; however, official sm does not do */ /* 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::SdkRecursiveMutex g_mutex; constinit std::array<ProcessInfo, ProcessCountMax> g_process_list = [] { std::array<ProcessInfo, ProcessCountMax> list = {}; /* Initialize each info. */ for (auto &process_info : list) { process_info = InvalidProcessInfo; } return list; }(); constinit std::array<ServiceInfo, ServiceCountMax> g_service_list = [] { std::array<ServiceInfo, ServiceCountMax> list = {}; /* Initialize each info. */ for (auto &service_info : list) { service_info = InvalidServiceInfo; } return list; }(); constinit std::array<ServiceName, MitmCountMax> g_future_mitm_list = [] { std::array<ServiceName, MitmCountMax> list = {}; /* Initialize each info. */ for (auto &name : list) { name = InvalidServiceName; } return list; }(); constinit std::array<MitmInfo, MitmCountMax> g_mitm_list = [] { std::array<MitmInfo, MitmCountMax> list = {}; /* Initialize each info. */ for (auto &mitm_info : list) { mitm_info = InvalidMitmInfo; } return list; }(); constinit bool g_ended_initial_defers = false; const InitialProcessIdLimits g_initial_process_id_limits; /* Helper functionality. */ bool IsInitialProcess(os::ProcessId process_id) { return g_initial_process_id_limits.IsInitialProcess(process_id); } constexpr inline bool IsValidProcessId(os::ProcessId process_id) { return process_id != os::InvalidProcessId; } Result ValidateAccessControl(AccessControlEntry access_control, ServiceName service, bool is_host, bool is_wildcard) { /* Iterate over all entries in the access control, checking to see if we have a match. */ while (access_control.IsValid()) { if (access_control.IsHost() == is_host) { bool is_valid = true; if (access_control.IsWildcard() == is_wildcard) { /* Check for exact match. */ is_valid &= access_control.GetServiceName() == service; } else if (access_control.IsWildcard()) { /* Also allow fuzzy match for wildcard. */ ServiceName ac_service = access_control.GetServiceName(); is_valid &= std::memcmp(std::addressof(ac_service), std::addressof(service), access_control.GetServiceNameSize() - 1) == 0; } R_SUCCEED_IF(is_valid); } access_control = access_control.GetNextEntry(); } R_THROW(sm::ResultNotAllowed()); } Result ValidateAccessControl(AccessControlEntry restriction, AccessControlEntry access) { /* Ensure that every entry in the access control is allowed by the restriction control. */ while (access.IsValid()) { R_TRY(ValidateAccessControl(restriction, access.GetServiceName(), access.IsHost(), access.IsWildcard())); access = access.GetNextEntry(); } R_SUCCEED(); } Result ValidateServiceName(ServiceName service) { /* Service names must be non-empty. */ R_UNLESS(service.name[0] != 0, sm::ResultInvalidServiceName()); /* Get name length. */ size_t name_len; for (name_len = 1; name_len < sizeof(service); name_len++) { if (service.name[name_len] == 0) { break; } } /* Names must be all-zero after they end. */ while (name_len < sizeof(service)) { R_UNLESS(service.name[name_len++] == 0, sm::ResultInvalidServiceName()); } R_SUCCEED(); } bool ShouldDeferForInit(ServiceName service) { /* Once end has been called, we're done. */ if (g_ended_initial_defers) { return false; } /* This is a mechanism by which certain services will always be deferred until sm:m receives a special command. */ /* This can be extended with more services as needed at a later date. */ for (const auto &service_name : InitiallyDeferredServices) { if (service == service_name) { return true; } } return false; } ProcessInfo *GetProcessInfo(os::ProcessId process_id) { /* Find a process info with a matching id. */ for (auto &process_info : g_process_list) { if (process_info.process_id == process_id) { return std::addressof(process_info); } } return nullptr; } ProcessInfo *GetFreeProcessInfo() { return GetProcessInfo(os::InvalidProcessId); } bool HasProcessInfo(os::ProcessId process_id) { return GetProcessInfo(process_id) != nullptr; } ServiceInfo *GetServiceInfo(ServiceName service_name) { /* Find a service with a matching name. */ for (auto &service_info : g_service_list) { if (service_info.name == service_name) { return std::addressof(service_info); } } return nullptr; } ServiceInfo *GetFreeServiceInfo() { return GetServiceInfo(InvalidServiceName); } bool HasServiceInfo(ServiceName service) { return GetServiceInfo(service) != nullptr; } MitmInfo *GetMitmInfo(const ServiceInfo *service_info) { if (service_info->mitm_index < MitmCountMax) { return std::addressof(g_mitm_list[service_info->mitm_index]); } else { return nullptr; } } MitmInfo *GetFreeMitmInfo() { /* Find a mitm info without an owner. */ for (auto &mitm_info : g_mitm_list) { if (!IsValidProcessId(mitm_info.process_id)) { return std::addressof(mitm_info); } } return nullptr; } bool HasMitm(ServiceName service) { const ServiceInfo *service_info = GetServiceInfo(service); return service_info != nullptr && GetMitmInfo(service_info) != nullptr; } Result AddFutureMitmDeclaration(ServiceName service) { for (auto &future_mitm : g_future_mitm_list) { if (future_mitm == InvalidServiceName) { future_mitm = service; R_SUCCEED(); } } R_THROW(sm::ResultOutOfServices()); } bool HasFutureMitmDeclaration(ServiceName service) { for (const auto &future_mitm : g_future_mitm_list){ if (future_mitm == service) { return true; } } return false; } void ClearFutureMitmDeclaration(ServiceName service) { for (auto &future_mitm : g_future_mitm_list) { if (future_mitm == service) { future_mitm = InvalidServiceName; } } /* This might undefer some requests. */ TriggerResume(service); } void GetMitmProcessInfo(MitmProcessInfo *out_info, os::ProcessId process_id) { /* Anything that can request a mitm session must have a process info. */ const auto process_info = GetProcessInfo(process_id); AMS_ABORT_UNLESS(process_info != nullptr); /* Write to output. */ out_info->process_id = process_id; out_info->program_id = process_info->program_id; out_info->override_status = process_info->override_status; } bool IsMitmDisallowed(ncm::ProgramId program_id) { /* Mitm used on certain programs can prevent the boot process from completing. */ /* TODO: Is there a way to do this that's less hardcoded? Needs design thought. */ return program_id == ncm::SystemProgramId::Loader || program_id == ncm::SystemProgramId::Pm || program_id == ncm::SystemProgramId::Spl || program_id == ncm::SystemProgramId::Boot || program_id == ncm::SystemProgramId::Ncm || program_id == ncm::AtmosphereProgramId::Mitm || program_id == ncm::SystemProgramId::Creport; } Result CreatePortImpl(os::NativeHandle *out_server, os::NativeHandle *out_client, size_t max_sessions, bool is_light, sm::ServiceName &name) { /* Create the port. */ svc::Handle server_port, client_port; R_TRY(svc::CreatePort(std::addressof(server_port), std::addressof(client_port), max_sessions, is_light, reinterpret_cast<uintptr_t>(name.name))); /* Set the output handles. */ *out_server = server_port; *out_client = client_port; R_SUCCEED(); } Result ConnectToPortImpl(os::NativeHandle *out, os::NativeHandle port) { /* Connect to the port. */ svc::Handle session; R_TRY(svc::ConnectToPort(std::addressof(session), port)); /* Set the output handle. */ *out = session; R_SUCCEED(); } Result GetMitmServiceHandleImpl(os::NativeHandle *out, ServiceInfo *service_info, const MitmProcessInfo &client_info) { /* Get the mitm info. */ MitmInfo *mitm_info = GetMitmInfo(service_info); AMS_ABORT_UNLESS(mitm_info != nullptr); /* Send command to query if we should mitm. */ bool should_mitm; { /* TODO: Convert mitm internal messaging to use tipc? */ ::Service srv { .session = mitm_info->query_h }; R_ABORT_UNLESS((serviceDispatchInOut(std::addressof(srv), 65000, client_info, should_mitm))); } /* If we shouldn't mitm, give normal session. */ R_UNLESS(should_mitm, ConnectToPortImpl(out, service_info->port_h)); /* Create both handles. */ { /* Get the forward handle. */ R_TRY(ConnectToPortImpl(std::addressof(mitm_info->fwd_sess_h), service_info->port_h)); /* Get the mitm handle. */ /* This should be guaranteed to succeed, since we got a forward handle. */ R_ABORT_UNLESS(ConnectToPortImpl(out, mitm_info->port_h)); } mitm_info->waiting_ack_process_id = client_info.process_id; mitm_info->waiting_ack = true; R_SUCCEED(); } Result GetServiceHandleImpl(os::NativeHandle *out, ServiceInfo *service_info, os::ProcessId process_id) { /* Get the mitm info. */ MitmInfo *mitm_info = GetMitmInfo(service_info); /* Check if we should return a mitm handle. */ if (mitm_info != nullptr && mitm_info->process_id != process_id) { /* Get mitm process info, ensure that we're allowed to mitm the given program. */ MitmProcessInfo client_info; GetMitmProcessInfo(std::addressof(client_info), process_id); if (!IsMitmDisallowed(client_info.program_id)) { /* Get a mitm service handle. */ R_RETURN(GetMitmServiceHandleImpl(out, service_info, client_info)); } } /* We're not returning a mitm handle, so just return a normal port handle. */ R_RETURN(ConnectToPortImpl(out, service_info->port_h)); } Result RegisterServiceImpl(os::NativeHandle *out, os::ProcessId process_id, ServiceName service, size_t max_sessions, bool is_light) { /* Validate service name. */ R_TRY(ValidateServiceName(service)); /* Don't try to register something already registered. */ R_UNLESS(!HasServiceInfo(service), sm::ResultAlreadyRegistered()); /* Get free service. */ ServiceInfo *free_service = GetFreeServiceInfo(); R_UNLESS(free_service != nullptr, sm::ResultOutOfServices()); /* Create the new service. */ R_TRY(CreatePortImpl(out, std::addressof(free_service->port_h), max_sessions, is_light, free_service->name)); /* Save info. */ free_service->name = service; free_service->owner_process_id = process_id; free_service->max_sessions = max_sessions; free_service->is_light = is_light; /* This might undefer some requests. */ TriggerResume(service); R_SUCCEED(); } void UnregisterServiceImpl(ServiceInfo *service_info) { /* Get the mitm info. */ MitmInfo *mitm_info = GetMitmInfo(service_info); /* Close all valid handles. */ os::CloseNativeHandle(service_info->port_h); /* Reset the info's state. */ *service_info = InvalidServiceInfo; /* Reset the mitm info, if necessary. */ if (mitm_info != nullptr) { os::CloseNativeHandle(mitm_info->port_h); os::CloseNativeHandle(mitm_info->query_h); os::CloseNativeHandle(mitm_info->fwd_sess_h); *mitm_info = InvalidMitmInfo; } } } /* Client disconnection callback. */ void OnClientDisconnected(os::ProcessId process_id) { /* Acquire exclusive access to global state. */ std::scoped_lock lk(g_mutex); /* Ensure that the process id is valid. */ if (process_id == os::InvalidProcessId) { return; } /* Unregister all services a client hosts, on attached-client-close. */ for (auto &service_info : g_service_list) { if (service_info.name != InvalidServiceName && service_info.owner_process_id == process_id) { UnregisterServiceImpl(std::addressof(service_info)); } } } /* Process management. */ Result RegisterProcess(os::ProcessId process_id, ncm::ProgramId program_id, cfg::OverrideStatus override_status, const void *acid_sac, size_t acid_sac_size, const void *aci_sac, size_t aci_sac_size) { /* Acquire exclusive access to global state. */ std::scoped_lock lk(g_mutex); /* Check that access control will fit in the ServiceInfo. */ R_UNLESS(aci_sac_size <= AccessControlSizeMax, sm::ResultTooLargeAccessControl()); /* Get free process. */ ProcessInfo *proc = GetFreeProcessInfo(); R_UNLESS(proc != nullptr, sm::ResultOutOfProcesses()); /* Validate restrictions. */ R_UNLESS(aci_sac_size != 0, sm::ResultNotAllowed()); R_TRY(ValidateAccessControl(AccessControlEntry(acid_sac, acid_sac_size), AccessControlEntry(aci_sac, aci_sac_size))); /* Save info. */ proc->process_id = process_id; proc->program_id = program_id; proc->override_status = override_status; proc->access_control_size = aci_sac_size; std::memcpy(proc->access_control, aci_sac, proc->access_control_size); R_SUCCEED(); } Result UnregisterProcess(os::ProcessId process_id) { /* Acquire exclusive access to global state. */ std::scoped_lock lk(g_mutex); /* Find the process. */ ProcessInfo *proc = GetProcessInfo(process_id); R_UNLESS(proc != nullptr, sm::ResultInvalidClient()); /* Free the process. */ *proc = InvalidProcessInfo; R_SUCCEED(); } /* Service management. */ Result HasService(bool *out, ServiceName service) { /* Acquire exclusive access to global state. */ std::scoped_lock lk(g_mutex); /* Validate service name. */ R_TRY(ValidateServiceName(service)); *out = HasServiceInfo(service); R_SUCCEED(); } Result WaitService(ServiceName service) { /* Acquire exclusive access to global state. */ std::scoped_lock lk(g_mutex); /* Check that we have the service. */ bool has_service = false; R_TRY(impl::HasService(std::addressof(has_service), service)); /* If we don't, we want to wait until the service is registered. */ R_UNLESS(has_service, tipc::ResultRequestDeferred()); R_SUCCEED(); } Result GetServiceHandle(os::NativeHandle *out, os::ProcessId process_id, ServiceName service) { /* Acquire exclusive access to global state. */ std::scoped_lock lk(g_mutex); /* Validate service name. */ R_TRY(ValidateServiceName(service)); /* Check that the process is registered and allowed to get the service. */ if (!IsInitialProcess(process_id)) { ProcessInfo *proc = GetProcessInfo(process_id); R_UNLESS(proc != nullptr, sm::ResultInvalidClient()); R_TRY(ValidateAccessControl(AccessControlEntry(proc->access_control, proc->access_control_size), service, false, false)); } /* Get service info/mitm info. */ ServiceInfo *service_info = GetServiceInfo(service); MitmInfo *mitm_info = service_info != nullptr ? GetMitmInfo(service_info) : nullptr; /* Check to see if we need to defer until later. */ R_UNLESS(service_info != nullptr, tipc::ResultRequestDeferred()); R_UNLESS(!ShouldDeferForInit(service), tipc::ResultRequestDeferred()); R_UNLESS(!HasFutureMitmDeclaration(service), tipc::ResultRequestDeferred()); R_UNLESS((mitm_info == nullptr || !mitm_info->waiting_ack), tipc::ResultRequestDeferred()); /* Get a handle from the service info. */ R_TRY_CATCH(GetServiceHandleImpl(out, service_info, process_id)) { R_CONVERT(svc::ResultOutOfSessions, sm::ResultOutOfSessions()) } R_END_TRY_CATCH; R_SUCCEED(); } Result RegisterService(os::NativeHandle *out, os::ProcessId process_id, ServiceName service, size_t max_sessions, bool is_light) { /* Acquire exclusive access to global state. */ std::scoped_lock lk(g_mutex); /* Validate service name. */ R_TRY(ValidateServiceName(service)); /* Check that the process is registered and allowed to register the service. */ if (!IsInitialProcess(process_id)) { ProcessInfo *proc = GetProcessInfo(process_id); R_UNLESS(proc != nullptr, sm::ResultInvalidClient()); R_TRY(ValidateAccessControl(AccessControlEntry(proc->access_control, proc->access_control_size), service, true, false)); } /* Check that the service isn't already registered. */ R_UNLESS(!HasServiceInfo(service), sm::ResultAlreadyRegistered()); R_RETURN(RegisterServiceImpl(out, process_id, service, max_sessions, is_light)); } Result RegisterServiceForSelf(os::NativeHandle *out, ServiceName service, size_t max_sessions) { /* Acquire exclusive access to global state. */ std::scoped_lock lk(g_mutex); R_RETURN(RegisterServiceImpl(out, os::GetCurrentProcessId(), service, max_sessions, false)); } Result UnregisterService(os::ProcessId process_id, ServiceName service) { /* Acquire exclusive access to global state. */ std::scoped_lock lk(g_mutex); /* Validate service name. */ R_TRY(ValidateServiceName(service)); /* Check that the process is registered. */ if (!IsInitialProcess(process_id)) { R_UNLESS(HasProcessInfo(process_id), sm::ResultInvalidClient()); } /* Ensure that the service is actually registered. */ ServiceInfo *service_info = GetServiceInfo(service); R_UNLESS(service_info != nullptr, sm::ResultNotRegistered()); /* Check if we have permission to do this. */ R_UNLESS(service_info->owner_process_id == process_id, sm::ResultNotAllowed()); /* Unregister the service. */ UnregisterServiceImpl(service_info); R_SUCCEED(); } /* Mitm extensions. */ Result HasMitm(bool *out, ServiceName service) { /* Acquire exclusive access to global state. */ std::scoped_lock lk(g_mutex); /* Validate service name. */ R_TRY(ValidateServiceName(service)); /* Get whether we have a mitm. */ *out = HasMitm(service); R_SUCCEED(); } Result WaitMitm(ServiceName service) { /* Acquire exclusive access to global state. */ std::scoped_lock lk(g_mutex); /* Check that we have the mitm. */ bool has_mitm = false; R_TRY(impl::HasMitm(std::addressof(has_mitm), service)); /* If we don't, we want to wait until the mitm is installed. */ R_UNLESS(has_mitm, tipc::ResultRequestDeferred()); R_SUCCEED(); } Result InstallMitm(os::NativeHandle *out, os::NativeHandle *out_query, os::ProcessId process_id, ServiceName service) { /* Acquire exclusive access to global state. */ std::scoped_lock lk(g_mutex); /* Validate service name. */ R_TRY(ValidateServiceName(service)); /* Check that the process is registered and allowed to register the service. */ if (!IsInitialProcess(process_id)) { ProcessInfo *proc = GetProcessInfo(process_id); R_UNLESS(proc != nullptr, sm::ResultInvalidClient()); R_TRY(ValidateAccessControl(AccessControlEntry(proc->access_control, proc->access_control_size), service, true, false)); } /* Validate that the service exists. */ ServiceInfo *service_info = GetServiceInfo(service); /* If it doesn't exist, defer until it does. */ R_UNLESS(service_info != nullptr, tipc::ResultRequestDeferred()); /* Validate that the service isn't already being mitm'd. */ R_UNLESS(GetMitmInfo(service_info) == nullptr, sm::ResultAlreadyRegistered()); /* Validate that we can create a new mitm. */ MitmInfo *mitm_info = GetFreeMitmInfo(); R_UNLESS(mitm_info != nullptr, sm::ResultOutOfServices()); /* If we don't have a future mitm declaration, add one. */ /* Client will clear this when ready to process. */ const bool has_existing_future_declaration = HasFutureMitmDeclaration(service); if (!has_existing_future_declaration) { R_TRY(AddFutureMitmDeclaration(service)); } /* If we fail past this point, clean up the future mitm declaration we just added. */ ON_RESULT_FAILURE { if (!has_existing_future_declaration) { ClearFutureMitmDeclaration(service); } }; /* Create mitm handles. */ { /* Get the port handles. */ os::NativeHandle hnd, port_hnd; R_TRY(CreatePortImpl(std::addressof(hnd), std::addressof(port_hnd), service_info->max_sessions, service_info->is_light, service_info->name)); /* Ensure that we clean up the port handles, if something goes wrong creating the query sessions. */ ON_RESULT_FAILURE { os::CloseNativeHandle(hnd); os::CloseNativeHandle(port_hnd); }; /* Create the session for our query service. */ os::NativeHandle qry_hnd, mitm_qry_hnd; R_TRY(svc::CreateSession(std::addressof(qry_hnd), std::addressof(mitm_qry_hnd), false, 0)); /* Setup the mitm info. */ mitm_info->process_id = process_id; mitm_info->port_h = port_hnd; mitm_info->query_h = mitm_qry_hnd; /* Setup the service info. */ service_info->mitm_index = mitm_info - g_mitm_list.data(); /* Copy to output. */ *out = hnd; *out_query = qry_hnd; /* This might undefer some requests. */ TriggerResume(service); } R_SUCCEED(); } Result UninstallMitm(os::ProcessId process_id, ServiceName service) { /* Acquire exclusive access to global state. */ std::scoped_lock lk(g_mutex); /* Validate service name. */ R_TRY(ValidateServiceName(service)); /* Check that the process is registered. */ if (!IsInitialProcess(process_id)) { ProcessInfo *proc = GetProcessInfo(process_id); R_UNLESS(proc != nullptr, sm::ResultInvalidClient()); } /* Validate that the service exists. */ ServiceInfo *service_info = GetServiceInfo(service); R_UNLESS(service_info != nullptr, sm::ResultNotRegistered()); /* Validate that the service is mitm'd. */ MitmInfo *mitm_info = GetMitmInfo(service_info); R_UNLESS(mitm_info != nullptr, sm::ResultNotRegistered()); /* Validate that the client process_id is the mitm process. */ R_UNLESS(mitm_info->process_id == process_id, sm::ResultNotAllowed()); /* Uninstall the mitm. */ { /* Close mitm handles. */ os::CloseNativeHandle(mitm_info->port_h); os::CloseNativeHandle(mitm_info->query_h); os::CloseNativeHandle(mitm_info->fwd_sess_h); /* Reset mitm members. */ *mitm_info = InvalidMitmInfo; /* Reset service info. */ service_info->mitm_index = MitmCountMax; } R_SUCCEED(); } Result DeclareFutureMitm(os::ProcessId process_id, ServiceName service) { /* Acquire exclusive access to global state. */ std::scoped_lock lk(g_mutex); /* Validate service name. */ R_TRY(ValidateServiceName(service)); /* Check that the process is registered and allowed to register the service. */ if (!IsInitialProcess(process_id)) { ProcessInfo *proc = GetProcessInfo(process_id); R_UNLESS(proc != nullptr, sm::ResultInvalidClient()); R_TRY(ValidateAccessControl(AccessControlEntry(proc->access_control, proc->access_control_size), service, true, false)); } /* Check that mitm hasn't already been registered or declared. */ R_UNLESS(!HasMitm(service), sm::ResultAlreadyRegistered()); R_UNLESS(!HasFutureMitmDeclaration(service), sm::ResultAlreadyRegistered()); /* Try to forward declare it. */ R_TRY(AddFutureMitmDeclaration(service)); R_SUCCEED(); } Result ClearFutureMitm(os::ProcessId process_id, ServiceName service) { /* Acquire exclusive access to global state. */ std::scoped_lock lk(g_mutex); /* Validate service name. */ R_TRY(ValidateServiceName(service)); /* Check that the process is registered and allowed to register the service. */ if (!IsInitialProcess(process_id)) { ProcessInfo *proc = GetProcessInfo(process_id); R_UNLESS(proc != nullptr, sm::ResultInvalidClient()); R_TRY(ValidateAccessControl(AccessControlEntry(proc->access_control, proc->access_control_size), service, true, false)); } /* Validate that the service exists. */ ServiceInfo *service_info = GetServiceInfo(service); R_UNLESS(service_info != nullptr, sm::ResultNotRegistered()); /* Check that we have a mitm or a future declaration. */ if (MitmInfo *mitm_info = GetMitmInfo(service_info); mitm_info != nullptr) { /* Validate that the client process_id is the mitm process. */ R_UNLESS(mitm_info->process_id == process_id, sm::ResultNotAllowed()); } else { R_UNLESS(HasFutureMitmDeclaration(service), sm::ResultNotRegistered()); } /* Clear the forward declaration. */ ClearFutureMitmDeclaration(service); R_SUCCEED(); } Result AcknowledgeMitmSession(MitmProcessInfo *out_info, os::NativeHandle *out_hnd, os::ProcessId process_id, ServiceName service) { /* Acquire exclusive access to global state. */ std::scoped_lock lk(g_mutex); /* Validate service name. */ R_TRY(ValidateServiceName(service)); /* Check that the process is registered. */ if (!IsInitialProcess(process_id)) { ProcessInfo *proc = GetProcessInfo(process_id); R_UNLESS(proc != nullptr, sm::ResultInvalidClient()); } /* Validate that the service exists. */ ServiceInfo *service_info = GetServiceInfo(service); R_UNLESS(service_info != nullptr, sm::ResultNotRegistered()); /* Get the mitm info. */ MitmInfo *mitm_info = GetMitmInfo(service_info); R_UNLESS(mitm_info != nullptr, sm::ResultNotRegistered()); /* Validate that the client process_id is the mitm process, and that an acknowledgement is waiting. */ R_UNLESS(mitm_info->process_id == process_id, sm::ResultNotAllowed()); R_UNLESS(mitm_info->waiting_ack, sm::ResultNotAllowed()); /* Acknowledge. */ { /* Copy the mitm info to output. */ GetMitmProcessInfo(out_info, mitm_info->waiting_ack_process_id); /* Set the output handle. */ *out_hnd = mitm_info->fwd_sess_h; mitm_info->fwd_sess_h = os::InvalidNativeHandle; /* Clear acknowledgement-related fields. */ mitm_info->waiting_ack = false; mitm_info->waiting_ack_process_id = os::InvalidProcessId; } /* Undefer requests to the session. */ TriggerResume(service); R_SUCCEED(); } /* Deferral extension (works around FS bug). */ Result EndInitialDefers() { /* Acquire exclusive access to global state. */ std::scoped_lock lk(g_mutex); /* Note that we have ended the initial deferral period. */ const bool had_ended_defers = g_ended_initial_defers; g_ended_initial_defers = true; /* Something about deferral state has changed, so we should refresh our hos version. */ hos::InitializeVersionInternal(!had_ended_defers); /* This might undefer some requests. */ for (const auto &service_name : InitiallyDeferredServices) { TriggerResume(service_name); } R_SUCCEED(); } }
37,207
C++
.cpp
746
38.136729
204
0.585214
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,141
fatal_scoped_file.cpp
Atmosphere-NX_Atmosphere/stratosphere/fatal/source/fatal_scoped_file.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have 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 "fatal_scoped_file.hpp" namespace ams::fatal::srv { namespace { /* Convenience definitions. */ constexpr size_t MaximumLineLength = 0x20; constinit os::SdkMutex g_format_lock; constinit char g_format_buffer[2 * os::MemoryPageSize]; } void ScopedFile::WriteString(const char *str) { this->Write(str, std::strlen(str)); } void ScopedFile::WriteFormat(const char *fmt, ...) { /* Acquire exclusive access to the format buffer. */ std::scoped_lock lk(g_format_lock); /* Format to the buffer. */ { std::va_list vl; va_start(vl, fmt); util::VSNPrintf(g_format_buffer, sizeof(g_format_buffer), fmt, vl); va_end(vl); } /* Write data. */ this->WriteString(g_format_buffer); } void ScopedFile::DumpMemory(const char *prefix, const void *data, size_t size) { const u8 *data_u8 = reinterpret_cast<const u8 *>(data); const int prefix_len = std::strlen(prefix); size_t data_ofs = 0; size_t remaining = size; bool first = true; while (remaining) { const size_t cur_size = std::min(MaximumLineLength, remaining); /* Print the line prefix. */ if (first) { this->WriteFormat("%s", prefix); first = false; } else { this->WriteFormat("%*s", prefix_len, ""); } /* Dump up to 0x20 of hex memory. */ { char hex[MaximumLineLength * 2 + 2] = {}; for (size_t i = 0; i < cur_size; i++) { util::SNPrintf(hex + i * 2, 3, "%02X", data_u8[data_ofs++]); } hex[cur_size * 2 + 0] = '\n'; hex[cur_size * 2 + 1] = '\x00'; this->WriteString(hex); } /* Continue. */ remaining -= cur_size; } } void ScopedFile::Write(const void *data, size_t size) { /* If we're not open, we can't write. */ if (!this->IsOpen()) { return; } /* Advance, if we write successfully. */ if (R_SUCCEEDED(fs::WriteFile(m_file, m_offset, data, size, fs::WriteOption::Flush))) { m_offset += size; } } }
3,022
C++
.cpp
80
28.9375
95
0.564786
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,142
fatal_config.cpp
Atmosphere-NX_Atmosphere/stratosphere/fatal/source/fatal_config.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "fatal_config.hpp" namespace ams::fatal::srv { namespace { /* Global config. */ constinit os::SdkMutex g_config_mutex; constinit bool g_initialized_config; constinit util::TypedStorage<FatalConfig> g_config; FatalConfig &GetFatalConfigImpl() { if (AMS_UNLIKELY(!g_initialized_config)) { std::scoped_lock lk(g_config_mutex); if (AMS_LIKELY(!g_initialized_config)) { util::ConstructAt(g_config); g_initialized_config = true; } } return util::GetReference(g_config); } /* Event creator. */ os::NativeHandle GetFatalDirtyEventReadableHandle() { Event evt; R_ABORT_UNLESS(setsysAcquireFatalDirtyFlagEventHandle(std::addressof(evt))); return evt.revent; } /* Global event. */ constinit os::SystemEventType g_fatal_dirty_event; constinit os::MultiWaitHolderType g_fatal_dirty_multi_wait_holder; constinit bool g_initialized_fatal_dirty_event; } os::MultiWaitHolderType *GetFatalDirtyMultiWaitHolder() { if (AMS_UNLIKELY(!g_initialized_fatal_dirty_event)) { os::AttachReadableHandleToSystemEvent(std::addressof(g_fatal_dirty_event), GetFatalDirtyEventReadableHandle(), true, os::EventClearMode_ManualClear); os::InitializeMultiWaitHolder(std::addressof(g_fatal_dirty_multi_wait_holder), std::addressof(g_fatal_dirty_event)); os::SetMultiWaitHolderUserData(std::addressof(g_fatal_dirty_multi_wait_holder), reinterpret_cast<uintptr_t>(std::addressof(g_fatal_dirty_multi_wait_holder))); g_initialized_fatal_dirty_event = true; } return std::addressof(g_fatal_dirty_multi_wait_holder); } void OnFatalDirtyEvent() { os::ClearSystemEvent(std::addressof(g_fatal_dirty_event)); u64 flags_0, flags_1; if (R_SUCCEEDED(setsysGetFatalDirtyFlags(std::addressof(flags_0), std::addressof(flags_1))) && (flags_0 & 1)) { GetFatalConfigImpl().UpdateLanguageCode(); } } FatalConfig::FatalConfig() { /* Get information from set. */ settings::system::GetSerialNumber(std::addressof(m_serial_number)); settings::system::GetFirmwareVersion(std::addressof(m_firmware_version)); setsysGetQuestFlag(std::addressof(m_quest_flag)); this->UpdateLanguageCode(); /* Read information from settings. */ settings::fwdbg::GetSettingsItemValue(std::addressof(m_transition_to_fatal), sizeof(m_transition_to_fatal), "fatal", "transition_to_fatal"); settings::fwdbg::GetSettingsItemValue(std::addressof(m_show_extra_info), sizeof(m_show_extra_info), "fatal", "show_extra_info"); u64 quest_interval_second; settings::fwdbg::GetSettingsItemValue(std::addressof(quest_interval_second), sizeof(quest_interval_second), "fatal", "quest_reboot_interval_second"); m_quest_reboot_interval = TimeSpan::FromSeconds(quest_interval_second); /* Atmosphere extension for automatic reboot. */ u64 auto_reboot_ms; if (settings::fwdbg::GetSettingsItemValue(std::addressof(auto_reboot_ms), sizeof(auto_reboot_ms), "atmosphere", "fatal_auto_reboot_interval") == sizeof(auto_reboot_ms)) { m_fatal_auto_reboot_interval = TimeSpan::FromMilliSeconds(auto_reboot_ms); m_fatal_auto_reboot_enabled = auto_reboot_ms != 0; } /* Setup messages. */ { m_error_msg = "Error Code: 2%03d-%04d (0x%x)\n"; m_error_desc = "An error has occurred.\n\n" "Please press the POWER Button to restart the console normally, or a VOL button\n" "to reboot to a payload (or RCM, if none is present). If you are unable to\n" "restart the console, hold the POWER Button for 12 seconds to turn the console off.\n\n" "If the problem persists, refer to the Nintendo Support Website.\n" "support.nintendo.com/switch/error\n"; /* If you're running Atmosphere on a quest unit for some reason, talk to me on discord. */ m_quest_desc = "Please call 1-800-875-1852 for service.\n\n" "Also, please be aware that running Atmosphere on a Quest device is not fully\n" "supported. Perhaps try booting your device without Atmosphere before calling\n" "an official Nintendo service hotline. If you encounter further issues, please\n" "contact SciresM#0524 on Discord, or via some other means.\n"; /* TODO: Try to load dynamically? */ /* FsStorage message_storage; */ /* TODO: if (R_SUCCEEDED(fsOpenDataStorageByDataId(0x010000000000081D, "fatal_msg"))) { ... } */ } } const FatalConfig &GetFatalConfig() { return GetFatalConfigImpl(); } }
5,744
C++
.cpp
102
45.892157
178
0.647739
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,143
fatal_task_error_report.cpp
Atmosphere-NX_Atmosphere/stratosphere/fatal/source/fatal_task_error_report.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "fatal_config.hpp" #include "fatal_task_error_report.hpp" #include "fatal_scoped_file.hpp" namespace ams::fatal::srv { namespace { /* Helpers. */ void TryEnsureReportDirectories() { fs::EnsureDirectory("sdmc:/atmosphere/fatal_reports/dumps"); } bool TryGetCurrentTimestamp(u64 *out) { /* Clear output. */ *out = 0; /* Check if we have time service. */ { bool has_time_service = false; if (R_FAILED(sm::HasService(std::addressof(has_time_service), sm::ServiceName::Encode("time:s"))) || !has_time_service) { return false; } } /* Try to get the current time. */ { if (R_FAILED(::timeInitialize())) { return false; } ON_SCOPE_EXIT { ::timeExit(); }; return R_SUCCEEDED(::timeGetCurrentTime(TimeType_LocalSystemClock, out)); } } /* Task definition. */ class ErrorReportTask : public ITaskWithDefaultStack { private: void SaveReportToSdCard(); public: virtual Result Run() override; virtual const char *GetName() const override { return "WriteErrorReport"; } }; /* Task globals. */ ErrorReportTask g_error_report_task; /* Task Implementation. */ void ErrorReportTask::SaveReportToSdCard() { char file_path[fs::EntryNameLengthMax + 1]; /* Try to Ensure path exists. */ TryEnsureReportDirectories(); /* Get a timestamp. */ u64 timestamp; if (!TryGetCurrentTimestamp(std::addressof(timestamp))) { timestamp = os::GetSystemTick().GetInt64Value(); } /* Open report file. */ { util::SNPrintf(file_path, sizeof(file_path) - 1, "sdmc:/atmosphere/fatal_reports/%011lu_%016lx.log", timestamp, static_cast<u64>(m_context->program_id)); ScopedFile file(file_path); if (file.IsOpen()) { file.WriteFormat("Atmosphère Fatal Report (v1.1):\n"); file.WriteFormat("Result: 0x%X (2%03d-%04d)\n\n", m_context->result.GetValue(), m_context->result.GetModule(), m_context->result.GetDescription()); file.WriteFormat("Program ID: %016lx\n", static_cast<u64>(m_context->program_id)); if (strlen(m_context->proc_name)) { file.WriteFormat("Process Name: %s\n", m_context->proc_name); } file.WriteFormat("Firmware: %s (Atmosphère %u.%u.%u-%s)\n", GetFatalConfig().GetFirmwareVersion().display_version, ATMOSPHERE_RELEASE_VERSION, ams::GetGitRevision()); if (m_context->cpu_ctx.architecture == CpuContext::Architecture_Aarch32) { file.WriteFormat("General Purpose Registers:\n"); for (size_t i = 0; i <= aarch32::RegisterName_PC; i++) { if (m_context->cpu_ctx.aarch32_ctx.HasRegisterValue(static_cast<aarch32::RegisterName>(i))) { file.WriteFormat( " %3s: %08x\n", aarch32::CpuContext::RegisterNameStrings[i], m_context->cpu_ctx.aarch32_ctx.r[i]); } } file.WriteFormat("Start Address: %08x\n", m_context->cpu_ctx.aarch32_ctx.base_address); file.WriteFormat("Stack Trace:\n"); for (unsigned int i = 0; i < m_context->cpu_ctx.aarch32_ctx.stack_trace_size; i++) { file.WriteFormat(" ReturnAddress[%02u]: %08x\n", i, m_context->cpu_ctx.aarch32_ctx.stack_trace[i]); } } else { file.WriteFormat("General Purpose Registers:\n"); for (size_t i = 0; i <= aarch64::RegisterName_PC; i++) { if (m_context->cpu_ctx.aarch64_ctx.HasRegisterValue(static_cast<aarch64::RegisterName>(i))) { file.WriteFormat( " %3s: %016lx\n", aarch64::CpuContext::RegisterNameStrings[i], m_context->cpu_ctx.aarch64_ctx.x[i]); } } file.WriteFormat("Start Address: %016lx\n", m_context->cpu_ctx.aarch64_ctx.base_address); file.WriteFormat("Stack Trace:\n"); for (unsigned int i = 0; i < m_context->cpu_ctx.aarch64_ctx.stack_trace_size; i++) { file.WriteFormat(" ReturnAddress[%02u]: %016lx\n", i, m_context->cpu_ctx.aarch64_ctx.stack_trace[i]); } } if (m_context->stack_dump_size != 0) { file.WriteFormat("Stack Dump: 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f\n"); for (size_t i = 0; i < 0x10; i++) { const size_t ofs = i * 0x10; file.WriteFormat(" %012lx %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x\n", m_context->stack_dump_base + ofs, m_context->stack_dump[ofs + 0], m_context->stack_dump[ofs + 1], m_context->stack_dump[ofs + 2], m_context->stack_dump[ofs + 3], m_context->stack_dump[ofs + 4], m_context->stack_dump[ofs + 5], m_context->stack_dump[ofs + 6], m_context->stack_dump[ofs + 7], m_context->stack_dump[ofs + 8], m_context->stack_dump[ofs + 9], m_context->stack_dump[ofs + 10], m_context->stack_dump[ofs + 11], m_context->stack_dump[ofs + 12], m_context->stack_dump[ofs + 13], m_context->stack_dump[ofs + 14], m_context->stack_dump[ofs + 15]); } } if (m_context->tls_address != 0) { file.WriteFormat("TLS Address: %016lx\n", m_context->tls_address); file.WriteFormat("TLS Dump: 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f\n"); for (size_t i = 0; i < 0x10; i++) { const size_t ofs = i * 0x10; file.WriteFormat(" %012lx %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x\n", m_context->tls_address + ofs, m_context->tls_dump[ofs + 0], m_context->tls_dump[ofs + 1], m_context->tls_dump[ofs + 2], m_context->tls_dump[ofs + 3], m_context->tls_dump[ofs + 4], m_context->tls_dump[ofs + 5], m_context->tls_dump[ofs + 6], m_context->tls_dump[ofs + 7], m_context->tls_dump[ofs + 8], m_context->tls_dump[ofs + 9], m_context->tls_dump[ofs + 10], m_context->tls_dump[ofs + 11], m_context->tls_dump[ofs + 12], m_context->tls_dump[ofs + 13], m_context->tls_dump[ofs + 14], m_context->tls_dump[ofs + 15]); } } } } /* Dump data to file. */ { util::SNPrintf(file_path, sizeof(file_path) - 1, "sdmc:/atmosphere/fatal_reports/dumps/%011lu_%016lx.bin", timestamp, static_cast<u64>(m_context->program_id)); ScopedFile file(file_path); if (file.IsOpen()) { file.Write(m_context->tls_dump, sizeof(m_context->tls_dump)); if (m_context->stack_dump_size) { file.Write(m_context->stack_dump, m_context->stack_dump_size); } } } } Result ErrorReportTask::Run() { if (m_context->generate_error_report) { /* Here, Nintendo creates an error report with erpt. AMS will not do that. */ } /* Save report to SD card. */ if (!m_context->is_creport) { this->SaveReportToSdCard(); } /* Signal we're done with our job. */ m_context->erpt_event->Signal(); R_SUCCEED(); } } ITask *GetErrorReportTask(const ThrowContext *ctx) { g_error_report_task.Initialize(ctx); return std::addressof(g_error_report_task); } }
9,416
C++
.cpp
154
44.993506
321
0.510125
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,144
fatal_repair.cpp
Atmosphere-NX_Atmosphere/stratosphere/fatal/source/fatal_repair.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have 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 "fatal_repair.hpp" #include "fatal_service_for_self.hpp" namespace ams::fatal::srv { namespace { bool IsInRepair() { /* Before firmware 3.0.0, this wasn't implemented. */ if (hos::GetVersion() < hos::Version_3_0_0) { return false; } bool in_repair; return R_SUCCEEDED(setsysGetInRepairProcessEnableFlag(std::addressof(in_repair))) && in_repair; } bool IsInRepairWithoutVolHeld() { if (IsInRepair()) { gpio::GpioPadSession vol_btn; if (R_FAILED(gpio::OpenSession(std::addressof(vol_btn), gpio::DeviceCode_ButtonVolUp))) { return true; } /* Ensure we close even on early return. */ ON_SCOPE_EXIT { gpio::CloseSession(std::addressof(vol_btn)); }; /* Set direction input. */ gpio::SetDirection(std::addressof(vol_btn), gpio::Direction_Input); /* Ensure that we're holding the volume button for a full second. */ auto start = os::GetSystemTick(); do { if (gpio::GetValue(std::addressof(vol_btn)) != gpio::GpioValue_Low) { return true; } /* Sleep for 100 ms. */ os::SleepThread(TimeSpan::FromMilliSeconds(100)); } while (os::ConvertToTimeSpan(os::GetSystemTick() - start) < TimeSpan::FromSeconds(1)); } return false; } bool NeedsRunTimeReviser() { /* Before firmware 5.0.0, this wasn't implemented. */ if (hos::GetVersion() < hos::Version_5_0_0) { return false; } bool requires_time_reviser; return R_SUCCEEDED(setsysGetRequiresRunRepairTimeReviser(std::addressof(requires_time_reviser))) && requires_time_reviser; } bool IsTimeReviserCartridgeInserted() { FsGameCardHandle gc_hnd; u8 gc_attr; { FsDeviceOperator devop; if (R_FAILED(fsOpenDeviceOperator(std::addressof(devop)))) { return false; } /* Ensure we close even on early return. */ ON_SCOPE_EXIT { fsDeviceOperatorClose(std::addressof(devop)); }; /* Check that a gamecard is inserted. */ bool inserted; if (R_FAILED(fsDeviceOperatorIsGameCardInserted(std::addressof(devop), std::addressof(inserted))) || !inserted) { return false; } /* Check that we can retrieve the gamecard's attributes. */ if (R_FAILED(fsDeviceOperatorGetGameCardHandle(std::addressof(devop), std::addressof(gc_hnd))) || R_FAILED(fsDeviceOperatorGetGameCardAttribute(std::addressof(devop), std::addressof(gc_hnd), std::addressof(gc_attr)))) { return false; } } /* Check that the gamecard is a repair tool. */ return (gc_attr & FsGameCardAttribute_RepairToolFlag); } bool IsInRepairWithoutTimeReviserCartridge() { return NeedsRunTimeReviser() && IsTimeReviserCartridgeInserted(); } } void CheckRepairStatus() { if (IsInRepairWithoutVolHeld()) { ThrowFatalForSelf(ResultInRepairWithoutVolHeld()); } if (IsInRepairWithoutTimeReviserCartridge()) { ThrowFatalForSelf(ResultInRepairWithoutTimeReviserCartridge()); } } }
4,307
C++
.cpp
94
34.053191
235
0.589358
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,145
fatal_service.cpp
Atmosphere-NX_Atmosphere/stratosphere/fatal/source/fatal_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 "fatal_config.hpp" #include "fatal_debug.hpp" #include "fatal_service.hpp" #include "fatal_service_for_self.hpp" #include "fatal_event_manager.hpp" #include "fatal_task.hpp" namespace ams::fatal::srv { namespace { /* Service Context. */ class ServiceContext { private: os::Event m_erpt_event; os::Event m_battery_event; ThrowContext m_context; FatalEventManager m_event_manager; bool m_has_thrown; private: Result TrySetHasThrown() { R_UNLESS(!m_has_thrown, fatal::ResultAlreadyThrown()); m_has_thrown = true; R_SUCCEED(); } public: ServiceContext() : m_erpt_event(os::EventClearMode_ManualClear), m_battery_event(os::EventClearMode_ManualClear), m_context(std::addressof(m_erpt_event), std::addressof(m_battery_event)), m_has_thrown(false) { /* ... */ } Result GetEvent(const os::SystemEventType **out) { R_RETURN(m_event_manager.GetEvent(out)); } Result GetThrowContext(Result *out_error, ncm::ProgramId *out_program_id, FatalPolicy *out_policy, CpuContext *out_ctx) { /* Set the output. */ *out_error = m_context.result; *out_program_id = m_context.throw_program_id; *out_policy = m_context.policy; *out_ctx = m_context.cpu_ctx; R_SUCCEED(); } Result ThrowFatal(Result result, os::ProcessId process_id) { R_RETURN(this->ThrowFatalWithCpuContext(result, process_id, FatalPolicy_ErrorReportAndErrorScreen, {})); } Result ThrowFatalWithPolicy(Result result, os::ProcessId process_id, FatalPolicy policy) { R_RETURN(this->ThrowFatalWithCpuContext(result, process_id, policy, {})); } Result ThrowFatalWithCpuContext(Result result, os::ProcessId process_id, FatalPolicy policy, const CpuContext &cpu_ctx); }; /* Context global. */ ServiceContext g_context; /* Throw implementation. */ Result ServiceContext::ThrowFatalWithCpuContext(Result result, os::ProcessId process_id, FatalPolicy policy, const CpuContext &cpu_ctx) { /* We don't support Error-Report-only fatals. */ R_SUCCEED_IF(policy == FatalPolicy_ErrorReport); /* Note that we've thrown fatal. */ R_TRY(this->TrySetHasThrown()); /* At this point we have exclusive access to m_context. */ m_context.result = result; m_context.cpu_ctx = cpu_ctx; m_context.policy = policy; /* Cap the stack trace to a sane limit. */ if (cpu_ctx.architecture == CpuContext::Architecture_Aarch64) { m_context.cpu_ctx.aarch64_ctx.stack_trace_size = std::max(size_t(m_context.cpu_ctx.aarch64_ctx.stack_trace_size), aarch64::CpuContext::MaxStackTraceDepth); } else { m_context.cpu_ctx.aarch32_ctx.stack_trace_size = std::max(size_t(m_context.cpu_ctx.aarch32_ctx.stack_trace_size), aarch32::CpuContext::MaxStackTraceDepth); } /* Get program id. */ pm::info::GetProgramId(std::addressof(m_context.throw_program_id), process_id); m_context.is_creport = (m_context.throw_program_id == ncm::SystemProgramId::Creport); if (!m_context.is_creport) { m_context.program_id = m_context.throw_program_id; /* On firmware version 2.0.0, use debugging SVCs to collect information. */ if (hos::GetVersion() >= hos::Version_2_0_0) { fatal::srv::TryCollectDebugInformation(std::addressof(m_context), process_id); } } else { /* We received info from creport. Parse program id from afsr0. */ if (cpu_ctx.architecture == CpuContext::Architecture_Aarch64) { m_context.program_id = cpu_ctx.aarch64_ctx.GetProgramIdForAtmosphere(); } else { m_context.program_id = cpu_ctx.aarch32_ctx.GetProgramIdForAtmosphere(); } } /* Decide whether to generate a report. */ m_context.generate_error_report = (policy == FatalPolicy_ErrorReportAndErrorScreen); /* Adjust error code (ResultSuccess()/2000-0000 -> err::ResultSystemProgramAbort()/2162-0002). */ if (R_SUCCEEDED(m_context.result)) { m_context.result = err::ResultSystemProgramAbort(); } switch (policy) { case FatalPolicy_ErrorReportAndErrorScreen: case FatalPolicy_ErrorScreen: /* Signal that we're throwing. */ m_event_manager.SignalEvents(); if (GetFatalConfig().ShouldTransitionToFatal()) { RunTasks(std::addressof(m_context)); } break; /* N aborts here. Should we just return an error code? */ AMS_UNREACHABLE_DEFAULT_CASE(); } R_SUCCEED(); } } Result ThrowFatalForSelf(Result result) { R_RETURN(g_context.ThrowFatalWithPolicy(result, os::GetCurrentProcessId(), FatalPolicy_ErrorScreen)); } Result Service::ThrowFatal(Result result, const sf::ClientProcessId &client_pid) { R_RETURN(g_context.ThrowFatal(result, client_pid.GetValue())); } Result Service::ThrowFatalWithPolicy(Result result, const sf::ClientProcessId &client_pid, FatalPolicy policy) { R_RETURN(g_context.ThrowFatalWithPolicy(result, client_pid.GetValue(), policy)); } Result Service::ThrowFatalWithCpuContext(Result result, const sf::ClientProcessId &client_pid, FatalPolicy policy, const CpuContext &cpu_ctx) { R_RETURN(g_context.ThrowFatalWithCpuContext(result, client_pid.GetValue(), policy, cpu_ctx)); } Result Service::GetFatalEvent(sf::OutCopyHandle out_h) { const os::SystemEventType *event; R_TRY(g_context.GetEvent(std::addressof(event))); out_h.SetValue(os::GetReadableHandleOfSystemEvent(event), false); R_SUCCEED(); } Result Service::GetFatalContext(sf::Out<Result> out_error, sf::Out<ncm::ProgramId> out_program_id, sf::Out<fatal::FatalPolicy> out_policy, sf::Out<fatal::CpuContext> out_ctx) { R_RETURN(g_context.GetThrowContext(out_error.GetPointer(), out_program_id.GetPointer(), out_policy.GetPointer(), out_ctx.GetPointer())); } }
7,566
C++
.cpp
142
40.915493
180
0.605761
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,146
fatal_task.cpp
Atmosphere-NX_Atmosphere/stratosphere/fatal/source/fatal_task.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "fatal_task.hpp" #include "fatal_task_error_report.hpp" #include "fatal_task_screen.hpp" #include "fatal_task_sound.hpp" #include "fatal_task_clock.hpp" #include "fatal_task_power.hpp" namespace ams::fatal::srv { namespace { class TaskThread { NON_COPYABLE(TaskThread); private: os::ThreadType m_thread; private: static void RunTaskImpl(void *arg) { ITask *task = reinterpret_cast<ITask *>(arg); if (R_FAILED(task->Run())) { /* TODO: Log task failure, somehow? */ } } public: TaskThread() { /* ... */ } void StartTask(ITask *task) { R_ABORT_UNLESS(os::CreateThread(std::addressof(m_thread), RunTaskImpl, task, task->GetStack(), task->GetStackSize(), AMS_GET_SYSTEM_THREAD_PRIORITY(fatalsrv, FatalTaskThread), 3)); os::SetThreadNamePointer(std::addressof(m_thread), AMS_GET_SYSTEM_THREAD_NAME(fatalsrv, FatalTaskThread)); os::StartThread(std::addressof(m_thread)); } }; class TaskManager { NON_COPYABLE(TaskManager); private: static constexpr size_t MaxTasks = 8; private: TaskThread m_task_threads[MaxTasks]; size_t m_task_count = 0; public: TaskManager() { /* ... */ } void StartTask(ITask *task) { AMS_ABORT_UNLESS(m_task_count < MaxTasks); m_task_threads[m_task_count++].StartTask(task); } }; /* Global task manager. */ TaskManager g_task_manager; } void RunTasks(const ThrowContext *ctx) { g_task_manager.StartTask(GetErrorReportTask(ctx)); g_task_manager.StartTask(GetPowerControlTask(ctx)); g_task_manager.StartTask(GetShowFatalTask(ctx)); g_task_manager.StartTask(GetStopSoundTask(ctx)); g_task_manager.StartTask(GetBacklightControlTask(ctx)); g_task_manager.StartTask(GetAdjustClockTask(ctx)); g_task_manager.StartTask(GetPowerButtonObserveTask(ctx)); g_task_manager.StartTask(GetStateTransitionStopTask(ctx)); } }
3,005
C++
.cpp
71
32.535211
200
0.611491
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,147
fatal_task_power.cpp
Atmosphere-NX_Atmosphere/stratosphere/fatal/source/fatal_task_power.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have 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 "fatal_config.hpp" #include "fatal_task_power.hpp" namespace ams::fatal::srv { namespace { /* Task types. */ class PowerControlTask : public ITaskWithDefaultStack { private: bool TryShutdown(); void MonitorBatteryState(); public: virtual Result Run() override; virtual const char *GetName() const override { return "PowerControlTask"; } }; class PowerButtonObserveTask : public ITaskWithDefaultStack { private: void WaitForPowerButton(); public: virtual Result Run() override; virtual const char *GetName() const override { return "PowerButtonObserveTask"; } }; class StateTransitionStopTask : public ITaskWithDefaultStack { public: virtual Result Run() override; virtual const char *GetName() const override { return "StateTransitionStopTask"; } }; class RebootTimingObserver { private: os::Tick m_start_tick; TimeSpan m_interval; bool m_flag; public: RebootTimingObserver(bool flag, TimeSpan iv) : m_start_tick(os::GetSystemTick()), m_interval(iv), m_flag(flag) { /* ... */ } bool IsRebootTiming() const { auto current_tick = os::GetSystemTick(); return m_flag && (current_tick - m_start_tick).ToTimeSpan() >= m_interval; } }; /* Task globals. */ PowerControlTask g_power_control_task; PowerButtonObserveTask g_power_button_observe_task; StateTransitionStopTask g_state_transition_stop_task; /* Task Implementations. */ bool PowerControlTask::TryShutdown() { /* Set a timeout of 30 seconds. */ constexpr auto MaxShutdownWaitInterval = TimeSpan::FromSeconds(30); auto start_tick = os::GetSystemTick(); bool perform_shutdown = true; PsmBatteryVoltageState bv_state = PsmBatteryVoltageState_Normal; while (true) { auto cur_tick = os::GetSystemTick(); if ((cur_tick - start_tick).ToTimeSpan() > MaxShutdownWaitInterval) { break; } if (R_FAILED(psmGetBatteryVoltageState(std::addressof(bv_state))) || bv_state == PsmBatteryVoltageState_NeedsShutdown) { break; } if (bv_state == PsmBatteryVoltageState_Normal) { perform_shutdown = false; break; } /* Query voltage state every 1 seconds, for 30 seconds. */ os::SleepThread(TimeSpan::FromSeconds(1)); } if (perform_shutdown) { bpcShutdownSystem(); } return perform_shutdown; } void PowerControlTask::MonitorBatteryState() { PsmBatteryVoltageState bv_state = PsmBatteryVoltageState_Normal; /* Check the battery state, and shutdown on low voltage. */ if (R_FAILED(psmGetBatteryVoltageState(std::addressof(bv_state))) || bv_state == PsmBatteryVoltageState_NeedsShutdown) { /* Wait a second for the error report task to finish. */ m_context->erpt_event->TimedWait(TimeSpan::FromSeconds(1)); this->TryShutdown(); return; } /* Signal we've checked the battery at least once. */ m_context->battery_event->Signal(); /* Loop querying voltage state every 5 seconds. */ while (true) { if (R_FAILED(psmGetBatteryVoltageState(std::addressof(bv_state)))) { bv_state = PsmBatteryVoltageState_NeedsShutdown; } switch (bv_state) { case PsmBatteryVoltageState_NeedsShutdown: case PsmBatteryVoltageState_NeedsSleep: { bool shutdown = this->TryShutdown(); if (shutdown) { return; } } break; default: break; } os::SleepThread(TimeSpan::FromSeconds(5)); } } bool IsPowerButtonHeld() { if (hos::GetVersion() >= hos::Version_14_0_0) { bool held = false; return R_SUCCEEDED(bpcGetPowerButton(std::addressof(held))) && held; } else if (hos::GetVersion() >= hos::Version_2_0_0) { BpcSleepButtonState state; return R_SUCCEEDED(bpcGetSleepButtonState(std::addressof(state))) && state == BpcSleepButtonState_Held; } else { return false; } } void PowerButtonObserveTask::WaitForPowerButton() { /* Wait up to a second for error report generation to finish. */ m_context->erpt_event->TimedWait(TimeSpan::FromSeconds(1)); /* Force a reboot after some time if kiosk unit. */ const auto &config = GetFatalConfig(); RebootTimingObserver quest_reboot_helper(config.IsQuest(), config.GetQuestRebootTimeoutInterval()); RebootTimingObserver fatal_reboot_helper(config.IsFatalRebootEnabled(), config.GetFatalRebootTimeoutInterval()); bool check_vol_up = true, check_vol_down = true; gpio::GpioPadSession vol_up_btn, vol_down_btn; if (R_FAILED(gpio::OpenSession(std::addressof(vol_up_btn), gpio::DeviceCode_ButtonVolUp))) { check_vol_up = false; } if (R_FAILED(gpio::OpenSession(std::addressof(vol_down_btn), gpio::DeviceCode_ButtonVolDn))) { check_vol_down = false; } /* Ensure we close on early return. */ ON_SCOPE_EXIT { if (check_vol_up) { gpio::CloseSession(std::addressof(vol_up_btn)); } }; ON_SCOPE_EXIT { if (check_vol_down) { gpio::CloseSession(std::addressof(vol_down_btn)); } }; /* Set direction input. */ if (check_vol_up) { gpio::SetDirection(std::addressof(vol_up_btn), gpio::Direction_Input); } if (check_vol_down) { gpio::SetDirection(std::addressof(vol_down_btn), gpio::Direction_Input); } while (true) { if (fatal_reboot_helper.IsRebootTiming() || (quest_reboot_helper.IsRebootTiming()) || (check_vol_up && gpio::GetValue(std::addressof(vol_up_btn)) == gpio::GpioValue_Low) || (check_vol_down && gpio::GetValue(std::addressof(vol_down_btn)) == gpio::GpioValue_Low) || IsPowerButtonHeld()) { /* If any of the above conditions succeeded, we should reboot. */ bpcRebootSystem(); return; } /* Wait 100 ms between button checks. */ os::SleepThread(TimeSpan::FromMilliSeconds(100)); } } Result PowerControlTask::Run() { this->MonitorBatteryState(); R_SUCCEED(); } Result PowerButtonObserveTask::Run() { this->WaitForPowerButton(); R_SUCCEED(); } Result StateTransitionStopTask::Run() { /* Nintendo ignores the output of this call... */ spsmPutErrorState(); R_SUCCEED(); } } ITask *GetPowerControlTask(const ThrowContext *ctx) { g_power_control_task.Initialize(ctx); return std::addressof(g_power_control_task); } ITask *GetPowerButtonObserveTask(const ThrowContext *ctx) { g_power_button_observe_task.Initialize(ctx); return std::addressof(g_power_button_observe_task); } ITask *GetStateTransitionStopTask(const ThrowContext *ctx) { g_state_transition_stop_task.Initialize(ctx); return std::addressof(g_state_transition_stop_task); } }
9,120
C++
.cpp
201
31.885572
136
0.557608
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,148
fatal_font.cpp
Atmosphere-NX_Atmosphere/stratosphere/fatal/source/fatal_font.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have 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 "fatal_config.hpp" #include "fatal_font.hpp" namespace ams::fatal::srv::font { constinit lmem::HeapHandle g_font_heap_handle; void SetHeapMemory(void *memory, size_t memory_size) { g_font_heap_handle = lmem::CreateExpHeap(memory, memory_size, lmem::CreateOption_None); } void *AllocateForFont(size_t size) { return lmem::AllocateFromExpHeap(g_font_heap_handle, size); } void DeallocateForFont(void *p) { if (p != nullptr) { return lmem::FreeToExpHeap(g_font_heap_handle, p); } } } #define STBTT_assert(x) AMS_ASSERT(x) #define STBTT_malloc(x,u) ((void)(u),ams::fatal::srv::font::AllocateForFont(x)) #define STBTT_free(x,u) ((void)(u),ams::fatal::srv::font::DeallocateForFont(x)) #define STBTT_STATIC #define STB_TRUETYPE_IMPLEMENTATION #include "stb_truetype.h" #undef STBTT_STATIC #undef STB_TRUETYPE_IMPLEMENTATION #undef STBTT_malloc #undef STBTT_free #undef STBTT_assert /* Define color conversion macros. */ #define RGB888_TO_RGB565(r, g, b) ((((r >> 3) << 11) & 0xF800) | (((g >> 2) << 5) & 0x7E0) | ((b >> 3) & 0x1F)) #define RGB565_GET_R8(c) ((((c >> 11) & 0x1F) << 3) | ((c >> 13) & 7)) #define RGB565_GET_G8(c) ((((c >> 5) & 0x3F) << 2) | ((c >> 9) & 3)) #define RGB565_GET_B8(c) ((((c >> 0) & 0x1F) << 3) | ((c >> 2) & 7)) namespace ams::fatal::srv::font { namespace { /* Font state globals. */ u16 *g_frame_buffer = nullptr; u32 (*g_unswizzle_func)(u32, u32) = nullptr; u16 g_font_color = 0xFFFF; /* White. */ float g_font_line_pixels = 16.0f; float g_font_size = 16.0f; u32 g_line_x = 0, g_cur_x = 0, g_cur_y = 0; u32 g_mono_adv = 0; PlFontData g_font; stbtt_fontinfo g_stb_font; /* Helpers. */ u16 Blend(u16 color, u16 bg, u8 alpha) { const u32 c_r = RGB565_GET_R8(color); const u32 c_g = RGB565_GET_G8(color); const u32 c_b = RGB565_GET_B8(color); const u32 b_r = RGB565_GET_R8(bg); const u32 b_g = RGB565_GET_G8(bg); const u32 b_b = RGB565_GET_B8(bg); const u32 r = ((alpha * c_r) + ((0xFF - alpha) * b_r)) / 0xFF; const u32 g = ((alpha * c_g) + ((0xFF - alpha) * b_g)) / 0xFF; const u32 b = ((alpha * c_b) + ((0xFF - alpha) * b_b)) / 0xFF; return RGB888_TO_RGB565(r, g, b); } void DrawCodePoint(u32 codepoint, u32 x, u32 y) { int width = 0, height = 0; u8* imageptr = stbtt_GetCodepointBitmap(std::addressof(g_stb_font), g_font_size, g_font_size, codepoint, std::addressof(width), std::addressof(height), 0, 0); ON_SCOPE_EXIT { DeallocateForFont(imageptr); }; for (int tmpy = 0; tmpy < height; tmpy++) { for (int tmpx = 0; tmpx < width; tmpx++) { /* Implement very simple blending, as the bitmap value is an alpha value. */ u16 *ptr = g_frame_buffer + g_unswizzle_func(x + tmpx, y + tmpy); *ptr = Blend(g_font_color, *ptr, imageptr[width * tmpy + tmpx]); } } } void DrawString(const char *str, bool add_line, bool mono = false) { const size_t len = strlen(str); u32 cur_x = g_cur_x, cur_y = g_cur_y; u32 prev_char = 0; for (u32 i = 0; i < len; ) { u32 cur_char; ssize_t unit_count = decode_utf8(std::addressof(cur_char), reinterpret_cast<const u8 *>(str + i)); if (unit_count <= 0) break; if (!g_mono_adv && i > 0) { cur_x += g_font_size * stbtt_GetCodepointKernAdvance(std::addressof(g_stb_font), prev_char, cur_char); } i += unit_count; if (cur_char == '\n') { cur_x = g_line_x; cur_y += g_font_line_pixels; continue; } int adv_width, left_side_bearing; stbtt_GetCodepointHMetrics(std::addressof(g_stb_font), cur_char, std::addressof(adv_width), std::addressof(left_side_bearing)); const u32 cur_width = static_cast<u32>(adv_width) * g_font_size; int x0, y0, x1, y1; stbtt_GetCodepointBitmapBoxSubpixel(std::addressof(g_stb_font), cur_char, g_font_size, g_font_size, 0, 0, std::addressof(x0), std::addressof(y0), std::addressof(x1), std::addressof(y1)); DrawCodePoint(cur_char, cur_x + x0 + ((mono && g_mono_adv > cur_width) ? ((g_mono_adv - cur_width) / 2) : 0), cur_y + y0); cur_x += (mono ? g_mono_adv : cur_width); prev_char = cur_char; } if (add_line) { /* Advance to next line. */ g_cur_x = g_line_x; g_cur_y = cur_y + g_font_line_pixels; } else { g_cur_x = cur_x; g_cur_y = cur_y; } } } void PrintLine(const char *str) { return DrawString(str, true); } void PrintFormatLine(const char *format, ...) { char char_buf[0x400]; std::va_list va_arg; va_start(va_arg, format); util::VSNPrintf(char_buf, sizeof(char_buf), format, va_arg); va_end(va_arg); PrintLine(char_buf); } void Print(const char *str) { return DrawString(str, false); } void PrintFormat(const char *format, ...) { char char_buf[0x400]; std::va_list va_arg; va_start(va_arg, format); util::VSNPrintf(char_buf, sizeof(char_buf), format, va_arg); va_end(va_arg); Print(char_buf); } void PrintMonospaceU64(u64 x) { char char_buf[0x400]; util::SNPrintf(char_buf, sizeof(char_buf), "%016lX", x); DrawString(char_buf, false, true); } void PrintMonospaceU32(u32 x) { char char_buf[0x400]; util::SNPrintf(char_buf, sizeof(char_buf), "%08X", x); DrawString(char_buf, false, true); } void PrintMonospaceBlank(u32 width) { char char_buf[0x400] = {0}; std::memset(char_buf, ' ', std::min(size_t(width), sizeof(char_buf))); DrawString(char_buf, false, true); } void SetFontColor(u16 color) { g_font_color = color; } void SetPosition(u32 x, u32 y) { g_line_x = x; g_cur_x = x; g_cur_y = y; } u32 GetX() { return g_cur_x; } u32 GetY() { return g_cur_y; } void SetFontSize(float fsz) { g_font_size = stbtt_ScaleForPixelHeight(std::addressof(g_stb_font), fsz * 1.375); int ascent; stbtt_GetFontVMetrics(std::addressof(g_stb_font), std::addressof(ascent),0,0); g_font_line_pixels = ascent * g_font_size * 1.125; int adv_width, left_side_bearing; stbtt_GetCodepointHMetrics(std::addressof(g_stb_font), 'A', std::addressof(adv_width), std::addressof(left_side_bearing)); g_mono_adv = adv_width * g_font_size; } void AddSpacingLines(float num_lines) { g_cur_x = g_line_x; g_cur_y += static_cast<u32>(g_font_line_pixels * num_lines); } void ConfigureFontFramebuffer(u16 *fb, u32 (*unswizzle_func)(u32, u32)) { g_frame_buffer = fb; g_unswizzle_func = unswizzle_func; } Result InitializeSharedFont() { R_TRY(plGetSharedFontByType(std::addressof(g_font), PlSharedFontType_Standard)); u8 *font_buffer = reinterpret_cast<u8 *>(g_font.address); stbtt_InitFont(std::addressof(g_stb_font), font_buffer, stbtt_GetFontOffsetForIndex(font_buffer, 0)); SetFontSize(16.0f); R_SUCCEED(); } }
8,471
C++
.cpp
197
34.096447
202
0.571307
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,149
fatal_event_manager.cpp
Atmosphere-NX_Atmosphere/stratosphere/fatal/source/fatal_event_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 "fatal_event_manager.hpp" namespace ams::fatal::srv { FatalEventManager::FatalEventManager() : m_lock() { /* Just create all the events. */ for (size_t i = 0; i < FatalEventManager::NumFatalEvents; i++) { R_ABORT_UNLESS(os::CreateSystemEvent(std::addressof(m_events[i]), os::EventClearMode_AutoClear, true)); } } Result FatalEventManager::GetEvent(const os::SystemEventType **out) { std::scoped_lock lk{m_lock}; /* Only allow GetEvent to succeed NumFatalEvents times. */ R_UNLESS(m_num_events_gotten < FatalEventManager::NumFatalEvents, fatal::ResultTooManyEvents()); *out = std::addressof(m_events[m_num_events_gotten++]); R_SUCCEED(); } void FatalEventManager::SignalEvents() { for (size_t i = 0; i < FatalEventManager::NumFatalEvents; i++) { os::SignalSystemEvent(std::addressof(m_events[i])); } } }
1,610
C++
.cpp
37
38.486486
115
0.690932
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,150
fatal_main.cpp
Atmosphere-NX_Atmosphere/stratosphere/fatal/source/fatal_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 "fatal_service.hpp" #include "fatal_config.hpp" #include "fatal_repair.hpp" #include "fatal_font.hpp" /* Set libnx graphics globals. */ extern "C" { u32 __nx_nv_transfermem_size = 0x40000; ViLayerFlags __nx_vi_stray_layer_flags = (ViLayerFlags)0; } namespace ams { namespace fatal::srv { namespace { constinit u8 g_fs_heap_memory[2_KB]; lmem::HeapHandle g_fs_heap_handle; void *AllocateForFs(size_t size) { return lmem::AllocateFromExpHeap(g_fs_heap_handle, size); } void DeallocateForFs(void *p, size_t size) { AMS_UNUSED(size); return lmem::FreeToExpHeap(g_fs_heap_handle, p); } void InitializeFsHeap() { g_fs_heap_handle = lmem::CreateExpHeap(g_fs_heap_memory, sizeof(g_fs_heap_memory), lmem::CreateOption_ThreadSafe); } } namespace { using ServerOptions = sf::hipc::DefaultServerManagerOptions; constexpr sm::ServiceName UserServiceName = sm::ServiceName::Encode("fatal:u"); constexpr size_t UserMaxSessions = 4; constexpr sm::ServiceName PrivateServiceName = sm::ServiceName::Encode("fatal:p"); constexpr size_t PrivateMaxSessions = 4; /* fatal:u, fatal:p. */ constexpr size_t NumServers = 2; constexpr size_t NumSessions = UserMaxSessions + PrivateMaxSessions; sf::hipc::ServerManager<NumServers, ServerOptions, NumSessions> g_server_manager; constinit sf::UnmanagedServiceObject<fatal::impl::IService, fatal::srv::Service> g_user_service_object; constinit sf::UnmanagedServiceObject<fatal::impl::IPrivateService, fatal::srv::Service> g_private_service_object; void InitializeAndLoopIpcServer() { /* Create services. */ R_ABORT_UNLESS(g_server_manager.RegisterObjectForServer(g_user_service_object.GetShared(), UserServiceName, UserMaxSessions)); R_ABORT_UNLESS(g_server_manager.RegisterObjectForServer(g_private_service_object.GetShared(), PrivateServiceName, PrivateMaxSessions)); /* Add dirty event holder. */ auto *dirty_event_holder = fatal::srv::GetFatalDirtyMultiWaitHolder(); g_server_manager.AddUserMultiWaitHolder(dirty_event_holder); /* Loop forever, servicing our services. */ /* Because fatal has a user wait holder, we need to specify how to process manually. */ while (auto *signaled_holder = g_server_manager.WaitSignaled()) { if (signaled_holder == dirty_event_holder) { /* Dirty event holder was signaled. */ fatal::srv::OnFatalDirtyEvent(); g_server_manager.AddUserMultiWaitHolder(signaled_holder); } else { /* A server/session was signaled. Have the manager handle it. */ R_ABORT_UNLESS(g_server_manager.Process(signaled_holder)); } } } } } namespace init { namespace { Result InitializePlatformServiceWithoutSessionCountForHomebrewCompatibility() { /* NOTE: This implements a hack, to keep a session to pl:u without counting against the global limit. */ /* This is done because as of 16.0.0, pl:u is the only way to get shared font access, and there are */ /* not enough sessions for all reasonable the clients when homebrew gets involved. */ /* Please do not do similar things for other services; this is a hack which may not always work, */ /* and which could cause problems in other contexts where the ServerManager doesn't have enough */ /* slots in truth. */ /* Initialize pl. */ R_ABORT_UNLESS(plInitialize(::PlServiceType_User)); /* Get the service session for pl. */ Service *srv = plGetServiceSession(); /* Next, create a clone. */ /* Because this doesn't go through sm, this does not count against the session limit. */ Service clone; R_TRY(serviceClone(srv, std::addressof(clone))); /* Next, close the pl service session from sm. */ /* This decrements the used session count by one, since the session is from sm. */ serviceClose(srv); /* HACK: replace the session with the clone we made, to restore functionality. */ *srv = clone; return 0; } } void InitializeSystemModule() { /* Initialize heap. */ fatal::srv::InitializeFsHeap(); /* Initialize our connection to sm. */ R_ABORT_UNLESS(sm::Initialize()); /* Initialize fs. */ fs::InitializeForSystem(); fs::SetAllocator(fatal::srv::AllocateForFs, fatal::srv::DeallocateForFs); fs::SetEnabledAutoAbort(false); /* Initialize other services we need. */ R_ABORT_UNLESS(setInitialize()); R_ABORT_UNLESS(setsysInitialize()); R_ABORT_UNLESS(pminfoInitialize()); R_ABORT_UNLESS(i2cInitialize()); R_ABORT_UNLESS(bpcInitialize()); if (hos::GetVersion() >= hos::Version_8_0_0) { R_ABORT_UNLESS(clkrstInitialize()); } else { R_ABORT_UNLESS(pcvInitialize()); } R_ABORT_UNLESS(psmInitialize()); R_ABORT_UNLESS(spsmInitialize()); R_ABORT_UNLESS(InitializePlatformServiceWithoutSessionCountForHomebrewCompatibility()); gpio::Initialize(); /* Mount the SD card. */ R_ABORT_UNLESS(fs::MountSdCard("sdmc")); } void FinalizeSystemModule() { /* ... */ } void Startup() { /* ... */ } } void Main() { /* Set thread name. */ os::SetThreadNamePointer(os::GetCurrentThread(), AMS_GET_SYSTEM_THREAD_NAME(fatal, Main)); AMS_ASSERT(os::GetThreadPriority(os::GetCurrentThread()) == AMS_GET_SYSTEM_THREAD_PRIORITY(fatal, Main)); /* Load shared font. */ R_ABORT_UNLESS(fatal::srv::font::InitializeSharedFont()); /* Check whether we should throw fatal due to repair process. */ fatal::srv::CheckRepairStatus(); /* Loop processing the IPC server. */ fatal::srv::InitializeAndLoopIpcServer(); } }
7,386
C++
.cpp
142
40.056338
151
0.605088
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,151
fatal_debug.cpp
Atmosphere-NX_Atmosphere/stratosphere/fatal/source/fatal_debug.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have 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 "fatal_debug.hpp" #include "fatal_config.hpp" namespace ams::fatal::srv { namespace { constexpr u32 SvcSendSyncRequestInstruction = 0xD4000421; struct StackFrame { u64 fp; u64 lr; }; constexpr inline size_t MaxThreads = 0x60; template<size_t MaxThreadCount> class ThreadTlsMapImpl { private: std::pair<u64, u64> m_map[MaxThreadCount]; size_t m_index; public: constexpr ThreadTlsMapImpl() : m_map(), m_index(0) { /* ... */ } constexpr void ResetThreadTlsMap() { m_index = 0; } constexpr void SetThreadTls(u64 thread_id, u64 tls) { if (m_index < util::size(m_map)) { m_map[m_index++] = std::make_pair(thread_id, tls); } } constexpr bool GetThreadTls(u64 *out, u64 thread_id) const { for (size_t i = 0; i < m_index; ++i) { if (m_map[i].first == thread_id) { *out = m_map[i].second; return true; } } return false; } }; using ThreadTlsMap = ThreadTlsMapImpl<MaxThreads>; constinit ThreadTlsMap g_thread_id_to_tls_map; bool IsThreadFatalCaller(Result result, os::NativeHandle debug_handle, u64 thread_id, u64 thread_tls_addr, svc::ThreadContext *thread_ctx) { /* Verify that the thread is running or waiting. */ { u64 _; u32 _thread_state; if (R_FAILED(svc::GetDebugThreadParam(&_, &_thread_state, debug_handle, thread_id, svc::DebugThreadParam_State))) { return false; } const auto thread_state = static_cast<svc::ThreadState>(_thread_state); if (thread_state != svc::ThreadState_Waiting && thread_state != svc::ThreadState_Running) { return false; } } /* Get the thread context. */ if (R_FAILED(svc::GetDebugThreadContext(thread_ctx, debug_handle, thread_id, svc::ThreadContextFlag_All))) { return false; } /* Try to read the current instruction. */ u32 insn; if (R_FAILED(svc::ReadDebugProcessMemory(reinterpret_cast<uintptr_t>(std::addressof(insn)), debug_handle, thread_ctx->pc, sizeof(insn)))) { return false; } /* If the instruction isn't svc::SendSyncRequest, it's not the fatal caller. */ if (insn != SvcSendSyncRequestInstruction) { return false; } /* Read in the fatal caller's TLS. */ u8 thread_tls[sizeof(svc::ThreadLocalRegion::message_buffer)]; if (R_FAILED(svc::ReadDebugProcessMemory(reinterpret_cast<uintptr_t>(thread_tls), debug_handle, thread_tls_addr, sizeof(thread_tls)))) { return false; } /* We want to parse the command the fatal caller sent. */ { const auto request = hipcParseRequest(thread_tls); const struct { CmifInHeader header; Result result; } *in_data = decltype(in_data)(request.data.data_words); static_assert(sizeof(*in_data) == 0x14, "InData!"); /* Fatal command takes in a PID, only one buffer max. */ if ((request.meta.type != CmifCommandType_Request && request.meta.type != CmifCommandType_RequestWithContext) || !request.meta.send_pid || request.meta.num_send_statics || request.meta.num_recv_statics || request.meta.num_recv_buffers || request.meta.num_exch_buffers || request.meta.num_copy_handles || request.meta.num_move_handles || request.meta.num_data_words < ((sizeof(*in_data) + 0x10) / sizeof(u32))) { return false; } if (in_data->header.magic != CMIF_IN_HEADER_MAGIC) { return false; } if (in_data->header.version > 1) { return false; } switch (in_data->header.command_id) { case 0: case 1: if (request.meta.num_send_buffers != 0) { return false; } break; case 2: if (request.meta.num_send_buffers != 1) { return false; } break; default: return false; } if (in_data->result.GetValue() != result.GetValue()) { return false; } } /* We found our caller. */ return true; } bool TryGuessBaseAddress(u64 *out_base_address, os::NativeHandle debug_handle, u64 guess) { svc::MemoryInfo mi; svc::PageInfo pi; if (R_FAILED(svc::QueryDebugProcessMemory(std::addressof(mi), std::addressof(pi), debug_handle, guess)) || mi.permission != svc::MemoryPermission_ReadExecute) { return false; } /* Iterate backwards until we find the memory before the code region. */ while (mi.base_address > 0) { if (R_FAILED(svc::QueryDebugProcessMemory(std::addressof(mi), std::addressof(pi), debug_handle, guess))) { return false; } if (mi.state == svc::MemoryState_Free) { /* Code region will be at the end of the unmapped region preceding it. */ *out_base_address = mi.base_address + mi.size; return true; } guess = mi.base_address - 4; } return false; } u64 GetBaseAddress(const ThrowContext *throw_ctx, const svc::ThreadContext *thread_ctx, os::NativeHandle debug_handle) { u64 base_address = 0; if (TryGuessBaseAddress(std::addressof(base_address), debug_handle, thread_ctx->pc)) { return base_address; } if (TryGuessBaseAddress(std::addressof(base_address), debug_handle, thread_ctx->lr)) { return base_address; } for (size_t i = 0; i < throw_ctx->cpu_ctx.aarch64_ctx.stack_trace_size; i++) { if (TryGuessBaseAddress(std::addressof(base_address), debug_handle, throw_ctx->cpu_ctx.aarch64_ctx.stack_trace[i])) { return base_address; } } return base_address; } } void TryCollectDebugInformation(ThrowContext *ctx, os::ProcessId process_id) { /* Try to debug the process. This may fail, if we called into ourself. */ os::NativeHandle debug_handle; if (R_FAILED(svc::DebugActiveProcess(std::addressof(debug_handle), process_id.value))) { return; } ON_SCOPE_EXIT { os::CloseNativeHandle(debug_handle); }; /* First things first, check if process is 64 bits, and get list of thread infos. */ g_thread_id_to_tls_map.ResetThreadTlsMap(); { bool got_create_process = false; svc::DebugEventInfo d; while (R_SUCCEEDED(svc::GetDebugEvent(std::addressof(d), debug_handle))) { switch (d.type) { case svc::DebugEvent_CreateProcess: ctx->cpu_ctx.architecture = (d.info.create_process.flags & 1) ? CpuContext::Architecture_Aarch64 : CpuContext::Architecture_Aarch32; std::memcpy(ctx->proc_name, d.info.create_process.name, sizeof(d.info.create_process.name)); got_create_process = true; break; case svc::DebugEvent_CreateThread: g_thread_id_to_tls_map.SetThreadTls(d.info.create_thread.thread_id, d.info.create_thread.tls_address); break; case svc::DebugEvent_Exception: case svc::DebugEvent_ExitProcess: case svc::DebugEvent_ExitThread: break; } } if (!got_create_process) { return; } } /* TODO: Try to collect information on 32-bit fatals. This shouldn't really matter for any real use case. */ if (ctx->cpu_ctx.architecture == CpuContext::Architecture_Aarch32) { return; } /* Welcome to hell. Here, we try to identify which thread called into fatal. */ bool found_fatal_caller = false; u64 thread_id = 0; u64 thread_tls = 0; svc::ThreadContext thread_ctx; { /* We start by trying to get a list of threads. */ s32 thread_count; u64 thread_ids[0x60]; if (R_FAILED(svc::GetThreadList(std::addressof(thread_count), thread_ids, 0x60, debug_handle))) { return; } /* We need to locate the thread that's called fatal. */ for (s32 i = 0; i < thread_count; i++) { const u64 cur_thread_id = thread_ids[i]; u64 cur_thread_tls; if (!g_thread_id_to_tls_map.GetThreadTls(std::addressof(cur_thread_tls), cur_thread_id)) { continue; } if (IsThreadFatalCaller(ctx->result, debug_handle, cur_thread_id, cur_thread_tls, std::addressof(thread_ctx))) { thread_id = cur_thread_id; thread_tls = cur_thread_tls; found_fatal_caller = true; break; } } if (!found_fatal_caller) { return; } } if (R_FAILED(svc::GetDebugThreadContext(std::addressof(thread_ctx), debug_handle, thread_id, svc::ThreadContextFlag_All))) { return; } /* Set register states. */ ctx->cpu_ctx.aarch64_ctx.SetRegisterValue(aarch64::RegisterName_FP, thread_ctx.fp); ctx->cpu_ctx.aarch64_ctx.SetRegisterValue(aarch64::RegisterName_LR, thread_ctx.lr); ctx->cpu_ctx.aarch64_ctx.SetRegisterValue(aarch64::RegisterName_SP, thread_ctx.sp); ctx->cpu_ctx.aarch64_ctx.SetRegisterValue(aarch64::RegisterName_PC, thread_ctx.pc); /* Parse a stack trace. */ u64 cur_fp = thread_ctx.fp; ctx->cpu_ctx.aarch64_ctx.stack_trace_size = 0; for (unsigned int i = 0; i < aarch64::CpuContext::MaxStackTraceDepth; i++) { /* Validate the current frame. */ if (cur_fp == 0 || (cur_fp & 0xF)) { break; } /* Read a new frame. */ StackFrame cur_frame = {}; if (R_FAILED(svc::ReadDebugProcessMemory(reinterpret_cast<uintptr_t>(std::addressof(cur_frame)), debug_handle, cur_fp, sizeof(StackFrame)))) { break; } /* Advance to the next frame. */ ctx->cpu_ctx.aarch64_ctx.stack_trace[ctx->cpu_ctx.aarch64_ctx.stack_trace_size++] = cur_frame.lr; cur_fp = cur_frame.fp; } /* Try to read up to 0x100 of stack. */ ctx->stack_dump_base = 0; for (size_t sz = 0x100; sz > 0; sz -= 0x10) { if (R_SUCCEEDED(svc::ReadDebugProcessMemory(reinterpret_cast<uintptr_t>(ctx->stack_dump), debug_handle, thread_ctx.sp, sz))) { ctx->stack_dump_base = thread_ctx.sp; ctx->stack_dump_size = sz; break; } } /* Try to read the first 0x100 of TLS. */ if (R_SUCCEEDED(svc::ReadDebugProcessMemory(reinterpret_cast<uintptr_t>(ctx->tls_dump), debug_handle, thread_tls, sizeof(ctx->tls_dump)))) { ctx->tls_address = thread_tls; } else { ctx->tls_address = 0; std::memset(ctx->tls_dump, 0xCC, sizeof(ctx->tls_dump)); } /* Parse the base address. */ ctx->cpu_ctx.aarch64_ctx.SetBaseAddress(GetBaseAddress(ctx, std::addressof(thread_ctx), debug_handle)); } }
13,375
C++
.cpp
280
33.292857
172
0.533732
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,152
fatal_task_clock.cpp
Atmosphere-NX_Atmosphere/stratosphere/fatal/source/fatal_task_clock.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "fatal_task_clock.hpp" namespace ams::fatal::srv { namespace { /* Task definition. */ class AdjustClockTask : public ITaskWithDefaultStack { private: Result AdjustClockForModule(PcvModule module, u32 hz); Result AdjustClock(); public: virtual Result Run() override; virtual const char *GetName() const override { return "AdjustClockTask"; } }; /* Task global. */ AdjustClockTask g_adjust_clock_task; /* Task implementation. */ Result AdjustClockTask::AdjustClockForModule(PcvModule module, u32 hz) { if (hos::GetVersion() >= hos::Version_8_0_0) { /* On 8.0.0+, convert to module id + use clkrst API. */ PcvModuleId module_id; R_TRY(pcvGetModuleId(std::addressof(module_id), module)); ClkrstSession session; R_TRY(clkrstOpenSession(std::addressof(session), module_id, 3)); ON_SCOPE_EXIT { clkrstCloseSession(std::addressof(session)); }; R_TRY(clkrstSetClockRate(std::addressof(session), hz)); } else { /* On 1.0.0-7.0.1, use pcv API. */ R_TRY(pcvSetClockRate(module, hz)); } R_SUCCEED(); } Result AdjustClockTask::AdjustClock() { /* Fatal sets the CPU to 1020MHz, the GPU to 307 MHz, and the EMC to 1331MHz. */ constexpr u32 CPU_CLOCK_1020MHZ = 0x3CCBF700L; constexpr u32 GPU_CLOCK_307MHZ = 0x124F8000L; constexpr u32 EMC_CLOCK_1331MHZ = 0x4F588000L; R_TRY(AdjustClockForModule(PcvModule_CpuBus, CPU_CLOCK_1020MHZ)); R_TRY(AdjustClockForModule(PcvModule_GPU, GPU_CLOCK_307MHZ)); R_TRY(AdjustClockForModule(PcvModule_EMC, EMC_CLOCK_1331MHZ)); R_SUCCEED(); } Result AdjustClockTask::Run() { R_RETURN(AdjustClock()); } } ITask *GetAdjustClockTask(const ThrowContext *ctx) { g_adjust_clock_task.Initialize(ctx); return std::addressof(g_adjust_clock_task); } }
2,901
C++
.cpp
67
33.61194
92
0.615685
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,153
fatal_task_sound.cpp
Atmosphere-NX_Atmosphere/stratosphere/fatal/source/fatal_task_sound.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have 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 "fatal_task_sound.hpp" namespace ams::fatal::srv { namespace { /* Task definition. */ class StopSoundTask : public ITaskWithDefaultStack { private: void StopSound(); public: virtual Result Run() override; virtual const char *GetName() const override { return "SoundTask"; } }; /* Task global. */ StopSoundTask g_stop_sound_task; /* Task implementation. */ void StopSoundTask::StopSound() { /* Talk to the ALC5639 over I2C, and disable audio output. */ { I2cSession audio; if (R_SUCCEEDED(i2cOpenSession(std::addressof(audio), I2cDevice_Alc5639))) { ON_SCOPE_EXIT { i2csessionClose(std::addressof(audio)); }; struct { u8 reg; u16 val; } __attribute__((packed)) cmd; static_assert(sizeof(cmd) == 3, "I2C command definition!"); cmd.reg = 0x01; cmd.val = 0xC8C8; i2csessionSendAuto(std::addressof(audio), std::addressof(cmd), sizeof(cmd), I2cTransactionOption_All); cmd.reg = 0x02; cmd.val = 0xC8C8; i2csessionSendAuto(std::addressof(audio), std::addressof(cmd), sizeof(cmd), I2cTransactionOption_All); for (u8 reg = 97; reg <= 102; reg++) { cmd.reg = reg; cmd.val = 0; i2csessionSendAuto(std::addressof(audio), std::addressof(cmd), sizeof(cmd), I2cTransactionOption_All); } } } /* Talk to the ALC5639 over GPIO, and disable audio output */ { gpio::GpioPadSession audio; if (R_SUCCEEDED(gpio::OpenSession(std::addressof(audio), gpio::DeviceCode_CodecLdoEnTemp))) { ON_SCOPE_EXIT { gpio::CloseSession(std::addressof(audio)); }; /* Set direction output, sleep 200 ms so it can take effect. */ gpio::SetDirection(std::addressof(audio), gpio::Direction_Output); os::SleepThread(TimeSpan::FromMilliSeconds(200)); /* Pull audio codec low. */ gpio::SetValue(std::addressof(audio), gpio::GpioValue_Low); } } } Result StopSoundTask::Run() { StopSound(); R_SUCCEED(); } } ITask *GetStopSoundTask(const ThrowContext *ctx) { g_stop_sound_task.Initialize(ctx); return std::addressof(g_stop_sound_task); } }
3,470
C++
.cpp
79
31.253165
126
0.554074
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,154
fatal_task_screen.cpp
Atmosphere-NX_Atmosphere/stratosphere/fatal/source/fatal_task_screen.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have 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 "fatal_task_screen.hpp" #include "fatal_config.hpp" #include "fatal_font.hpp" namespace ams::fatal::srv { /* Include Atmosphere logo into its own anonymous namespace. */ namespace { #include "fatal_ams_logo.inc" } namespace { /* Screen definitions. */ constexpr u32 FatalScreenWidth = 1280; constexpr u32 FatalScreenHeight = 720; constexpr u32 FatalScreenBpp = 2; constexpr u32 FatalLayerZ = 100; constexpr u32 FatalScreenWidthAlignedBytes = util::AlignUp(FatalScreenWidth * FatalScreenBpp, 64); constexpr u32 FatalScreenWidthAligned = FatalScreenWidthAlignedBytes / FatalScreenBpp; /* There should only be a single transfer memory (for nv). */ alignas(os::MemoryPageSize) constinit u8 g_nv_transfer_memory[0x40000]; /* There should only be a single (1280*768) framebuffer. */ constexpr size_t FrameBufferRequiredSizeBytes = FatalScreenWidthAlignedBytes * util::AlignUp(FatalScreenHeight, 128); constexpr size_t FrameBufferRequiredSizePageAligned = util::AlignUp(FrameBufferRequiredSizeBytes, os::MemoryPageSize); constexpr size_t FrameBufferRequiredSizeHeapAligned = util::AlignUp(FrameBufferRequiredSizeBytes, os::MemoryHeapUnitSize); constinit u8 *g_framebuffer_pointer = nullptr; void InitializeFrameBufferPointer() { /* Try to get a framebuffer from heap. */ { if (R_SUCCEEDED(os::SetMemoryHeapSize(FrameBufferRequiredSizeHeapAligned))) { g_framebuffer_pointer = reinterpret_cast<u8 *>(os::GetMemoryHeapAddress()); return; } } /* We couldn't use heap, so try insecure memory, from the system nonsecure pool. */ { uintptr_t address = 0; if (R_SUCCEEDED(os::AllocateInsecureMemory(std::addressof(address), FrameBufferRequiredSizePageAligned))) { g_framebuffer_pointer = reinterpret_cast<u8 *>(address); return; } } /* Neither heap nor insecure is available, so we're going to have to try to raid the unsafe pool. */ { /* First, increase the limit to an extremely high value. */ size_t large_size = std::max(128_MB, FrameBufferRequiredSizeHeapAligned); while (svc::ResultLimitReached::Includes(svc::SetUnsafeLimit(large_size))) { large_size *= 2; } /* Next, map some unsafe memory. */ uintptr_t address = 0; if (R_SUCCEEDED(os::AllocateUnsafeMemory(std::addressof(address), FrameBufferRequiredSizePageAligned))) { g_framebuffer_pointer = reinterpret_cast<u8 *>(address); return; } } } } } extern "C" ::Result __nx_nv_create_tmem(TransferMemory *t, u32 *out_size, Permission perm) { *out_size = sizeof(ams::fatal::srv::g_nv_transfer_memory); return tmemCreateFromMemory(t, ams::fatal::srv::g_nv_transfer_memory, sizeof(ams::fatal::srv::g_nv_transfer_memory), perm); } namespace ams::fatal::srv { namespace { /* Pixel calculation helper. */ constexpr u32 GetPixelOffset(u32 x, u32 y) { u32 tmp_pos = ((y & 127) / 16) + (x/32*8) + ((y/16/8)*(((FatalScreenWidthAligned/2)/16*8))); tmp_pos *= 16*16 * 4; tmp_pos += ((y%16)/8)*512 + ((x%32)/16)*256 + ((y%8)/2)*64 + ((x%16)/8)*32 + (y%2)*16 + (x%8)*2;//This line is a modified version of code from the Tegra X1 datasheet. return tmp_pos / 2; } /* Task definitions. */ class ShowFatalTask : public ITaskWithStack<0x8000> { private: ViDisplay m_display; ViLayer m_layer; NWindow m_win; NvMap m_map; private: Result SetupDisplayInternal(); Result SetupDisplayExternal(); Result PrepareScreenForDrawing(); void PreRenderFrameBuffer(); Result InitializeNativeWindow(); void DisplayPreRenderedFrame(); Result ShowFatal(); public: virtual Result Run() override; virtual const char *GetName() const override { return "ShowFatal"; } }; class BacklightControlTask : public ITaskWithDefaultStack { private: void TurnOnBacklight(); public: virtual Result Run() override; virtual const char *GetName() const override { return "BacklightControlTask"; } }; /* Task globals. */ ShowFatalTask g_show_fatal_task; BacklightControlTask g_backlight_control_task; /* Task implementations. */ Result ShowFatalTask::SetupDisplayInternal() { ViDisplay temp_display; /* Try to open the display. */ R_TRY_CATCH(viOpenDisplay("Internal", std::addressof(temp_display))) { R_CONVERT(vi::ResultNotFound, ResultSuccess()); } R_END_TRY_CATCH; /* Guarantee we close the display. */ ON_SCOPE_EXIT { viCloseDisplay(std::addressof(temp_display)); }; /* Turn on the screen. */ if (hos::GetVersion() >= hos::Version_3_0_0) { R_TRY(viSetDisplayPowerState(std::addressof(temp_display), ViPowerState_On)); } else { /* Prior to 3.0.0, the ViPowerState enum was different (0 = Off, 1 = On). */ R_TRY(viSetDisplayPowerState(std::addressof(temp_display), ViPowerState_On_Deprecated)); } /* Set alpha to 1.0f. */ R_TRY(viSetDisplayAlpha(std::addressof(temp_display), 1.0f)); R_SUCCEED(); } Result ShowFatalTask::SetupDisplayExternal() { ViDisplay temp_display; /* Try to open the display. */ R_TRY_CATCH(viOpenDisplay("External", std::addressof(temp_display))) { R_CONVERT(vi::ResultNotFound, ResultSuccess()); } R_END_TRY_CATCH; /* Guarantee we close the display. */ ON_SCOPE_EXIT { viCloseDisplay(std::addressof(temp_display)); }; /* Set alpha to 1.0f. */ R_TRY(viSetDisplayAlpha(std::addressof(temp_display), 1.0f)); R_SUCCEED(); } Result ShowFatalTask::PrepareScreenForDrawing() { /* Connect to vi. */ R_TRY(viInitialize(ViServiceType_Manager)); /* Close other content. */ viSetContentVisibility(false); /* Setup the two displays. */ R_TRY(SetupDisplayInternal()); R_TRY(SetupDisplayExternal()); /* Open the default display. */ R_TRY(viOpenDefaultDisplay(std::addressof(m_display))); /* Reset the display magnification to its default value. */ s32 display_width, display_height; R_TRY(viGetDisplayLogicalResolution(std::addressof(m_display), std::addressof(display_width), std::addressof(display_height))); /* viSetDisplayMagnification was added in 3.0.0. */ if (hos::GetVersion() >= hos::Version_3_0_0) { R_TRY(viSetDisplayMagnification(std::addressof(m_display), 0, 0, display_width, display_height)); } /* Create layer to draw to. */ R_TRY(viCreateLayer(std::addressof(m_display), std::addressof(m_layer))); /* Setup the layer. */ { /* Display a layer of 1280 x 720 at 1.5x magnification */ /* NOTE: N uses 2 (770x400) RGBA4444 buffers (tiled buffer + linear). */ /* We use a single 1280x720 tiled RGB565 buffer. */ constexpr s32 RawWidth = FatalScreenWidth; constexpr s32 RawHeight = FatalScreenHeight; constexpr s32 LayerWidth = ((RawWidth) * 3) / 2; constexpr s32 LayerHeight = ((RawHeight) * 3) / 2; const float layer_x = static_cast<float>((display_width - LayerWidth) / 2); const float layer_y = static_cast<float>((display_height - LayerHeight) / 2); R_TRY(viSetLayerSize(std::addressof(m_layer), LayerWidth, LayerHeight)); /* Set the layer's Z at display maximum, to be above everything else .*/ R_TRY(viSetLayerZ(std::addressof(m_layer), FatalLayerZ)); /* Center the layer in the screen. */ R_TRY(viSetLayerPosition(std::addressof(m_layer), layer_x, layer_y)); /* Create framebuffer. */ R_TRY(nwindowCreateFromLayer(std::addressof(m_win), std::addressof(m_layer))); R_TRY(this->InitializeNativeWindow()); } R_SUCCEED(); } void ShowFatalTask::PreRenderFrameBuffer() { const FatalConfig &config = GetFatalConfig(); /* Allocate a frame buffer. */ InitializeFrameBufferPointer(); AMS_ABORT_UNLESS(g_framebuffer_pointer != nullptr); /* Pre-render the image into the static framebuffer. */ u16 *tiled_buf = reinterpret_cast<u16 *>(g_framebuffer_pointer); /* Temporarily use the NV transfer memory as font backing heap. */ font::SetHeapMemory(g_nv_transfer_memory, sizeof(g_nv_transfer_memory)); ON_SCOPE_EXIT { std::memset(g_nv_transfer_memory, 0, sizeof(g_nv_transfer_memory)); }; /* Let the font manager know about our framebuffer. */ font::ConfigureFontFramebuffer(tiled_buf, GetPixelOffset); font::SetFontColor(0xFFFF); /* Draw a background. */ for (size_t i = 0; i < FrameBufferRequiredSizeBytes / sizeof(*tiled_buf); i++) { tiled_buf[i] = AtmosphereLogoData[0]; } /* Draw the atmosphere logo in the upper right corner. */ const u32 start_x = 32, start_y = 64; for (size_t y = 0; y < AtmosphereLogoHeight; y++) { for (size_t x = 0; x < AtmosphereLogoWidth; x++) { tiled_buf[GetPixelOffset(FatalScreenWidth - AtmosphereLogoWidth - start_x + x, start_x + y)] = AtmosphereLogoData[y * AtmosphereLogoWidth + x]; } } /* Draw error message and firmware. */ font::SetPosition(start_x, start_y); font::SetFontSize(16.0f); font::PrintFormat(config.GetErrorMessage(), m_context->result.GetModule(), m_context->result.GetDescription(), m_context->result.GetValue()); font::AddSpacingLines(0.5f); font::PrintFormatLine( "Program: %016lX", static_cast<u64>(m_context->program_id)); font::AddSpacingLines(0.5f); font::PrintFormatLine("Firmware: %s (Atmosphère %u.%u.%u-%s)", config.GetFirmwareVersion().display_version, ATMOSPHERE_RELEASE_VERSION, ams::GetGitRevision()); font::AddSpacingLines(1.5f); if (!exosphere::ResultVersionMismatch::Includes(m_context->result)) { font::Print(config.GetErrorDescription()); } else { /* Print a special message for atmosphere version mismatch. */ font::Print("Atmosphère version mismatch detected.\n\n" "Please press the POWER Button to restart the console normally, or a VOL button\n" "to reboot to a payload (or RCM, if none is present). If you are unable to\n" "restart the console, hold the POWER Button for 12 seconds to turn the console off.\n\n" "Please ensure that all Atmosphère components are updated.\n" "github.com/Atmosphere-NX/Atmosphere/releases\n"); } /* Add a line. */ for (size_t x = start_x; x < FatalScreenWidth - start_x; x++) { tiled_buf[GetPixelOffset(x, font::GetY())] = 0xFFFF; } font::AddSpacingLines(1.5f); u32 backtrace_y = font::GetY(); u32 backtrace_x = 0; u32 pc_x = 0; /* Note architecutre. */ const bool is_aarch32 = m_context->cpu_ctx.architecture == CpuContext::Architecture_Aarch32; /* Print GPRs. */ font::SetFontSize(14.0f); font::Print("General Purpose Registers "); font::PrintLine(""); font::SetPosition(start_x, font::GetY()); font::AddSpacingLines(0.5f); if (is_aarch32) { for (size_t i = 0; i < (aarch32::RegisterName_GeneralPurposeCount / 2); i++) { u32 x = font::GetX(); font::PrintFormat("%s:", aarch32::CpuContext::RegisterNameStrings[i]); font::SetPosition(x + 47, font::GetY()); if (m_context->cpu_ctx.aarch32_ctx.HasRegisterValue(static_cast<aarch32::RegisterName>(i))) { font::PrintMonospaceU32(m_context->cpu_ctx.aarch32_ctx.r[i]); font::PrintMonospaceBlank(8); } else { font::PrintMonospaceBlank(16); } font::Print(" "); pc_x = font::GetX(); font::PrintFormat("%s:", aarch32::CpuContext::RegisterNameStrings[i + (aarch32::RegisterName_GeneralPurposeCount / 2)]); font::SetPosition(pc_x + 47, font::GetY()); if (m_context->cpu_ctx.aarch32_ctx.HasRegisterValue(static_cast<aarch32::RegisterName>(i + (aarch32::RegisterName_GeneralPurposeCount / 2)))) { font::PrintMonospaceU32(m_context->cpu_ctx.aarch32_ctx.r[i + (aarch32::RegisterName_GeneralPurposeCount / 2)]); font::PrintMonospaceBlank(8); } else { font::PrintMonospaceBlank(16); } if (i == (aarch32::RegisterName_GeneralPurposeCount / 2) - 1) { font::Print(" "); backtrace_x = font::GetX(); } font::PrintLine(""); font::SetPosition(start_x, font::GetY()); } } else { for (size_t i = 0; i < aarch64::RegisterName_GeneralPurposeCount / 2; i++) { u32 x = font::GetX(); font::PrintFormat("%s:", aarch64::CpuContext::RegisterNameStrings[i]); font::SetPosition(x + 47, font::GetY()); if (m_context->cpu_ctx.aarch64_ctx.HasRegisterValue(static_cast<aarch64::RegisterName>(i))) { font::PrintMonospaceU64(m_context->cpu_ctx.aarch64_ctx.x[i]); } else { font::PrintMonospaceBlank(16); } font::Print(" "); pc_x = font::GetX(); font::PrintFormat("%s:", aarch64::CpuContext::RegisterNameStrings[i + (aarch64::RegisterName_GeneralPurposeCount / 2)]); font::SetPosition(pc_x + 47, font::GetY()); if (m_context->cpu_ctx.aarch64_ctx.HasRegisterValue(static_cast<aarch64::RegisterName>(i + (aarch64::RegisterName_GeneralPurposeCount / 2)))) { font::PrintMonospaceU64(m_context->cpu_ctx.aarch64_ctx.x[i + (aarch64::RegisterName_GeneralPurposeCount / 2)]); } else { font::PrintMonospaceBlank(16); } if (i == (aarch64::RegisterName_GeneralPurposeCount / 2) - 1) { font::Print(" "); backtrace_x = font::GetX(); } font::PrintLine(""); font::SetPosition(start_x, font::GetY()); } } /* Print PC. */ { font::SetPosition(pc_x, backtrace_y); const u32 x = font::GetX(); font::Print("PC: "); font::SetPosition(x + 47, font::GetY()); } if (is_aarch32) { font::PrintMonospaceU32(m_context->cpu_ctx.aarch32_ctx.pc); } else { font::PrintMonospaceU64(m_context->cpu_ctx.aarch64_ctx.pc); } /* Print Backtrace. */ u32 bt_size; if (is_aarch32) { bt_size = m_context->cpu_ctx.aarch32_ctx.stack_trace_size; } else { bt_size = m_context->cpu_ctx.aarch64_ctx.stack_trace_size; } font::SetPosition(backtrace_x, backtrace_y); if (bt_size == 0) { if (is_aarch32) { font::Print("Start Address: "); font::PrintMonospaceU32(m_context->cpu_ctx.aarch32_ctx.base_address); font::PrintLine(""); } else { font::Print("Start Address: "); font::PrintMonospaceU64(m_context->cpu_ctx.aarch64_ctx.base_address); font::PrintLine(""); } } else { if (is_aarch32) { font::Print("Backtrace - Start Address: "); font::PrintMonospaceU32(m_context->cpu_ctx.aarch32_ctx.base_address); font::PrintLine(""); font::AddSpacingLines(0.5f); for (u32 i = 0; i < aarch32::CpuContext::MaxStackTraceDepth / 2; i++) { u32 bt_cur = 0, bt_next = 0; if (i < m_context->cpu_ctx.aarch32_ctx.stack_trace_size) { bt_cur = m_context->cpu_ctx.aarch32_ctx.stack_trace[i]; } if (i + aarch32::CpuContext::MaxStackTraceDepth / 2 < m_context->cpu_ctx.aarch32_ctx.stack_trace_size) { bt_next = m_context->cpu_ctx.aarch32_ctx.stack_trace[i + aarch32::CpuContext::MaxStackTraceDepth / 2]; } if (i < m_context->cpu_ctx.aarch32_ctx.stack_trace_size) { u32 x = font::GetX(); font::PrintFormat("BT[%02d]: ", i); font::SetPosition(x + 72, font::GetY()); font::PrintMonospaceU32(bt_cur); font::PrintMonospaceBlank(8); font::Print(" "); } if (i + aarch32::CpuContext::MaxStackTraceDepth / 2 < m_context->cpu_ctx.aarch32_ctx.stack_trace_size) { u32 x = font::GetX(); font::PrintFormat("BT[%02d]: ", i + aarch32::CpuContext::MaxStackTraceDepth / 2); font::SetPosition(x + 72, font::GetY()); font::PrintMonospaceU32(bt_next); font::PrintMonospaceBlank(8); } font::PrintLine(""); font::SetPosition(backtrace_x, font::GetY()); } } else { font::Print("Backtrace - Start Address: "); font::PrintMonospaceU64(m_context->cpu_ctx.aarch64_ctx.base_address); font::PrintLine(""); font::AddSpacingLines(0.5f); for (u32 i = 0; i < aarch64::CpuContext::MaxStackTraceDepth / 2; i++) { u64 bt_cur = 0, bt_next = 0; if (i < m_context->cpu_ctx.aarch64_ctx.stack_trace_size) { bt_cur = m_context->cpu_ctx.aarch64_ctx.stack_trace[i]; } if (i + aarch64::CpuContext::MaxStackTraceDepth / 2 < m_context->cpu_ctx.aarch64_ctx.stack_trace_size) { bt_next = m_context->cpu_ctx.aarch64_ctx.stack_trace[i + aarch64::CpuContext::MaxStackTraceDepth / 2]; } if (i < m_context->cpu_ctx.aarch64_ctx.stack_trace_size) { u32 x = font::GetX(); font::PrintFormat("BT[%02d]: ", i); font::SetPosition(x + 72, font::GetY()); font::PrintMonospaceU64(bt_cur); font::Print(" "); } if (i + aarch64::CpuContext::MaxStackTraceDepth / 2 < m_context->cpu_ctx.aarch64_ctx.stack_trace_size) { u32 x = font::GetX(); font::PrintFormat("BT[%02d]: ", i + aarch64::CpuContext::MaxStackTraceDepth / 2); font::SetPosition(x + 72, font::GetY()); font::PrintMonospaceU64(bt_next); } font::PrintLine(""); font::SetPosition(backtrace_x, font::GetY()); } } } } Result ShowFatalTask::InitializeNativeWindow() { /* Setup nv driver. */ R_TRY(nvInitialize()); R_TRY(nvMapInit()); R_TRY(nvFenceInit()); /* Create nvmap. */ R_TRY(nvMapCreate(std::addressof(m_map), g_framebuffer_pointer, FrameBufferRequiredSizeBytes, 0x20000, NvKind_Pitch, true)); /* Setup graphics buffer. */ { NvGraphicBuffer grbuf = {}; grbuf.header.num_ints = (sizeof(NvGraphicBuffer) - sizeof(NativeHandle)) / 4; grbuf.unk0 = -1; grbuf.magic = 0xDAFFCAFF; grbuf.pid = 42; grbuf.usage = GRALLOC_USAGE_HW_COMPOSER | GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE; grbuf.format = PIXEL_FORMAT_RGB_565; grbuf.ext_format = PIXEL_FORMAT_RGB_565; grbuf.num_planes = 1; grbuf.planes[0].width = FatalScreenWidth; grbuf.planes[0].height = FatalScreenHeight; grbuf.planes[0].color_format = NvColorFormat_R5G6B5; grbuf.planes[0].layout = NvLayout_BlockLinear; grbuf.planes[0].kind = NvKind_Generic_16BX2; grbuf.planes[0].block_height_log2 = 4; grbuf.nvmap_id = nvMapGetId(std::addressof(m_map)); grbuf.stride = FatalScreenWidthAligned; grbuf.total_size = FrameBufferRequiredSizeBytes; grbuf.planes[0].pitch = FatalScreenWidthAlignedBytes; grbuf.planes[0].size = FrameBufferRequiredSizeBytes; grbuf.planes[0].offset = 0; R_TRY(nwindowConfigureBuffer(std::addressof(m_win), 0, std::addressof(grbuf))); } R_SUCCEED(); } void ShowFatalTask::DisplayPreRenderedFrame() { s32 slot; R_ABORT_UNLESS(nwindowDequeueBuffer(std::addressof(m_win), std::addressof(slot), nullptr)); dd::FlushDataCache(g_framebuffer_pointer, FrameBufferRequiredSizeBytes); R_ABORT_UNLESS(nwindowQueueBuffer(std::addressof(m_win), m_win.cur_slot, NULL)); } Result ShowFatalTask::ShowFatal() { /* Pre-render the framebuffer. */ PreRenderFrameBuffer(); /* Prepare screen for drawing. */ R_ABORT_UNLESS(PrepareScreenForDrawing()); /* Display the pre-rendered frame. */ this->DisplayPreRenderedFrame(); R_SUCCEED(); } Result ShowFatalTask::Run() { /* Don't show the fatal error screen until we've verified the battery is okay. */ m_context->battery_event->Wait(); R_RETURN(ShowFatal()); } void BacklightControlTask::TurnOnBacklight() { R_ABORT_UNLESS(::lblInitialize()); ::lblSwitchBacklightOn(0); ::lblExit(); } Result BacklightControlTask::Run() { TurnOnBacklight(); R_SUCCEED(); } } ITask *GetShowFatalTask(const ThrowContext *ctx) { g_show_fatal_task.Initialize(ctx); return std::addressof(g_show_fatal_task); } ITask *GetBacklightControlTask(const ThrowContext *ctx) { g_backlight_control_task.Initialize(ctx); return std::addressof(g_backlight_control_task); } }
25,915
C++
.cpp
473
38.983087
178
0.532552
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,155
boot_check_clock.cpp
Atmosphere-NX_Atmosphere/stratosphere/boot/source/boot_check_clock.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "boot_check_clock.hpp" #include "boot_power_utils.hpp" namespace ams::boot { namespace { /* Convenience definitions. */ constexpr u32 ExpectedPlluDivP = (1 << 16); constexpr u32 ExpectedPlluDivN = (25 << 8); constexpr u32 ExpectedPlluDivM = (2 << 0); constexpr u32 ExpectedPlluVal = (ExpectedPlluDivP | ExpectedPlluDivN | ExpectedPlluDivM); constexpr u32 ExpectedPlluMask = 0x1FFFFF; constexpr u32 ExpectedUtmipDivN = (25 << 16); constexpr u32 ExpectedUtmipDivM = (1 << 8); constexpr u32 ExpectedUtmipVal = (ExpectedUtmipDivN | ExpectedUtmipDivM); constexpr u32 ExpectedUtmipMask = 0xFFFF00; /* Helpers. */ bool IsUsbClockValid() { uintptr_t car_regs = dd::QueryIoMapping(0x60006000ul, os::MemoryPageSize); AMS_ASSERT(car_regs != 0); const u32 pllu = reg::Read(car_regs + 0xC0); const u32 utmip = reg::Read(car_regs + 0x480); return ((pllu & ExpectedPlluMask) == ExpectedPlluVal) && ((utmip & ExpectedUtmipMask) == ExpectedUtmipVal); } } void CheckClock() { if (!IsUsbClockValid()) { /* Sleep for 1s, then reboot. */ os::SleepThread(TimeSpan::FromSeconds(1)); RebootSystem(); } } }
1,998
C++
.cpp
47
36.085106
119
0.664779
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,156
boot_display.cpp
Atmosphere-NX_Atmosphere/stratosphere/boot/source/boot_display.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have 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 "boot_display.hpp" #include "boot_i2c_utils.hpp" #include "boot_registers_di.hpp" namespace ams::boot { /* Display configuration included into anonymous namespace. */ namespace { #include "boot_display_config.inc" } namespace { /* Helpful defines. */ constexpr size_t DeviceAddressSpaceAlignSize = 4_MB; constexpr dd::DeviceVirtualAddress FrameBufferDeviceAddress = DisplayConfigFrameBufferAddress; constexpr size_t FrameBufferWidth = 768; constexpr size_t FrameBufferHeight = 1280; constexpr size_t FrameBufferSize = FrameBufferHeight * FrameBufferWidth * sizeof(u32); constexpr dd::PhysicalAddress PmcBase = 0x7000E400ul; constexpr dd::PhysicalAddress Disp1Base = 0x54200000ul; constexpr dd::PhysicalAddress DsiBase = 0x54300000ul; constexpr dd::PhysicalAddress ClkRstBase = 0x60006000ul; constexpr dd::PhysicalAddress GpioBase = 0x6000D000ul; constexpr dd::PhysicalAddress ApbMiscBase = 0x70000000ul; constexpr dd::PhysicalAddress MipiCalBase = 0x700E3000ul; constexpr size_t Disp1Size = 3 * os::MemoryPageSize; constexpr size_t DsiSize = os::MemoryPageSize; constexpr size_t ClkRstSize = os::MemoryPageSize; constexpr size_t GpioSize = os::MemoryPageSize; constexpr size_t ApbMiscSize = os::MemoryPageSize; constexpr size_t MipiCalSize = os::MemoryPageSize; constexpr int DsiWaitForCommandMilliSecondsMax = 250; constexpr int DsiWaitForCommandCompletionMilliSeconds = 5; constexpr int DsiWaitForHostControlMilliSecondsMax = 150; constexpr size_t GPIO_PORT3_CNF_0 = 0x200; constexpr size_t GPIO_PORT3_OE_0 = 0x210; constexpr size_t GPIO_PORT3_OUT_0 = 0x220; constexpr size_t GPIO_PORT6_CNF_1 = 0x504; constexpr size_t GPIO_PORT6_OE_1 = 0x514; constexpr size_t GPIO_PORT6_OUT_1 = 0x524; /* Globals. */ constinit bool g_is_display_intialized = false; constinit spl::SocType g_soc_type = spl::SocType_Erista; constinit u32 g_lcd_vendor = 0; constinit int g_display_brightness = 100; constinit dd::DeviceAddressSpaceType g_device_address_space; constinit pwm::driver::ChannelSession g_lcd_backlight_session; constinit u32 *g_frame_buffer = nullptr; constinit u8 g_frame_buffer_storage[DeviceAddressSpaceAlignSize + FrameBufferSize]; constinit uintptr_t g_disp1_regs = 0; constinit uintptr_t g_dsi_regs = 0; constinit uintptr_t g_clk_rst_regs = 0; constinit uintptr_t g_gpio_regs = 0; constinit uintptr_t g_apb_misc_regs = 0; constinit uintptr_t g_mipi_cal_regs = 0; /* Helper functions. */ void InitializeRegisterVirtualAddresses() { g_disp1_regs = dd::QueryIoMapping(Disp1Base, Disp1Size); g_dsi_regs = dd::QueryIoMapping(DsiBase, DsiSize); g_clk_rst_regs = dd::QueryIoMapping(ClkRstBase, ClkRstSize); g_gpio_regs = dd::QueryIoMapping(GpioBase, GpioSize); g_apb_misc_regs = dd::QueryIoMapping(ApbMiscBase, ApbMiscSize); g_mipi_cal_regs = dd::QueryIoMapping(MipiCalBase, MipiCalSize); AMS_ABORT_UNLESS(g_disp1_regs != 0); AMS_ABORT_UNLESS(g_dsi_regs != 0); AMS_ABORT_UNLESS(g_clk_rst_regs != 0); AMS_ABORT_UNLESS(g_gpio_regs != 0); AMS_ABORT_UNLESS(g_apb_misc_regs != 0); AMS_ABORT_UNLESS(g_mipi_cal_regs != 0); } inline void DoRegisterWrites(uintptr_t base_address, const RegisterWrite *reg_writes, size_t num_writes) { for (size_t i = 0; i < num_writes; i++) { reg::Write(base_address + reg_writes[i].offset, reg_writes[i].value); } } inline void DoSocDependentRegisterWrites(uintptr_t base_address, const RegisterWrite *reg_writes_erista, size_t num_writes_erista, const RegisterWrite *reg_writes_mariko, size_t num_writes_mariko) { switch (g_soc_type) { case spl::SocType_Erista: DoRegisterWrites(base_address, reg_writes_erista, num_writes_erista); break; case spl::SocType_Mariko: DoRegisterWrites(base_address, reg_writes_mariko, num_writes_mariko); break; AMS_UNREACHABLE_DEFAULT_CASE(); } } inline void DoSleepOrRegisterWrites(uintptr_t base_address, const SleepOrRegisterWrite *reg_writes, size_t num_writes) { for (size_t i = 0; i < num_writes; i++) { switch (reg_writes[i].kind) { case SleepOrRegisterWriteKind_Write: reg::Write(base_address + sizeof(u32) * reg_writes[i].offset, reg_writes[i].value); break; case SleepOrRegisterWriteKind_Sleep: os::SleepThread(TimeSpan::FromMilliSeconds(reg_writes[i].offset)); break; AMS_UNREACHABLE_DEFAULT_CASE(); } } } #define DO_REGISTER_WRITES(base_address, writes) DoRegisterWrites(base_address, writes, util::size(writes)) #define DO_SOC_DEPENDENT_REGISTER_WRITES(base_address, writes) DoSocDependentRegisterWrites(base_address, writes##Erista, util::size(writes##Erista), writes##Mariko, util::size(writes##Mariko)) #define DO_SLEEP_OR_REGISTER_WRITES(base_address, writes) DoSleepOrRegisterWrites(base_address, writes, util::size(writes)) void InitializeFrameBuffer() { if (g_frame_buffer != nullptr) { std::memset(g_frame_buffer, 0x00, FrameBufferSize); dd::FlushDataCache(g_frame_buffer, FrameBufferSize); } else { const uintptr_t frame_buffer_aligned = util::AlignUp(reinterpret_cast<uintptr_t>(g_frame_buffer_storage), DeviceAddressSpaceAlignSize); g_frame_buffer = reinterpret_cast<u32 *>(frame_buffer_aligned); std::memset(g_frame_buffer, 0x00, FrameBufferSize); dd::FlushDataCache(g_frame_buffer, FrameBufferSize); /* Create Address Space. */ R_ABORT_UNLESS(dd::CreateDeviceAddressSpace(std::addressof(g_device_address_space), 0, (UINT64_C(1) << 32))); /* Attach it to the DC. */ R_ABORT_UNLESS(dd::AttachDeviceAddressSpace(std::addressof(g_device_address_space), svc::DeviceName_Dc)); /* Map the framebuffer for the DC as read-only. */ R_ABORT_UNLESS(dd::MapDeviceAddressSpaceAligned(std::addressof(g_device_address_space), dd::GetCurrentProcessHandle(), frame_buffer_aligned, FrameBufferSize, FrameBufferDeviceAddress, dd::MemoryPermission_ReadOnly)); } } void FinalizeFrameBuffer() { if (g_frame_buffer != nullptr) { const uintptr_t frame_buffer_aligned = util::AlignUp(reinterpret_cast<uintptr_t>(g_frame_buffer_storage), DeviceAddressSpaceAlignSize); /* Unmap the framebuffer from the DC. */ dd::UnmapDeviceAddressSpace(std::addressof(g_device_address_space), dd::GetCurrentProcessHandle(), frame_buffer_aligned, FrameBufferSize, FrameBufferDeviceAddress); /* Detach address space from the DC. */ dd::DetachDeviceAddressSpace(std::addressof(g_device_address_space), svc::DeviceName_Dc); /* Destroy the address space. */ dd::DestroyDeviceAddressSpace(std::addressof(g_device_address_space)); g_frame_buffer = nullptr; } } void WaitDsiTrigger() { os::Tick timeout = os::GetSystemTick() + os::ConvertToTick(TimeSpan::FromMilliSeconds(DsiWaitForCommandMilliSecondsMax)); while (true) { if (os::GetSystemTick() >= timeout) { break; } if (reg::Read(g_dsi_regs + sizeof(u32) * DSI_TRIGGER) == 0) { break; } } os::SleepThread(TimeSpan::FromMilliSeconds(DsiWaitForCommandCompletionMilliSeconds)); } void WaitDsiHostControl() { os::Tick timeout = os::GetSystemTick() + os::ConvertToTick(TimeSpan::FromMilliSeconds(DsiWaitForHostControlMilliSecondsMax)); while (true) { if (os::GetSystemTick() >= timeout) { break; } if ((reg::Read(g_dsi_regs + sizeof(u32) * DSI_HOST_CONTROL) & DSI_HOST_CONTROL_IMM_BTA) == 0) { break; } } } void EnableBacklightForVendor2050ForAula(int brightness) { /* Enable FRAME_END_INT */ reg::Write(g_disp1_regs + sizeof(u32) * DC_CMD_INT_ENABLE, 2); /* Configure DSI_LINE_TYPE as FOUR */ reg::Write(g_dsi_regs + sizeof(u32) * DSI_VIDEO_MODE_CONTROL, 1); reg::Write(g_dsi_regs + sizeof(u32) * DSI_VIDEO_MODE_CONTROL, 9); /* Set and wait for FRAME_END_INT */ reg::Write(g_disp1_regs + sizeof(u32) * DC_CMD_INT_STATUS, 2); while ((reg::Read(g_disp1_regs + sizeof(u32) * DC_CMD_INT_STATUS) & 2) != 0) { /* ... */ } /* Configure display brightness. */ const u32 brightness_val = ((0x7FF * brightness) / 100); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x339); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, (brightness_val & 0x700) | ((brightness_val & 0xFF) << 16) | 0x51); /* Set and wait for FRAME_END_INT */ reg::Write(g_disp1_regs + sizeof(u32) * DC_CMD_INT_STATUS, 2); while ((reg::Read(g_disp1_regs + sizeof(u32) * DC_CMD_INT_STATUS) & 2) != 0) { /* ... */ } /* Set client sync point block reset. */ reg::Write(g_dsi_regs + sizeof(u32) * DSI_INCR_SYNCPT_CNTRL, 1); os::SleepThread(TimeSpan::FromMilliSeconds(300)); /* Clear client sync point block resest. */ reg::Write(g_dsi_regs + sizeof(u32) * DSI_INCR_SYNCPT_CNTRL, 0); os::SleepThread(TimeSpan::FromMilliSeconds(300)); /* Clear DSI_LINE_TYPE config. */ reg::Write(g_dsi_regs + sizeof(u32) * DSI_VIDEO_MODE_CONTROL, 0); /* Disable FRAME_END_INT */ reg::Write(g_disp1_regs + sizeof(u32) * DC_CMD_INT_ENABLE, 0); reg::Write(g_disp1_regs + sizeof(u32) * DC_CMD_INT_STATUS, 2); } void EnableBacklightForGeneric(int brightness) { pwm::driver::SetScale(g_lcd_backlight_session, static_cast<double>(brightness)); pwm::driver::SetEnabled(g_lcd_backlight_session, true); } } void InitializeDisplay() { /* Setup globals. */ InitializeRegisterVirtualAddresses(); g_soc_type = spl::GetSocType(); InitializeFrameBuffer(); /* Get the hardware type. */ const auto hw_type = spl::GetHardwareType(); /* Turn on DSI/voltage rail. */ { i2c::driver::I2cSession i2c_session; R_ABORT_UNLESS(i2c::driver::OpenSession(std::addressof(i2c_session), i2c::DeviceCode_Max77620Pmic)); if (g_soc_type == spl::SocType_Mariko) { WriteI2cRegister(i2c_session, 0x18, 0x3A); WriteI2cRegister(i2c_session, 0x1F, 0x71); } WriteI2cRegister(i2c_session, 0x23, 0xD0); i2c::driver::CloseSession(i2c_session); } /* Enable MIPI CAL, DSI, DISP1, HOST1X, UART_FST_MIPI_CAL, DSIA LP clocks. */ reg::Write(g_clk_rst_regs + CLK_RST_CONTROLLER_RST_DEV_H_CLR, CLK_RST_REG_BITS_ENUM(RST_DEV_H_CLR_CLR_MIPI_CAL_RST, ENABLE), CLK_RST_REG_BITS_ENUM(RST_DEV_H_CLR_CLR_DSI_RST, ENABLE)); reg::Write(g_clk_rst_regs + CLK_RST_CONTROLLER_CLK_ENB_H_SET, CLK_RST_REG_BITS_ENUM(CLK_ENB_H_SET_SET_CLK_ENB_MIPI_CAL, ENABLE), CLK_RST_REG_BITS_ENUM(CLK_ENB_H_SET_SET_CLK_ENB_DSI, ENABLE)); reg::Write(g_clk_rst_regs + CLK_RST_CONTROLLER_RST_DEV_L_CLR, CLK_RST_REG_BITS_ENUM(RST_DEV_L_CLR_CLR_HOST1X_RST, ENABLE), CLK_RST_REG_BITS_ENUM(RST_DEV_L_CLR_CLR_DISP1_RST, ENABLE)); reg::Write(g_clk_rst_regs + CLK_RST_CONTROLLER_CLK_ENB_L_SET, CLK_RST_REG_BITS_ENUM(CLK_ENB_L_SET_SET_CLK_ENB_HOST1X, ENABLE), CLK_RST_REG_BITS_ENUM(CLK_ENB_L_SET_SET_CLK_ENB_DISP1, ENABLE)); reg::Write(g_clk_rst_regs + CLK_RST_CONTROLLER_CLK_ENB_X_SET, CLK_RST_REG_BITS_ENUM(CLK_ENB_X_SET_SET_CLK_ENB_UART_FST_MIPI_CAL, ENABLE)); reg::Write(g_clk_rst_regs + CLK_RST_CONTROLLER_CLK_SOURCE_UART_FST_MIPI_CAL, CLK_RST_REG_BITS_VALUE(CLK_SOURCE_UART_FST_MIPI_CAL_UART_FST_MIPI_CAL_CLK_DIVISOR, 10), CLK_RST_REG_BITS_ENUM (CLK_SOURCE_UART_FST_MIPI_CAL_UART_FST_MIPI_CAL_CLK_SRC, PLLP_OUT3)); reg::Write(g_clk_rst_regs + CLK_RST_CONTROLLER_CLK_ENB_W_SET, CLK_RST_REG_BITS_ENUM(CLK_ENB_W_SET_SET_CLK_ENB_DSIA_LP, ENABLE)); reg::Write(g_clk_rst_regs + CLK_RST_CONTROLLER_CLK_SOURCE_DSIA_LP, CLK_RST_REG_BITS_VALUE(CLK_SOURCE_DSIA_LP_DSIA_LP_CLK_DIVISOR, 10), CLK_RST_REG_BITS_ENUM (CLK_SOURCE_DSIA_LP_DSIA_LP_CLK_SRC, PLLP_OUT0)); /* Set IO_DPD_REQ to DPD_OFF. */ dd::WriteIoRegister(PmcBase + APBDEV_PMC_IO_DPD_REQ, reg::Encode(PMC_REG_BITS_ENUM(IO_DPD_REQ_CODE, DPD_OFF))); dd::WriteIoRegister(PmcBase + APBDEV_PMC_IO_DPD2_REQ, reg::Encode(PMC_REG_BITS_ENUM(IO_DPD2_REQ_CODE, DPD_OFF))); /* Configure LCD pinmux tristate + passthrough. */ reg::ClearBits(g_apb_misc_regs + PINMUX_AUX_NFC_EN, reg::EncodeMask(PINMUX_REG_BITS_MASK(AUX_TRISTATE))); reg::ClearBits(g_apb_misc_regs + PINMUX_AUX_NFC_INT, reg::EncodeMask(PINMUX_REG_BITS_MASK(AUX_TRISTATE))); reg::ClearBits(g_apb_misc_regs + PINMUX_AUX_LCD_BL_PWM, reg::EncodeMask(PINMUX_REG_BITS_MASK(AUX_TRISTATE))); reg::ClearBits(g_apb_misc_regs + PINMUX_AUX_LCD_BL_EN, reg::EncodeMask(PINMUX_REG_BITS_MASK(AUX_TRISTATE))); reg::ClearBits(g_apb_misc_regs + PINMUX_AUX_LCD_RST, reg::EncodeMask(PINMUX_REG_BITS_MASK(AUX_TRISTATE))); if (hw_type == spl::HardwareType::Aula) { /* Configure LCD backlight. */ reg::SetBits(g_gpio_regs + GPIO_PORT6_CNF_1, 0x4); reg::SetBits(g_gpio_regs + GPIO_PORT6_OE_1, 0x4); } else { /* Configure LCD power, VDD. */ reg::SetBits(g_gpio_regs + GPIO_PORT3_CNF_0, 0x3); reg::SetBits(g_gpio_regs + GPIO_PORT3_OE_0, 0x3); reg::SetBits(g_gpio_regs + GPIO_PORT3_OUT_0, 0x1); os::SleepThread(TimeSpan::FromMilliSeconds(10)); reg::SetBits(g_gpio_regs + GPIO_PORT3_OUT_0, 0x2); os::SleepThread(TimeSpan::FromMilliSeconds(10)); reg::SetBits(g_gpio_regs + GPIO_PORT6_CNF_1, 0x7); reg::SetBits(g_gpio_regs + GPIO_PORT6_OE_1, 0x7); reg::SetBits(g_gpio_regs + GPIO_PORT6_OUT_1, 0x2); } /* Configure display interface and display. */ reg::Write(g_mipi_cal_regs + MIPI_CAL_MIPI_BIAS_PAD_CFG2, 0); if (g_soc_type == spl::SocType_Mariko) { reg::Write(g_mipi_cal_regs + MIPI_CAL_MIPI_BIAS_PAD_CFG0, 0); reg::Write(g_apb_misc_regs + APB_MISC_GP_DSI_PAD_CONTROL, 0); } /* Execute configs. */ DO_SOC_DEPENDENT_REGISTER_WRITES(g_clk_rst_regs, DisplayConfigPlld01); DO_SLEEP_OR_REGISTER_WRITES(g_disp1_regs, DisplayConfigDc01); DO_REGISTER_WRITES(g_dsi_regs, DisplayConfigDsi01Init01); DO_SOC_DEPENDENT_REGISTER_WRITES(g_dsi_regs, DisplayConfigDsi01Init02); DO_REGISTER_WRITES(g_dsi_regs, DisplayConfigDsi01Init03); DO_SOC_DEPENDENT_REGISTER_WRITES(g_dsi_regs, DisplayConfigDsi01Init04); DO_REGISTER_WRITES(g_dsi_regs, DisplayConfigDsi01Init05); DO_SOC_DEPENDENT_REGISTER_WRITES(g_dsi_regs, DisplayConfigDsiPhyTiming); DO_REGISTER_WRITES(g_dsi_regs, DisplayConfigDsi01Init06); DO_SOC_DEPENDENT_REGISTER_WRITES(g_dsi_regs, DisplayConfigDsiPhyTiming); DO_REGISTER_WRITES(g_dsi_regs, DisplayConfigDsi01Init07); os::SleepThread(TimeSpan::FromMilliSeconds(10)); /* Enable backlight reset. */ reg::SetBits(g_gpio_regs + GPIO_PORT6_OUT_1, 0x4); os::SleepThread(TimeSpan::FromMilliSeconds(60)); if (hw_type == spl::HardwareType::Aula) { reg::Write(g_dsi_regs + sizeof(u32) * DSI_BTA_TIMING, 0x40103); } else { reg::Write(g_dsi_regs + sizeof(u32) * DSI_BTA_TIMING, 0x50204); } reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x337); reg::Write(g_dsi_regs + sizeof(u32) * DSI_TRIGGER, DSI_TRIGGER_HOST); WaitDsiTrigger(); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x406); reg::Write(g_dsi_regs + sizeof(u32) * DSI_TRIGGER, DSI_TRIGGER_HOST); WaitDsiTrigger(); reg::Write(g_dsi_regs + sizeof(u32) * DSI_HOST_CONTROL, DSI_HOST_CONTROL_TX_TRIG_HOST | DSI_HOST_CONTROL_IMM_BTA | DSI_HOST_CONTROL_CS | DSI_HOST_CONTROL_ECC); WaitDsiHostControl(); os::SleepThread(TimeSpan::FromMilliSeconds(5)); /* Parse LCD vendor. */ { u32 host_response[3]; for (size_t i = 0; i < util::size(host_response); i++) { host_response[i] = reg::Read(g_dsi_regs + sizeof(u32) * DSI_RD_DATA); } /* The last word from host response is: Bits 0-7: FAB Bits 8-15: REV Bits 16-23: Minor REV */ if ((host_response[2] & 0xFF) == 0x10) { g_lcd_vendor = 0; } else { g_lcd_vendor = (host_response[2] >> 8) & 0xFF00; } g_lcd_vendor = (g_lcd_vendor & 0xFFFFFF00) | (host_response[2] & 0xFF); } /* LCD vendor specific configuration. */ if (g_lcd_vendor != 0x2050) { /* Configure LCD backlight to use PWM. */ reg::ClearBits(g_gpio_regs + GPIO_PORT6_CNF_1, 0x1); reg::Write(g_apb_misc_regs + PINMUX_AUX_LCD_BL_PWM, PINMUX_REG_BITS_ENUM(AUX_LCD_BL_PWM_PM, PWM0), PINMUX_REG_BITS_ENUM(AUX_PUPD, PULL_DOWN)); /* Configure LCD backlight. */ R_ABORT_UNLESS(pwm::driver::OpenSession(std::addressof(g_lcd_backlight_session), pwm::DeviceCode_LcdBacklight)); pwm::driver::SetPeriod(g_lcd_backlight_session, TimeSpan::FromNanoSeconds(33898)); switch (g_lcd_vendor) { case 0x10: /* Japan Display Inc screens. */ DO_SLEEP_OR_REGISTER_WRITES(g_dsi_regs, DisplayConfigJdiSpecificInit01); break; case 0xF20: /* Innolux first revision screens. */ reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x1105); reg::Write(g_dsi_regs + sizeof(u32) * DSI_TRIGGER, DSI_TRIGGER_HOST); os::SleepThread(TimeSpan::FromMilliSeconds(180)); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x439); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x9483FFB9); reg::Write(g_dsi_regs + sizeof(u32) * DSI_TRIGGER, DSI_TRIGGER_HOST); os::SleepThread(TimeSpan::FromMilliSeconds(5)); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x739); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x751548B1); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x143209); reg::Write(g_dsi_regs + sizeof(u32) * DSI_TRIGGER, DSI_TRIGGER_HOST); os::SleepThread(TimeSpan::FromMilliSeconds(5)); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x2905); reg::Write(g_dsi_regs + sizeof(u32) * DSI_TRIGGER, DSI_TRIGGER_HOST); break; case 0xF30: /* AUO first revision screens. */ reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x1105); reg::Write(g_dsi_regs + sizeof(u32) * DSI_TRIGGER, DSI_TRIGGER_HOST); os::SleepThread(TimeSpan::FromMilliSeconds(180)); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x439); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x9483FFB9); reg::Write(g_dsi_regs + sizeof(u32) * DSI_TRIGGER, DSI_TRIGGER_HOST); os::SleepThread(TimeSpan::FromMilliSeconds(5)); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x739); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x711148B1); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x143209); reg::Write(g_dsi_regs + sizeof(u32) * DSI_TRIGGER, DSI_TRIGGER_HOST); os::SleepThread(TimeSpan::FromMilliSeconds(5)); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x2905); reg::Write(g_dsi_regs + sizeof(u32) * DSI_TRIGGER, DSI_TRIGGER_HOST); break; case 0x1020: /* Innolux second revision screen. */ case 0x1030: /* AUO second revision screen. */ case 0x1040: /* Unknown second revision screen. */ default: reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x1105); reg::Write(g_dsi_regs + sizeof(u32) * DSI_TRIGGER, DSI_TRIGGER_HOST); os::SleepThread(TimeSpan::FromMilliSeconds(120)); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x2905); reg::Write(g_dsi_regs + sizeof(u32) * DSI_TRIGGER, DSI_TRIGGER_HOST); break; } } else { /* LCD vendor 0x2050, unknown Aula (OLED) screen. */ reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x1105); reg::Write(g_dsi_regs + sizeof(u32) * DSI_TRIGGER, DSI_TRIGGER_HOST); os::SleepThread(TimeSpan::FromMilliSeconds(180)); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0xA015); reg::Write(g_dsi_regs + sizeof(u32) * DSI_TRIGGER, DSI_TRIGGER_HOST); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x205315); reg::Write(g_dsi_regs + sizeof(u32) * DSI_TRIGGER, DSI_TRIGGER_HOST); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x339); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x51); reg::Write(g_dsi_regs + sizeof(u32) * DSI_TRIGGER, DSI_TRIGGER_HOST); os::SleepThread(TimeSpan::FromMilliSeconds(5)); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x2905); reg::Write(g_dsi_regs + sizeof(u32) * DSI_TRIGGER, DSI_TRIGGER_HOST); } os::SleepThread(TimeSpan::FromMilliSeconds(20)); DO_SOC_DEPENDENT_REGISTER_WRITES(g_clk_rst_regs, DisplayConfigPlld02); DO_REGISTER_WRITES(g_dsi_regs, DisplayConfigDsi01Init08); DO_SOC_DEPENDENT_REGISTER_WRITES(g_dsi_regs, DisplayConfigDsiPhyTiming); DO_SLEEP_OR_REGISTER_WRITES(g_dsi_regs, DisplayConfigDsi01Init09); reg::Write(g_disp1_regs + sizeof(u32) * DC_DISP_DISP_CLOCK_CONTROL, SHIFT_CLK_DIVIDER(4)); DO_REGISTER_WRITES(g_dsi_regs, DisplayConfigDsi01Init10); os::SleepThread(TimeSpan::FromMilliSeconds(10)); /* Configure MIPI CAL. */ DO_REGISTER_WRITES(g_mipi_cal_regs, DisplayConfigMipiCal01); DO_SOC_DEPENDENT_REGISTER_WRITES(g_mipi_cal_regs, DisplayConfigMipiCal02); DO_SOC_DEPENDENT_REGISTER_WRITES(g_dsi_regs, DisplayConfigDsi01Init11); DO_SOC_DEPENDENT_REGISTER_WRITES(g_mipi_cal_regs, DisplayConfigMipiCal03); DO_REGISTER_WRITES(g_mipi_cal_regs, DisplayConfigMipiCal04); if (g_soc_type == spl::SocType_Mariko) { /* On Mariko the above configurations are executed twice, for some reason. */ DO_SOC_DEPENDENT_REGISTER_WRITES(g_mipi_cal_regs, DisplayConfigMipiCal02); DO_SOC_DEPENDENT_REGISTER_WRITES(g_dsi_regs, DisplayConfigDsi01Init11); DO_SOC_DEPENDENT_REGISTER_WRITES(g_mipi_cal_regs, DisplayConfigMipiCal03); DO_REGISTER_WRITES(g_mipi_cal_regs, DisplayConfigMipiCal04); } os::SleepThread(TimeSpan::FromMilliSeconds(10)); /* Write DISP1, FrameBuffer config. */ DO_SLEEP_OR_REGISTER_WRITES(g_disp1_regs, DisplayConfigDc02); DO_SLEEP_OR_REGISTER_WRITES(g_disp1_regs, DisplayConfigFrameBuffer); if (g_lcd_vendor != 0x2050) { os::SleepThread(TimeSpan::FromMilliSeconds(35)); } g_is_display_intialized = true; } void ShowDisplay(size_t x, size_t y, size_t width, size_t height, const u32 *img) { if (!g_is_display_intialized) { return; } /* Draw the image to the screen. */ std::memset(g_frame_buffer, 0, FrameBufferSize); { for (size_t cur_y = 0; cur_y < height; cur_y++) { for (size_t cur_x = 0; cur_x < width; cur_x++) { g_frame_buffer[(FrameBufferHeight - (x + cur_x)) * FrameBufferWidth + y + cur_y] = img[cur_y * width + cur_x]; } } } dd::FlushDataCache(g_frame_buffer, FrameBufferSize); /* Enable backlight. */ if (g_lcd_vendor == 0x2050) { EnableBacklightForVendor2050ForAula(g_display_brightness); } else { EnableBacklightForGeneric(g_display_brightness); } } void FinalizeDisplay() { if (!g_is_display_intialized) { return; } /* Disable backlight. */ if (g_lcd_vendor == 0x2050) { EnableBacklightForVendor2050ForAula(0); } else { pwm::driver::SetEnabled(g_lcd_backlight_session, false); pwm::driver::CloseSession(g_lcd_backlight_session); } reg::Write(g_disp1_regs + sizeof(u32) * DSI_VIDEO_MODE_CONTROL, 1); reg::Write(g_disp1_regs + sizeof(u32) * DSI_WR_DATA, 0x2805); /* Nintendo waits 5 frames before continuing. */ { const uintptr_t host1x_vaddr = dd::GetIoMapping(0x500030A4, 4); const u32 start_val = reg::Read(host1x_vaddr); while (reg::Read(host1x_vaddr) < start_val + 5) { /* spinlock here. */ } } reg::Write(g_disp1_regs + sizeof(u32) * DC_CMD_STATE_ACCESS, (READ_MUX | WRITE_MUX)); reg::Write(g_disp1_regs + sizeof(u32) * DSI_VIDEO_MODE_CONTROL, 0); DO_REGISTER_WRITES(g_disp1_regs, DisplayConfigDc01Fini01); os::SleepThread(TimeSpan::FromMilliSeconds(40)); DO_SOC_DEPENDENT_REGISTER_WRITES(g_clk_rst_regs, DisplayConfigPlld01); DO_REGISTER_WRITES(g_dsi_regs, DisplayConfigDsi01Fini01); DO_SOC_DEPENDENT_REGISTER_WRITES(g_dsi_regs, DisplayConfigDsiPhyTiming); DO_REGISTER_WRITES(g_dsi_regs, DisplayConfigDsi01Fini02); if (g_lcd_vendor != 0x2050) { os::SleepThread(TimeSpan::FromMilliSeconds(10)); } /* Vendor specific shutdown. */ switch (g_lcd_vendor) { case 0x10: /* Japan Display Inc screens. */ DO_SLEEP_OR_REGISTER_WRITES(g_dsi_regs, DisplayConfigJdiSpecificFini01); break; case 0xF30: /* AUO first revision screens. */ DO_SLEEP_OR_REGISTER_WRITES(g_dsi_regs, DisplayConfigAuoRev1SpecificFini01); break; case 0x1020: /* Innolux second revision screens. */ reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x439); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x9483FFB9); reg::Write(g_dsi_regs + sizeof(u32) * DSI_TRIGGER, DSI_TRIGGER_HOST); os::SleepThread(TimeSpan::FromMilliSeconds(5)); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0xB39); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x751548B1); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x71143209); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x115631); reg::Write(g_dsi_regs + sizeof(u32) * DSI_TRIGGER, DSI_TRIGGER_HOST); os::SleepThread(TimeSpan::FromMilliSeconds(5)); break; case 0x1030: /* AUO second revision screens. */ reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x439); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x9483FFB9); reg::Write(g_dsi_regs + sizeof(u32) * DSI_TRIGGER, DSI_TRIGGER_HOST); os::SleepThread(TimeSpan::FromMilliSeconds(5)); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0xB39); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x711148B1); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x71143209); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x114D31); reg::Write(g_dsi_regs + sizeof(u32) * DSI_TRIGGER, DSI_TRIGGER_HOST); os::SleepThread(TimeSpan::FromMilliSeconds(5)); break; case 0x1040: /* Unknown second revision screens. */ reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x439); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x9483FFB9); reg::Write(g_dsi_regs + sizeof(u32) * DSI_TRIGGER, DSI_TRIGGER_HOST); os::SleepThread(TimeSpan::FromMilliSeconds(5)); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0xB39); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x731348B1); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x71243209); reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x4C31); reg::Write(g_dsi_regs + sizeof(u32) * DSI_TRIGGER, DSI_TRIGGER_HOST); os::SleepThread(TimeSpan::FromMilliSeconds(5)); break; default: break; } reg::Write(g_dsi_regs + sizeof(u32) * DSI_WR_DATA, 0x1005); reg::Write(g_dsi_regs + sizeof(u32) * DSI_TRIGGER, DSI_TRIGGER_HOST); os::SleepThread(g_lcd_vendor == 0x2050 ? TimeSpan::FromMilliSeconds(120) : TimeSpan::FromMilliSeconds(50)); /* Disable backlight RST/Voltage. */ reg::ClearBits(g_gpio_regs + GPIO_PORT6_OUT_1, 0x4); if (g_lcd_vendor == 0x2050) { os::SleepThread(TimeSpan::FromMilliSeconds(30)); } else { os::SleepThread(TimeSpan::FromMilliSeconds(10)); reg::ClearBits(g_gpio_regs + GPIO_PORT3_OUT_0, 0x2); os::SleepThread(TimeSpan::FromMilliSeconds(10)); reg::ClearBits(g_gpio_regs + GPIO_PORT3_OUT_0, 0x1); os::SleepThread(TimeSpan::FromMilliSeconds(10)); } /* Cut clock to DSI. */ reg::Write(g_clk_rst_regs + CLK_RST_CONTROLLER_RST_DEV_H_SET, CLK_RST_REG_BITS_ENUM(RST_DEV_H_SET_SET_MIPI_CAL_RST, ENABLE), CLK_RST_REG_BITS_ENUM(RST_DEV_H_SET_SET_DSI_RST, ENABLE)); reg::Write(g_clk_rst_regs + CLK_RST_CONTROLLER_CLK_ENB_H_CLR, CLK_RST_REG_BITS_ENUM(CLK_ENB_H_CLR_CLR_CLK_ENB_MIPI_CAL, ENABLE), CLK_RST_REG_BITS_ENUM(CLK_ENB_H_CLR_CLR_CLK_ENB_DSI, ENABLE)); reg::Write(g_clk_rst_regs + CLK_RST_CONTROLLER_RST_DEV_L_SET, CLK_RST_REG_BITS_ENUM(RST_DEV_L_SET_SET_HOST1X_RST, ENABLE), CLK_RST_REG_BITS_ENUM(RST_DEV_L_SET_SET_DISP1_RST, ENABLE)); reg::Write(g_clk_rst_regs + CLK_RST_CONTROLLER_CLK_ENB_L_CLR, CLK_RST_REG_BITS_ENUM(CLK_ENB_L_CLR_CLR_CLK_ENB_HOST1X, ENABLE), CLK_RST_REG_BITS_ENUM(CLK_ENB_L_CLR_CLR_CLK_ENB_DISP1, ENABLE)); reg::Write(g_dsi_regs + sizeof(u32) * DSI_PAD_CONTROL_0, (DSI_PAD_CONTROL_VS1_PULLDN_CLK | DSI_PAD_CONTROL_VS1_PULLDN(0xF) | DSI_PAD_CONTROL_VS1_PDIO_CLK | DSI_PAD_CONTROL_VS1_PDIO(0xF))); reg::Write(g_dsi_regs + sizeof(u32) * DSI_POWER_CONTROL, 0); /* Unmap framebuffer from DC virtual address space. */ FinalizeFrameBuffer(); g_is_display_intialized = false; } void SetDisplayBrightness(int percentage) { g_display_brightness = percentage; } }
34,047
C++
.cpp
543
49.075506
232
0.593999
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,157
boot_splash_screen.cpp
Atmosphere-NX_Atmosphere/stratosphere/boot/source/boot_splash_screen.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have 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 "boot_boot_reason.hpp" #include "boot_display.hpp" #include "boot_splash_screen.hpp" namespace ams::boot { namespace { /* Include splash screen into anonymous namespace. */ /* TODO: Compile-time switch for splash_screen_text.hpp? */ #include "boot_splash_screen_notext.inc" } void ShowSplashScreen() { const auto boot_reason = GetBootReason(); if (boot_reason == spl::BootReason_AcOk || boot_reason == spl::BootReason_RtcAlarm2) { return; } InitializeDisplay(); { /* Splash screen is shown for 2 seconds. */ ShowDisplay(SplashScreenX, SplashScreenY, SplashScreenW, SplashScreenH, SplashScreen); os::SleepThread(TimeSpan::FromSeconds(2)); } FinalizeDisplay(); } }
1,463
C++
.cpp
39
32.871795
98
0.700565
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,158
boot_pmic_driver.cpp
Atmosphere-NX_Atmosphere/stratosphere/boot/source/boot_pmic_driver.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "boot_i2c_utils.hpp" #include "boot_pmic_driver.hpp" namespace ams::boot { void PmicDriver::ShutdownSystem() { this->ShutdownSystem(false); } void PmicDriver::RebootSystem() { this->ShutdownSystem(true); } Result PmicDriver::GetAcOk(bool *out) { u8 power_status; R_TRY(this->GetPowerStatus(std::addressof(power_status))); *out = (power_status & 0x02) != 0; R_SUCCEED(); } Result PmicDriver::GetOnOffIrq(u8 *out) { const u8 addr = 0x0B; R_RETURN(ReadI2cRegister(m_i2c_session, out, sizeof(*out), std::addressof(addr), sizeof(addr))); } Result PmicDriver::GetPowerStatus(u8 *out) { const u8 addr = 0x15; R_RETURN(ReadI2cRegister(m_i2c_session, out, sizeof(*out), std::addressof(addr), sizeof(addr))); } Result PmicDriver::GetNvErc(u8 *out) { const u8 addr = 0x0C; R_RETURN(ReadI2cRegister(m_i2c_session, out, sizeof(*out), std::addressof(addr), sizeof(addr))); } Result PmicDriver::GetPowerButtonPressed(bool *out) { u8 on_off_irq; R_TRY(this->GetOnOffIrq(std::addressof(on_off_irq))); *out = (on_off_irq & 0x08) != 0; R_SUCCEED(); } void PmicDriver::ShutdownSystem(bool reboot) { const u8 on_off_1_addr = 0x41; const u8 on_off_2_addr = 0x42; /* Get value, set or clear software reset mask. */ u8 on_off_2_val = 0; R_ABORT_UNLESS(ReadI2cRegister(m_i2c_session, std::addressof(on_off_2_val), sizeof(on_off_2_val), std::addressof(on_off_2_addr), sizeof(on_off_2_addr))); if (reboot) { on_off_2_val |= 0x80; } else { on_off_2_val &= ~0x80; } R_ABORT_UNLESS(WriteI2cRegister(m_i2c_session, std::addressof(on_off_2_val), sizeof(on_off_2_val), std::addressof(on_off_2_addr), sizeof(on_off_2_addr))); /* Get value, set software reset mask. */ u8 on_off_1_val = 0; R_ABORT_UNLESS(ReadI2cRegister(m_i2c_session, std::addressof(on_off_1_val), sizeof(on_off_1_val), std::addressof(on_off_1_addr), sizeof(on_off_1_addr))); on_off_1_val |= 0x80; /* Finalize the battery on non-Calcio. */ if (spl::GetHardwareType() != spl::HardwareType::Calcio) { BatteryDriver battery_driver; this->FinalizeBattery(battery_driver); } /* Actually write the value to trigger shutdown/reset. */ R_ABORT_UNLESS(WriteI2cRegister(m_i2c_session, std::addressof(on_off_1_val), sizeof(on_off_1_val), std::addressof(on_off_1_addr), sizeof(on_off_1_addr))); /* Allow up to 5 seconds for shutdown/reboot to take place. */ os::SleepThread(TimeSpan::FromSeconds(5)); AMS_ABORT("Shutdown failed"); } void PmicDriver::FinalizeBattery(BatteryDriver &battery_driver) { /* Get whether shutdown is enabled. */ bool shutdown_enabled; if (R_FAILED(battery_driver.IsI2cShutdownEnabled(std::addressof(shutdown_enabled)))) { return; } /* On Hoag, we don't want to use the desired shutdown value when battery charged. */ bool use_desired_shutdown = true; if (spl::GetHardwareType() == spl::HardwareType::Hoag) { float battery_charge_raw; if (R_FAILED(battery_driver.GetChargePercentage(std::addressof(battery_charge_raw))) || battery_charge_raw >= 80.0) { use_desired_shutdown = false; } } bool ac_ok; bool desired_shutdown_enabled; if (R_FAILED(this->GetAcOk(&ac_ok)) || ac_ok) { desired_shutdown_enabled = false; } else { desired_shutdown_enabled = true; } desired_shutdown_enabled &= use_desired_shutdown; if (shutdown_enabled != desired_shutdown_enabled) { battery_driver.SetI2cShutdownEnabled(desired_shutdown_enabled); } } }
4,610
C++
.cpp
103
37.174757
162
0.638734
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,159
boot_clock_initial_configuration.cpp
Atmosphere-NX_Atmosphere/stratosphere/boot/source/boot_clock_initial_configuration.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "boot_clock_initial_configuration.hpp" namespace ams::boot { namespace { constexpr inline dd::PhysicalAddress PmcBase = 0x7000E400; /* Convenience definitions. */ constexpr u32 InitialClockOutMask1x = 0x00C4; constexpr u32 InitialClockOutMask6x = 0xC4C4; } void SetInitialClockConfiguration() { /* Write mask to APBDEV_PMC_PWR_DET, then clear APBDEV_PMC_PWR_DET_VAL. */ const u32 mask = hos::GetVersion() >= hos::Version_6_0_0 ? InitialClockOutMask6x : InitialClockOutMask1x; dd::ReadModifyWriteIoRegister(PmcBase + APBDEV_PMC_CLK_OUT_CNTRL, mask, mask); } }
1,310
C++
.cpp
30
39.566667
113
0.731343
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,160
boot_pinmux_initial_configuration.cpp
Atmosphere-NX_Atmosphere/stratosphere/boot/source/boot_pinmux_initial_configuration.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "boot_pinmux_initial_configuration.hpp" namespace ams::boot { void SetInitialPinmuxConfiguration() { pinmux::driver::Initialize(); pinmux::driver::SetInitialConfig(); pinmux::driver::SetInitialDrivePadConfig(); pinmux::driver::Finalize(); } }
958
C++
.cpp
25
35.04
76
0.737634
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,161
boot_check_battery.cpp
Atmosphere-NX_Atmosphere/stratosphere/boot/source/boot_check_battery.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have 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 "boot_check_battery.hpp" #include "boot_battery_icons.hpp" #include "boot_boot_reason.hpp" #include "boot_pmic_driver.hpp" #include "boot_battery_driver.hpp" #include "boot_charger_driver.hpp" #include "boot_power_utils.hpp" namespace ams::boot { namespace { /* Value definitions. */ constexpr inline double BatteryLevelThresholdForBoot = 3.0; constexpr inline double BatteryLevelThresholdForFullCharge = 99.0; constexpr inline int BatteryVoltageThresholdConnected = 4000; constexpr inline int BatteryVoltageThresholdDisconnected = 3650; /* Types. */ enum class CheckBatteryResult { Success, Shutdown, Reboot, }; class BatteryChecker { private: boot::ChargerDriver &m_charger_driver; boot::BatteryDriver &m_battery_driver; const powctl::driver::impl::ChargeParameters &m_charge_parameters; powctl::driver::impl::ChargeArbiter m_charge_arbiter; powctl::ChargeCurrentState m_charge_current_state; int m_fast_charge_current_limit; int m_charge_voltage_limit; int m_battery_compensation; int m_voltage_clamp; TimeSpan m_charging_done_interval; bool m_has_start_time; TimeSpan m_start_time; private: bool IsChargeDone(); void UpdateChargeDoneCurrent(); void ApplyArbiterRule(); void PrintBatteryStatus(float raw_charge, int voltage, int voltage_threshold); CheckBatteryResult LoopCheckBattery(bool reboot_on_power_button_press, bool return_on_enough_battery, bool shutdown_on_full_battery, bool show_display, bool show_charging_display); void UpdateStartTime() { /* Update start time. */ m_start_time = os::ConvertToTimeSpan(os::GetSystemTick()); m_has_start_time = true; } public: BatteryChecker(boot::ChargerDriver &cd, boot::BatteryDriver &bd, const powctl::driver::impl::ChargeParameters &cp, int cvl) : m_charger_driver(cd), m_battery_driver(bd), m_charge_parameters(cp), m_charge_arbiter(cp.rules, cp.num_rules, cvl), m_charging_done_interval(TimeSpan::FromSeconds(2)), m_has_start_time(false) { /* Get parameters from charger. */ if (R_FAILED(m_charger_driver.GetChargeCurrentState(std::addressof(m_charge_current_state)))) { boot::ShutdownSystem(); } if (R_FAILED(m_charger_driver.GetFastChargeCurrentLimit(std::addressof(m_fast_charge_current_limit)))) { boot::ShutdownSystem(); } if (R_FAILED(m_charger_driver.GetChargeVoltageLimit(std::addressof(m_charge_voltage_limit)))) { boot::ShutdownSystem(); } if (R_FAILED(m_charger_driver.GetBatteryCompensation(std::addressof(m_battery_compensation)))) { boot::ShutdownSystem(); } if (R_FAILED(m_charger_driver.GetVoltageClamp(std::addressof(m_voltage_clamp)))) { boot::ShutdownSystem(); } /* Update start time. */ this->UpdateStartTime(); } CheckBatteryResult LoopCheckBattery(spl::BootReason boot_reason) { if (boot_reason == spl::BootReason_RtcAlarm2) { /* RTC Alarm 2 boot (QuasiOff) */ return this->LoopCheckBattery(true, false, true, false, false); } else if (boot_reason == spl::BootReason_AcOk) { /* ACOK boot */ return this->LoopCheckBattery(true, true, false, true, true); } else { /* Normal boot */ return this->LoopCheckBattery(false, true, false, true, false); } } void UpdateCharger(); }; void BatteryChecker::PrintBatteryStatus(float raw_charge, int voltage, int voltage_threshold) { /* TODO: Print charge/voltage/threshold. */ AMS_UNUSED(raw_charge, voltage, voltage_threshold); /* Get various battery metrics. */ int avg_current, current; float temp, voltage_fuel_gauge_percentage; if (R_FAILED(m_battery_driver.GetAverageCurrent(std::addressof(avg_current)))) { return; } if (R_FAILED(m_battery_driver.GetCurrent(std::addressof(current)))) { return; } if (R_FAILED(m_battery_driver.GetTemperature(std::addressof(temp)))) { return; } if (R_FAILED(m_battery_driver.GetVoltageFuelGaugePercentage(std::addressof(voltage_fuel_gauge_percentage)))) { return; } /* TODO: Print the things we just got. */ AMS_UNUSED(avg_current, current, temp, voltage_fuel_gauge_percentage); } bool BatteryChecker::IsChargeDone() { /* Get the charger status. */ boot::ChargerStatus charger_status; if (R_FAILED(m_charger_driver.GetChargerStatus(std::addressof(charger_status)))) { boot::ShutdownSystem(); } /* If charge status isn't done, we're not done. */ if (charger_status != boot::ChargerStatus_ChargeTerminationDone) { return false; } /* Return whether a done current of zero is acceptable. */ return m_charge_arbiter.IsBatteryDoneCurrentAcceptable(0); } void BatteryChecker::UpdateChargeDoneCurrent() { int done_current = 0; if (m_has_start_time && (os::ConvertToTimeSpan(os::GetSystemTick()) - m_start_time) >= m_charging_done_interval) { /* Get the current. */ if (R_FAILED(m_battery_driver.GetCurrent(std::addressof(done_current)))) { boot::ShutdownSystem(); } } else { /* Get the charger status. */ boot::ChargerStatus charger_status; if (R_FAILED(m_charger_driver.GetChargerStatus(std::addressof(charger_status)))) { boot::ShutdownSystem(); } /* If the charger status isn't done, don't update. */ if (charger_status != boot::ChargerStatus_ChargeTerminationDone) { return; } } /* Update done current. */ m_charge_arbiter.SetBatteryDoneCurrent(done_current); } void BatteryChecker::UpdateCharger() { /* Get the battery temperature. */ float temp; if (R_FAILED(m_battery_driver.GetTemperature(std::addressof(temp)))) { boot::ShutdownSystem(); } /* Update the temperature level. */ powctl::BatteryTemperatureLevel temp_level; if (temp < static_cast<float>(m_charge_parameters.temp_min)) { temp_level = powctl::BatteryTemperatureLevel::TooLow; } else if (temp < static_cast<float>(m_charge_parameters.temp_low)) { temp_level = powctl::BatteryTemperatureLevel::Low; } else if (temp < static_cast<float>(m_charge_parameters.temp_high)) { temp_level = powctl::BatteryTemperatureLevel::Medium; } else if (temp < static_cast<float>(m_charge_parameters.temp_max)) { temp_level = powctl::BatteryTemperatureLevel::High; } else { temp_level = powctl::BatteryTemperatureLevel::TooHigh; } m_charge_arbiter.SetBatteryTemperatureLevel(temp_level); /* Update average voltage. */ int avg_v_cell; if (R_FAILED(m_battery_driver.GetAverageVCell(std::addressof(avg_v_cell)))) { boot::ShutdownSystem(); } m_charge_arbiter.SetBatteryAverageVCell(avg_v_cell); /* Update voltage fuel gauge percentage. */ float vfgp; if (R_FAILED(m_battery_driver.GetVoltageFuelGaugePercentage(std::addressof(vfgp)))) { boot::ShutdownSystem(); } m_charge_arbiter.SetBatteryVoltageFuelGaugePercentage(vfgp); /* Update charge done current. */ this->UpdateChargeDoneCurrent(); /* Update arbiter power state. */ m_charge_arbiter.SetPowerState(powctl::PowerState::ShutdownChargeMain); /* Apply the newly selected rule. */ this->ApplyArbiterRule(); } void BatteryChecker::ApplyArbiterRule() { /* Get the selected rule. */ const auto *rule = m_charge_arbiter.GetSelectedRule(); AMS_ASSERT(rule != nullptr); /* Check if we need to perform charger initialization. */ const bool reinit_charger = rule->reinitialize_charger; const auto cur_charge_current_state = m_charge_current_state; /* Set the charger to not charging while we make changes. */ if (!reinit_charger || cur_charge_current_state != powctl::ChargeCurrentState_NotCharging) { if (R_FAILED(m_charger_driver.SetChargeCurrentState(powctl::ChargeCurrentState_NotCharging))) { boot::ShutdownSystem(); } m_charge_current_state = powctl::ChargeCurrentState_NotCharging; /* Update start time. */ this->UpdateStartTime(); } /* Process fast charge current limit when rule is smaller. */ const auto rule_fast_charge_current_limit = rule->fast_charge_current_limit; const auto cur_fast_charge_current_limit = m_fast_charge_current_limit; if (rule_fast_charge_current_limit < cur_fast_charge_current_limit) { if (R_FAILED(m_charger_driver.SetFastChargeCurrentLimit(rule_fast_charge_current_limit))) { boot::ShutdownSystem(); } m_fast_charge_current_limit = rule_fast_charge_current_limit; /* Update start time. */ this->UpdateStartTime(); } /* Process charge voltage limit when rule is smaller. */ const auto rule_charge_voltage_limit = std::min(rule->charge_voltage_limit, m_charge_arbiter.GetChargeVoltageLimit()); const auto cur_charge_voltage_limit = m_charge_voltage_limit; if (rule_charge_voltage_limit < cur_charge_voltage_limit) { if (R_FAILED(m_charger_driver.SetChargeVoltageLimit(rule_charge_voltage_limit))) { boot::ShutdownSystem(); } m_charge_voltage_limit = rule_charge_voltage_limit; /* Update start time. */ this->UpdateStartTime(); } /* Process battery compensation when rule is smaller. */ const auto rule_battery_compensation = rule->battery_compensation; const auto cur_battery_compensation = m_battery_compensation; if (rule_battery_compensation < cur_battery_compensation) { if (R_FAILED(m_charger_driver.SetBatteryCompensation(rule_battery_compensation))) { boot::ShutdownSystem(); } m_battery_compensation = rule_battery_compensation; /* Update start time. */ this->UpdateStartTime(); } /* Process voltage clamp when rule is smaller. */ const auto rule_voltage_clamp = rule->voltage_clamp; const auto cur_voltage_clamp = m_voltage_clamp; if (rule_voltage_clamp < cur_voltage_clamp) { if (R_FAILED(m_charger_driver.SetVoltageClamp(rule_voltage_clamp))) { boot::ShutdownSystem(); } m_voltage_clamp = rule_voltage_clamp; /* Update start time. */ this->UpdateStartTime(); } /* Process voltage clamp when rule is larger. */ if (rule_voltage_clamp > cur_voltage_clamp) { if (R_FAILED(m_charger_driver.SetVoltageClamp(rule_voltage_clamp))) { boot::ShutdownSystem(); } m_voltage_clamp = rule_voltage_clamp; /* Update start time. */ this->UpdateStartTime(); } /* Process battery compensation when rule is larger. */ if (rule_battery_compensation > cur_battery_compensation) { if (R_FAILED(m_charger_driver.SetBatteryCompensation(rule_battery_compensation))) { boot::ShutdownSystem(); } m_battery_compensation = rule_battery_compensation; /* Update start time. */ this->UpdateStartTime(); } /* Process fast charge current limit when rule is larger. */ if (rule_fast_charge_current_limit > cur_fast_charge_current_limit) { if (R_FAILED(m_charger_driver.SetFastChargeCurrentLimit(rule_fast_charge_current_limit))) { boot::ShutdownSystem(); } m_fast_charge_current_limit = rule_fast_charge_current_limit; /* Update start time. */ this->UpdateStartTime(); } /* Process charge voltage limit when rule is larger. */ if (rule_charge_voltage_limit > cur_charge_voltage_limit) { if (R_FAILED(m_charger_driver.SetChargeVoltageLimit(rule_charge_voltage_limit))) { boot::ShutdownSystem(); } m_charge_voltage_limit = rule_charge_voltage_limit; /* Update start time. */ this->UpdateStartTime(); } /* If we're not charging and we expect to reinitialize the charger, do so. */ if (cur_charge_current_state != powctl::ChargeCurrentState_Charging && reinit_charger) { if (R_FAILED(m_charger_driver.SetChargeCurrentState(powctl::ChargeCurrentState_Charging))) { boot::ShutdownSystem(); } m_charge_current_state = powctl::ChargeCurrentState_Charging; /* Update start time. */ this->UpdateStartTime(); } } CheckBatteryResult BatteryChecker::LoopCheckBattery(bool reboot_on_power_button_press, bool return_on_enough_battery, bool shutdown_on_full_battery, bool show_display, bool show_charging_display) { /* Ensure that if we show a charging icon, we stop showing it when we're done. */ bool is_showing_charging_icon = false; ON_SCOPE_EXIT { if (is_showing_charging_icon) { boot::EndShowChargingIcon(); is_showing_charging_icon = false; } }; /* Show the charging display, if we should. */ if (show_charging_display) { /* Get the raw battery charge. */ float raw_battery_charge; if (R_FAILED(m_battery_driver.GetChargePercentage(std::addressof(raw_battery_charge)))) { return CheckBatteryResult::Shutdown; } /* Display the battery with the appropriate percentage. */ const auto battery_charge = powctl::impl::ConvertBatteryChargePercentage(raw_battery_charge); boot::StartShowChargingIcon(battery_charge); is_showing_charging_icon = true; } /* Loop, checking the battery status. */ TimeSpan last_progress_time = TimeSpan(0); while (true) { /* Get the raw battery charge. */ float raw_battery_charge; if (R_FAILED(m_battery_driver.GetChargePercentage(std::addressof(raw_battery_charge)))) { return CheckBatteryResult::Shutdown; } /* Get the average vcell. */ int battery_voltage; if (R_FAILED(m_battery_driver.GetAverageVCell(std::addressof(battery_voltage)))) { return CheckBatteryResult::Shutdown; } /* Get whether we're connected to charger. */ bool ac_ok; if (R_FAILED((boot::PmicDriver().GetAcOk(std::addressof(ac_ok))))) { return CheckBatteryResult::Shutdown; } /* Decide on a battery voltage threshold. */ const auto battery_voltage_threshold = ac_ok ? BatteryVoltageThresholdConnected : BatteryVoltageThresholdDisconnected; /* Check if we should return. */ if (return_on_enough_battery) { if (raw_battery_charge >= BatteryLevelThresholdForBoot || battery_voltage >= battery_voltage_threshold) { this->PrintBatteryStatus(raw_battery_charge, battery_voltage, battery_voltage_threshold); return CheckBatteryResult::Success; } } /* Otherwise, check if we should shut down. */ if (shutdown_on_full_battery) { if (raw_battery_charge >= BatteryLevelThresholdForFullCharge || this->IsChargeDone()) { return CheckBatteryResult::Shutdown; } } /* Perform periodic printing. */ constexpr TimeSpan PrintProgressInterval = TimeSpan::FromSeconds(10); const auto cur_time = os::ConvertToTimeSpan(os::GetSystemTick()); if ((cur_time - last_progress_time) >= PrintProgressInterval) { last_progress_time = cur_time; this->PrintBatteryStatus(raw_battery_charge, battery_voltage, battery_voltage_threshold); } /* If we've gotten to this point, we have insufficient battery to boot. If we aren't charging, show low battery and shutdown. */ if (!ac_ok) { this->PrintBatteryStatus(raw_battery_charge, battery_voltage, battery_voltage_threshold); if (show_display && !is_showing_charging_icon) { boot::ShowLowBatteryIcon(); } return CheckBatteryResult::Shutdown; } /* Check if we should reboot due to a power button press. */ if (reboot_on_power_button_press) { /* Get the power button value. */ bool power_button_pressed; if (R_FAILED((boot::PmicDriver().GetPowerButtonPressed(std::addressof(power_button_pressed))))) { return CheckBatteryResult::Shutdown; } /* Handle the press (or not). */ if (power_button_pressed) { return CheckBatteryResult::Reboot; } } /* If we got to this point, we should show the low-battery charging screen. */ if (show_display && !is_showing_charging_icon) { boot::StartShowLowBatteryChargingIcon(); is_showing_charging_icon = true; } /* Wait a bit before checking again. */ constexpr auto BatteryChargeCheckInterval = TimeSpan::FromMilliSeconds(20); os::SleepThread(BatteryChargeCheckInterval); /* Update the charger. */ this->UpdateCharger(); } } } void CheckBatteryCharge() { /* Open a sessions for the charger/battery. */ boot::ChargerDriver charger_driver; boot::BatteryDriver battery_driver; /* Check if the battery is removed. */ { bool removed = false; if (R_FAILED(battery_driver.IsBatteryRemoved(std::addressof(removed))) || removed) { boot::ShutdownSystem(); } } /* Get the boot reason. */ const auto boot_reason = boot::GetBootReason(); /* Initialize the charger driver. */ if (R_FAILED(charger_driver.Initialize(boot_reason != spl::BootReason_RtcAlarm2))) /* Check that the charger input limit is greater than 150 milli-amps. */ { int input_current_limit_ma; if (R_FAILED(charger_driver.GetInputCurrentLimit(std::addressof(input_current_limit_ma)))) { boot::ShutdownSystem(); } if (input_current_limit_ma <= 150) { charger_driver.SetChargerConfiguration(powctl::ChargerConfiguration_ChargeDisable); boot::ShutdownSystem(); } } /* Get the charge parameters. */ const auto &charge_parameters = powctl::driver::impl::GetChargeParameters(); /* Get the charge voltage limit. */ int charge_voltage_limit_mv; if (boot_reason != spl::BootReason_RtcAlarm2 || charge_parameters.unknown_x_table == nullptr || charge_parameters.x_table_size == 0) { charge_voltage_limit_mv = charge_parameters.default_charge_voltage_limit; } else { if (R_FAILED(charger_driver.GetChargeVoltageLimit(std::addressof(charge_voltage_limit_mv)))) { boot::ShutdownSystem(); } } /* Create and update a battery checker. */ BatteryChecker battery_checker(charger_driver, battery_driver, charge_parameters, charge_voltage_limit_mv); battery_checker.UpdateCharger(); /* Set the display brightness to 25%. */ boot::SetDisplayBrightness(25); /* Check the battery. */ const CheckBatteryResult check_result = battery_checker.LoopCheckBattery(boot_reason); /* Set the display brightness to 100%. */ boot::SetDisplayBrightness(100); /* Handle the check result. */ switch (check_result) { case CheckBatteryResult::Success: break; case CheckBatteryResult::Shutdown: boot::ShutdownSystem(); break; case CheckBatteryResult::Reboot: boot::RebootSystem(); break; AMS_UNREACHABLE_DEFAULT_CASE(); } } }
23,627
C++
.cpp
450
37.635556
335
0.569833
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,162
boot_i2c_utils.cpp
Atmosphere-NX_Atmosphere/stratosphere/boot/source/boot_i2c_utils.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "boot_i2c_utils.hpp" namespace ams::boot { namespace { template<typename F> constexpr Result RetryUntilSuccess(F f) { constexpr auto Timeout = TimeSpan::FromSeconds(10); constexpr auto RetryInterval = TimeSpan::FromMilliSeconds(20); TimeSpan cur_time = TimeSpan(0); while (true) { const auto retry_result = f(); R_SUCCEED_IF(R_SUCCEEDED(retry_result)); cur_time += RetryInterval; R_UNLESS(cur_time < Timeout, retry_result); os::SleepThread(RetryInterval); } } } Result ReadI2cRegister(i2c::driver::I2cSession &session, u8 *dst, size_t dst_size, const u8 *cmd, size_t cmd_size) { AMS_ABORT_UNLESS(dst != nullptr && dst_size > 0); AMS_ABORT_UNLESS(cmd != nullptr && cmd_size > 0); u8 cmd_list[i2c::CommandListLengthMax]; i2c::CommandListFormatter formatter(cmd_list, sizeof(cmd_list)); R_ABORT_UNLESS(formatter.EnqueueSendCommand(i2c::TransactionOption_StartCondition, cmd, cmd_size)); R_ABORT_UNLESS(formatter.EnqueueReceiveCommand(static_cast<i2c::TransactionOption>(i2c::TransactionOption_StartCondition | i2c::TransactionOption_StopCondition), dst_size)); R_RETURN(RetryUntilSuccess([&]() { R_RETURN(i2c::driver::ExecuteCommandList(dst, dst_size, session, cmd_list, formatter.GetCurrentLength())); })); } Result WriteI2cRegister(i2c::driver::I2cSession &session, const u8 *src, size_t src_size, const u8 *cmd, size_t cmd_size) { AMS_ABORT_UNLESS(src != nullptr && src_size > 0); AMS_ABORT_UNLESS(cmd != nullptr && cmd_size > 0); u8 cmd_list[0x20]; /* N doesn't use a CommandListFormatter here... */ std::memcpy(cmd_list + 0, cmd, cmd_size); std::memcpy(cmd_list + cmd_size, src, src_size); R_RETURN(RetryUntilSuccess([&]() { R_RETURN(i2c::driver::Send(session, cmd_list, src_size + cmd_size, static_cast<i2c::TransactionOption>(i2c::TransactionOption_StartCondition | i2c::TransactionOption_StopCondition))); })); } Result WriteI2cRegister(i2c::driver::I2cSession &session, const u8 address, const u8 value) { R_RETURN(WriteI2cRegister(session, std::addressof(value), sizeof(value), &address, sizeof(address))); } }
3,023
C++
.cpp
55
47.654545
231
0.677736
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,163
boot_rtc_driver.cpp
Atmosphere-NX_Atmosphere/stratosphere/boot/source/boot_rtc_driver.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "boot_rtc_driver.hpp" namespace ams::boot { Result RtcDriver::ReadRtcRegister(u8 *out, u8 address) { const u8 update_addr = 0x04; const u8 update_val = 0x10; R_TRY(WriteI2cRegister(m_i2c_session, &update_val, sizeof(update_val), &update_addr, sizeof(update_addr))); os::SleepThread(TimeSpan::FromMilliSeconds(16)); R_RETURN(ReadI2cRegister(m_i2c_session, out, sizeof(*out), &address, sizeof(address))); } Result RtcDriver::GetRtcIntr(u8 *out) { const u8 addr = 0x00; R_RETURN(ReadI2cRegister(m_i2c_session, out, sizeof(*out), &addr, sizeof(addr))); } Result RtcDriver::GetRtcIntrM(u8 *out) { const u8 addr = 0x01; R_RETURN(this->ReadRtcRegister(out, addr)); } }
1,435
C++
.cpp
34
37.823529
115
0.704155
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,164
boot_repair_boot_images.cpp
Atmosphere-NX_Atmosphere/stratosphere/boot/source/boot_repair_boot_images.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have 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 "boot_power_utils.hpp" #include "boot_repair_boot_images.hpp" namespace ams::boot { namespace { /* Globals. */ alignas(os::MemoryPageSize) u8 g_boot_image_work_buffer[0x10000]; } void CheckAndRepairBootImages() { const auto boot_image_update_type = updater::GetBootImageUpdateType(spl::GetHardwareType()); bool repaired_normal, repaired_safe; if (R_SUCCEEDED(updater::VerifyBootImagesAndRepairIfNeeded(&repaired_normal, &repaired_safe, g_boot_image_work_buffer, sizeof(g_boot_image_work_buffer), boot_image_update_type)) && repaired_normal) { /* Nintendo only performs a reboot on successful normal repair. */ RebootSystem(); } } }
1,399
C++
.cpp
32
39.3125
207
0.722059
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,165
boot_boot_reason.cpp
Atmosphere-NX_Atmosphere/stratosphere/boot/source/boot_boot_reason.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have 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 "boot_boot_reason.hpp" #include "boot_pmic_driver.hpp" #include "boot_rtc_driver.hpp" namespace ams::boot { namespace { /* Globals. */ constinit spl::BootReason g_boot_reason = spl::BootReason_Unknown; constinit bool g_detected_boot_reason = false; /* Helpers. */ spl::BootReason DetectBootReason(u32 power_intr, u8 rtc_intr, u8 nv_erc, bool ac_ok) { if (power_intr & 0x08) { return spl::BootReason_OnKey; } if (rtc_intr & 0x02) { return spl::BootReason_RtcAlarm1; } if (power_intr & 0x80) { return spl::BootReason_AcOk; } if (rtc_intr & 0x04) { if (nv_erc != 0x80 && !spl::IsRecoveryBoot()) { return spl::BootReason_RtcAlarm2; } } if ((nv_erc & 0x40) && ac_ok) { return spl::BootReason_AcOk; } return spl::BootReason_Unknown; } } void DetectBootReason() { u8 power_intr; u8 rtc_intr; u8 rtc_intr_m; u8 nv_erc; bool ac_ok; /* Get values from PMIC. */ { PmicDriver pmic_driver; R_ABORT_UNLESS(pmic_driver.GetOnOffIrq(std::addressof(power_intr))); R_ABORT_UNLESS(pmic_driver.GetNvErc(std::addressof(nv_erc))); R_ABORT_UNLESS(pmic_driver.GetAcOk(std::addressof(ac_ok))); } /* Get values from RTC. */ { RtcDriver rtc_driver; R_ABORT_UNLESS(rtc_driver.GetRtcIntr(std::addressof(rtc_intr))); R_ABORT_UNLESS(rtc_driver.GetRtcIntrM(std::addressof(rtc_intr_m))); } /* Set global derived boot reason. */ g_boot_reason = DetectBootReason(power_intr, rtc_intr & ~rtc_intr_m, nv_erc, ac_ok); /* Set boot reason for SPL. */ if (hos::GetVersion() >= hos::Version_3_0_0) { /* Create the boot reason value. */ spl::BootReasonValue boot_reason_value = {}; boot_reason_value.power_intr = power_intr; boot_reason_value.rtc_intr = rtc_intr & ~rtc_intr_m; boot_reason_value.nv_erc = nv_erc; boot_reason_value.boot_reason = g_boot_reason; /* Set the boot reason value. */ R_ABORT_UNLESS(spl::SetBootReason(boot_reason_value)); } g_detected_boot_reason = true; } spl::BootReason GetBootReason() { AMS_ABORT_UNLESS(g_detected_boot_reason); return g_boot_reason; } }
3,288
C++
.cpp
85
29.694118
94
0.587774
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,166
boot_power_utils.cpp
Atmosphere-NX_Atmosphere/stratosphere/boot/source/boot_power_utils.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "boot_power_utils.hpp" #include "boot_pmic_driver.hpp" #include "fusee_bin.h" namespace ams::boot { namespace { /* Convenience definitions. */ constexpr uintptr_t IramBase = 0x40000000ull; constexpr uintptr_t IramPayloadBase = 0x40010000ull; constexpr size_t IramSize = 0x40000; constexpr size_t IramPayloadMaxSize = 0x24000; constexpr size_t IramFatalErrorContextOffset = 0x2E000; /* Globals. */ alignas(os::MemoryPageSize) u8 g_work_page[os::MemoryPageSize]; /* Helpers. */ void ClearIram() { /* Make page FFs. */ std::memset(g_work_page, 0xFF, sizeof(g_work_page)); /* Overwrite all of IRAM with FFs. */ for (size_t ofs = 0; ofs < IramSize; ofs += sizeof(g_work_page)) { exosphere::CopyToIram(IramBase + ofs, g_work_page, sizeof(g_work_page)); } } void DoRebootToPayload() { /* Ensure clean IRAM state. */ ClearIram(); /* Copy in payload. */ for (size_t ofs = 0; ofs < fusee_bin_size; ofs += sizeof(g_work_page)) { std::memcpy(g_work_page, fusee_bin + ofs, std::min(static_cast<size_t>(fusee_bin_size - ofs), sizeof(g_work_page))); exosphere::CopyToIram(IramPayloadBase + ofs, g_work_page, sizeof(g_work_page)); } exosphere::ForceRebootToIramPayload(); } void DoRebootToFatalError(const ams::FatalErrorContext *ctx) { /* Ensure clean IRAM state. */ ClearIram(); /* Copy in payload. */ for (size_t ofs = 0; ofs < fusee_bin_size; ofs += sizeof(g_work_page)) { std::memcpy(g_work_page, fusee_bin + ofs, std::min(static_cast<size_t>(fusee_bin_size - ofs), sizeof(g_work_page))); exosphere::CopyToIram(IramPayloadBase + ofs, g_work_page, sizeof(g_work_page)); } /* Copy in fatal error context, if relevant. */ if (ctx != nullptr) { std::memset(g_work_page, 0xCC, sizeof(g_work_page)); std::memcpy(g_work_page, ctx, sizeof(*ctx)); exosphere::CopyToIram(IramPayloadBase + IramFatalErrorContextOffset, g_work_page, sizeof(g_work_page)); } exosphere::ForceRebootToFatalError(); } } void RebootSystem() { if (spl::GetSocType() == spl::SocType_Erista) { DoRebootToPayload(); } else { /* On Mariko, we can't reboot to payload, so we should just do a reboot. */ PmicDriver().RebootSystem(); } } void ShutdownSystem() { PmicDriver().ShutdownSystem(); } void SetInitialRebootPayload() { ::ams::SetInitialRebootPayload(fusee_bin, fusee_bin_size); } void RebootForFatalError(ams::FatalErrorContext *ctx) { DoRebootToFatalError(ctx); } }
3,627
C++
.cpp
83
34.915663
132
0.613791
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,167
boot_battery_icons.cpp
Atmosphere-NX_Atmosphere/stratosphere/boot/source/boot_battery_icons.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have 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 "boot_battery_icons.hpp" #include "boot_display.hpp" namespace ams::boot { namespace { /* Pull in icon definitions. */ #include "boot_battery_icon_low.inc" #include "boot_battery_icon_charging.inc" #include "boot_battery_icon_charging_red.inc" /* Helpers. */ void FillBatteryMeter(u32 *icon, const size_t icon_w, const size_t icon_h, const size_t meter_x, const size_t meter_y, const size_t meter_w, const size_t meter_h, const size_t fill_w) { const size_t fill_x = meter_x + meter_w - fill_w; if (fill_x + fill_w > icon_w || meter_y + meter_h > icon_h || fill_x == 0) { return; } u32 *cur_row = icon + meter_y * icon_w + fill_x; for (size_t y = 0; y < meter_h; y++) { /* Make last column of meter identical to first column of meter. */ cur_row[-1] = icon[(meter_y + y) * icon_w + meter_x]; /* Black out further pixels. */ for (size_t x = 0; x < fill_w; x++) { cur_row[x] = 0xFF000000; } cur_row += icon_w; } } } void ShowLowBatteryIcon() { InitializeDisplay(); { /* Low battery icon is shown for 5 seconds. */ ShowDisplay(LowBatteryX, LowBatteryY, LowBatteryW, LowBatteryH, LowBattery); os::SleepThread(TimeSpan::FromSeconds(5)); } FinalizeDisplay(); } void StartShowChargingIcon(int battery_percentage, bool wait) { const bool is_red = battery_percentage <= 15; const size_t IconX = is_red ? ChargingRedBatteryX : ChargingBatteryX; const size_t IconY = is_red ? ChargingRedBatteryY : ChargingBatteryY; const size_t IconW = is_red ? ChargingRedBatteryW : ChargingBatteryW; const size_t IconH = is_red ? ChargingRedBatteryH : ChargingBatteryH; const size_t IconMeterX = is_red ? ChargingRedBatteryMeterX : ChargingBatteryMeterX; const size_t IconMeterY = is_red ? ChargingRedBatteryMeterY : ChargingBatteryMeterY; const size_t IconMeterW = is_red ? ChargingRedBatteryMeterW : ChargingBatteryMeterW; const size_t IconMeterH = is_red ? ChargingRedBatteryMeterH : ChargingBatteryMeterH; const size_t MeterFillW = static_cast<size_t>(IconMeterW * (1.0 - (0.0404 + 0.0096 * static_cast<double>(battery_percentage))) + 0.5); /* Create stack buffer, copy icon into it, draw fill meter, draw. */ { u32 Icon[IconW * IconH]; std::memcpy(Icon, is_red ? ChargingRedBattery : ChargingBattery, sizeof(Icon)); FillBatteryMeter(Icon, IconW, IconH, IconMeterX, IconMeterY, IconMeterW, IconMeterH, MeterFillW); InitializeDisplay(); ShowDisplay(IconX, IconY, IconW, IconH, Icon); } /* Wait for 2 seconds if we're supposed to. */ if (wait) { os::SleepThread(TimeSpan::FromSeconds(2)); } } void EndShowChargingIcon() { FinalizeDisplay(); } }
3,778
C++
.cpp
79
39.253165
193
0.630464
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,168
boot_main.cpp
Atmosphere-NX_Atmosphere/stratosphere/boot/source/boot_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 "boot_boot_reason.hpp" #include "boot_change_voltage.hpp" #include "boot_check_battery.hpp" #include "boot_check_clock.hpp" #include "boot_clock_initial_configuration.hpp" #include "boot_driver_management.hpp" #include "boot_fan_enable.hpp" #include "boot_pinmux_initial_configuration.hpp" #include "boot_repair_boot_images.hpp" #include "boot_splash_screen.hpp" #include "boot_power_utils.hpp" namespace ams { namespace boot { namespace { constinit u8 g_exp_heap_memory[20_KB]; constinit u8 g_unit_heap_memory[5_KB]; constinit lmem::HeapHandle g_exp_heap_handle; constinit lmem::HeapHandle g_unit_heap_handle; constinit sf::ExpHeapMemoryResource g_exp_heap_memory_resource; constinit sf::UnitHeapMemoryResource g_unit_heap_memory_resource; void *Allocate(size_t size) { void *mem = lmem::AllocateFromExpHeap(g_exp_heap_handle, size); return mem; } void Deallocate(void *p, size_t size) { AMS_UNUSED(size); lmem::FreeToExpHeap(g_exp_heap_handle, p); } void InitializeHeaps() { /* Create the heaps. */ g_exp_heap_handle = lmem::CreateExpHeap(g_exp_heap_memory, sizeof(g_exp_heap_memory), lmem::CreateOption_ThreadSafe); g_unit_heap_handle = lmem::CreateUnitHeap(g_unit_heap_memory, sizeof(g_unit_heap_memory), sizeof(ddsf::DeviceCodeEntryHolder), lmem::CreateOption_ThreadSafe); /* Attach the memory resources. */ g_exp_heap_memory_resource.Attach(g_exp_heap_handle); g_unit_heap_memory_resource.Attach(g_unit_heap_handle); /* Register with ddsf. */ ddsf::SetMemoryResource(std::addressof(g_exp_heap_memory_resource)); ddsf::SetDeviceCodeEntryHolderMemoryResource(std::addressof(g_unit_heap_memory_resource)); } } } namespace hos { void SetNonApproximateVersionInternal(); } namespace init { void InitializeSystemModule() { /* Initialize heaps. */ boot::InitializeHeaps(); /* Connect to sm. */ R_ABORT_UNLESS(sm::Initialize()); /* Initialize fs. */ fs::InitializeForSystem(); fs::SetAllocator(boot::Allocate, boot::Deallocate); fs::SetEnabledAutoAbort(false); /* Initialize spl. */ spl::Initialize(); /* Set the true hos version. */ hos::SetNonApproximateVersionInternal(); /* Verify that we can sanely execute. */ ams::CheckApiVersion(); } void FinalizeSystemModule() { /* ... */ } void Startup() { /* ... */ } } void ExceptionHandler(FatalErrorContext *ctx) { /* We're boot sysmodule, so manually reboot to fatal error. */ boot::RebootForFatalError(ctx); } void Main() { /* Set thread name. */ os::SetThreadNamePointer(os::GetCurrentThread(), AMS_GET_SYSTEM_THREAD_NAME(boot, Main)); AMS_ASSERT(os::GetThreadPriority(os::GetCurrentThread()) == AMS_GET_SYSTEM_THREAD_PRIORITY(boot, Main)); /* Perform atmosphere-specific init. */ ams::InitializeForBoot(); /* Set the reboot payload with ams.mitm. */ boot::SetInitialRebootPayload(); /* Change voltage from 3.3v to 1.8v for select devices. */ boot::ChangeGpioVoltageTo1_8v(); /* Setup gpio. */ gpio::driver::SetInitialGpioConfig(); /* Initialize the gpio server library. */ boot::InitializeGpioDriverLibrary(); /* Initialize the i2c server library. */ boot::InitializeI2cDriverLibrary(); /* Get the hardware type. */ const auto hw_type = spl::GetHardwareType(); /* Initialize the power control library without interrupt event handling. */ if (hw_type != spl::HardwareType::Calcio) { powctl::Initialize(false); } /* Check USB PLL/UTMIP clock. */ boot::CheckClock(); /* Talk to PMIC/RTC, set boot reason with SPL. */ boot::DetectBootReason(); /* Display the splash screen and check the battery charge. */ if (hw_type != spl::HardwareType::Calcio) { /* Display splash screen for two seconds. */ boot::ShowSplashScreen(); /* Check that the battery has enough to boot. */ boot::CheckBatteryCharge(); } /* Configure pinmux + drive pads. */ boot::SetInitialPinmuxConfiguration(); /* Configure the PMC wake pin settings. */ gpio::driver::SetInitialWakePinConfig(); /* Configure output clock. */ if (hw_type != spl::HardwareType::Calcio) { boot::SetInitialClockConfiguration(); } /* Set Fan enable config (Copper only). */ boot::SetFanPowerEnabled(); /* Repair boot partitions in NAND if needed. */ boot::CheckAndRepairBootImages(); /* Finalize the power control library. */ if (hw_type != spl::HardwareType::Calcio) { powctl::Finalize(); } /* Finalize the i2c server library. */ boot::FinalizeI2cDriverLibrary(); /* Finalize the gpio server library. */ boot::FinalizeGpioDriverLibrary(); /* Tell PM to start boot2. */ R_ABORT_UNLESS(pmshellInitialize()); R_ABORT_UNLESS(pmshellNotifyBootFinished()); } } /* Override operator new. */ void *operator new(size_t size) { return ams::boot::Allocate(size); } void *operator new(size_t size, const std::nothrow_t &) { return ams::boot::Allocate(size); } void operator delete(void *p) { return ams::boot::Deallocate(p, 0); } void operator delete(void *p, size_t size) { return ams::boot::Deallocate(p, size); } void *operator new[](size_t size) { return ams::boot::Allocate(size); } void *operator new[](size_t size, const std::nothrow_t &) { return ams::boot::Allocate(size); } void operator delete[](void *p) { return ams::boot::Deallocate(p, 0); } void operator delete[](void *p, size_t size) { return ams::boot::Deallocate(p, size); }
6,985
C++
.cpp
167
33.622754
174
0.628457
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,169
boot_fan_enable.cpp
Atmosphere-NX_Atmosphere/stratosphere/boot/source/boot_fan_enable.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have 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 "boot_fan_enable.hpp" namespace ams::boot { void SetFanPowerEnabled() { if (spl::GetHardwareType() == spl::HardwareType::Copper) { /* TODO */ /* boot::gpio::Configure(GpioPadName_FanEnable); */ /* boot::gpio::SetDirection(GpioPadName_FanEnable, GpioDirection_Output); */ /* boot::gpio::SetValue(GpioPadName_FanEnable, GpioValue_High); */ } } }
1,126
C++
.cpp
27
37.407407
88
0.677007
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,170
boot_change_voltage.cpp
Atmosphere-NX_Atmosphere/stratosphere/boot/source/boot_change_voltage.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have 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 "boot_change_voltage.hpp" namespace ams::boot { namespace { /* Convenience definitions. */ constexpr u32 Sdmmc3VoltageBit = (1 << 13); /* SDMMC3 */ constexpr u32 AudioVoltageBit = (1 << 18); /* AUDIO_HV */ constexpr u32 GpioVoltageBit = (1 << 21); /* GPIO */ constexpr u32 SpiVoltageBit = (1 << 23); /* SPI_HV */ constexpr u32 VoltageChangeMask = SpiVoltageBit | GpioVoltageBit | AudioVoltageBit | Sdmmc3VoltageBit; constexpr u32 PmcPwrDet = 0x7000E448; constexpr u32 PmcPwrDetVal = 0x7000E4E4; } void ChangeGpioVoltageTo1_8v() { /* Write mask to APBDEV_PMC_PWR_DET, then clear APBDEV_PMC_PWR_DET_VAL. */ dd::ReadModifyWriteIoRegister(PmcPwrDet, VoltageChangeMask, VoltageChangeMask); dd::ReadModifyWriteIoRegister(PmcPwrDetVal, 0, VoltageChangeMask); /* Sleep for 100 us. */ os::SleepThread(TimeSpan::FromMicroSeconds(100)); } }
1,659
C++
.cpp
36
41.111111
110
0.69145
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,171
boot_driver_management.cpp
Atmosphere-NX_Atmosphere/stratosphere/boot/source/boot_driver_management.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have 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 "boot_driver_management.hpp" namespace ams::boot { void InitializeGpioDriverLibrary() { /* Initialize the gpio client library with the server manager object. */ gpio::InitializeWith(gpio::server::GetServiceObject()); /* Initialize the board driver without enabling interrupt handlers. */ gpio::driver::board::Initialize(false); /* Initialize the driver library. */ gpio::driver::Initialize(); } void InitializeI2cDriverLibrary() { /* Initialize the i2c client library with the server manager object. */ i2c::InitializeWith(i2c::server::GetServiceObject(), i2c::server::GetServiceObjectPowerBus()); /* Initialize the board driver. */ i2c::driver::board::Initialize(); /* Initialize the driver library. */ i2c::driver::Initialize(); /* Initialize the pwm client library with the server manager object. */ pwm::InitializeWith(pwm::server::GetServiceObject()); /* Initialize the pwm board driver. */ pwm::driver::board::Initialize(); /* Initialize the pwm driver library. */ pwm::driver::Initialize(); } void FinalizeGpioDriverLibrary() { /* Finalize the gpio client library. */ gpio::Finalize(); } void FinalizeI2cDriverLibrary() { /* Finalize the i2c driver library. */ i2c::driver::Finalize(); /* Finalize the i2c client library. */ i2c::Finalize(); /* NOTE: Unknown finalize function is called here by Nintendo. */ /* Finalize the pwm client library. */ pwm::Finalize(); } }
2,311
C++
.cpp
54
36.648148
102
0.676037
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,172
pcv_clkrst_api_for_boot.board.nintendo_nx.cpp
Atmosphere-NX_Atmosphere/stratosphere/boot/source/api_overrides/pcv_clkrst_api_for_boot.board.nintendo_nx.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have 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 { namespace { constexpr inline dd::PhysicalAddress ClkRstRegistersPhysicalAddress = 0x60006000; constexpr inline size_t ClkRstRegistersSize = 0x1000; uintptr_t g_clkrst_registers = dd::QueryIoMapping(ClkRstRegistersPhysicalAddress, ClkRstRegistersSize); struct ClkRstDefinition { u32 clk_src_ofs; u32 clk_en_ofs; u32 rst_ofs; u32 clk_en_index; u32 rst_index; u8 clk_src; u8 clk_divisor; }; constexpr inline const ClkRstDefinition Definitions[] = { { CLK_RST_CONTROLLER_CLK_SOURCE_I2C1, CLK_RST_CONTROLLER_CLK_OUT_ENB_L, CLK_RST_CONTROLLER_RST_DEVICES_L, CLK_RST_CONTROLLER_CLK_ENB_I2C1_INDEX, CLK_RST_CONTROLLER_RST_I2C1_INDEX, 0x00 /* PLLP_OUT0 */, 0x04 }, { CLK_RST_CONTROLLER_CLK_SOURCE_I2C2, CLK_RST_CONTROLLER_CLK_OUT_ENB_H, CLK_RST_CONTROLLER_RST_DEVICES_H, CLK_RST_CONTROLLER_CLK_ENB_I2C2_INDEX, CLK_RST_CONTROLLER_RST_I2C2_INDEX, 0x00 /* PLLP_OUT0 */, 0x04 }, { CLK_RST_CONTROLLER_CLK_SOURCE_I2C3, CLK_RST_CONTROLLER_CLK_OUT_ENB_U, CLK_RST_CONTROLLER_RST_DEVICES_U, CLK_RST_CONTROLLER_CLK_ENB_I2C3_INDEX, CLK_RST_CONTROLLER_RST_I2C3_INDEX, 0x00 /* PLLP_OUT0 */, 0x04 }, { CLK_RST_CONTROLLER_CLK_SOURCE_I2C4, CLK_RST_CONTROLLER_CLK_OUT_ENB_V, CLK_RST_CONTROLLER_RST_DEVICES_V, CLK_RST_CONTROLLER_CLK_ENB_I2C4_INDEX, CLK_RST_CONTROLLER_RST_I2C4_INDEX, 0x00 /* PLLP_OUT0 */, 0x04 }, { CLK_RST_CONTROLLER_CLK_SOURCE_I2C5, CLK_RST_CONTROLLER_CLK_OUT_ENB_H, CLK_RST_CONTROLLER_RST_DEVICES_H, CLK_RST_CONTROLLER_CLK_ENB_I2C5_INDEX, CLK_RST_CONTROLLER_RST_I2C5_INDEX, 0x00 /* PLLP_OUT0 */, 0x04 }, { CLK_RST_CONTROLLER_CLK_SOURCE_I2C6, CLK_RST_CONTROLLER_CLK_OUT_ENB_X, CLK_RST_CONTROLLER_RST_DEVICES_X, CLK_RST_CONTROLLER_CLK_ENB_I2C6_INDEX, CLK_RST_CONTROLLER_RST_I2C6_INDEX, 0x00 /* PLLP_OUT0 */, 0x04 }, { CLK_RST_CONTROLLER_CLK_SOURCE_PWM, CLK_RST_CONTROLLER_CLK_OUT_ENB_L, CLK_RST_CONTROLLER_RST_DEVICES_L, CLK_RST_CONTROLLER_CLK_ENB_PWM_INDEX, CLK_RST_CONTROLLER_RST_PWM_INDEX, 0x00 /* PLLP_OUT0 */, 0x10 }, }; constexpr inline const struct { const ClkRstDefinition *definition; DeviceCode device_code; pcv::Module pcv_module; } ClkRstDefinitionMap[] = { { std::addressof(Definitions[0]), i2c::DeviceCode_I2c1, pcv::Module_I2c1 }, { std::addressof(Definitions[1]), i2c::DeviceCode_I2c2, pcv::Module_I2c2 }, { std::addressof(Definitions[2]), i2c::DeviceCode_I2c3, pcv::Module_I2c3 }, { std::addressof(Definitions[3]), i2c::DeviceCode_I2c4, pcv::Module_I2c4 }, { std::addressof(Definitions[4]), i2c::DeviceCode_I2c5, pcv::Module_I2c5 }, { std::addressof(Definitions[5]), i2c::DeviceCode_I2c6, pcv::Module_I2c6 }, { std::addressof(Definitions[6]), pwm::DeviceCode_LcdBacklight, pcv::Module_Pwm }, }; ALWAYS_INLINE const ClkRstDefinition *GetDefinition(DeviceCode device_code) { const ClkRstDefinition *def = nullptr; for (const auto &entry : ClkRstDefinitionMap) { if (entry.device_code == device_code) { def = entry.definition; break; } } AMS_ABORT_UNLESS(def != nullptr); return def; } ALWAYS_INLINE const ClkRstDefinition &GetDefinition(pcv::Module module) { const ClkRstDefinition *def = nullptr; for (const auto &entry : ClkRstDefinitionMap) { if (entry.pcv_module == module) { def = entry.definition; break; } } AMS_ABORT_UNLESS(def != nullptr); return *def; } ALWAYS_INLINE const ClkRstDefinition &GetDefinition(clkrst::ClkRstSession *session) { const ClkRstDefinition *def = nullptr; for (const auto &entry : ClkRstDefinitionMap) { if (session->_session == entry.definition) { def = entry.definition; break; } } AMS_ABORT_UNLESS(def != nullptr); return *def; } void SetResetEnabled(const ClkRstDefinition &def, bool en) { /* Set or clear reset. */ reg::ReadWrite(g_clkrst_registers + def.rst_ofs, (en ? 1u : 0u) << def.rst_index, 1u << def.rst_index); } void SetClockEnabled(const ClkRstDefinition &def, bool en) { /* Set or clear reset. */ reg::ReadWrite(g_clkrst_registers + def.clk_en_ofs, (en ? 1u : 0u) << def.clk_en_index, 1u << def.clk_en_index); } void SetClockRate(const ClkRstDefinition &def, u32 hz) { AMS_UNUSED(hz); /* Enable clock. */ reg::ReadWrite(g_clkrst_registers + def.clk_en_ofs, 1u << def.clk_en_index, 1u << def.clk_en_index); /* Set the clock divisor. */ reg::ReadWrite(g_clkrst_registers + def.clk_src_ofs, CLK_RST_REG_BITS_VALUE(CLK_SOURCE_CLK_DIVISOR, def.clk_divisor)); /* Wait for 2us for clock setting to take. */ os::SleepThread(TimeSpan::FromMicroSeconds(2)); /* Set the clock source. */ reg::ReadWrite(g_clkrst_registers + def.clk_src_ofs, CLK_RST_REG_BITS_VALUE(CLK_SOURCE_CLK_SOURCE, def.clk_src)); /* Wait for 2us for clock setting to take. */ os::SleepThread(TimeSpan::FromMicroSeconds(2)); } } namespace clkrst { void Initialize() { /* ... */ } void Finalize() { /* ... */ } Result OpenSession(ClkRstSession *out, DeviceCode device_code) { /* Get the relevant definition. */ out->_session = const_cast<ClkRstDefinition *>(GetDefinition(device_code)); R_SUCCEED(); } void CloseSession(ClkRstSession *session) { /* Clear the session. */ session->_session = nullptr; } void SetResetAsserted(ClkRstSession *session) { /* Assert reset. */ SetResetEnabled(GetDefinition(session), true); } void SetResetDeasserted(ClkRstSession *session) { /* Assert reset. */ SetResetEnabled(GetDefinition(session), false); } void SetClockRate(ClkRstSession *session, u32 hz) { /* Set the clock rate. */ SetClockRate(GetDefinition(session), hz); } void SetClockDisabled(ClkRstSession *session) { AMS_UNUSED(session); AMS_ABORT("SetClockDisabled not implemented for boot system module"); } } namespace pcv { void Initialize() { /* ... */ } void Finalize() { /* ... */ } Result SetClockEnabled(Module module, bool en) { /* Set clock. */ SetClockEnabled(GetDefinition(module), en); R_SUCCEED(); } Result SetClockRate(Module module, ClockHz hz) { /* Set the clock rate. */ SetClockRate(GetDefinition(module), hz); R_SUCCEED(); } Result SetReset(Module module, bool en) { /* Set reset. */ SetResetEnabled(GetDefinition(module), en); R_SUCCEED(); } } }
8,233
C++
.cpp
164
39.176829
221
0.599277
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,173
regulator_api_for_boot.cpp
Atmosphere-NX_Atmosphere/stratosphere/boot/source/api_overrides/regulator_api_for_boot.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have 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::regulator { void Initialize() { /* ... */ } void Finalize() { /* ... */ } Result OpenSession(RegulatorSession *out, DeviceCode device_code) { AMS_UNUSED(out, device_code); R_SUCCEED(); } void CloseSession(RegulatorSession *session) { AMS_UNUSED(session); } bool GetVoltageEnabled(RegulatorSession *session) { AMS_UNUSED(session); return true; } Result SetVoltageEnabled(RegulatorSession *session, bool enabled) { AMS_UNUSED(session, enabled); R_SUCCEED(); } Result SetVoltageValue(RegulatorSession *session, u32 micro_volts) { AMS_UNUSED(session, micro_volts); R_SUCCEED(); } }
1,409
C++
.cpp
43
27.883721
76
0.683861
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,174
ro_ro_service.cpp
Atmosphere-NX_Atmosphere/stratosphere/ro/source/ro_ro_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 "ro_ro_service.hpp" #include "impl/ro_service_impl.hpp" namespace ams::ro { void SetDevelopmentHardware(bool is_development_hardware) { impl::SetDevelopmentHardware(is_development_hardware); } void SetDevelopmentFunctionEnabled(bool is_development_function_enabled) { impl::SetDevelopmentFunctionEnabled(is_development_function_enabled); } RoService::RoService(NrrKind k) : m_context_id(impl::InvalidContextId), m_nrr_kind(k) { /* ... */ } RoService::~RoService() { impl::UnregisterProcess(m_context_id); } Result RoService::MapManualLoadModuleMemory(sf::Out<u64> load_address, const sf::ClientProcessId &client_pid, u64 nro_address, u64 nro_size, u64 bss_address, u64 bss_size) { R_TRY(impl::ValidateProcess(m_context_id, client_pid.GetValue())); R_RETURN(impl::MapManualLoadModuleMemory(load_address.GetPointer(), m_context_id, nro_address, nro_size, bss_address, bss_size)); } Result RoService::UnmapManualLoadModuleMemory(const sf::ClientProcessId &client_pid, u64 nro_address) { R_TRY(impl::ValidateProcess(m_context_id, client_pid.GetValue())); R_RETURN(impl::UnmapManualLoadModuleMemory(m_context_id, nro_address)); } Result RoService::RegisterModuleInfo(const sf::ClientProcessId &client_pid, u64 nrr_address, u64 nrr_size) { R_TRY(impl::ValidateProcess(m_context_id, client_pid.GetValue())); R_RETURN(impl::RegisterModuleInfo(m_context_id, os::InvalidNativeHandle, nrr_address, nrr_size, NrrKind_User, true)); } Result RoService::UnregisterModuleInfo(const sf::ClientProcessId &client_pid, u64 nrr_address) { R_TRY(impl::ValidateProcess(m_context_id, client_pid.GetValue())); R_RETURN(impl::UnregisterModuleInfo(m_context_id, nrr_address)); } Result RoService::RegisterProcessHandle(const sf::ClientProcessId &client_pid, sf::CopyHandle &&process_h) { /* Register the process. */ R_RETURN(impl::RegisterProcess(std::addressof(m_context_id), std::move(process_h), client_pid.GetValue())); } Result RoService::RegisterProcessModuleInfo(const sf::ClientProcessId &client_pid, u64 nrr_address, u64 nrr_size, sf::CopyHandle &&process_h) { /* Validate the process. */ R_TRY(impl::ValidateProcess(m_context_id, client_pid.GetValue())); /* Register the module. */ R_RETURN(impl::RegisterModuleInfo(m_context_id, process_h.GetOsHandle(), nrr_address, nrr_size, m_nrr_kind, m_nrr_kind == NrrKind_JitPlugin)); } }
3,221
C++
.cpp
58
50.206897
177
0.72127
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,175
ro_main.cpp
Atmosphere-NX_Atmosphere/stratosphere/ro/source/ro_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 "ro_debug_monitor_service.hpp" #include "ro_ro_service.hpp" namespace ams { namespace ro { namespace { /* ldr:ro, ro:dmnt, ro:1. */ enum PortIndex { PortIndex_DebugMonitor, PortIndex_User, PortIndex_JitPlugin, PortIndex_Count, }; constexpr sm::ServiceName DebugMonitorServiceName = sm::ServiceName::Encode("ro:dmnt"); constexpr size_t DebugMonitorMaxSessions = 2; /* NOTE: Official code passes 32 for ldr:ro max sessions. We will pass 2, because that's the actual limit. */ constexpr sm::ServiceName UserServiceName = sm::ServiceName::Encode("ldr:ro"); constexpr size_t UserMaxSessions = 2; constexpr sm::ServiceName JitPluginServiceName = sm::ServiceName::Encode("ro:1"); constexpr size_t JitPluginMaxSessions = 2; static constexpr size_t MaxSessions = DebugMonitorMaxSessions + UserMaxSessions + JitPluginMaxSessions; using ServerOptions = sf::hipc::DefaultServerManagerOptions; class ServerManager final : public sf::hipc::ServerManager<PortIndex_Count, ServerOptions, MaxSessions> { private: virtual ams::Result OnNeedsToAccept(int port_index, Server *server) override; }; using Allocator = sf::ExpHeapAllocator; using ObjectFactory = sf::ObjectFactory<sf::ExpHeapAllocator::Policy>; alignas(0x40) constinit u8 g_server_allocator_buffer[4_KB]; lmem::HeapHandle g_server_heap_handle; Allocator g_server_allocator; ServerManager g_server_manager; ams::Result ServerManager::OnNeedsToAccept(int port_index, Server *server) { switch (port_index) { case PortIndex_DebugMonitor: R_RETURN(this->AcceptImpl(server, ObjectFactory::CreateSharedEmplaced<ro::impl::IDebugMonitorInterface, ro::DebugMonitorService>(std::addressof(g_server_allocator)))); case PortIndex_User: R_RETURN(this->AcceptImpl(server, ObjectFactory::CreateSharedEmplaced<ro::impl::IRoInterface, ro::RoService>(std::addressof(g_server_allocator), ro::NrrKind_User))); case PortIndex_JitPlugin: R_RETURN(this->AcceptImpl(server, ObjectFactory::CreateSharedEmplaced<ro::impl::IRoInterface, ro::RoService>(std::addressof(g_server_allocator), ro::NrrKind_JitPlugin))); AMS_UNREACHABLE_DEFAULT_CASE(); } } void *Allocate(size_t size) { return lmem::AllocateFromExpHeap(g_server_heap_handle, size); } void Deallocate(void *p, size_t size) { AMS_UNUSED(size); return lmem::FreeToExpHeap(g_server_heap_handle, p); } void InitializeHeap() { /* Setup server allocator. */ g_server_heap_handle = lmem::CreateExpHeap(g_server_allocator_buffer, sizeof(g_server_allocator_buffer), lmem::CreateOption_None); } void LoopServer() { /* Create services. */ R_ABORT_UNLESS(ro::g_server_manager.RegisterServer(PortIndex_DebugMonitor, DebugMonitorServiceName, DebugMonitorMaxSessions)); R_ABORT_UNLESS(ro::g_server_manager.RegisterServer(PortIndex_User, UserServiceName, UserMaxSessions)); if (hos::GetVersion() >= hos::Version_7_0_0) { R_ABORT_UNLESS(ro::g_server_manager.RegisterServer(PortIndex_JitPlugin, JitPluginServiceName, JitPluginMaxSessions)); } /* Loop forever, servicing our services. */ ro::g_server_manager.LoopProcess(); } } } namespace init { void InitializeSystemModule() { /* Initialize heap. */ ro::InitializeHeap(); /* Initialize our connection to sm. */ R_ABORT_UNLESS(sm::Initialize()); /* Initialize fs. */ fs::InitializeForSystem(); fs::SetAllocator(ro::Allocate, ro::Deallocate); fs::SetEnabledAutoAbort(false); /* Initialize other services we need. */ R_ABORT_UNLESS(setsysInitialize()); /* Mount the SD card. */ R_ABORT_UNLESS(fs::MountSdCard("sdmc")); /* Verify that we can sanely execute. */ ams::CheckApiVersion(); } void FinalizeSystemModule() { /* ... */ } void Startup() { /* ... */ } } void Main() { /* Set thread name. */ os::SetThreadNamePointer(os::GetCurrentThread(), AMS_GET_SYSTEM_THREAD_NAME(ro, Main)); AMS_ASSERT(os::GetThreadPriority(os::GetCurrentThread()) == AMS_GET_SYSTEM_THREAD_PRIORITY(ro, Main)); /* Attach the server allocator. */ ro::g_server_allocator.Attach(ro::g_server_heap_handle); /* Initialize Debug config. */ { spl::Initialize(); ON_SCOPE_EXIT { spl::Finalize(); }; ro::SetDevelopmentHardware(spl::IsDevelopment()); ro::SetDevelopmentFunctionEnabled(spl::IsDevelopmentFunctionEnabled()); } /* Run the ro server. */ ro::LoopServer(); } }
6,108
C++
.cpp
118
39.940678
194
0.612502
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,176
ro_debug_monitor_service.cpp
Atmosphere-NX_Atmosphere/stratosphere/ro/source/ro_debug_monitor_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 "ro_debug_monitor_service.hpp" #include "impl/ro_service_impl.hpp" namespace ams::ro { Result DebugMonitorService::GetProcessModuleInfo(sf::Out<u32> out_count, const sf::OutArray<ldr::ModuleInfo> &out_infos, os::ProcessId process_id) { R_UNLESS(out_infos.GetSize() <= std::numeric_limits<s32>::max(), ro::ResultInvalidSize()); R_RETURN(impl::GetProcessModuleInfo(out_count.GetPointer(), out_infos.GetPointer(), out_infos.GetSize(), process_id)); } }
1,149
C++
.cpp
24
45.166667
152
0.743316
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,177
ro_random.cpp
Atmosphere-NX_Atmosphere/stratosphere/ro/source/impl/ro_random.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have 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 "ro_random.hpp" namespace ams::ro::impl { u64 GenerateSecureRandom(u64 max) { /* Generate a cryptographically random number. */ u64 rand; crypto::GenerateCryptographicallyRandomBytes(std::addressof(rand), sizeof(rand)); /* Coerce into range. */ return rand % (max + 1); } }
997
C++
.cpp
26
34.846154
89
0.721074
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,178
ro_service_impl.cpp
Atmosphere-NX_Atmosphere/stratosphere/ro/source/impl/ro_service_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 "ro_nrr_utils.hpp" #include "ro_nro_utils.hpp" #include "ro_patcher.hpp" #include "ro_random.hpp" #include "ro_service_impl.hpp" namespace ams::ro::impl { namespace { /* Convenience definitions. */ constexpr size_t MaxSessions = 0x3; /* 2 official sessions (applet + application, 1 homebrew session). */ constexpr size_t MaxNrrInfos = 0x40; constexpr size_t MaxNroInfos = 0x40; /* Types. */ struct Sha256Hash { u8 hash[crypto::Sha256Generator::HashSize]; bool operator==(const Sha256Hash &o) const { return std::memcmp(this, std::addressof(o), sizeof(*this)) == 0; } bool operator!=(const Sha256Hash &o) const { return std::memcmp(this, std::addressof(o), sizeof(*this)) != 0; } bool operator<(const Sha256Hash &o) const { return std::memcmp(this, std::addressof(o), sizeof(*this)) < 0; } bool operator>(const Sha256Hash &o) const { return std::memcmp(this, std::addressof(o), sizeof(*this)) > 0; } }; static_assert(sizeof(Sha256Hash) == sizeof(Sha256Hash::hash)); struct NroInfo { u64 base_address; u64 nro_heap_address; u64 nro_heap_size; u64 bss_heap_address; u64 bss_heap_size; u64 code_size; u64 rw_size; ModuleId module_id; }; struct NrrInfo { const NrrHeader *mapped_header; u64 nrr_heap_address; u64 nrr_heap_size; u64 mapped_code_address; /* Verification. */ u32 cached_signed_area_size; u32 cached_hashes_offset; u32 cached_num_hashes; u8 cached_signed_area[sizeof(NrrHeader) - NrrHeader::GetSignedAreaOffset()]; Sha256Hash signed_area_hash; }; struct ProcessContext { private: bool m_nro_in_use[MaxNroInfos]{}; bool m_nrr_in_use[MaxNrrInfos]{}; NroInfo m_nro_infos[MaxNroInfos]{}; NrrInfo m_nrr_infos[MaxNrrInfos]{}; os::NativeHandle m_process_handle = os::InvalidNativeHandle; os::ProcessId m_process_id = os::InvalidProcessId; bool m_in_use{}; public: constexpr ProcessContext() = default; void Initialize(os::NativeHandle process_handle, os::ProcessId process_id) { AMS_ABORT_UNLESS(!m_in_use); std::memset(m_nro_in_use, 0, sizeof(m_nro_in_use)); std::memset(m_nrr_in_use, 0, sizeof(m_nrr_in_use)); std::memset(m_nro_infos, 0, sizeof(m_nro_infos)); std::memset(m_nrr_infos, 0, sizeof(m_nrr_infos)); m_process_handle = process_handle; m_process_id = process_id; m_in_use = true; } void Finalize() { AMS_ABORT_UNLESS(m_in_use); if (m_process_handle != os::InvalidNativeHandle) { for (size_t i = 0; i < MaxNrrInfos; i++) { if (m_nrr_in_use[i]) { UnmapNrr(m_process_handle, m_nrr_infos[i].mapped_header, m_nrr_infos[i].nrr_heap_address, m_nrr_infos[i].nrr_heap_size, m_nrr_infos[i].mapped_code_address); } } os::CloseNativeHandle(m_process_handle); } std::memset(m_nro_in_use, 0, sizeof(m_nro_in_use)); std::memset(m_nrr_in_use, 0, sizeof(m_nrr_in_use)); std::memset(m_nro_infos, 0, sizeof(m_nro_infos)); std::memset(m_nrr_infos, 0, sizeof(m_nrr_infos)); m_process_handle = os::InvalidNativeHandle; m_process_id = os::InvalidProcessId; m_in_use = false; } os::NativeHandle GetProcessHandle() const { return m_process_handle; } os::ProcessId GetProcessId() const { return m_process_id; } bool IsFree() const { return !m_in_use; } ncm::ProgramId GetProgramId(os::NativeHandle other_process_h) const { /* Automatically select a handle, allowing for override. */ if (other_process_h != os::InvalidNativeHandle) { return os::GetProgramId(other_process_h); } else { return os::GetProgramId(m_process_handle); } } Result GetNrrInfoByAddress(NrrInfo **out, u64 nrr_heap_address) { for (size_t i = 0; i < MaxNrrInfos; i++) { if (m_nrr_in_use[i] && m_nrr_infos[i].nrr_heap_address == nrr_heap_address) { if (out != nullptr) { *out = m_nrr_infos + i; } R_SUCCEED(); } } R_THROW(ro::ResultNotRegistered()); } Result GetFreeNrrInfo(NrrInfo **out) { for (size_t i = 0; i < MaxNrrInfos; i++) { if (!m_nrr_in_use[i]) { if (out != nullptr) { *out = m_nrr_infos + i; } R_SUCCEED(); } } R_THROW(ro::ResultTooManyNrr()); } Result GetNroInfoByAddress(NroInfo **out, u64 nro_address) { for (size_t i = 0; i < MaxNroInfos; i++) { if (m_nro_in_use[i] && m_nro_infos[i].base_address == nro_address) { if (out != nullptr) { *out = m_nro_infos + i; } R_SUCCEED(); } } R_THROW(ro::ResultNotLoaded()); } Result GetNroInfoByModuleId(NroInfo **out, const ModuleId *module_id) { for (size_t i = 0; i < MaxNroInfos; i++) { if (m_nro_in_use[i] && std::memcmp(std::addressof(m_nro_infos[i].module_id), module_id, sizeof(*module_id)) == 0) { if (out != nullptr) { *out = m_nro_infos + i; } R_SUCCEED(); } } R_THROW(ro::ResultNotLoaded()); } Result GetFreeNroInfo(NroInfo **out) { for (size_t i = 0; i < MaxNroInfos; i++) { if (!m_nro_in_use[i]) { if (out != nullptr) { *out = m_nro_infos + i; } R_SUCCEED(); } } R_THROW(ro::ResultTooManyNro()); } Result ValidateHasNroHash(const NroHeader *nro_header) const { /* Calculate hash. */ Sha256Hash hash; crypto::GenerateSha256(std::addressof(hash), sizeof(hash), nro_header, nro_header->GetSize()); for (size_t i = 0; i < MaxNrrInfos; i++) { /* Ensure we only check NRRs that are used. */ if (!m_nrr_in_use[i]) { continue; } /* Get the mapped header, ensure that it has hashes. */ const NrrHeader *mapped_nrr_header = m_nrr_infos[i].mapped_header; const size_t mapped_num_hashes = mapped_nrr_header->GetNumHashes(); if (mapped_num_hashes == 0) { continue; } /* Locate the hash within the mapped array. */ const Sha256Hash *mapped_nro_hashes_start = reinterpret_cast<const Sha256Hash *>(mapped_nrr_header->GetHashes()); const Sha256Hash *mapped_nro_hashes_end = mapped_nro_hashes_start + mapped_nrr_header->GetNumHashes(); const Sha256Hash *mapped_lower_bound = std::lower_bound(mapped_nro_hashes_start, mapped_nro_hashes_end, hash); if (mapped_lower_bound == mapped_nro_hashes_end || (*mapped_lower_bound != hash)) { continue; } /* Check that the hash entry is valid, since our heuristic passed. */ const void *nrr_hash = std::addressof(m_nrr_infos[i].signed_area_hash); const void *signed_area = m_nrr_infos[i].cached_signed_area; const size_t signed_area_size = m_nrr_infos[i].cached_signed_area_size; const size_t hashes_offset = m_nrr_infos[i].cached_hashes_offset; const size_t num_hashes = m_nrr_infos[i].cached_num_hashes; const u8 *hash_table = reinterpret_cast<const u8 *>(mapped_nro_hashes_start); if (!ValidateNrrHashTableEntry(signed_area, signed_area_size, hashes_offset, num_hashes, nrr_hash, hash_table, std::addressof(hash))) { continue; } /* The hash is valid! */ R_SUCCEED(); } R_THROW(ro::ResultNotAuthorized()); } Result ValidateNro(ModuleId *out_module_id, u64 *out_rx_size, u64 *out_ro_size, u64 *out_rw_size, bool *out_aligned_header, u64 base_address, u64 expected_nro_size, u64 expected_bss_size) { /* Map the NRO. */ void *mapped_memory = nullptr; R_TRY_CATCH(os::MapProcessMemory(std::addressof(mapped_memory), m_process_handle, base_address, expected_nro_size, ro::impl::GenerateSecureRandom)) { R_CONVERT(os::ResultOutOfAddressSpace, ro::ResultOutOfAddressSpace()) } R_END_TRY_CATCH; /* When we're done, unmap the memory. */ ON_SCOPE_EXIT { os::UnmapProcessMemory(mapped_memory, m_process_handle, base_address, expected_nro_size); }; /* Validate header. */ const NroHeader *header = static_cast<const NroHeader *>(mapped_memory); R_UNLESS(header->IsMagicValid(), ro::ResultInvalidNro()); /* Read sizes from header. */ const u64 nro_size = header->GetSize(); const u64 text_ofs = header->GetTextOffset(); const u64 text_size = header->GetTextSize(); const u64 ro_ofs = header->GetRoOffset(); const u64 ro_size = header->GetRoSize(); const u64 rw_ofs = header->GetRwOffset(); const u64 rw_size = header->GetRwSize(); const u64 bss_size = header->GetBssSize(); /* Validate sizes meet expected. */ R_UNLESS(nro_size == expected_nro_size, ro::ResultInvalidNro()); R_UNLESS(bss_size == expected_bss_size, ro::ResultInvalidNro()); /* Validate all sizes are aligned. */ R_UNLESS(util::IsAligned(text_size, os::MemoryPageSize), ro::ResultInvalidNro()); R_UNLESS(util::IsAligned(ro_size, os::MemoryPageSize), ro::ResultInvalidNro()); R_UNLESS(util::IsAligned(rw_size, os::MemoryPageSize), ro::ResultInvalidNro()); R_UNLESS(util::IsAligned(bss_size, os::MemoryPageSize), ro::ResultInvalidNro()); /* Validate sections are in order. */ R_UNLESS(text_ofs <= ro_ofs, ro::ResultInvalidNro()); R_UNLESS(ro_ofs <= rw_ofs, ro::ResultInvalidNro()); /* Validate sections are sequential and contiguous. */ R_UNLESS(text_ofs == 0, ro::ResultInvalidNro()); R_UNLESS(text_ofs + text_size == ro_ofs, ro::ResultInvalidNro()); R_UNLESS(ro_ofs + ro_size == rw_ofs, ro::ResultInvalidNro()); R_UNLESS(rw_ofs + rw_size == nro_size, ro::ResultInvalidNro()); /* Verify NRO hash. */ R_TRY(this->ValidateHasNroHash(header)); /* Check if NRO has already been loaded. */ const ModuleId *module_id = header->GetModuleId(); R_UNLESS(R_FAILED(this->GetNroInfoByModuleId(nullptr, module_id)), ro::ResultAlreadyLoaded()); /* Apply patches to NRO. */ LocateAndApplyIpsPatchesToModule(module_id, static_cast<u8 *>(mapped_memory), nro_size); /* Copy to output. */ *out_module_id = *module_id; *out_rx_size = text_size; *out_ro_size = ro_size; *out_rw_size = rw_size; *out_aligned_header = header->IsAlignedHeader(); R_SUCCEED(); } void SetNrrInfoInUse(const NrrInfo *info, bool in_use) { AMS_ASSERT(std::addressof(m_nrr_infos[0]) <= info && info <= std::addressof(m_nrr_infos[MaxNrrInfos - 1])); const size_t index = info - std::addressof(m_nrr_infos[0]); m_nrr_in_use[index] = in_use; } void SetNroInfoInUse(const NroInfo *info, bool in_use) { AMS_ASSERT(std::addressof(m_nro_infos[0]) <= info && info <= std::addressof(m_nro_infos[MaxNroInfos - 1])); const size_t index = info - std::addressof(m_nro_infos[0]); m_nro_in_use[index] = in_use; } void GetProcessModuleInfo(u32 *out_count, ldr::ModuleInfo *out_infos, size_t max_out_count) const { size_t count = 0; for (size_t i = 0; i < MaxNroInfos && count < max_out_count; i++) { if (!m_nro_in_use[i]) { continue; } const NroInfo *nro_info = m_nro_infos + i; /* Just copy out the info. */ auto &out_info = out_infos[count++]; std::memcpy(out_info.module_id, nro_info->module_id.data, sizeof(out_info.module_id)); out_info.address = nro_info->base_address; out_info.size = nro_info->nro_heap_size + nro_info->bss_heap_size; } *out_count = static_cast<u32>(count); } }; /* Globals. */ constinit ProcessContext g_process_contexts[MaxSessions] = {}; constinit bool g_is_development_hardware = false; constinit bool g_is_development_function_enabled = false; /* Context Helpers. */ ProcessContext *GetContextById(size_t context_id) { if (context_id == InvalidContextId) { return nullptr; } AMS_ABORT_UNLESS(context_id < MaxSessions); return g_process_contexts + context_id; } ProcessContext *GetContextByProcessId(os::ProcessId process_id) { for (size_t i = 0; i < MaxSessions; i++) { if (g_process_contexts[i].GetProcessId() == process_id) { return g_process_contexts + i; } } return nullptr; } size_t AllocateContext(os::NativeHandle process_handle, os::ProcessId process_id) { /* Find a free process context. */ for (size_t i = 0; i < MaxSessions; i++) { ProcessContext *context = g_process_contexts + i; if (context->IsFree()) { context->Initialize(process_handle, process_id); return i; } } /* Failure to find a free context is actually an abort condition. */ AMS_ABORT_UNLESS(false); } void FreeContext(size_t context_id) { if (ProcessContext *context = GetContextById(context_id); context != nullptr) { context->Finalize(); } } constexpr inline Result ValidateAddressAndNonZeroSize(u64 address, u64 size) { R_UNLESS(util::IsAligned(address, os::MemoryPageSize), ro::ResultInvalidAddress()); R_UNLESS(size != 0, ro::ResultInvalidSize()); R_UNLESS(util::IsAligned(size, os::MemoryPageSize), ro::ResultInvalidSize()); R_UNLESS(address < address + size, ro::ResultInvalidSize()); R_SUCCEED(); } constexpr inline Result ValidateAddressAndSize(u64 address, u64 size) { R_UNLESS(util::IsAligned(address, os::MemoryPageSize), ro::ResultInvalidAddress()); R_UNLESS(util::IsAligned(size, os::MemoryPageSize), ro::ResultInvalidSize()); R_UNLESS(size == 0 || address < address + size, ro::ResultInvalidSize()); R_SUCCEED(); } } /* Access utilities. */ void SetDevelopmentHardware(bool is_development_hardware) { g_is_development_hardware = is_development_hardware; } void SetDevelopmentFunctionEnabled(bool is_development_function_enabled) { g_is_development_function_enabled = is_development_function_enabled; } bool IsDevelopmentHardware() { return g_is_development_hardware; } bool IsDevelopmentFunctionEnabled() { return g_is_development_function_enabled; } bool ShouldEaseNroRestriction() { /* Retrieve whether we should ease restrictions from set:sys. */ u8 should_ease = 0; if (settings::fwdbg::GetSettingsItemValue(std::addressof(should_ease), sizeof(should_ease), "ro", "ease_nro_restriction") != sizeof(should_ease)) { return false; } /* Nintendo only allows easing restriction on dev, we will allow on production, as well. */ /* should_ease &= IsDevelopmentFunctionEnabled(); */ return should_ease != 0; } /* Context utilities. */ Result RegisterProcess(size_t *out_context_id, sf::NativeHandle &&process_handle, os::ProcessId process_id) { /* Validate process handle. */ { /* Validate handle is a valid process handle. */ os::ProcessId handle_pid; R_UNLESS(R_SUCCEEDED(os::GetProcessId(std::addressof(handle_pid), process_handle.GetOsHandle())), ro::ResultInvalidProcess()); /* Validate process id. */ R_UNLESS(handle_pid == process_id, ro::ResultInvalidProcess()); } /* Check if a process context already exists. */ R_UNLESS(GetContextByProcessId(process_id) == nullptr, ro::ResultInvalidSession()); /* Allocate a context to manage the process handle. */ *out_context_id = AllocateContext(process_handle.GetOsHandle(), process_id); process_handle.Detach(); R_SUCCEED(); } Result ValidateProcess(size_t context_id, os::ProcessId process_id) { const ProcessContext *ctx = GetContextById(context_id); R_UNLESS(ctx != nullptr, ro::ResultInvalidProcess()); R_UNLESS(ctx->GetProcessId() == process_id, ro::ResultInvalidProcess()); R_SUCCEED(); } void UnregisterProcess(size_t context_id) { FreeContext(context_id); } /* Service implementations. */ Result RegisterModuleInfo(size_t context_id, os::NativeHandle process_handle, u64 nrr_address, u64 nrr_size, NrrKind nrr_kind, bool enforce_nrr_kind) { /* Get context. */ ProcessContext *context = GetContextById(context_id); AMS_ABORT_UNLESS(context != nullptr); /* Get program id. */ const ncm::ProgramId program_id = context->GetProgramId(process_handle); /* Validate address/size. */ R_TRY(ValidateAddressAndNonZeroSize(nrr_address, nrr_size)); /* Check we have space for a new NRR. */ NrrInfo *nrr_info = nullptr; R_TRY(context->GetFreeNrrInfo(std::addressof(nrr_info))); /* Prepare to cache the NRR's signature hash. */ Sha256Hash signed_area_hash; ON_SCOPE_EXIT { crypto::ClearMemory(std::addressof(signed_area_hash), sizeof(signed_area_hash)); }; /* Map. */ NrrHeader *header = nullptr; u64 mapped_code_address = 0; R_TRY(MapAndValidateNrr(std::addressof(header), std::addressof(mapped_code_address), std::addressof(signed_area_hash), sizeof(signed_area_hash), context->GetProcessHandle(), program_id, nrr_address, nrr_size, nrr_kind, enforce_nrr_kind)); /* Set NRR info. */ context->SetNrrInfoInUse(nrr_info, true); nrr_info->mapped_header = header; nrr_info->nrr_heap_address = nrr_address; nrr_info->nrr_heap_size = nrr_size; nrr_info->mapped_code_address = mapped_code_address; nrr_info->cached_signed_area_size = header->GetSignedAreaSize(); nrr_info->cached_hashes_offset = header->GetHashesOffset(); nrr_info->cached_num_hashes = header->GetNumHashes(); std::memcpy(nrr_info->cached_signed_area, header->GetSignedArea(), std::min(sizeof(nrr_info->cached_signed_area), header->GetHashesOffset() - header->GetSignedAreaOffset())); std::memcpy(std::addressof(nrr_info->signed_area_hash), std::addressof(signed_area_hash), sizeof(signed_area_hash)); R_SUCCEED(); } Result UnregisterModuleInfo(size_t context_id, u64 nrr_address) { /* Get context. */ ProcessContext *context = GetContextById(context_id); AMS_ABORT_UNLESS(context != nullptr); /* Validate address. */ R_UNLESS(util::IsAligned(nrr_address, os::MemoryPageSize), ro::ResultInvalidAddress()); /* Check the NRR is loaded. */ NrrInfo *nrr_info = nullptr; R_TRY(context->GetNrrInfoByAddress(std::addressof(nrr_info), nrr_address)); /* Unmap. */ const NrrInfo nrr_backup = *nrr_info; { /* Nintendo does this unconditionally, whether or not the actual unmap succeeds. */ context->SetNrrInfoInUse(nrr_info, false); std::memset(nrr_info, 0, sizeof(*nrr_info)); } R_RETURN(UnmapNrr(context->GetProcessHandle(), nrr_backup.mapped_header, nrr_backup.nrr_heap_address, nrr_backup.nrr_heap_size, nrr_backup.mapped_code_address)); } Result MapManualLoadModuleMemory(u64 *out_address, size_t context_id, u64 nro_address, u64 nro_size, u64 bss_address, u64 bss_size) { /* Get context. */ ProcessContext *context = GetContextById(context_id); AMS_ABORT_UNLESS(context != nullptr); /* Validate address/size. */ R_TRY(ValidateAddressAndNonZeroSize(nro_address, nro_size)); R_TRY(ValidateAddressAndSize(bss_address, bss_size)); const u64 total_size = nro_size + bss_size; R_UNLESS(total_size >= nro_size, ro::ResultInvalidSize()); R_UNLESS(total_size >= bss_size, ro::ResultInvalidSize()); /* Check we have space for a new NRO. */ NroInfo *nro_info = nullptr; R_TRY(context->GetFreeNroInfo(std::addressof(nro_info))); nro_info->nro_heap_address = nro_address; nro_info->nro_heap_size = nro_size; nro_info->bss_heap_address = bss_address; nro_info->bss_heap_size = bss_size; /* Map the NRO. */ R_TRY(MapNro(std::addressof(nro_info->base_address), context->GetProcessHandle(), nro_address, nro_size, bss_address, bss_size)); ON_RESULT_FAILURE { UnmapNro(context->GetProcessHandle(), nro_info->base_address, nro_address, nro_size, bss_address, bss_size); }; /* Validate the NRO (parsing region extents). */ u64 rx_size = 0, ro_size = 0, rw_size = 0; bool aligned_header = false; R_TRY(context->ValidateNro(std::addressof(nro_info->module_id), std::addressof(rx_size), std::addressof(ro_size), std::addressof(rw_size), std::addressof(aligned_header), nro_info->base_address, nro_size, bss_size)); /* Set NRO perms. */ R_TRY(SetNroPerms(context->GetProcessHandle(), nro_info->base_address, rx_size, ro_size, rw_size + bss_size, aligned_header)); context->SetNroInfoInUse(nro_info, true); nro_info->code_size = rx_size + ro_size; nro_info->rw_size = rw_size; *out_address = nro_info->base_address; R_SUCCEED(); } Result UnmapManualLoadModuleMemory(size_t context_id, u64 nro_address) { /* Get context. */ ProcessContext *context = GetContextById(context_id); AMS_ABORT_UNLESS(context != nullptr); /* Validate address. */ R_UNLESS(util::IsAligned(nro_address, os::MemoryPageSize), ro::ResultInvalidAddress()); /* Check the NRO is loaded. */ NroInfo *nro_info = nullptr; R_TRY(context->GetNroInfoByAddress(std::addressof(nro_info), nro_address)); /* Unmap. */ const NroInfo nro_backup = *nro_info; { /* Nintendo does this unconditionally, whether or not the actual unmap succeeds. */ context->SetNroInfoInUse(nro_info, false); std::memset(nro_info, 0, sizeof(*nro_info)); } R_RETURN(UnmapNro(context->GetProcessHandle(), nro_backup.base_address, nro_backup.nro_heap_address, nro_backup.code_size + nro_backup.rw_size, nro_backup.bss_heap_address, nro_backup.bss_heap_size)); } /* Debug service implementations. */ Result GetProcessModuleInfo(u32 *out_count, ldr::ModuleInfo *out_infos, size_t max_out_count, os::ProcessId process_id) { if (const ProcessContext *context = GetContextByProcessId(process_id); context != nullptr) { context->GetProcessModuleInfo(out_count, out_infos, max_out_count); } R_SUCCEED(); } }
27,534
C++
.cpp
499
39.90982
246
0.543243
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,179
ro_patcher.cpp
Atmosphere-NX_Atmosphere/stratosphere/ro/source/impl/ro_patcher.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have 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 "ro_patcher.hpp" namespace ams::ro::impl { namespace { constexpr const char *NroPatchesDirectory = "nro_patches"; /* NRO patches want to prevent modification of header, */ /* but don't want to adjust offset relative to mapped location. */ constexpr size_t NroPatchesProtectedSize = sizeof(NroHeader); constexpr size_t NroPatchesProtectedOffset = 0; } /* Apply IPS patches. */ void LocateAndApplyIpsPatchesToModule(const ModuleId *module_id, u8 *mapped_nro, size_t mapped_size) { ams::patcher::LocateAndApplyIpsPatchesToModule("sdmc", NroPatchesDirectory, NroPatchesProtectedSize, NroPatchesProtectedOffset, module_id, mapped_nro, mapped_size); } }
1,394
C++
.cpp
30
42.533333
172
0.740795
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,180
ro_nro_utils.cpp
Atmosphere-NX_Atmosphere/stratosphere/ro/source/impl/ro_nro_utils.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "ro_nro_utils.hpp" #include "ro_random.hpp" namespace ams::ro::impl { namespace { ALWAYS_INLINE size_t SetupNroProcessMemoryRegions(os::ProcessMemoryRegion *regions, u64 nro_heap_address, u64 nro_heap_size, u64 bss_heap_address, u64 bss_heap_size) { /* Reset region count. */ size_t num_regions = 0; /* We always want a region for the nro. */ regions[num_regions++] = { nro_heap_address, nro_heap_size }; /* If we have bss, create a region for bss. */ if (bss_heap_size > 0) { regions[num_regions++] = { bss_heap_address, bss_heap_size }; } return num_regions; } } Result MapNro(u64 *out_base_address, os::NativeHandle process_handle, u64 nro_heap_address, u64 nro_heap_size, u64 bss_heap_address, u64 bss_heap_size) { /* Set up the process memory regions. */ os::ProcessMemoryRegion regions[2]; const size_t num_regions = SetupNroProcessMemoryRegions(regions, nro_heap_address, nro_heap_size, bss_heap_address, bss_heap_size); /* Re-map the nro/bss as code memory in the destination process. */ R_TRY_CATCH(os::MapProcessCodeMemory(out_base_address, process_handle, regions, num_regions, ro::impl::GenerateSecureRandom)) { R_CONVERT(os::ResultOutOfAddressSpace, ro::ResultOutOfAddressSpace()) } R_END_TRY_CATCH; R_SUCCEED(); } Result SetNroPerms(os::NativeHandle process_handle, u64 base_address, u64 rx_size, u64 ro_size, u64 rw_size, bool is_aligned_header) { const u64 rx_offset = is_aligned_header ? os::MemoryPageSize : 0; const u64 ro_offset = rx_offset + rx_size; const u64 rw_offset = ro_offset + ro_size; if (is_aligned_header) { R_TRY(os::SetProcessMemoryPermission(process_handle, base_address, os::MemoryPageSize, os::MemoryPermission_ReadOnly)); } R_TRY(os::SetProcessMemoryPermission(process_handle, base_address + rx_offset, rx_size, os::MemoryPermission_ReadExecute)); R_TRY(os::SetProcessMemoryPermission(process_handle, base_address + ro_offset, ro_size, os::MemoryPermission_ReadOnly)); R_TRY(os::SetProcessMemoryPermission(process_handle, base_address + rw_offset, rw_size, os::MemoryPermission_ReadWrite)); R_SUCCEED(); } Result UnmapNro(os::NativeHandle process_handle, u64 base_address, u64 nro_heap_address, u64 nro_heap_size, u64 bss_heap_address, u64 bss_heap_size) { /* Set up the process memory regions. */ os::ProcessMemoryRegion regions[2]; const size_t num_regions = SetupNroProcessMemoryRegions(regions, nro_heap_address, nro_heap_size, bss_heap_address, bss_heap_size); /* Unmap the nro/bss. */ R_RETURN(os::UnmapProcessCodeMemory(process_handle, base_address, regions, num_regions)); } }
3,564
C++
.cpp
62
50.306452
175
0.687231
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,181
ro_nrr_utils.cpp
Atmosphere-NX_Atmosphere/stratosphere/ro/source/impl/ro_nrr_utils.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "ro_nrr_utils.hpp" #include "ro_random.hpp" #include "ro_service_impl.hpp" namespace ams::ro::impl { namespace { constexpr size_t KeyGenerationMax100 = 0; constexpr size_t KeyGenerationMax910 = 1; constexpr size_t KeyGenerationMax = std::max(KeyGenerationMax100, KeyGenerationMax910); constexpr size_t KeyGenerationCount = KeyGenerationMax + 1; constexpr size_t RsaKeySize = 0x100; constexpr const u8 Exponent[3] = { 0x01, 0x00, 0x01 }; constexpr const u8 DevModuli[KeyGenerationCount][RsaKeySize] = { { 0xC1, 0x15, 0x7C, 0x02, 0x26, 0xE5, 0x35, 0x6F, 0x99, 0xDB, 0xBE, 0xBD, 0xD7, 0x01, 0x07, 0x1C, 0xC2, 0x3D, 0x1E, 0x6B, 0x7E, 0x08, 0x07, 0xBC, 0xE2, 0x6D, 0x49, 0xEC, 0x0B, 0xFF, 0xE4, 0x91, 0x8C, 0x62, 0xB9, 0xFC, 0x69, 0xBF, 0x3A, 0xB6, 0x6C, 0x3A, 0x5D, 0x0E, 0x31, 0x5E, 0x6C, 0x1D, 0x9A, 0x21, 0xD9, 0x9D, 0xD3, 0xB8, 0x50, 0x5F, 0x27, 0x7C, 0x4A, 0xD2, 0xFE, 0xE8, 0xDA, 0x1C, 0xB9, 0x9E, 0x7E, 0x1E, 0x2F, 0x7D, 0xF9, 0x70, 0xA2, 0x98, 0x19, 0x6A, 0x53, 0x40, 0x64, 0xE7, 0xC0, 0x92, 0xAE, 0x64, 0xD2, 0x01, 0xB2, 0x49, 0x30, 0x19, 0x7F, 0xF8, 0x6E, 0x0D, 0x49, 0x35, 0xE9, 0x95, 0x77, 0x00, 0x65, 0xC5, 0x1E, 0xF5, 0x2A, 0xF9, 0xA1, 0x52, 0xA0, 0xA4, 0xFA, 0x87, 0x3D, 0x8F, 0x51, 0xEC, 0x02, 0x80, 0xA4, 0xC7, 0x22, 0x74, 0xEF, 0x56, 0x61, 0x71, 0x39, 0xE2, 0x2F, 0x03, 0x82, 0xDB, 0x50, 0xE9, 0xCC, 0x60, 0x48, 0x46, 0x71, 0xE2, 0xC6, 0x71, 0xF3, 0xF9, 0x85, 0x52, 0x1A, 0xE2, 0xA8, 0x18, 0x77, 0x86, 0xD0, 0x12, 0xEB, 0x4F, 0x81, 0xA0, 0xDF, 0x20, 0x42, 0xF0, 0xF8, 0xE3, 0x00, 0xE6, 0xFC, 0xA7, 0x44, 0xF0, 0xDC, 0x2B, 0x5B, 0xA0, 0xD3, 0x01, 0x34, 0xD0, 0xD7, 0xFD, 0xEF, 0x66, 0x92, 0xB3, 0x87, 0x64, 0xD9, 0x76, 0xDA, 0x6E, 0x3A, 0x19, 0x98, 0x1F, 0xBD, 0x1F, 0x25, 0x69, 0x9F, 0x28, 0xE6, 0x9E, 0xB7, 0x38, 0x92, 0x12, 0x16, 0xDE, 0xDA, 0xE2, 0xB9, 0x7E, 0xFA, 0x98, 0x94, 0xF4, 0x9A, 0xDF, 0x2D, 0xC0, 0x99, 0x83, 0x61, 0xAD, 0xB8, 0x3E, 0x27, 0x3F, 0x0E, 0xB8, 0x9E, 0x9B, 0x11, 0x78, 0xF1, 0x06, 0x30, 0x5B, 0xCA, 0xF4, 0xEB, 0x72, 0x20, 0xD3, 0x15, 0x15, 0xC0, 0xC7, 0x1A, 0x08, 0xAE, 0x6E, 0xB2, 0x02, 0x43, 0xE9, }, { 0xB0, 0x3A, 0xC3, 0x11, 0x58, 0xAC, 0x95, 0x9D, 0xED, 0x88, 0x80, 0xD9, 0x93, 0x71, 0x8E, 0xA0, 0xBD, 0x19, 0x68, 0x6A, 0x06, 0x63, 0x7F, 0x06, 0x93, 0xBA, 0x43, 0x24, 0x5E, 0xD0, 0x54, 0x76, 0x2F, 0x8D, 0x6A, 0xF4, 0x7B, 0x16, 0x7A, 0x68, 0xE2, 0xE6, 0x95, 0x82, 0x57, 0xD9, 0x01, 0x34, 0x87, 0x42, 0x24, 0x83, 0x91, 0x7F, 0xE7, 0xB4, 0xB7, 0xE5, 0x8B, 0x4B, 0x08, 0x1F, 0x70, 0x58, 0x5A, 0x30, 0xE0, 0xC9, 0xAB, 0xB8, 0xB1, 0x96, 0xFA, 0x45, 0xA2, 0xF7, 0x3C, 0x94, 0x65, 0x97, 0xE2, 0x72, 0x7A, 0x19, 0xE2, 0x5F, 0x30, 0xF0, 0xA9, 0x44, 0xD8, 0x4B, 0x00, 0xEE, 0xD0, 0x99, 0xA7, 0xAB, 0xC7, 0x14, 0x94, 0xE8, 0xD8, 0x70, 0x8F, 0xC7, 0x3C, 0x95, 0x0F, 0xE9, 0x52, 0x44, 0x7A, 0xA4, 0xCA, 0xB4, 0xCE, 0x31, 0xCD, 0xC8, 0xC0, 0xF3, 0x08, 0x51, 0xA3, 0xC1, 0x5D, 0xA5, 0x3E, 0x4A, 0xCE, 0xE8, 0x17, 0xA2, 0xED, 0xB8, 0x94, 0xD7, 0x3C, 0xF0, 0x42, 0x5A, 0xC1, 0x83, 0xE8, 0x65, 0x28, 0x79, 0x43, 0x2C, 0x17, 0xBB, 0x68, 0x91, 0x80, 0xE3, 0xDA, 0x6B, 0xD4, 0x0B, 0xA3, 0x6A, 0x8B, 0xDB, 0x1E, 0x2E, 0x16, 0xFE, 0xAB, 0x81, 0x16, 0x84, 0x6E, 0x53, 0xFD, 0xB6, 0x1F, 0x12, 0xDE, 0x77, 0x79, 0xE6, 0x9A, 0x02, 0x95, 0x6B, 0x22, 0xFF, 0xE3, 0x10, 0xD2, 0x0D, 0x5B, 0x33, 0xB1, 0xC0, 0x5C, 0xF6, 0xAC, 0x69, 0xAF, 0xCF, 0xD2, 0x34, 0x4B, 0x76, 0x88, 0xC1, 0x91, 0x66, 0x6C, 0x2F, 0x06, 0xBA, 0x2B, 0xC7, 0x35, 0x0A, 0xD8, 0xD7, 0x5C, 0xF1, 0x20, 0x67, 0x31, 0x4A, 0x9B, 0xB7, 0xCA, 0x4A, 0x3F, 0xAE, 0x4F, 0xF3, 0x02, 0x71, 0x97, 0xD6, 0x78, 0xC6, 0x8E, 0x4B, 0x41, 0x78, 0x5B, 0x56, 0x6F, 0x6C, 0xA0, 0x0D, 0x83, 0x28, 0x25, 0x07, 0x75, 0x15, } }; constexpr const u8 ProdModuli[KeyGenerationCount][RsaKeySize] = { { 0xCF, 0x2F, 0x54, 0xF1, 0x7D, 0xA3, 0x11, 0x47, 0xC3, 0xBD, 0xED, 0x10, 0x3D, 0x64, 0xF8, 0x6B, 0x51, 0x62, 0x05, 0x6F, 0x10, 0x5F, 0x50, 0x76, 0xF2, 0x40, 0x09, 0xA3, 0x16, 0xFC, 0xC3, 0xA8, 0x75, 0xFD, 0x7C, 0xB4, 0x38, 0x9D, 0x30, 0x5C, 0x02, 0x6E, 0x2C, 0xCF, 0x03, 0x84, 0x23, 0x64, 0x4A, 0xF9, 0x90, 0x44, 0x58, 0xAF, 0x43, 0x19, 0xD2, 0x27, 0xF1, 0x60, 0x28, 0xB8, 0x7B, 0x26, 0xD3, 0x21, 0xE8, 0xF0, 0xED, 0x65, 0x01, 0x31, 0x51, 0x45, 0xD3, 0x93, 0xCF, 0x07, 0x65, 0xF1, 0x8A, 0x72, 0x61, 0x55, 0x63, 0x91, 0x84, 0x63, 0x2C, 0x0B, 0x3E, 0xF6, 0x7E, 0x9B, 0x19, 0x4C, 0x42, 0xE3, 0xB9, 0x83, 0xF3, 0xA1, 0x2B, 0x7B, 0xA1, 0x5F, 0x00, 0xDC, 0x80, 0x1A, 0x6D, 0x6C, 0x22, 0x20, 0x2F, 0x19, 0x61, 0x96, 0x5E, 0xD9, 0x93, 0x45, 0x62, 0x48, 0xC1, 0xB1, 0x48, 0x8A, 0x07, 0x6C, 0xBB, 0x3D, 0xCC, 0xE0, 0xEF, 0x43, 0x56, 0x1D, 0x2A, 0x1D, 0x8E, 0x19, 0xBF, 0x99, 0x7A, 0x56, 0x9B, 0x72, 0xB9, 0x49, 0x86, 0xD4, 0x5D, 0xA0, 0xE5, 0x40, 0x2C, 0x2D, 0x31, 0x5A, 0x68, 0x90, 0xA4, 0xDA, 0xED, 0x52, 0xCF, 0xE4, 0x3C, 0x35, 0x5E, 0x94, 0xC8, 0x36, 0x6E, 0x5F, 0xF5, 0x50, 0x9D, 0xBD, 0x3F, 0x86, 0x28, 0xC4, 0xF7, 0x0D, 0xFA, 0x1D, 0x65, 0xCE, 0x7F, 0x83, 0x8E, 0xEE, 0x75, 0x8B, 0x8D, 0xF3, 0x1C, 0x3E, 0x8B, 0xB7, 0x31, 0x60, 0x0E, 0x33, 0xC0, 0x8C, 0xEF, 0xBA, 0xD0, 0xF0, 0x56, 0x35, 0x11, 0x70, 0x3D, 0x3A, 0x60, 0xFF, 0xBB, 0xC8, 0x49, 0xB3, 0x50, 0x93, 0xB5, 0x0C, 0x4D, 0x62, 0x2A, 0x53, 0x76, 0x69, 0x5D, 0x81, 0x35, 0x79, 0x08, 0xAE, 0x08, 0x7D, 0x51, 0x72, 0xE4, 0xE9, 0xD9, 0xBE, 0x91, 0xB9, 0x29, 0x89, 0xDD, 0xC9, 0xF9, 0xDB, }, { 0xBD, 0x8E, 0x75, 0x8D, 0x6A, 0x5E, 0xCF, 0x1A, 0x68, 0x7D, 0x9D, 0x06, 0x80, 0x60, 0x48, 0x56, 0x73, 0x13, 0xB8, 0x8D, 0xA5, 0x83, 0x11, 0xE3, 0xF4, 0xB5, 0xBF, 0x21, 0x56, 0x50, 0x6F, 0x68, 0xFD, 0x2E, 0xEF, 0x3A, 0xE1, 0x7D, 0x5D, 0xA2, 0x02, 0x21, 0xAD, 0x57, 0x7F, 0xA9, 0xD1, 0x95, 0xA6, 0x5C, 0x80, 0x67, 0x2A, 0xAE, 0x29, 0xCD, 0x98, 0x4C, 0x71, 0x98, 0x22, 0xD3, 0x39, 0x77, 0xA3, 0x39, 0xE8, 0xB0, 0x7E, 0x77, 0x4D, 0x54, 0xA5, 0x9F, 0xF3, 0xF1, 0xF0, 0x85, 0x74, 0x64, 0xF7, 0x17, 0xAC, 0xEB, 0x95, 0xAD, 0x01, 0x3A, 0xA2, 0xFB, 0x18, 0xEC, 0x6C, 0x06, 0xD5, 0xBD, 0x0F, 0x66, 0x99, 0x2C, 0xEE, 0x81, 0x87, 0x40, 0xDA, 0xBC, 0x30, 0xC9, 0x54, 0x21, 0x46, 0x6B, 0xD5, 0xAE, 0xDF, 0xA8, 0x8F, 0x61, 0x19, 0x5E, 0x75, 0x68, 0xED, 0x80, 0x73, 0x5F, 0x4D, 0xF2, 0xC2, 0x09, 0xC8, 0x2D, 0x73, 0x12, 0x18, 0x35, 0x7F, 0x5E, 0xA8, 0xAD, 0x37, 0x6B, 0x9C, 0x14, 0x8C, 0x4E, 0x7D, 0xC0, 0xDC, 0x42, 0x45, 0xDD, 0x84, 0x5A, 0x0B, 0xED, 0x97, 0xBE, 0x66, 0xD1, 0xC0, 0xC4, 0x7C, 0x48, 0x66, 0x22, 0xAA, 0xFB, 0x47, 0x95, 0x84, 0x45, 0x2E, 0x70, 0x35, 0x68, 0x04, 0xF0, 0xBC, 0xEE, 0xCB, 0x6E, 0xB7, 0x09, 0xBA, 0xD9, 0xEA, 0xF9, 0x78, 0x32, 0x4C, 0xD5, 0x0F, 0x6E, 0xEF, 0x4D, 0x21, 0xE0, 0xE7, 0xEA, 0x17, 0xA3, 0xEC, 0x0D, 0x76, 0xC0, 0xB9, 0xCC, 0x1B, 0x8C, 0x7E, 0xFB, 0x56, 0x5B, 0x60, 0x94, 0x26, 0xB7, 0x9F, 0x2B, 0xAD, 0xC6, 0x1F, 0xBD, 0xB6, 0xFA, 0x33, 0xDB, 0x1C, 0xBC, 0x28, 0xE1, 0x85, 0x1E, 0x2F, 0xF9, 0xFD, 0xEA, 0x83, 0x52, 0x2F, 0xEE, 0x07, 0x7C, 0x1E, 0x2F, 0xCD, 0x76, 0x91, 0xEA, 0x27, 0xE6, 0x50, 0x9A, 0x86, 0x23, } }; /* Helper functions. */ Result GetCertificationModulus(const u8 **out, u32 key_generation) { if (hos::GetVersion() >= hos::Version_9_1_0) { R_UNLESS(key_generation <= KeyGenerationMax910, ro::ResultNotAuthorized()); } else { R_UNLESS(key_generation <= KeyGenerationMax100, ro::ResultNotAuthorized()); } *out = IsDevelopmentHardware() ? DevModuli[key_generation] : ProdModuli[key_generation]; R_SUCCEED(); } Result ValidateNrrCertification(const NrrHeader *header, const u8 *mod) { static_assert(RsaKeySize == NrrCertification::RsaKeySize); /* Verify the signature. */ const u8 *sig = header->GetCertificationSignature(); const size_t sig_size = RsaKeySize; const size_t mod_size = RsaKeySize; const u8 *exp = Exponent; const size_t exp_size = util::size(Exponent); const u8 *msg = header->GetCertificationSignedArea(); const size_t msg_size = NrrCertification::SignedSize; R_UNLESS(crypto::VerifyRsa2048PssSha256(sig, sig_size, mod, mod_size, exp, exp_size, msg, msg_size), ro::ResultNotAuthorized()); /* Check ProgramId pattern is valid. */ R_UNLESS(header->IsProgramIdValid(), ro::ResultNotAuthorized()); R_SUCCEED(); } Result ValidateNrrSignature(const NrrHeader *header) { static_assert(RsaKeySize == NrrCertification::RsaKeySize); /* Verify the signature. */ const u8 *sig = header->GetSignature(); const size_t sig_size = RsaKeySize; const u8 *mod = header->GetCertificationModulus(); const size_t mod_size = RsaKeySize; const u8 *exp = Exponent; const size_t exp_size = util::size(Exponent); const u8 *msg = header->GetSignedArea(); const size_t msg_size = header->GetSignedAreaSize(); R_UNLESS(crypto::VerifyRsa2048PssSha256(sig, sig_size, mod, mod_size, exp, exp_size, msg, msg_size), ro::ResultNotAuthorized()); R_SUCCEED(); } Result ValidateNrr(const NrrHeader *header, u64 size, ncm::ProgramId program_id, NrrKind nrr_kind, bool enforce_nrr_kind) { /* Check magic. */ R_UNLESS(header->IsMagicValid(), ro::ResultInvalidNrr()); /* Check size. */ R_UNLESS(header->GetSize() == size, ro::ResultInvalidSize()); /* Only perform checks if we must. */ const bool ease_nro_restriction = ShouldEaseNroRestriction(); /* Get certification modulus. */ /* NOTE: This must succeed even when ease_nro_restriction is true. */ const u8 *modulus; R_TRY(GetCertificationModulus(std::addressof(modulus), header->GetKeyGeneration())); if (!ease_nro_restriction) { /* Check certification signature. */ R_TRY(ValidateNrrCertification(header, modulus)); /* Check NRR signature. */ R_TRY(ValidateNrrSignature(header)); /* Check program id. */ R_UNLESS(header->GetProgramId() == program_id, ro::ResultInvalidNrr()); /* Check nrr kind. */ if (hos::GetVersion() >= hos::Version_7_0_0 && enforce_nrr_kind) { R_UNLESS(header->GetNrrKind() == nrr_kind, ro::ResultInvalidNrrKind()); } } R_SUCCEED(); } } /* Utilities for working with NRRs. */ Result MapAndValidateNrr(NrrHeader **out_header, u64 *out_mapped_code_address, void *out_hash, size_t out_hash_size, os::NativeHandle process_handle, ncm::ProgramId program_id, u64 nrr_heap_address, u64 nrr_heap_size, NrrKind nrr_kind, bool enforce_nrr_kind) { /* Re-map the nrr as code memory in the destination process. */ u64 code_address = 0; const os::ProcessMemoryRegion region = { nrr_heap_address, nrr_heap_size }; R_TRY_CATCH(os::MapProcessCodeMemory(std::addressof(code_address), process_handle, std::addressof(region), 1, ro::impl::GenerateSecureRandom)) { R_CONVERT(os::ResultOutOfAddressSpace, ro::ResultOutOfAddressSpace()) } R_END_TRY_CATCH; /* If we fail, unmap the nrr code memory. */ ON_RESULT_FAILURE { R_ABORT_UNLESS(os::UnmapProcessCodeMemory(process_handle, code_address, std::addressof(region), 1)); }; /* Map the nrr in our process. */ void *mapped_memory = nullptr; R_TRY_CATCH(os::MapProcessMemory(std::addressof(mapped_memory), process_handle, code_address, region.size, ro::impl::GenerateSecureRandom)) { R_CONVERT(os::ResultOutOfAddressSpace, ro::ResultOutOfAddressSpace()) } R_END_TRY_CATCH; /* If we fail, unmap the nrr memory. */ ON_RESULT_FAILURE_2 { os::UnmapProcessMemory(mapped_memory, process_handle, code_address, region.size); }; /* Validate the nrr header. */ NrrHeader *nrr_header = static_cast<NrrHeader *>(mapped_memory); R_TRY(ValidateNrr(nrr_header, nrr_heap_size, program_id, nrr_kind, enforce_nrr_kind)); /* Save a copy of the hash that we verified. */ crypto::GenerateSha256(out_hash, out_hash_size, nrr_header->GetSignedArea(), nrr_header->GetSignedAreaSize()); *out_header = nrr_header; *out_mapped_code_address = code_address; R_SUCCEED(); } Result UnmapNrr(os::NativeHandle process_handle, const NrrHeader *header, u64 nrr_heap_address, u64 nrr_heap_size, u64 mapped_code_address) { /* Unmap our process mapping. */ os::UnmapProcessMemory(const_cast<NrrHeader *>(header), process_handle, mapped_code_address, nrr_heap_size); /* Unmap the code memory mapping. */ const os::ProcessMemoryRegion region = { nrr_heap_address, nrr_heap_size }; R_RETURN(os::UnmapProcessCodeMemory(process_handle, mapped_code_address, std::addressof(region), 1)); } bool ValidateNrrHashTableEntry(const void *signed_area, size_t signed_area_size, size_t hashes_offset, size_t num_hashes, const void *nrr_hash, const u8 *hash_table, const void *desired_hash) { crypto::Sha256Generator sha256; sha256.Initialize(); /* Hash data before the hash table. */ const size_t pre_hash_table_size = hashes_offset - NrrHeader::GetSignedAreaOffset(); sha256.Update(signed_area, pre_hash_table_size); /* Hash the hash table, checking if the desired hash exists inside it. */ size_t remaining_size = signed_area_size - pre_hash_table_size; bool found_hash = false; for (size_t i = 0; i < num_hashes; i++) { /* Get the current hash. */ u8 cur_hash[crypto::Sha256Generator::HashSize]; std::memcpy(cur_hash, hash_table, sizeof(cur_hash)); /* Hash the current hash. */ sha256.Update(cur_hash, sizeof(cur_hash)); /* Check if the current hash is our target. */ found_hash |= std::memcmp(cur_hash, desired_hash, sizeof(cur_hash)) == 0; /* Advance our pointers. */ hash_table += sizeof(cur_hash); remaining_size -= sizeof(cur_hash); } /* Data after the hash table should be all zeroes. */ u8 work_buf[crypto::Sha256Generator::HashSize]; { crypto::ClearMemory(work_buf, sizeof(work_buf)); while (remaining_size > 0) { const size_t cur_size = std::min(remaining_size, sizeof(work_buf)); sha256.Update(work_buf, cur_size); remaining_size -= cur_size; } } /* Validate the final hash. */ sha256.GetHash(work_buf, sizeof(work_buf)); /* Use & operator to avoid short circuiting. */ const bool is_valid = found_hash & (std::memcmp(work_buf, nrr_hash, sizeof(work_buf)) == 0); /* Return result. */ return is_valid; } }
16,784
C++
.cpp
240
57.779167
264
0.600837
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,182
pgl_main.cpp
Atmosphere-NX_Atmosphere/stratosphere/pgl/source/pgl_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> namespace ams { namespace init { void InitializeSystemModule() { /* Initialize heap. */ pgl::srv::InitializeHeap(); /* Initialize our connection to sm. */ R_ABORT_UNLESS(sm::Initialize()); /* Initialize fs. */ fs::InitializeForSystem(); fs::SetAllocator(pgl::srv::Allocate, pgl::srv::Deallocate); fs::SetEnabledAutoAbort(false); /* Initialize other services we need. */ R_ABORT_UNLESS(setInitialize()); R_ABORT_UNLESS(setsysInitialize()); R_ABORT_UNLESS(pmshellInitialize()); R_ABORT_UNLESS(ldrShellInitialize()); R_ABORT_UNLESS(lrInitialize()); /* Verify that we can sanely execute. */ ams::CheckApiVersion(); } void FinalizeSystemModule() { /* ... */ } void Startup() { /* ... */ } } void Main() { /* Set thread name. */ os::SetThreadNamePointer(os::GetCurrentThread(), AMS_GET_SYSTEM_THREAD_NAME(pgl, Main)); AMS_ASSERT(os::GetThreadPriority(os::GetCurrentThread()) == AMS_GET_SYSTEM_THREAD_PRIORITY(pgl, Main)); /* Initialize and start the server. */ pgl::srv::StartServer(); } }
1,940
C++
.cpp
47
33.744681
111
0.632447
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,183
creport_scoped_file.cpp
Atmosphere-NX_Atmosphere/stratosphere/creport/source/creport_scoped_file.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have 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 "creport_scoped_file.hpp" namespace ams::creport { namespace { /* Convenience definitions. */ constexpr size_t MaximumLineLength = 0x20; constinit os::SdkMutex g_format_lock; constinit char g_format_buffer[2 * os::MemoryPageSize]; } void ScopedFile::WriteString(const char *str) { this->Write(str, std::strlen(str)); } void ScopedFile::WriteFormat(const char *fmt, ...) { /* Acquire exclusive access to the format buffer. */ std::scoped_lock lk(g_format_lock); /* Format to the buffer. */ { std::va_list vl; va_start(vl, fmt); util::VSNPrintf(g_format_buffer, sizeof(g_format_buffer), fmt, vl); va_end(vl); } /* Write data. */ this->WriteString(g_format_buffer); } void ScopedFile::DumpMemory(const char *prefix, const void *data, size_t size) { const u8 *data_u8 = reinterpret_cast<const u8 *>(data); const int prefix_len = std::strlen(prefix); size_t data_ofs = 0; size_t remaining = size; bool first = true; while (remaining) { const size_t cur_size = std::min(MaximumLineLength, remaining); /* Print the line prefix. */ if (first) { this->Write(prefix, prefix_len); first = false; } else { std::memset(g_format_buffer, ' ', prefix_len); this->Write(g_format_buffer, prefix_len); } /* Dump up to 0x20 of hex memory. */ { char hex[MaximumLineLength * 2 + 2] = {}; for (size_t i = 0; i < cur_size; i++) { hex[i * 2 + 0] = "0123456789ABCDEF"[data_u8[data_ofs] >> 4]; hex[i * 2 + 1] = "0123456789ABCDEF"[data_u8[data_ofs] & 0xF]; ++data_ofs; } hex[cur_size * 2 + 0] = '\n'; this->Write(hex, cur_size * 2 + 1); } /* Continue. */ remaining -= cur_size; } } void ScopedFile::Write(const void *data, size_t size) { /* If we're not open, we can't write. */ if (!this->IsOpen()) { return; } /* If we have a cache, write to it. */ if (m_cache != nullptr) { /* Write into the cache, if we can. */ if (m_cache_size - m_cache_offset >= size || R_SUCCEEDED(this->TryWriteCache())) { std::memcpy(m_cache + m_cache_offset, data, size); m_cache_offset += size; } } else { /* Advance, if we write successfully. */ if (R_SUCCEEDED(fs::WriteFile(m_file, m_offset, data, size, fs::WriteOption::None))) { m_offset += size; } } } Result ScopedFile::TryWriteCache() { /* If there's no cached data, there's nothing to do. */ R_SUCCEED_IF(m_cache_offset == 0); /* Try to write any cached data. */ R_TRY(fs::WriteFile(m_file, m_offset, m_cache, m_cache_offset, fs::WriteOption::None)); /* Update our extents. */ m_offset += m_cache_offset; m_cache_offset = 0; R_SUCCEED(); } }
3,970
C++
.cpp
101
29.792079
98
0.553158
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,184
creport_crash_report.cpp
Atmosphere-NX_Atmosphere/stratosphere/creport/source/creport_crash_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 "creport_crash_report.hpp" #include "creport_utils.hpp" namespace ams::creport { namespace { /* Convenience definitions. */ constexpr size_t DyingMessageAddressOffset = 0x1C0; static_assert(DyingMessageAddressOffset == AMS_OFFSETOF(ams::svc::aarch64::ProcessLocalRegion, dying_message_region_address)); static_assert(DyingMessageAddressOffset == AMS_OFFSETOF(ams::svc::aarch32::ProcessLocalRegion, dying_message_region_address)); constexpr size_t CrashReportDataCacheSize = 256_KB; /* Helper functions. */ bool TryGetCurrentTimestamp(u64 *out) { /* Clear output. */ *out = 0; /* Check if we have time service. */ { bool has_time_service = false; if (R_FAILED(sm::HasService(&has_time_service, sm::ServiceName::Encode("time:s"))) || !has_time_service) { return false; } } /* Try to get the current time. */ { if (R_FAILED(::timeInitialize())) { return false; } ON_SCOPE_EXIT { ::timeExit(); }; return R_SUCCEEDED(::timeGetCurrentTime(TimeType_LocalSystemClock, out)); } } void TryCreateReportDirectories() { fs::EnsureDirectory("sdmc:/atmosphere/crash_reports/dumps"); fs::EnsureDirectory("sdmc:/atmosphere/fatal_reports/dumps"); } constexpr const char *GetDebugExceptionString(const svc::DebugException type) { switch (type) { case svc::DebugException_UndefinedInstruction: return "Undefined Instruction"; case svc::DebugException_InstructionAbort: return "Instruction Abort"; case svc::DebugException_DataAbort: return "Data Abort"; case svc::DebugException_AlignmentFault: return "Alignment Fault"; case svc::DebugException_DebuggerAttached: return "Debugger Attached"; case svc::DebugException_BreakPoint: return "Break Point"; case svc::DebugException_UserBreak: return "User Break"; case svc::DebugException_DebuggerBreak: return "Debugger Break"; case svc::DebugException_UndefinedSystemCall: return "Undefined System Call"; case svc::DebugException_MemorySystemError: return "System Memory Error"; default: return "Unknown"; } } } void CrashReport::Initialize() { /* Initialize the heap. */ m_heap_handle = lmem::CreateExpHeap(m_heap_storage, sizeof(m_heap_storage), lmem::CreateOption_None); /* Allocate members. */ m_module_list = std::construct_at(static_cast<ModuleList *>(lmem::AllocateFromExpHeap(m_heap_handle, sizeof(ModuleList)))); m_thread_list = std::construct_at(static_cast<ThreadList *>(lmem::AllocateFromExpHeap(m_heap_handle, sizeof(ThreadList)))); m_dying_message = static_cast<u8 *>(lmem::AllocateFromExpHeap(m_heap_handle, DyingMessageSizeMax)); if (m_dying_message != nullptr) { std::memset(m_dying_message, 0, DyingMessageSizeMax); } } void CrashReport::BuildReport(os::ProcessId process_id, bool has_extra_info) { m_has_extra_info = has_extra_info; if (this->OpenProcess(process_id)) { /* Parse info from the crashed process. */ this->ProcessExceptions(); m_module_list->FindModulesFromThreadInfo(m_debug_handle, m_crashed_thread, this->Is64Bit()); m_thread_list->ReadFromProcess(m_debug_handle, m_thread_tls_map, this->Is64Bit()); /* Associate module list to threads. */ m_crashed_thread.SetModuleList(m_module_list); m_thread_list->SetModuleList(m_module_list); /* Process dying message for applications. */ if (this->IsApplication()) { this->ProcessDyingMessage(); } /* Nintendo's creport finds extra modules by looking at all threads if application, */ /* but there's no reason for us not to always go looking. */ for (size_t i = 0; i < m_thread_list->GetThreadCount(); i++) { m_module_list->FindModulesFromThreadInfo(m_debug_handle, m_thread_list->GetThreadInfo(i), this->Is64Bit()); } /* Cache the module base address to send to fatal. */ if (m_module_list->GetModuleCount()) { m_module_base_address = m_module_list->GetModuleStartAddress(0); } /* Nintendo's creport saves the report to erpt here, but we'll save to SD card later. */ } } void CrashReport::GetFatalContext(::FatalCpuContext *_out) const { static_assert(sizeof(*_out) == sizeof(ams::fatal::CpuContext)); ams::fatal::CpuContext *out = reinterpret_cast<ams::fatal::CpuContext *>(_out); std::memset(out, 0, sizeof(*out)); /* TODO: Support generating 32-bit fatal contexts? */ out->architecture = fatal::CpuContext::Architecture_Aarch64; out->type = static_cast<u32>(m_exception_info.type); for (size_t i = 0; i < fatal::aarch64::RegisterName_FP; i++) { out->aarch64_ctx.SetRegisterValue(static_cast<fatal::aarch64::RegisterName>(i), m_crashed_thread.GetGeneralPurposeRegister(i)); } out->aarch64_ctx.SetRegisterValue(fatal::aarch64::RegisterName_FP, m_crashed_thread.GetFP()); out->aarch64_ctx.SetRegisterValue(fatal::aarch64::RegisterName_LR, m_crashed_thread.GetLR()); out->aarch64_ctx.SetRegisterValue(fatal::aarch64::RegisterName_SP, m_crashed_thread.GetSP()); out->aarch64_ctx.SetRegisterValue(fatal::aarch64::RegisterName_PC, m_crashed_thread.GetPC()); out->aarch64_ctx.stack_trace_size = m_crashed_thread.GetStackTraceSize(); for (size_t i = 0; i < out->aarch64_ctx.stack_trace_size; i++) { out->aarch64_ctx.stack_trace[i] = m_crashed_thread.GetStackTrace(i); } if (m_module_base_address != 0) { out->aarch64_ctx.SetBaseAddress(m_module_base_address); } /* For ams fatal, which doesn't use afsr0, pass program_id instead. */ out->aarch64_ctx.SetProgramIdForAtmosphere(ncm::ProgramId{m_process_info.program_id}); } void CrashReport::ProcessExceptions() { /* Loop all debug events. */ svc::DebugEventInfo d; while (R_SUCCEEDED(svc::GetDebugEvent(std::addressof(d), m_debug_handle))) { switch (d.type) { case svc::DebugEvent_CreateProcess: this->HandleDebugEventInfoCreateProcess(d); break; case svc::DebugEvent_CreateThread: this->HandleDebugEventInfoCreateThread(d); break; case svc::DebugEvent_Exception: this->HandleDebugEventInfoException(d); break; case svc::DebugEvent_ExitProcess: case svc::DebugEvent_ExitThread: break; } } /* Parse crashed thread info. */ m_crashed_thread.ReadFromProcess(m_debug_handle, m_thread_tls_map, m_crashed_thread_id, this->Is64Bit()); } void CrashReport::HandleDebugEventInfoCreateProcess(const svc::DebugEventInfo &d) { m_process_info = d.info.create_process; /* On 5.0.0+, we want to parse out a dying message from application crashes. */ if (hos::GetVersion() < hos::Version_5_0_0 || !IsApplication()) { return; } /* Parse out user data. */ const u64 address = m_process_info.user_exception_context_address + DyingMessageAddressOffset; u64 userdata_address = 0; u64 userdata_size = 0; /* Read userdata address. */ if (R_FAILED(svc::ReadDebugProcessMemory(reinterpret_cast<uintptr_t>(std::addressof(userdata_address)), m_debug_handle, address, sizeof(userdata_address)))) { return; } /* Validate userdata address. */ if (userdata_address == 0 || userdata_address & 0xFFF) { return; } /* Read userdata size. */ if (R_FAILED(svc::ReadDebugProcessMemory(reinterpret_cast<uintptr_t>(std::addressof(userdata_size)), m_debug_handle, address + sizeof(userdata_address), sizeof(userdata_size)))) { return; } /* Cap userdata size. */ userdata_size = std::min(size_t(userdata_size), DyingMessageSizeMax); m_dying_message_address = userdata_address; m_dying_message_size = userdata_size; } void CrashReport::HandleDebugEventInfoCreateThread(const svc::DebugEventInfo &d) { /* Save info on the thread's TLS address for later. */ m_thread_tls_map.SetThreadTls(d.info.create_thread.thread_id, d.info.create_thread.tls_address); } void CrashReport::HandleDebugEventInfoException(const svc::DebugEventInfo &d) { switch (d.info.exception.type) { case svc::DebugException_UndefinedInstruction: m_result = creport::ResultUndefinedInstruction(); break; case svc::DebugException_InstructionAbort: m_result = creport::ResultInstructionAbort(); break; case svc::DebugException_DataAbort: m_result = creport::ResultDataAbort(); break; case svc::DebugException_AlignmentFault: m_result = creport::ResultAlignmentFault(); break; case svc::DebugException_UserBreak: m_result = creport::ResultUserBreak(); /* Try to parse out the user break result. */ if (hos::GetVersion() >= hos::Version_5_0_0) { svc::ReadDebugProcessMemory(reinterpret_cast<uintptr_t>(std::addressof(m_result)), m_debug_handle, d.info.exception.specific.user_break.address, sizeof(m_result)); } break; case svc::DebugException_UndefinedSystemCall: m_result = creport::ResultUndefinedSystemCall(); break; case svc::DebugException_MemorySystemError: m_result = creport::ResultMemorySystemError(); break; case svc::DebugException_DebuggerAttached: case svc::DebugException_BreakPoint: case svc::DebugException_DebuggerBreak: return; } /* Save exception info. */ m_exception_info = d.info.exception; m_crashed_thread_id = d.thread_id; } void CrashReport::ProcessDyingMessage() { /* Dying message is only stored starting in 5.0.0. */ if (hos::GetVersion() < hos::Version_5_0_0) { return; } /* Validate address/size. */ if (m_dying_message_address == 0 || m_dying_message_address & 0xFFF) { return; } if (m_dying_message_size > DyingMessageSizeMax) { return; } /* Validate that the current report isn't garbage. */ if (!IsOpen() || !IsComplete()) { return; } /* Verify that we have a dying message buffer. */ if (m_dying_message == nullptr) { return; } /* Read the dying message. */ svc::ReadDebugProcessMemory(reinterpret_cast<uintptr_t>(m_dying_message), m_debug_handle, m_dying_message_address, m_dying_message_size); } void CrashReport::SaveReport(bool enable_screenshot) { /* Try to ensure path exists. */ TryCreateReportDirectories(); /* Get a timestamp. */ u64 timestamp; if (!TryGetCurrentTimestamp(&timestamp)) { timestamp = os::GetSystemTick().GetInt64Value(); } /* Save files. */ { char file_path[fs::EntryNameLengthMax + 1]; /* Save crash report. */ util::SNPrintf(file_path, sizeof(file_path), "sdmc:/atmosphere/crash_reports/%011lu_%016lx.log", timestamp, m_process_info.program_id); { /* Try to allocate data cache. */ void * const data_cache = lmem::AllocateFromExpHeap(m_heap_handle, CrashReportDataCacheSize + os::MemoryPageSize); ON_SCOPE_EXIT { if (data_cache != nullptr) { lmem::FreeToExpHeap(m_heap_handle, data_cache); } }; /* Align up the data cache. This is safe because null will align up to null. */ void * const aligned_cache = reinterpret_cast<void *>(util::AlignUp(reinterpret_cast<uintptr_t>(data_cache), os::MemoryPageSize)); /* Open and save the file using the cache. */ ScopedFile file(file_path, aligned_cache, aligned_cache != nullptr ? CrashReportDataCacheSize : 0); if (file.IsOpen()) { this->SaveToFile(file); } } /* Dump threads. */ util::SNPrintf(file_path, sizeof(file_path), "sdmc:/atmosphere/crash_reports/dumps/%011lu_%016lx_thread_info.bin", timestamp, m_process_info.program_id); { ScopedFile file(file_path); if (file.IsOpen()) { m_thread_list->DumpBinary(file, m_crashed_thread.GetThreadId()); } } /* If we're open, we need to close here. */ if (this->IsOpen()) { this->Close(); } /* Finalize our heap. */ std::destroy_at(m_module_list); std::destroy_at(m_thread_list); lmem::FreeToExpHeap(m_heap_handle, m_module_list); lmem::FreeToExpHeap(m_heap_handle, m_thread_list); if (m_dying_message != nullptr) { lmem::FreeToExpHeap(m_heap_handle, m_dying_message); } m_module_list = nullptr; m_thread_list = nullptr; m_dying_message = nullptr; /* Try to take a screenshot. */ /* NOTE: Nintendo validates that enable_screenshot is true here, and validates that the application id is not in a blacklist. */ /* Since we save reports only locally and do not send them via telemetry, we will skip this. */ AMS_UNUSED(enable_screenshot); if (hos::GetVersion() >= hos::Version_9_0_0 && this->IsApplication()) { if (R_SUCCEEDED(capsrv::InitializeScreenShotControl())) { ON_SCOPE_EXIT { capsrv::FinalizeScreenShotControl(); }; u64 jpeg_size; if (R_SUCCEEDED(capsrv::CaptureJpegScreenshot(std::addressof(jpeg_size), m_heap_storage, sizeof(m_heap_storage), vi::LayerStack_ApplicationForDebug, TimeSpan::FromSeconds(10)))) { util::SNPrintf(file_path, sizeof(file_path), "sdmc:/atmosphere/crash_reports/%011lu_%016lx.jpg", timestamp, m_process_info.program_id); ScopedFile file(file_path); if (file.IsOpen()) { file.Write(m_heap_storage, jpeg_size); } } } } } } void CrashReport::SaveToFile(ScopedFile &file) { file.WriteFormat("Atmosphère Crash Report (v1.7):\n"); file.WriteFormat("Result: 0x%X (2%03d-%04d)\n\n", m_result.GetValue(), m_result.GetModule(), m_result.GetDescription()); /* Process Info. */ char name_buf[0x10] = {}; static_assert(sizeof(name_buf) >= sizeof(m_process_info.name), "buffer overflow!"); std::memcpy(name_buf, m_process_info.name, sizeof(m_process_info.name)); file.WriteFormat("Process Info:\n"); file.WriteFormat(" Process Name: %s\n", name_buf); file.WriteFormat(" Program ID: %016lx\n", m_process_info.program_id); file.WriteFormat(" Process ID: %016lx\n", m_process_info.process_id); file.WriteFormat(" Process Flags: %08x\n", m_process_info.flags); if (hos::GetVersion() >= hos::Version_5_0_0) { file.WriteFormat(" User Exception Address: %s\n", m_module_list->GetFormattedAddressString(m_process_info.user_exception_context_address)); } /* Exception Info. */ file.WriteFormat("Exception Info:\n"); file.WriteFormat(" Type: %s\n", GetDebugExceptionString(m_exception_info.type)); file.WriteFormat(" Address: %s\n", m_module_list->GetFormattedAddressString(m_exception_info.address)); switch (m_exception_info.type) { case svc::DebugException_UndefinedInstruction: file.WriteFormat(" Opcode: %08x\n", m_exception_info.specific.undefined_instruction.insn); break; case svc::DebugException_DataAbort: case svc::DebugException_AlignmentFault: if (m_exception_info.specific.raw != m_exception_info.address) { file.WriteFormat(" Fault Address: %s\n", m_module_list->GetFormattedAddressString(m_exception_info.specific.raw)); } break; case svc::DebugException_UndefinedSystemCall: file.WriteFormat(" Svc Id: 0x%02x\n", m_exception_info.specific.undefined_system_call.id); break; case svc::DebugException_UserBreak: file.WriteFormat(" Break Reason: 0x%x\n", m_exception_info.specific.user_break.break_reason); file.WriteFormat(" Break Address: %s\n", m_module_list->GetFormattedAddressString(m_exception_info.specific.user_break.address)); file.WriteFormat(" Break Size: 0x%lx\n", m_exception_info.specific.user_break.size); break; default: break; } /* Crashed Thread Info. */ file.WriteFormat("Crashed Thread Info:\n"); m_crashed_thread.SaveToFile(file); /* Dying Message. */ if (hos::GetVersion() >= hos::Version_5_0_0 && m_dying_message_size != 0) { file.WriteFormat("Dying Message Info:\n"); file.WriteFormat(" Address: 0x%s\n", m_module_list->GetFormattedAddressString(m_dying_message_address)); file.WriteFormat(" Size: 0x%016lx\n", m_dying_message_size); file.DumpMemory( " Dying Message: ", m_dying_message, m_dying_message_size); } /* Module Info. */ file.WriteFormat("Module Info:\n"); m_module_list->SaveToFile(file); /* Thread Info. */ file.WriteFormat("Thread Report:\n"); m_thread_list->SaveToFile(file); } }
19,964
C++
.cpp
374
41.149733
199
0.588916
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,185
creport_threads.cpp
Atmosphere-NX_Atmosphere/stratosphere/creport/source/creport_threads.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have 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 "creport_threads.hpp" #include "creport_modules.hpp" namespace ams::creport { namespace { /* Convenience definitions. */ constexpr u32 LibnxThreadVarMagic = util::FourCC<'!','T','V','$'>::Code; constexpr u32 DumpedThreadInfoMagic = util::FourCC<'D','T','I','2'>::Code; /* Types. */ template<typename T> struct StackFrame { T fp; T lr; }; /* Helpers. */ template<typename T> void ReadStackTrace(size_t *out_trace_size, u64 *out_trace, size_t max_out_trace_size, os::NativeHandle debug_handle, u64 fp) { size_t trace_size = 0; u64 cur_fp = fp; for (size_t i = 0; i < max_out_trace_size; i++) { /* Validate the current frame. */ if (cur_fp == 0 || (cur_fp % sizeof(T) != 0)) { break; } /* Read a new frame. */ StackFrame<T> cur_frame; if (R_FAILED(svc::ReadDebugProcessMemory(reinterpret_cast<uintptr_t>(std::addressof(cur_frame)), debug_handle, cur_fp, sizeof(cur_frame)))) { break; } /* Advance to the next frame. */ out_trace[trace_size++] = cur_frame.lr; cur_fp = cur_frame.fp; } *out_trace_size = trace_size; } } void ThreadList::SaveToFile(ScopedFile &file) { file.WriteFormat("Number of Threads: %02zu\n", m_thread_count); for (size_t i = 0; i < m_thread_count; i++) { file.WriteFormat("Threads[%02zu]:\n", i); m_threads[i].SaveToFile(file); } } void ThreadInfo::SaveToFile(ScopedFile &file) { file.WriteFormat(" Thread ID: %016lx\n", m_thread_id); if (std::strcmp(m_name, "") != 0) { file.WriteFormat(" Thread Name: %s\n", m_name); } if (m_stack_top != 0) { file.WriteFormat(" Stack Region: %016lx-%016lx\n", m_stack_bottom, m_stack_top); } file.WriteFormat(" Registers:\n"); { for (unsigned int i = 0; i <= 28; i++) { file.WriteFormat(" X[%02u]: %s\n", i, m_module_list->GetFormattedAddressString(m_context.r[i])); } file.WriteFormat(" FP: %s\n", m_module_list->GetFormattedAddressString(m_context.fp)); file.WriteFormat(" LR: %s\n", m_module_list->GetFormattedAddressString(m_context.lr)); file.WriteFormat(" SP: %s\n", m_module_list->GetFormattedAddressString(m_context.sp)); file.WriteFormat(" PC: %s\n", m_module_list->GetFormattedAddressString(m_context.pc)); } if (m_stack_trace_size != 0) { file.WriteFormat(" Stack Trace:\n"); for (size_t i = 0; i < m_stack_trace_size; i++) { file.WriteFormat(" ReturnAddress[%02zu]: %s\n", i, m_module_list->GetFormattedAddressString(m_stack_trace[i])); } } if (m_stack_dump_base != 0) { file.WriteFormat(" Stack Dump: 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f\n"); for (size_t i = 0; i < 0x10; i++) { const size_t ofs = i * 0x10; file.WriteFormat(" %012lx %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x\n", m_stack_dump_base + ofs, m_stack_dump[ofs + 0], m_stack_dump[ofs + 1], m_stack_dump[ofs + 2], m_stack_dump[ofs + 3], m_stack_dump[ofs + 4], m_stack_dump[ofs + 5], m_stack_dump[ofs + 6], m_stack_dump[ofs + 7], m_stack_dump[ofs + 8], m_stack_dump[ofs + 9], m_stack_dump[ofs + 10], m_stack_dump[ofs + 11], m_stack_dump[ofs + 12], m_stack_dump[ofs + 13], m_stack_dump[ofs + 14], m_stack_dump[ofs + 15]); } } if (m_tls_address != 0) { file.WriteFormat(" TLS Address: %016lx\n", m_tls_address); file.WriteFormat(" TLS Dump: 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f\n"); for (size_t i = 0; i < 0x10; i++) { const size_t ofs = i * 0x10; file.WriteFormat(" %012lx %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x\n", m_tls_address + ofs, m_tls[ofs + 0], m_tls[ofs + 1], m_tls[ofs + 2], m_tls[ofs + 3], m_tls[ofs + 4], m_tls[ofs + 5], m_tls[ofs + 6], m_tls[ofs + 7], m_tls[ofs + 8], m_tls[ofs + 9], m_tls[ofs + 10], m_tls[ofs + 11], m_tls[ofs + 12], m_tls[ofs + 13], m_tls[ofs + 14], m_tls[ofs + 15]); } } } bool ThreadInfo::ReadFromProcess(os::NativeHandle debug_handle, ThreadTlsMap &tls_map, u64 thread_id, bool is_64_bit) { /* Set thread id. */ m_thread_id = thread_id; /* Verify that the thread is running or waiting. */ { u64 _; u32 _thread_state; if (R_FAILED(svc::GetDebugThreadParam(&_, &_thread_state, debug_handle, m_thread_id, svc::DebugThreadParam_State))) { return false; } const svc::ThreadState thread_state = static_cast<svc::ThreadState>(_thread_state); if (thread_state != svc::ThreadState_Waiting && thread_state != svc::ThreadState_Running) { return false; } } /* Get the thread context. */ if (R_FAILED(svc::GetDebugThreadContext(std::addressof(m_context), debug_handle, m_thread_id, svc::ThreadContextFlag_All))) { return false; } /* In aarch32 mode svc::GetDebugThreadContext does not set the LR, FP, and SP registers correctly. */ if (!is_64_bit) { m_context.fp = m_context.r[11]; m_context.sp = m_context.r[13]; m_context.lr = m_context.r[14]; } /* Read TLS, if present. */ /* TODO: struct definitions for nnSdk's ThreadType/TLS Layout? */ m_tls_address = 0; if (tls_map.GetThreadTls(std::addressof(m_tls_address), thread_id)) { u8 thread_tls[sizeof(svc::ThreadLocalRegion)]; if (R_SUCCEEDED(svc::ReadDebugProcessMemory(reinterpret_cast<uintptr_t>(thread_tls), debug_handle, m_tls_address, sizeof(thread_tls)))) { std::memcpy(m_tls, thread_tls, sizeof(m_tls)); /* Try to detect libnx threads, and skip name parsing then. */ if (*(reinterpret_cast<u32 *>(std::addressof(thread_tls[0x1E0]))) != LibnxThreadVarMagic) { u8 thread_type[0x1C0]; const u64 thread_type_addr = *(reinterpret_cast<u64 *>(std::addressof(thread_tls[0x1F8]))); if (R_SUCCEEDED(svc::ReadDebugProcessMemory(reinterpret_cast<uintptr_t>(thread_type), debug_handle, thread_type_addr, sizeof(thread_type)))) { /* Get the thread version. */ const u16 thread_version = *reinterpret_cast<u16 *>(std::addressof(thread_type[0x46])); if (thread_version == 0 || thread_version == 0xFFFF) { /* Check thread name is actually at thread name. */ static_assert(0x1A8 - 0x188 == NameLengthMax, "NameLengthMax definition!"); if (*(reinterpret_cast<u64 *>(std::addressof(thread_type[0x1A8]))) == thread_type_addr + 0x188) { std::memcpy(m_name, thread_type + 0x188, NameLengthMax); } } else if (thread_version == 1) { static_assert(0x1A0 - 0x180 == NameLengthMax, "NameLengthMax definition!"); if (*(reinterpret_cast<u64 *>(std::addressof(thread_type[0x1A0]))) == thread_type_addr + 0x180) { std::memcpy(m_name, thread_type + 0x180, NameLengthMax); } } } } } } /* Parse stack extents and dump stack. */ this->TryGetStackInfo(debug_handle); /* Dump stack trace. */ if (is_64_bit) { ReadStackTrace<u64>(std::addressof(m_stack_trace_size), m_stack_trace, StackTraceSizeMax, debug_handle, m_context.fp); } else { ReadStackTrace<u32>(std::addressof(m_stack_trace_size), m_stack_trace, StackTraceSizeMax, debug_handle, m_context.fp); } return true; } void ThreadInfo::TryGetStackInfo(os::NativeHandle debug_handle) { /* Query stack region. */ svc::MemoryInfo mi; svc::PageInfo pi; if (R_FAILED(svc::QueryDebugProcessMemory(std::addressof(mi), std::addressof(pi), debug_handle, m_context.sp))) { return; } /* Check if sp points into the stack. */ if (mi.state != svc::MemoryState_Stack) { /* It's possible that sp is below the stack... */ if (R_FAILED(svc::QueryDebugProcessMemory(std::addressof(mi), std::addressof(pi), debug_handle, mi.base_address + mi.size)) || mi.state != svc::MemoryState_Stack) { return; } } /* Save stack extents. */ m_stack_bottom = mi.base_address; m_stack_top = mi.base_address + mi.size; /* We always want to dump 0x100 of stack, starting from the lowest 0x10-byte aligned address below the stack pointer. */ /* Note: if the stack pointer is below the stack bottom, we will start dumping from the stack bottom. */ m_stack_dump_base = std::min(std::max(m_context.sp & ~0xFul, m_stack_bottom), m_stack_top - sizeof(m_stack_dump)); /* Try to read stack. */ if (R_FAILED(svc::ReadDebugProcessMemory(reinterpret_cast<uintptr_t>(m_stack_dump), debug_handle, m_stack_dump_base, sizeof(m_stack_dump)))) { m_stack_dump_base = 0; } } void ThreadInfo::DumpBinary(ScopedFile &file) { /* Dump id and context. */ file.Write(std::addressof(m_thread_id), sizeof(m_thread_id)); file.Write(std::addressof(m_context), sizeof(m_context)); /* Dump TLS info and name. */ file.Write(std::addressof(m_tls_address), sizeof(m_tls_address)); file.Write(std::addressof(m_tls), sizeof(m_tls)); file.Write(std::addressof(m_name), sizeof(m_name)); /* Dump stack extents and stack dump. */ file.Write(std::addressof(m_stack_bottom), sizeof(m_stack_bottom)); file.Write(std::addressof(m_stack_top), sizeof(m_stack_top)); file.Write(std::addressof(m_stack_dump_base), sizeof(m_stack_dump_base)); file.Write(std::addressof(m_stack_dump), sizeof(m_stack_dump)); /* Dump stack trace. */ { const u64 sts = m_stack_trace_size; file.Write(std::addressof(sts), sizeof(sts)); } file.Write(m_stack_trace, m_stack_trace_size); } void ThreadList::DumpBinary(ScopedFile &file, u64 crashed_thread_id) { const u32 magic = DumpedThreadInfoMagic; const u32 count = m_thread_count; file.Write(std::addressof(magic), sizeof(magic)); file.Write(std::addressof(count), sizeof(count)); file.Write(std::addressof(crashed_thread_id), sizeof(crashed_thread_id)); for (size_t i = 0; i < m_thread_count; i++) { m_threads[i].DumpBinary(file); } } void ThreadList::ReadFromProcess(os::NativeHandle debug_handle, ThreadTlsMap &tls_map, bool is_64_bit) { m_thread_count = 0; /* Get thread list. */ s32 num_threads; u64 thread_ids[ThreadCountMax]; { if (R_FAILED(svc::GetThreadList(std::addressof(num_threads), thread_ids, ThreadCountMax, debug_handle))) { return; } num_threads = std::min(size_t(num_threads), ThreadCountMax); } /* Parse thread infos. */ for (s32 i = 0; i < num_threads; i++) { if (m_threads[m_thread_count].ReadFromProcess(debug_handle, tls_map, thread_ids[i], is_64_bit)) { m_thread_count++; } } } }
13,182
C++
.cpp
241
43.053942
228
0.549899
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,186
creport_modules.cpp
Atmosphere-NX_Atmosphere/stratosphere/creport/source/creport_modules.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have 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 "creport_modules.hpp" #include "creport_utils.hpp" namespace ams::creport { namespace { /* Convenience definitions/types. */ constexpr size_t ModulePathLengthMax = 0x200; constexpr u8 GnuSignature[4] = {'G', 'N', 'U', 0}; struct ModulePath { u32 zero; s32 path_length; char path[ModulePathLengthMax]; }; static_assert(sizeof(ModulePath) == 0x208, "ModulePath definition!"); struct RoDataStart { union { u64 deprecated_rwdata_offset; ModulePath module_path; }; }; static_assert(sizeof(RoDataStart) == sizeof(ModulePath), "RoDataStart definition!"); /* Globals. */ u8 g_last_rodata_pages[2 * os::MemoryPageSize]; } void ModuleList::SaveToFile(ScopedFile &file) { file.WriteFormat(" Number of Modules: %02zu\n", m_num_modules); for (size_t i = 0; i < m_num_modules; i++) { const auto& module = m_modules[i]; file.WriteFormat(" Module %02zu:\n", i); file.WriteFormat(" Address: %016lx-%016lx\n", module.start_address, module.end_address); if (std::strcmp(m_modules[i].name, "") != 0) { file.WriteFormat(" Name: %s\n", module.name); } file.DumpMemory(" Module Id: ", module.module_id, sizeof(module.module_id)); } } void ModuleList::FindModulesFromThreadInfo(os::NativeHandle debug_handle, const ThreadInfo &thread, bool is_64_bit) { /* Set the debug handle, for access in other member functions. */ m_debug_handle = debug_handle; /* Try to add the thread's PC. */ this->TryAddModule(thread.GetPC(), is_64_bit); /* Try to add the thread's LR. */ this->TryAddModule(thread.GetLR(), is_64_bit); /* Try to add all the addresses in the thread's stacktrace. */ for (size_t i = 0; i < thread.GetStackTraceSize(); i++) { this->TryAddModule(thread.GetStackTrace(i), is_64_bit); } } void ModuleList::TryAddModule(uintptr_t guess, bool is_64_bit) { /* Try to locate module from guess. */ uintptr_t base_address = 0; if (!this->TryFindModule(std::addressof(base_address), guess, is_64_bit)) { return; } /* Check whether we already have this module. */ for (size_t i = 0; i < m_num_modules; i++) { if (m_modules[i].start_address <= base_address && base_address < m_modules[i].end_address) { return; } } /* Add all contiguous modules. */ uintptr_t cur_address = base_address; while (m_num_modules < ModuleCountMax) { /* Get the region extents. */ svc::MemoryInfo mi; svc::PageInfo pi; if (R_FAILED(svc::QueryDebugProcessMemory(std::addressof(mi), std::addressof(pi), m_debug_handle, cur_address))) { break; } /* Parse module. */ if (mi.permission == svc::MemoryPermission_ReadExecute) { auto& module = m_modules[m_num_modules++]; module.start_address = mi.base_address; module.end_address = mi.base_address + mi.size; GetModuleName(module.name, module.start_address, module.end_address); GetModuleId(module.module_id, module.end_address); /* Default to no symbol table. */ module.has_sym_table = false; if (std::strcmp(module.name, "") == 0) { /* Some homebrew won't have a name. Add a fake one for readability. */ util::SNPrintf(module.name, sizeof(module.name), "[%02x%02x%02x%02x]", module.module_id[0], module.module_id[1], module.module_id[2], module.module_id[3]); } else { /* The module has a name, and so might have a symbol table. Try to add it, if it does. */ if (is_64_bit) { DetectModuleSymbolTable(module); } } } /* If we're out of readable memory, we're done reading code. */ if (mi.state == svc::MemoryState_Free || mi.state == svc::MemoryState_Inaccessible) { break; } /* Verify we're not getting stuck in an infinite loop. */ if (mi.size == 0 || cur_address + mi.size <= cur_address) { break; } cur_address += mi.size; } } bool ModuleList::TryFindModule(uintptr_t *out_address, uintptr_t guess, bool is_64_bit) { AMS_UNUSED(is_64_bit); /* Query the memory region our guess falls in. */ svc::MemoryInfo mi; svc::PageInfo pi; if (R_FAILED(svc::QueryDebugProcessMemory(std::addressof(mi), std::addressof(pi), m_debug_handle, guess))) { return false; } /* If we fall into a RW region, it may be rwdata. Query the region before it, which may be rodata or text. */ if (mi.permission == svc::MemoryPermission_ReadWrite) { if (R_FAILED(svc::QueryDebugProcessMemory(std::addressof(mi), std::addressof(pi), m_debug_handle, mi.base_address - 4))) { return false; } } /* If we fall into an RO region, it may be rodata. Query the region before it, which should be text. */ if (mi.permission == svc::MemoryPermission_Read) { if (R_FAILED(svc::QueryDebugProcessMemory(std::addressof(mi), std::addressof(pi), m_debug_handle, mi.base_address - 4))) { return false; } } /* We should, at this point, be looking at an executable region (text). */ if (mi.permission != svc::MemoryPermission_ReadExecute) { return false; } /* Modules are a series of contiguous (text/rodata/rwdata) regions. */ /* Iterate backwards until we find unmapped memory, to find the start of the set of modules loaded here. */ while (mi.base_address > 0) { if (R_FAILED(svc::QueryDebugProcessMemory(std::addressof(mi), std::addressof(pi), m_debug_handle, mi.base_address - 4))) { return false; } if (mi.state == svc::MemoryState_Free) { /* We've found unmapped memory, so output the mapped memory afterwards. */ *out_address = mi.base_address + mi.size; return true; } } /* Something weird happened here. */ return false; } void ModuleList::GetModuleName(char *out_name, uintptr_t text_start_address, uintptr_t ro_start_address) { /* Clear output. */ std::memset(out_name, 0, ModuleNameLengthMax); /* Read module path from process memory. */ RoDataStart rodata_start; { svc::MemoryInfo mi; svc::PageInfo pi; /* Verify .rodata is read-only. */ if (R_FAILED(svc::QueryDebugProcessMemory(std::addressof(mi), std::addressof(pi), m_debug_handle, ro_start_address)) || mi.permission != svc::MemoryPermission_Read) { return; } /* Calculate start of rwdata. */ const u64 rw_start_address = mi.base_address + mi.size; /* Read start of .rodata. */ if (R_FAILED(svc::ReadDebugProcessMemory(reinterpret_cast<uintptr_t>(std::addressof(rodata_start)), m_debug_handle, ro_start_address, sizeof(rodata_start)))) { return; } /* If data is valid under deprecated format, there's no name. */ if (text_start_address + rodata_start.deprecated_rwdata_offset == rw_start_address) { return; } /* Also validate that we're looking at a valid name. */ if (rodata_start.module_path.zero != 0 || rodata_start.module_path.path_length <= 0) { return; } } /* Start after last slash in path. */ const char *path = rodata_start.module_path.path; int ofs; for (ofs = std::min<size_t>(rodata_start.module_path.path_length, sizeof(rodata_start.module_path.path)); ofs >= 0; ofs--) { if (path[ofs] == '/' || path[ofs] == '\\') { break; } } ofs++; /* Copy name to output. */ const size_t name_size = std::min(ModuleNameLengthMax, std::min<size_t>(rodata_start.module_path.path_length, sizeof(rodata_start.module_path.path)) - ofs); std::memcpy(out_name, path + ofs, name_size); out_name[ModuleNameLengthMax - 1] = '\x00'; } void ModuleList::GetModuleId(u8 *out, uintptr_t ro_start_address) { /* Clear output. */ std::memset(out, 0, ModuleIdSize); /* Verify .rodata is read-only. */ svc::MemoryInfo mi; svc::PageInfo pi; if (R_FAILED(svc::QueryDebugProcessMemory(std::addressof(mi), std::addressof(pi), m_debug_handle, ro_start_address)) || mi.permission != svc::MemoryPermission_Read) { return; } /* We want to read the last two pages of .rodata. */ const size_t read_size = mi.size >= sizeof(g_last_rodata_pages) ? sizeof(g_last_rodata_pages) : (sizeof(g_last_rodata_pages) / 2); if (R_FAILED(svc::ReadDebugProcessMemory(reinterpret_cast<uintptr_t>(g_last_rodata_pages), m_debug_handle, mi.base_address + mi.size - read_size, read_size))) { return; } /* Find GNU\x00 to locate start of module id (GNU build id). */ for (int ofs = read_size - sizeof(GnuSignature) - ModuleIdSize; ofs >= 0; ofs--) { if (std::memcmp(g_last_rodata_pages + ofs, GnuSignature, sizeof(GnuSignature)) == 0) { std::memcpy(out, g_last_rodata_pages + ofs + sizeof(GnuSignature), ModuleIdSize); break; } } } void ModuleList::DetectModuleSymbolTable(ModuleInfo &module) { /* If we already have a symbol table, no more parsing is needed. */ if (module.has_sym_table) { return; } /* Declare temporaries. */ u64 temp_64; u32 temp_32; /* Get module state. */ svc::MemoryInfo mi; svc::PageInfo pi; if (R_FAILED(svc::QueryDebugProcessMemory(std::addressof(mi), std::addressof(pi), m_debug_handle, module.start_address))) { return; } const auto module_state = mi.state; /* Verify .rodata is read-only with same state as .text. */ if (R_FAILED(svc::QueryDebugProcessMemory(std::addressof(mi), std::addressof(pi), m_debug_handle, module.end_address)) || mi.permission != svc::MemoryPermission_Read || mi.state != module_state) { return; } /* We want to find the symbol table/.dynamic. */ uintptr_t dyn_address = 0; uintptr_t sym_tab = 0; uintptr_t str_tab = 0; size_t num_sym = 0; /* Locate .dyn using rocrt::ModuleHeader. */ { /* Determine the ModuleHeader offset. */ u32 mod_offset; if (R_FAILED(svc::ReadDebugProcessMemory(reinterpret_cast<uintptr_t>(std::addressof(mod_offset)), m_debug_handle, module.start_address + sizeof(u32), sizeof(u32)))) { return; } /* Read the signature. */ constexpr u32 SignatureFieldOffset = AMS_OFFSETOF(rocrt::ModuleHeader, signature); if (R_FAILED(svc::ReadDebugProcessMemory(reinterpret_cast<uintptr_t>(std::addressof(temp_32)), m_debug_handle, module.start_address + mod_offset + SignatureFieldOffset, sizeof(u32)))) { return; } /* Check that the module signature is expected. */ if (temp_32 != rocrt::ModuleHeaderVersion) { /* MOD0 */ return; } /* Determine the dynamic offset. */ constexpr u32 DynamicFieldOffset = AMS_OFFSETOF(rocrt::ModuleHeader, dynamic_offset); if (R_FAILED(svc::ReadDebugProcessMemory(reinterpret_cast<uintptr_t>(std::addressof(temp_32)), m_debug_handle, module.start_address + mod_offset + DynamicFieldOffset, sizeof(u32)))) { return; } dyn_address = module.start_address + mod_offset + temp_32; } /* Locate tables inside .dyn. */ for (size_t ofs = 0; /* ... */; ofs += 0x10) { /* Read the DynamicTag. */ if (R_FAILED(svc::ReadDebugProcessMemory(reinterpret_cast<uintptr_t>(std::addressof(temp_64)), m_debug_handle, dyn_address + ofs, sizeof(u64)))) { return; } if (temp_64 == 0) { /* We're done parsing .dyn. */ break; } else if (temp_64 == 4) { /* We found DT_HASH */ if (R_FAILED(svc::ReadDebugProcessMemory(reinterpret_cast<uintptr_t>(std::addressof(temp_64)), m_debug_handle, dyn_address + ofs + sizeof(u64), sizeof(u64)))) { return; } /* Read nchain, to get the number of symbols. */ if (R_FAILED(svc::ReadDebugProcessMemory(reinterpret_cast<uintptr_t>(std::addressof(temp_32)), m_debug_handle, module.start_address + temp_64 + sizeof(u32), sizeof(u32)))) { return; } num_sym = temp_32; } else if (temp_64 == 5) { /* We found DT_STRTAB */ if (R_FAILED(svc::ReadDebugProcessMemory(reinterpret_cast<uintptr_t>(std::addressof(temp_64)), m_debug_handle, dyn_address + ofs + sizeof(u64), sizeof(u64)))) { return; } str_tab = module.start_address + temp_64; } else if (temp_64 == 6) { /* We found DT_SYMTAB */ if (R_FAILED(svc::ReadDebugProcessMemory(reinterpret_cast<uintptr_t>(std::addressof(temp_64)), m_debug_handle, dyn_address + ofs + sizeof(u64), sizeof(u64)))) { return; } sym_tab = module.start_address + temp_64; } } /* Check that we found all the tables. */ if (!(sym_tab != 0 && str_tab != 0 && num_sym != 0)) { return; } module.has_sym_table = true; module.sym_tab = sym_tab; module.str_tab = str_tab; module.num_sym = static_cast<u32>(num_sym); } const char *ModuleList::GetFormattedAddressString(uintptr_t address) { /* Print default formatted string. */ util::SNPrintf(m_address_str_buf, sizeof(m_address_str_buf), "%016lx", address); /* See if the address is inside a module, for pretty-printing. */ for (size_t i = 0; i < m_num_modules; i++) { const auto& module = m_modules[i]; if (module.start_address <= address && address < module.end_address) { if (module.has_sym_table) { /* Try to locate an appropriate symbol. */ for (size_t j = 0; j < module.num_sym; ++j) { /* Read symbol from the module's symbol table. */ struct { u32 st_name; u8 st_info; u8 st_other; u16 st_shndx; u64 st_value; u64 st_size; } sym; if (R_FAILED(svc::ReadDebugProcessMemory(reinterpret_cast<uintptr_t>(std::addressof(sym)), m_debug_handle, module.sym_tab + j * sizeof(sym), sizeof(sym)))) { break; } /* Check the symbol is valid/STT_FUNC. */ if (sym.st_shndx == 0 || ((sym.st_shndx & 0xFF00) == 0xFF00)) { continue; } if ((sym.st_info & 0xF) != 2) { continue; } /* Check the address. */ const uintptr_t func_start = module.start_address + sym.st_value; if (func_start <= address && address < func_start + sym.st_size) { /* Read the symbol name. */ const uintptr_t sym_address = module.str_tab + sym.st_name; char sym_name[0x80]; if (R_FAILED(svc::ReadDebugProcessMemory(reinterpret_cast<uintptr_t>(sym_name), m_debug_handle, sym_address, sizeof(sym_name)))) { break; } /* Ensure null-termination. */ sym_name[sizeof(sym_name) - 1] = '\x00'; /* Print the symbol. */ util::SNPrintf(m_address_str_buf, sizeof(m_address_str_buf), "%016lx (%s + 0x%lx) (%s + 0x%lx)", address, module.name, address - module.start_address, sym_name, address - func_start); return m_address_str_buf; } } } util::SNPrintf(m_address_str_buf, sizeof(m_address_str_buf), "%016lx (%s + 0x%lx)", address, module.name, address - module.start_address); return m_address_str_buf; } } return m_address_str_buf; } }
18,425
C++
.cpp
358
38.382682
211
0.546819
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,187
creport_main.cpp
Atmosphere-NX_Atmosphere/stratosphere/creport/source/creport_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 "creport_crash_report.hpp" #include "creport_utils.hpp" namespace ams { namespace creport { namespace { constinit u8 g_fs_heap_memory[4_KB]; lmem::HeapHandle g_fs_heap_handle; void *AllocateForFs(size_t size) { return lmem::AllocateFromExpHeap(g_fs_heap_handle, size); } void DeallocateForFs(void *p, size_t size) { AMS_UNUSED(size); return lmem::FreeToExpHeap(g_fs_heap_handle, p); } void InitializeFsHeap() { g_fs_heap_handle = lmem::CreateExpHeap(g_fs_heap_memory, sizeof(g_fs_heap_memory), lmem::CreateOption_None); } } } namespace init { void InitializeSystemModule() { /* Initialize heap. */ creport::InitializeFsHeap(); /* Initialize our connection to sm. */ R_ABORT_UNLESS(sm::Initialize()); /* Initialize fs. */ fs::InitializeForSystem(); fs::SetAllocator(creport::AllocateForFs, creport::DeallocateForFs); fs::SetEnabledAutoAbort(false); /* Mount the SD card. */ R_ABORT_UNLESS(fs::MountSdCard("sdmc")); } void FinalizeSystemModule() { /* ... */ } void Startup() { /* ... */ } } namespace { constinit creport::CrashReport g_crash_report; } void Main() { /* Set thread name. */ os::SetThreadNamePointer(os::GetCurrentThread(), AMS_GET_SYSTEM_THREAD_NAME(creport, Main)); AMS_ASSERT(os::GetThreadPriority(os::GetCurrentThread()) == AMS_GET_SYSTEM_THREAD_PRIORITY(creport, Main)); /* Get arguments. */ const int num_args = os::GetHostArgc(); char ** const args = os::GetHostArgv(); /* Validate arguments. */ if (num_args < 2) { return; } for (auto i = 0; i < num_args; ++i) { if (args[i] == nullptr) { return; } } /* Parse arguments. */ const os::ProcessId crashed_pid = creport::ParseProcessIdArgument(args[0]); const bool has_extra_info = args[1][0] == '1'; const bool enable_screenshot = num_args >= 3 && args[2][0] == '1'; const bool enable_jit_debug = num_args >= 4 && args[3][0] == '1'; /* Initialize the crash report. */ g_crash_report.Initialize(); /* Try to debug the crashed process. */ { g_crash_report.BuildReport(crashed_pid, has_extra_info); ON_SCOPE_EXIT { if (g_crash_report.IsOpen()) { g_crash_report.Close(); } }; if (!g_crash_report.IsComplete()) { return; } /* Save report to file. */ g_crash_report.SaveReport(enable_screenshot); } /* Try to terminate the process, if we should. */ const auto fw_ver = hos::GetVersion(); if (fw_ver < hos::Version_11_0_0 || !enable_jit_debug) { if (fw_ver >= hos::Version_10_0_0) { /* Use pgl to terminate. */ if (R_SUCCEEDED(pgl::Initialize())) { ON_SCOPE_EXIT { pgl::Finalize(); }; pgl::TerminateProcess(crashed_pid); } } else { /* Use ns to terminate. */ if (R_SUCCEEDED(::nsdevInitialize())) { ON_SCOPE_EXIT { ::nsdevExit(); }; nsdevTerminateProcess(crashed_pid.value); } } } /* If we're on 5.0.0+ and an application crashed, or if we have extra info, we don't need to fatal. */ if (fw_ver >= hos::Version_5_0_0) { if (g_crash_report.IsApplication()) { return; } } else if (has_extra_info) { return; } /* We also don't need to fatal on user break. */ if (g_crash_report.IsUserBreak()) { return; } /* Throw fatal error. */ { ::FatalCpuContext ctx; g_crash_report.GetFatalContext(std::addressof(ctx)); fatalThrowWithContext(g_crash_report.GetResult().GetValue(), FatalPolicy_ErrorScreen, std::addressof(ctx)); } } }
5,000
C++
.cpp
124
30.048387
124
0.554959
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,188
creport_utils.cpp
Atmosphere-NX_Atmosphere/stratosphere/creport/source/creport_utils.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "creport_utils.hpp" namespace ams::creport { os::ProcessId ParseProcessIdArgument(const char *s) { /* Official creport uses this custom parsing logic... */ u64 out_val = 0; for (unsigned int i = 0; i < 20 && s[i]; i++) { if ('0' <= s[i] && s[i] <= '9') { out_val *= 10; out_val += (s[i] - '0'); } else { break; } } return os::ProcessId{out_val}; } }
1,158
C++
.cpp
32
30.5
76
0.628342
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,189
amsmitm_main.cpp
Atmosphere-NX_Atmosphere/stratosphere/ams_mitm/source/amsmitm_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 "amsmitm_initialization.hpp" #include "amsmitm_module_management.hpp" #include "bpc_mitm/bpc_ams_power_utils.hpp" #include "sysupdater/sysupdater_fs_utils.hpp" namespace ams { namespace { /* TODO: we really shouldn't be using malloc just to avoid dealing with real allocator separation. */ constexpr size_t MallocBufferSize = 32_MB; alignas(os::MemoryPageSize) constinit u8 g_malloc_buffer[MallocBufferSize]; } namespace init { void InitializeSystemModule() { /* Initialize our connection to sm. */ R_ABORT_UNLESS(sm::Initialize()); /* Initialize fs. */ fs::InitializeForSystem(); fs::SetEnabledAutoAbort(false); /* Initialize other services. */ R_ABORT_UNLESS(pmdmntInitialize()); R_ABORT_UNLESS(pminfoInitialize()); ncm::Initialize(); /* Verify that we can sanely execute. */ ams::CheckApiVersion(); } void FinalizeSystemModule() { /* ... */ } void Startup() { /* Initialize the global malloc allocator. */ init::InitializeAllocator(g_malloc_buffer, sizeof(g_malloc_buffer)); } } void ExceptionHandler(FatalErrorContext *ctx) { /* We're bpc-mitm (or ams_mitm, anyway), so manually reboot to fatal error. */ mitm::bpc::RebootForFatalError(ctx); } void NORETURN Exit(int rc) { AMS_UNUSED(rc); AMS_ABORT("Exit called by immortal process"); } void Main() { /* Register "ams" port, use up its session. */ { svc::Handle ams_port; R_ABORT_UNLESS(svc::ManageNamedPort(std::addressof(ams_port), "ams", 1)); svc::Handle ams_session; R_ABORT_UNLESS(svc::ConnectToNamedPort(std::addressof(ams_session), "ams")); } /* Initialize fssystem library. */ fssystem::InitializeForAtmosphereMitm(); /* Configure ncm to use fssystem library to mount content from the sd card. */ ncm::SetMountContentMetaFunction(mitm::sysupdater::MountSdCardContentMeta); /* Launch all mitm modules in sequence. */ mitm::LaunchAllModules(); /* Wait for all mitm modules to end. */ mitm::WaitAllModules(); } }
2,993
C++
.cpp
72
34.138889
109
0.65
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,190
amsmitm_prodinfo_utils.cpp
Atmosphere-NX_Atmosphere/stratosphere/ams_mitm/source/amsmitm_prodinfo_utils.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "amsmitm_fs_utils.hpp" #include "amsmitm_prodinfo_utils.hpp" namespace ams::mitm { namespace { constexpr inline u16 Crc16InitialValue = 0x55AA; constexpr inline u16 Crc16Table[] = { 0x0000, 0xCC01, 0xD801, 0x1400, 0xF001, 0x3C00, 0x2800, 0xE401, 0xA001, 0x6C00, 0x7800, 0xB401, 0x5000, 0x9C01, 0x8801, 0x4400, }; u16 GetCrc16(const void *data, size_t size) { AMS_ASSERT(data != nullptr); AMS_ASSERT(size > 0); const u8 *src = static_cast<const u8 *>(data); u16 crc = Crc16InitialValue; u16 tmp = 0; while ((size--) > 0) { tmp = Crc16Table[crc & 0xF]; crc = ((crc >> 4) & 0x0FFF) ^ tmp ^ Crc16Table[*src & 0xF]; tmp = Crc16Table[crc & 0xF]; crc = ((crc >> 4) & 0x0FFF) ^ tmp ^ Crc16Table[(*(src++) >> 4) & 0xF]; } return crc; } bool IsBlank(const void *data, size_t size) { AMS_ASSERT(data != nullptr); AMS_ASSERT(size > 0); const u8 *src = static_cast<const u8 *>(data); while ((size--) > 0) { if (*(src++) != 0) { return false; } } return true; } constexpr inline u32 CalibrationMagic = util::FourCC<'C','A','L','0'>::Code; struct Sha256Hash { u8 data[crypto::Sha256Generator::HashSize]; }; struct CalibrationInfoHeader { u32 magic; u32 version; u32 body_size; u16 model; u16 update_count; u8 pad[0xE]; u16 crc; Sha256Hash body_hash; }; static_assert(sizeof(CalibrationInfoHeader) == 0x40); constexpr inline size_t CalibrationInfoBodySizeMax = CalibrationBinarySize - sizeof(CalibrationInfoHeader); struct CalibrationInfo { CalibrationInfoHeader header; u8 body[CalibrationInfoBodySizeMax]; /* TODO: CalibrationInfoBody body; */ template<typename Block> Block &GetBlock() { static_assert(Block::Offset >= sizeof(CalibrationInfoHeader)); static_assert(Block::Offset < sizeof(CalibrationInfo)); static_assert(Block::Offset + Block::Size <= sizeof(CalibrationInfo)); return *static_cast<Block *>(static_cast<void *>(std::addressof(this->body[Block::Offset - sizeof(this->header)]))); } template<typename Block> const Block &GetBlock() const { static_assert(Block::Offset >= sizeof(CalibrationInfoHeader)); static_assert(Block::Offset < sizeof(CalibrationInfo)); static_assert(Block::Offset + Block::Size <= sizeof(CalibrationInfo)); return *static_cast<const Block *>(static_cast<const void *>(std::addressof(this->body[Block::Offset - sizeof(this->header)]))); } }; static_assert(sizeof(CalibrationInfo) == CalibrationBinarySize); struct SecureCalibrationInfoBackup { CalibrationInfo info; Sha256Hash hash; u8 pad[SecureCalibrationBinaryBackupSize - sizeof(info) - sizeof(hash)]; }; static_assert(sizeof(SecureCalibrationInfoBackup) == SecureCalibrationBinaryBackupSize); bool IsValidSha256Hash(const Sha256Hash &hash, const void *data, size_t data_size) { Sha256Hash calc_hash; ON_SCOPE_EXIT { ::ams::crypto::ClearMemory(std::addressof(calc_hash), sizeof(calc_hash)); }; ::ams::crypto::GenerateSha256(std::addressof(calc_hash), sizeof(calc_hash), data, data_size); return ::ams::crypto::IsSameBytes(std::addressof(calc_hash), std::addressof(hash), sizeof(Sha256Hash)); } bool IsValid(const CalibrationInfoHeader &header) { return header.magic == CalibrationMagic && GetCrc16(std::addressof(header), AMS_OFFSETOF(CalibrationInfoHeader, crc)) == header.crc; } bool IsValid(const CalibrationInfoHeader &header, const void *body) { return IsValid(header) && IsValidSha256Hash(header.body_hash, body, header.body_size); } #define DEFINE_CALIBRATION_CRC_BLOCK(_TypeName, _Offset, _Size, _Decl, _MemberName) \ struct _TypeName { \ static constexpr size_t Offset = _Offset; \ static constexpr size_t Size = _Size; \ static constexpr bool IsCrcBlock = true; \ static constexpr bool IsShaBlock = false; \ _Decl; \ static_assert(Size >= sizeof(_MemberName) + sizeof(u16)); \ u8 pad[Size - sizeof(_MemberName) - sizeof(u16)]; \ u16 crc; \ }; \ static_assert(sizeof(_TypeName) == _TypeName::Size) #define DEFINE_CALIBRATION_SHA_BLOCK(_TypeName, _Offset, _Size, _Decl, _MemberName) \ struct _TypeName { \ static constexpr size_t Offset = _Offset; \ static constexpr size_t Size = _Size; \ static constexpr bool IsCrcBlock = false; \ static constexpr bool IsShaBlock = true; \ _Decl; \ static_assert(Size == sizeof(_MemberName) + sizeof(Sha256Hash)); \ Sha256Hash sha256_hash; \ }; \ static_assert(sizeof(_TypeName) == _TypeName::Size) DEFINE_CALIBRATION_CRC_BLOCK(SerialNumberBlock, 0x0250, 0x020, ::ams::settings::factory::SerialNumber serial_number, serial_number); DEFINE_CALIBRATION_CRC_BLOCK(EccB233DeviceCertificateBlock, 0x0480, 0x190, ::ams::settings::factory::EccB233DeviceCertificate device_certificate, device_certificate); DEFINE_CALIBRATION_CRC_BLOCK(SslKeyBlock, 0x09B0, 0x120, u8 ssl_key[0x110], ssl_key); DEFINE_CALIBRATION_CRC_BLOCK(SslCertificateSizeBlock, 0x0AD0, 0x010, u64 ssl_certificate_size, ssl_certificate_size); DEFINE_CALIBRATION_SHA_BLOCK(SslCertificateBlock, 0x0AE0, 0x820, u8 ssl_certificate[0x800], ssl_certificate); DEFINE_CALIBRATION_CRC_BLOCK(EcqvEcdsaAmiiboRootCertificateBlock, 0x35A0, 0x080, u8 data[0x70], data); DEFINE_CALIBRATION_CRC_BLOCK(EcqvBlsAmiiboRootCertificateBlock, 0x36A0, 0x0A0, u8 data[0x90], data); DEFINE_CALIBRATION_CRC_BLOCK(ExtendedSslKeyBlock, 0x3AE0, 0x140, u8 ssl_key[0x134], ssl_key); DEFINE_CALIBRATION_CRC_BLOCK(Rsa2048DeviceKeyBlock, 0x3D70, 0x250, u8 device_key[0x240], device_key); DEFINE_CALIBRATION_CRC_BLOCK(Rsa2048DeviceCertificateBlock, 0x3FC0, 0x250, ::ams::settings::factory::Rsa2048DeviceCertificate device_certificate, device_certificate); #undef DEFINE_CALIBRATION_CRC_BLOCK #undef DEFINE_CALIBRATION_SHA_BLOCK constexpr inline const char BlankSerialNumberString[] = "XAW00000000000"; template<typename Block> void Blank(Block &block) { if constexpr (std::is_same<Block, SerialNumberBlock>::value) { static_assert(sizeof(BlankSerialNumberString) <= sizeof(SerialNumberBlock::serial_number)); std::memset(std::addressof(block), 0, Block::Size - sizeof(block.crc)); std::memcpy(block.serial_number.str, BlankSerialNumberString, sizeof(BlankSerialNumberString)); block.crc = GetCrc16(std::addressof(block), Block::Size - sizeof(block.crc)); } else if constexpr (std::is_same<Block, SslCertificateBlock>::value) { std::memset(std::addressof(block), 0, sizeof(block.ssl_certificate)); } else if constexpr (Block::IsCrcBlock) { std::memset(std::addressof(block), 0, Block::Size - sizeof(block.crc)); block.crc = GetCrc16(std::addressof(block), Block::Size - sizeof(block.crc)); } else { static_assert(Block::IsShaBlock); std::memset(std::addressof(block), 0, Block::Size); ::ams::crypto::GenerateSha256(std::addressof(block.sha256_hash), sizeof(block.sha256_hash), std::addressof(block), Block::Size - sizeof(block.sha256_hash)); } } template<typename Block> bool IsBlank(const Block &block) { if constexpr (std::is_same<Block, SerialNumberBlock>::value) { static_assert(sizeof(BlankSerialNumberString) <= sizeof(SerialNumberBlock::serial_number)); return std::memcmp(block.serial_number.str, BlankSerialNumberString, sizeof(BlankSerialNumberString) - 1) == 0 || IsBlank(std::addressof(block), Block::Size - sizeof(block.crc)); } else if constexpr (Block::IsCrcBlock) { return IsBlank(std::addressof(block), Block::Size - sizeof(block.crc)); } else { return IsBlank(std::addressof(block), Block::Size - sizeof(block.sha256_hash)); } } template<typename Block> bool IsValid(const Block &block, size_t size = 0) { if constexpr (Block::IsCrcBlock) { return GetCrc16(std::addressof(block), Block::Size - sizeof(block.crc)) == block.crc; } else { static_assert(Block::IsShaBlock); return IsValidSha256Hash(block.sha256_hash, std::addressof(block), size != 0 ? size : Block::Size - sizeof(block.sha256_hash)); } } void Blank(CalibrationInfo &info) { /* Set header. */ info.header.magic = CalibrationMagic; info.header.body_size = sizeof(info.body); info.header.crc = GetCrc16(std::addressof(info.header), AMS_OFFSETOF(CalibrationInfoHeader, crc)); /* Set blocks. */ Blank(info.GetBlock<SerialNumberBlock>()); Blank(info.GetBlock<SslCertificateSizeBlock>()); Blank(info.GetBlock<SslCertificateBlock>()); Blank(info.GetBlock<EcqvEcdsaAmiiboRootCertificateBlock>()); Blank(info.GetBlock<EcqvBlsAmiiboRootCertificateBlock>()); Blank(info.GetBlock<ExtendedSslKeyBlock>()); /* Set header hash. */ crypto::GenerateSha256(std::addressof(info.header.body_hash), sizeof(info.header.body_hash), std::addressof(info.body), sizeof(info.body)); } bool IsValidHeader(const CalibrationInfo &cal) { return IsValid(cal.header) && cal.header.body_size <= CalibrationInfoBodySizeMax && IsValid(cal.header, cal.body); } bool IsValidSerialNumber(const char *sn) { for (size_t i = 0; i < std::strlen(sn); i++) { if (!std::isalnum(static_cast<unsigned char>(sn[i]))) { return false; } } return true; } void GetSerialNumber(char *dst, const CalibrationInfo &info) { std::memcpy(dst, std::addressof(info.GetBlock<SerialNumberBlock>()), sizeof(info.GetBlock<SerialNumberBlock>().serial_number)); dst[sizeof(info.GetBlock<SerialNumberBlock>().serial_number) + 1] = '\x00'; } bool IsValidSerialNumber(const CalibrationInfo &cal) { char sn[0x20] = {}; ON_SCOPE_EXIT { std::memset(sn, 0, sizeof(sn)); }; GetSerialNumber(sn, cal); return IsValidSerialNumber(sn); } bool IsValid(const CalibrationInfo &cal) { return IsValidHeader(cal) && IsValid(cal.GetBlock<SerialNumberBlock>()) && IsValid(cal.GetBlock<EccB233DeviceCertificateBlock>()) && IsValid(cal.GetBlock<SslKeyBlock>()) && IsValid(cal.GetBlock<SslCertificateSizeBlock>()) && cal.GetBlock<SslCertificateSizeBlock>().ssl_certificate_size <= sizeof(cal.GetBlock<SslCertificateBlock>().ssl_certificate) && IsValid(cal.GetBlock<SslCertificateBlock>(), cal.GetBlock<SslCertificateSizeBlock>().ssl_certificate_size) && IsValid(cal.GetBlock<EcqvEcdsaAmiiboRootCertificateBlock>()) && IsValid(cal.GetBlock<EcqvBlsAmiiboRootCertificateBlock>()) && IsValid(cal.GetBlock<ExtendedSslKeyBlock>()) && IsValidSerialNumber(cal); } bool ContainsCorrectDeviceId(const EccB233DeviceCertificateBlock &block, u64 device_id) { static constexpr size_t DeviceIdOffset = 0xC6; char found_device_id_str[sizeof("0011223344556677")] = {}; ON_SCOPE_EXIT { std::memset(found_device_id_str, 0, sizeof(found_device_id_str)); }; std::memcpy(found_device_id_str, std::addressof(block.device_certificate.data[DeviceIdOffset]), sizeof(found_device_id_str) - 1); static constexpr u64 DeviceIdLowMask = 0x00FFFFFFFFFFFFFFul; return (std::strtoul(found_device_id_str, nullptr, 16) & DeviceIdLowMask) == (device_id & DeviceIdLowMask); } bool ContainsCorrectDeviceId(const CalibrationInfo &cal) { return ContainsCorrectDeviceId(cal.GetBlock<EccB233DeviceCertificateBlock>(), exosphere::GetDeviceId()); } bool IsValidForSecureBackup(const CalibrationInfo &cal) { return IsValid(cal) && ContainsCorrectDeviceId(cal); } bool IsBlank(const CalibrationInfo &cal) { return IsBlank(cal.GetBlock<SerialNumberBlock>()) || IsBlank(cal.GetBlock<SslCertificateSizeBlock>()) || IsBlank(cal.GetBlock<SslCertificateBlock>()) || IsBlank(cal.GetBlock<EcqvEcdsaAmiiboRootCertificateBlock>()) || IsBlank(cal.GetBlock<EcqvBlsAmiiboRootCertificateBlock>()) || IsBlank(cal.GetBlock<ExtendedSslKeyBlock>()); } void ReadStorageCalibrationBinary(CalibrationInfo *out) { FsStorage calibration_binary_storage; R_ABORT_UNLESS(fsOpenBisStorage(std::addressof(calibration_binary_storage), FsBisPartitionId_CalibrationBinary)); ON_SCOPE_EXIT { fsStorageClose(std::addressof(calibration_binary_storage)); }; R_ABORT_UNLESS(fsStorageRead(std::addressof(calibration_binary_storage), 0, out, sizeof(*out))); } constexpr inline const u8 SecureCalibrationBinaryBackupIv[crypto::Aes128CtrDecryptor::IvSize] = {}; void ReadStorageEncryptedSecureCalibrationBinaryBackupUnsafe(SecureCalibrationInfoBackup *out) { FsStorage calibration_binary_storage; R_ABORT_UNLESS(fsOpenBisStorage(std::addressof(calibration_binary_storage), FsBisPartitionId_CalibrationBinary)); ON_SCOPE_EXIT { fsStorageClose(std::addressof(calibration_binary_storage)); }; R_ABORT_UNLESS(fsStorageRead(std::addressof(calibration_binary_storage), SecureCalibrationInfoBackupOffset, out, sizeof(*out))); } void WriteStorageEncryptedSecureCalibrationBinaryBackupUnsafe(const SecureCalibrationInfoBackup *src) { FsStorage calibration_binary_storage; R_ABORT_UNLESS(fsOpenBisStorage(std::addressof(calibration_binary_storage), FsBisPartitionId_CalibrationBinary)); ON_SCOPE_EXIT { fsStorageClose(std::addressof(calibration_binary_storage)); }; R_ABORT_UNLESS(fsStorageWrite(std::addressof(calibration_binary_storage), SecureCalibrationInfoBackupOffset, src, sizeof(*src))); } void GenerateSecureCalibrationBinaryBackupKey(void *dst, size_t dst_size) { static constexpr const u8 SecureCalibrationBinaryBackupKeySource[crypto::Aes128CtrDecryptor::KeySize] = { '|', '-', 'A', 'M', 'S', '-', 'C', 'A', 'L', '0', '-', 'K', 'E', 'Y', '-', '|' }; spl::AccessKey access_key; ON_SCOPE_EXIT { crypto::ClearMemory(std::addressof(access_key), sizeof(access_key)); }; /* Generate a personalized kek. */ R_ABORT_UNLESS(spl::GenerateAesKek(std::addressof(access_key), SecureCalibrationBinaryBackupKeySource, sizeof(SecureCalibrationBinaryBackupKeySource), 0, 1)); /* Generate a personalized key. */ R_ABORT_UNLESS(spl::GenerateAesKey(dst, dst_size, access_key, SecureCalibrationBinaryBackupKeySource, sizeof(SecureCalibrationBinaryBackupKeySource))); } bool ReadStorageSecureCalibrationBinaryBackup(SecureCalibrationInfoBackup *out) { /* Read the data. */ ReadStorageEncryptedSecureCalibrationBinaryBackupUnsafe(out); /* Don't leak any data unless we validate. */ auto clear_guard = SCOPE_GUARD { std::memset(out, 0, sizeof(*out)); }; { /* Create a buffer to hold our key. */ u8 key[crypto::Aes128CtrDecryptor::KeySize]; ON_SCOPE_EXIT { crypto::ClearMemory(key, sizeof(key)); }; /* Generate the key. */ GenerateSecureCalibrationBinaryBackupKey(key, sizeof(key)); /* Decrypt the data in place. */ crypto::DecryptAes128Ctr(out, sizeof(*out), key, sizeof(key), SecureCalibrationBinaryBackupIv, sizeof(SecureCalibrationBinaryBackupIv), out, sizeof(*out)); } /* Generate a hash for the data. */ if (!IsValidSha256Hash(out->hash, std::addressof(out->info), sizeof(out->info))) { return false; } /* Validate the backup. */ if (!IsValidForSecureBackup(out->info)) { return false; } /* Our backup is valid. */ clear_guard.Cancel(); return true; } void WriteStorageSecureCalibrationBinaryBackup(SecureCalibrationInfoBackup *src) { /* Clear the input once we've written it. */ ON_SCOPE_EXIT { std::memset(src, 0, sizeof(*src)); }; /* Ensure that the input is valid. */ AMS_ABORT_UNLESS(IsValidForSecureBackup(src->info)); /* Set the Sha256 hash. */ crypto::GenerateSha256(std::addressof(src->hash), sizeof(src->hash), std::addressof(src->info), sizeof(src->info)); /* Validate the hash. */ AMS_ABORT_UNLESS(IsValidSha256Hash(src->hash, std::addressof(src->info), sizeof(src->info))); /* Encrypt the data. */ { /* Create a buffer to hold our key. */ u8 key[crypto::Aes128CtrDecryptor::KeySize]; ON_SCOPE_EXIT { crypto::ClearMemory(key, sizeof(key)); }; /* Generate the key. */ GenerateSecureCalibrationBinaryBackupKey(key, sizeof(key)); /* Encrypt the data in place. */ crypto::EncryptAes128Ctr(src, sizeof(*src), key, sizeof(key), SecureCalibrationBinaryBackupIv, sizeof(SecureCalibrationBinaryBackupIv), src, sizeof(*src)); } /* Write the encrypted data. */ WriteStorageEncryptedSecureCalibrationBinaryBackupUnsafe(src); } void GetBackupFileName(char *dst, size_t dst_size, const CalibrationInfo &info) { char sn[0x20] = {}; ON_SCOPE_EXIT { std::memset(sn, 0, sizeof(sn)); }; if (IsValidForSecureBackup(info)) { GetSerialNumber(sn, info); util::SNPrintf(dst, dst_size, "automatic_backups/%s_PRODINFO.bin", sn); } else { Sha256Hash hash; crypto::GenerateSha256(std::addressof(hash), sizeof(hash), std::addressof(info), sizeof(info)); ON_SCOPE_EXIT { crypto::ClearMemory(std::addressof(hash), sizeof(hash)); }; if (IsValid(info)) { if (IsBlank(info)) { util::SNPrintf(dst, dst_size, "automatic_backups/BLANK_PRODINFO_%02X%02X%02X%02X.bin", hash.data[0], hash.data[1], hash.data[2], hash.data[3]); } else { GetSerialNumber(sn, info); util::SNPrintf(dst, dst_size, "automatic_backups/%s_PRODINFO_%02X%02X%02X%02X.bin", sn, hash.data[0], hash.data[1], hash.data[2], hash.data[3]); } } else { util::SNPrintf(dst, dst_size, "automatic_backups/INVALID_PRODINFO_%02X%02X%02X%02X.bin", hash.data[0], hash.data[1], hash.data[2], hash.data[3]); } } } void SafeRead(ams::fs::fsa::IFile *file, s64 offset, void *dst, size_t size) { size_t read_size = 0; R_ABORT_UNLESS(file->Read(std::addressof(read_size), offset, dst, size)); AMS_ABORT_UNLESS(read_size == size); } alignas(os::MemoryPageSize) CalibrationInfo g_temp_calibration_info = {}; void SaveProdInfoBackup(util::optional<ams::fs::FileStorage> *dst, const CalibrationInfo &info) { char backup_fn[0x100]; GetBackupFileName(backup_fn, sizeof(backup_fn), info); /* Create the file, in case it does not exist. */ mitm::fs::CreateAtmosphereSdFile(backup_fn, sizeof(CalibrationInfo), ams::fs::CreateOption_None); /* Open the file. */ FsFile libnx_file; R_ABORT_UNLESS(mitm::fs::OpenAtmosphereSdFile(std::addressof(libnx_file), backup_fn, ams::fs::OpenMode_ReadWrite)); /* Create our accessor. */ std::unique_ptr<ams::fs::fsa::IFile> file = std::make_unique<ams::fs::RemoteFile>(libnx_file); AMS_ABORT_UNLESS(file != nullptr); /* Check if we're valid already. */ bool valid = false; s64 size; R_ABORT_UNLESS(file->GetSize(std::addressof(size))); if (size == sizeof(CalibrationInfo)) { SafeRead(file.get(), 0, std::addressof(g_temp_calibration_info), sizeof(g_temp_calibration_info)); ON_SCOPE_EXIT { std::memset(std::addressof(g_temp_calibration_info), 0, sizeof(g_temp_calibration_info)); }; if (std::memcmp(std::addressof(info), std::addressof(g_temp_calibration_info), sizeof(CalibrationInfo)) == 0) { valid = true; } } /* If we're not valid, we need to save. */ if (!valid) { R_ABORT_UNLESS(file->Write(0, std::addressof(info), sizeof(info), ams::fs::WriteOption::Flush)); } /* Save our storage to output. */ if (dst != nullptr) { dst->emplace(std::move(file)); } } void GetRandomEntropy(Sha256Hash *dst) { AMS_ASSERT(dst != nullptr); u64 data_buffer[3] = {}; ON_SCOPE_EXIT { crypto::ClearMemory(data_buffer, sizeof(data_buffer)); }; data_buffer[0] = os::GetSystemTick().GetInt64Value(); R_ABORT_UNLESS(svc::GetInfo(data_buffer + 1, svc::InfoType_AliasRegionAddress, svc::PseudoHandle::CurrentProcess, 0)); if (hos::GetVersion() >= hos::Version_2_0_0) { R_ABORT_UNLESS(svc::GetInfo(data_buffer + 2, svc::InfoType_RandomEntropy, svc::InvalidHandle, (data_buffer[0] ^ (data_buffer[1] >> 24)) & 3)); } else { data_buffer[2] = os::GetSystemTick().GetInt64Value(); } return crypto::GenerateSha256(dst, sizeof(*dst), data_buffer, sizeof(data_buffer)); } void FillWithGarbage(void *dst, size_t dst_size) { /* Get random entropy. */ Sha256Hash entropy; ON_SCOPE_EXIT { crypto::ClearMemory(std::addressof(entropy), sizeof(entropy)); }; GetRandomEntropy(std::addressof(entropy)); /* Clear dst. */ std::memset(dst, 0xCC, dst_size); /* Encrypt dst. */ static_assert(sizeof(entropy) == crypto::Aes128CtrEncryptor::KeySize + crypto::Aes128CtrEncryptor::IvSize); crypto::EncryptAes128Ctr(dst, dst_size, entropy.data, crypto::Aes128CtrEncryptor::KeySize, entropy.data + crypto::Aes128CtrEncryptor::KeySize, crypto::Aes128CtrEncryptor::IvSize, dst, dst_size); } 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 = {}; 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; constinit bool g_allow_writes = false; constinit bool g_has_secure_backup = false; constinit os::SdkMutex g_prodinfo_management_lock; } void InitializeProdInfoManagement() { std::scoped_lock lk(g_prodinfo_management_lock); /* First, get our options. */ const bool should_blank = exosphere::ShouldBlankProdInfo(); bool allow_writes = exosphere::ShouldAllowWritesToProdInfo(); /* Next, read our prodinfo. */ ReadStorageCalibrationBinary(std::addressof(g_calibration_info)); /* Next, check if we have a secure backup. */ bool has_secure_backup = ReadStorageSecureCalibrationBinaryBackup(std::addressof(g_secure_calibration_info_backup)); /* Only allow writes if we have a secure backup. */ if (allow_writes && !has_secure_backup) { /* If we can make a secure backup, great. */ if (IsValidForSecureBackup(g_calibration_info)) { g_secure_calibration_info_backup.info = g_calibration_info; WriteStorageSecureCalibrationBinaryBackup(std::addressof(g_secure_calibration_info_backup)); g_secure_calibration_info_backup.info = g_calibration_info; has_secure_backup = true; } else { /* Don't allow writes if we can't make a secure backup. */ allow_writes = false; } } /* Ensure our preconditions are met. */ AMS_ABORT_UNLESS(!allow_writes || has_secure_backup); /* Set globals. */ g_allow_writes = allow_writes; g_has_secure_backup = has_secure_backup; /* If we should blank, do so. */ if (should_blank) { g_blank_calibration_info = g_calibration_info; Blank(g_blank_calibration_info); g_blank_prodinfo_storage.emplace(std::addressof(g_blank_calibration_info), sizeof(g_blank_calibration_info)); } /* Ensure that we have a blank file only if we need one. */ AMS_ABORT_UNLESS(should_blank == static_cast<bool>(g_blank_prodinfo_storage)); } void SaveProdInfoBackupsAndWipeMemory(char *out_name, size_t out_name_size) { std::scoped_lock lk(g_prodinfo_management_lock); ON_SCOPE_EXIT { FillWithGarbage(std::addressof(g_calibration_info), sizeof(g_calibration_info)); FillWithGarbage(std::addressof(g_secure_calibration_info_backup), sizeof(g_secure_calibration_info_backup)); }; /* Save our backup. We always prefer to save a secure copy of data over a non-secure one. */ if (g_has_secure_backup) { GetSerialNumber(out_name, g_secure_calibration_info_backup.info); SaveProdInfoBackup(std::addressof(g_prodinfo_backup_file), g_secure_calibration_info_backup.info); } else { if (IsValid(g_calibration_info) && !IsBlank(g_calibration_info)) { GetSerialNumber(out_name, g_calibration_info); } else { Sha256Hash hash; ON_SCOPE_EXIT { crypto::ClearMemory(std::addressof(hash), sizeof(hash)); }; crypto::GenerateSha256(std::addressof(hash), sizeof(hash), std::addressof(g_calibration_info), sizeof(g_calibration_info)); util::SNPrintf(out_name, out_name_size, "%02X%02X%02X%02X", hash.data[0], hash.data[1], hash.data[2], hash.data[3]); } SaveProdInfoBackup(std::addressof(g_prodinfo_backup_file), g_calibration_info); } /* Ensure we made our backup. */ AMS_ABORT_UNLESS(g_prodinfo_backup_file); /* Setup our memory storage. */ g_fake_secure_backup_storage.emplace(std::addressof(g_secure_calibration_info_backup), sizeof(g_secure_calibration_info_backup)); /* Ensure that we have a fake storage. */ AMS_ABORT_UNLESS(static_cast<bool>(g_fake_secure_backup_storage)); } bool ShouldReadBlankCalibrationBinary() { std::scoped_lock lk(g_prodinfo_management_lock); return static_cast<bool>(g_blank_prodinfo_storage); } bool IsWriteToCalibrationBinaryAllowed() { std::scoped_lock lk(g_prodinfo_management_lock); return g_allow_writes; } void ReadFromBlankCalibrationBinary(s64 offset, void *dst, size_t size) { AMS_ABORT_UNLESS(ShouldReadBlankCalibrationBinary()); std::scoped_lock lk(g_prodinfo_management_lock); R_ABORT_UNLESS(g_blank_prodinfo_storage->Read(offset, dst, size)); } void WriteToBlankCalibrationBinary(s64 offset, const void *src, size_t size) { AMS_ABORT_UNLESS(ShouldReadBlankCalibrationBinary()); std::scoped_lock lk(g_prodinfo_management_lock); R_ABORT_UNLESS(g_blank_prodinfo_storage->Write(offset, src, size)); } void ReadFromFakeSecureBackupStorage(s64 offset, void *dst, size_t size) { AMS_ABORT_UNLESS(IsWriteToCalibrationBinaryAllowed()); std::scoped_lock lk(g_prodinfo_management_lock); R_ABORT_UNLESS(g_fake_secure_backup_storage->Read(offset, dst, size)); } void WriteToFakeSecureBackupStorage(s64 offset, const void *src, size_t size) { AMS_ABORT_UNLESS(IsWriteToCalibrationBinaryAllowed()); std::scoped_lock lk(g_prodinfo_management_lock); R_ABORT_UNLESS(g_fake_secure_backup_storage->Write(offset, src, size)); } }
32,454
C++
.cpp
512
51.128906
206
0.590376
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,191
amsmitm_fs_utils.cpp
Atmosphere-NX_Atmosphere/stratosphere/ams_mitm/source/amsmitm_fs_utils.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "amsmitm_initialization.hpp" #include "amsmitm_fs_utils.hpp" namespace ams::mitm::fs { using namespace ams::fs; namespace { /* Globals. */ FsFileSystem g_sd_filesystem; /* Helpers. */ Result EnsureSdInitialized() { R_UNLESS(serviceIsActive(std::addressof(g_sd_filesystem.s)), ams::fs::ResultSdCardNotPresent()); R_SUCCEED(); } void FormatAtmosphereRomfsPath(char *dst_path, size_t dst_path_size, ncm::ProgramId program_id, const char *src_path) { return FormatAtmosphereSdPath(dst_path, dst_path_size, program_id, "romfs", src_path); } } void OpenGlobalSdCardFileSystem() { R_ABORT_UNLESS(fsOpenSdCardFileSystem(std::addressof(g_sd_filesystem))); } Result CreateSdFile(const char *path, s64 size, s32 option) { R_TRY(EnsureSdInitialized()); R_RETURN(fsFsCreateFile(std::addressof(g_sd_filesystem), path, size, option)); } Result DeleteSdFile(const char *path) { R_TRY(EnsureSdInitialized()); R_RETURN(fsFsDeleteFile(std::addressof(g_sd_filesystem), path)); } bool HasSdFile(const char *path) { if (R_FAILED(EnsureSdInitialized())) { return false; } FsDirEntryType type; if (R_FAILED(fsFsGetEntryType(std::addressof(g_sd_filesystem), path, std::addressof(type)))) { return false; } return type == FsDirEntryType_File; } bool HasAtmosphereSdFile(const char *path) { char fixed_path[ams::fs::EntryNameLengthMax + 1]; FormatAtmosphereSdPath(fixed_path, sizeof(fixed_path), path); return HasSdFile(fixed_path); } Result DeleteAtmosphereSdFile(const char *path) { char fixed_path[ams::fs::EntryNameLengthMax + 1]; FormatAtmosphereSdPath(fixed_path, sizeof(fixed_path), path); R_RETURN(DeleteSdFile(fixed_path)); } Result CreateAtmosphereSdFile(const char *path, s64 size, s32 option) { char fixed_path[ams::fs::EntryNameLengthMax + 1]; FormatAtmosphereSdPath(fixed_path, sizeof(fixed_path), path); R_RETURN(CreateSdFile(fixed_path, size, option)); } Result OpenSdFile(FsFile *out, const char *path, u32 mode) { R_TRY(EnsureSdInitialized()); R_RETURN(fsFsOpenFile(std::addressof(g_sd_filesystem), path, mode, out)); } Result OpenAtmosphereSdFile(FsFile *out, const char *path, u32 mode) { char fixed_path[ams::fs::EntryNameLengthMax + 1]; FormatAtmosphereSdPath(fixed_path, sizeof(fixed_path), path); R_RETURN(OpenSdFile(out, fixed_path, mode)); } Result OpenAtmosphereSdFile(FsFile *out, ncm::ProgramId program_id, const char *path, u32 mode) { char fixed_path[ams::fs::EntryNameLengthMax + 1]; FormatAtmosphereSdPath(fixed_path, sizeof(fixed_path), program_id, path); R_RETURN(OpenSdFile(out, fixed_path, mode)); } Result OpenAtmosphereSdRomfsFile(FsFile *out, ncm::ProgramId program_id, const char *path, u32 mode) { char fixed_path[ams::fs::EntryNameLengthMax + 1]; FormatAtmosphereRomfsPath(fixed_path, sizeof(fixed_path), program_id, path); R_RETURN(OpenSdFile(out, fixed_path, mode)); } Result OpenAtmosphereRomfsFile(FsFile *out, ncm::ProgramId program_id, const char *path, u32 mode, FsFileSystem *fs) { char fixed_path[ams::fs::EntryNameLengthMax + 1]; FormatAtmosphereRomfsPath(fixed_path, sizeof(fixed_path), program_id, path); R_RETURN(fsFsOpenFile(fs, fixed_path, mode, out)); } Result CreateSdDirectory(const char *path) { R_TRY(EnsureSdInitialized()); R_RETURN(fsFsCreateDirectory(std::addressof(g_sd_filesystem), path)); } Result CreateAtmosphereSdDirectory(const char *path) { char fixed_path[ams::fs::EntryNameLengthMax + 1]; FormatAtmosphereSdPath(fixed_path, sizeof(fixed_path), path); R_RETURN(CreateSdDirectory(fixed_path)); } Result OpenSdDirectory(FsDir *out, const char *path, u32 mode) { R_TRY(EnsureSdInitialized()); R_RETURN(fsFsOpenDirectory(std::addressof(g_sd_filesystem), path, mode, out)); } Result OpenAtmosphereSdDirectory(FsDir *out, const char *path, u32 mode) { char fixed_path[ams::fs::EntryNameLengthMax + 1]; FormatAtmosphereSdPath(fixed_path, sizeof(fixed_path), path); R_RETURN(OpenSdDirectory(out, fixed_path, mode)); } Result OpenAtmosphereSdDirectory(FsDir *out, ncm::ProgramId program_id, const char *path, u32 mode) { char fixed_path[ams::fs::EntryNameLengthMax + 1]; FormatAtmosphereSdPath(fixed_path, sizeof(fixed_path), program_id, path); R_RETURN(OpenSdDirectory(out, fixed_path, mode)); } Result OpenAtmosphereSdRomfsDirectory(FsDir *out, ncm::ProgramId program_id, const char *path, u32 mode) { char fixed_path[ams::fs::EntryNameLengthMax + 1]; FormatAtmosphereRomfsPath(fixed_path, sizeof(fixed_path), program_id, path); R_RETURN(OpenSdDirectory(out, fixed_path, mode)); } Result OpenAtmosphereRomfsDirectory(FsDir *out, ncm::ProgramId program_id, const char *path, u32 mode, FsFileSystem *fs) { char fixed_path[ams::fs::EntryNameLengthMax + 1]; FormatAtmosphereRomfsPath(fixed_path, sizeof(fixed_path), program_id, path); R_RETURN(fsFsOpenDirectory(fs, fixed_path, mode, out)); } void FormatAtmosphereSdPath(char *dst_path, size_t dst_path_size, const char *src_path) { if (src_path[0] == '/') { util::SNPrintf(dst_path, dst_path_size, "/atmosphere%s", src_path); } else { util::SNPrintf(dst_path, dst_path_size, "/atmosphere/%s", src_path); } } void FormatAtmosphereSdPath(char *dst_path, size_t dst_path_size, const char *subdir, const char *src_path) { if (src_path[0] == '/') { util::SNPrintf(dst_path, dst_path_size, "/atmosphere/%s%s", subdir, src_path); } else { util::SNPrintf(dst_path, dst_path_size, "/atmosphere/%s/%s", subdir, src_path); } } void FormatAtmosphereSdPath(char *dst_path, size_t dst_path_size, ncm::ProgramId program_id, const char *src_path) { if (src_path[0] == '/') { util::SNPrintf(dst_path, dst_path_size, "/atmosphere/contents/%016lx%s", static_cast<u64>(program_id), src_path); } else { util::SNPrintf(dst_path, dst_path_size, "/atmosphere/contents/%016lx/%s", static_cast<u64>(program_id), src_path); } } void FormatAtmosphereSdPath(char *dst_path, size_t dst_path_size, ncm::ProgramId program_id, const char *subdir, const char *src_path) { if (src_path[0] == '/') { util::SNPrintf(dst_path, dst_path_size, "/atmosphere/contents/%016lx/%s%s", static_cast<u64>(program_id), subdir, src_path); } else { util::SNPrintf(dst_path, dst_path_size, "/atmosphere/contents/%016lx/%s/%s", static_cast<u64>(program_id), subdir, src_path); } } bool HasSdRomfsContent(ncm::ProgramId program_id) { /* Check if romfs.bin is present. */ { FsFile romfs_file; if (R_SUCCEEDED(OpenAtmosphereSdFile(std::addressof(romfs_file), program_id, "romfs.bin", OpenMode_Read))) { fsFileClose(std::addressof(romfs_file)); return true; } } /* Check for romfs folder with content. */ FsDir romfs_dir; if (R_FAILED(OpenAtmosphereSdRomfsDirectory(std::addressof(romfs_dir), program_id, "", fs::OpenDirectoryMode_All))) { return false; } ON_SCOPE_EXIT { fsDirClose(std::addressof(romfs_dir)); }; /* Verify the folder has at least one entry. */ s64 num_entries = 0; return R_SUCCEEDED(fsDirGetEntryCount(std::addressof(romfs_dir), std::addressof(num_entries))) && num_entries > 0; } Result SaveAtmosphereSdFile(FsFile *out, ncm::ProgramId program_id, const char *path, void *data, size_t size) { R_TRY(EnsureSdInitialized()); char fixed_path[ams::fs::EntryNameLengthMax + 1]; FormatAtmosphereSdPath(fixed_path, sizeof(fixed_path), program_id, path); /* Unconditionally create. */ /* Don't check error, as a failure here should be okay. */ FsFile f; fsFsCreateFile(std::addressof(g_sd_filesystem), fixed_path, size, 0); /* Try to open. */ R_TRY(fsFsOpenFile(std::addressof(g_sd_filesystem), fixed_path, OpenMode_ReadWrite, std::addressof(f))); auto file_guard = SCOPE_GUARD { fsFileClose(std::addressof(f)); }; /* Try to set the size. */ R_TRY(fsFileSetSize(std::addressof(f), static_cast<s64>(size))); /* Try to write data. */ R_TRY(fsFileWrite(std::addressof(f), 0, data, size, FsWriteOption_Flush)); /* Set output. */ file_guard.Cancel(); *out = f; R_SUCCEED(); } Result CreateAndOpenAtmosphereSdFile(FsFile *out, ncm::ProgramId program_id, const char *path, size_t size) { R_TRY(EnsureSdInitialized()); char fixed_path[ams::fs::EntryNameLengthMax + 1]; FormatAtmosphereSdPath(fixed_path, sizeof(fixed_path), program_id, path); /* Unconditionally create. */ /* Don't check error, as a failure here should be okay. */ FsFile f; fsFsCreateFile(std::addressof(g_sd_filesystem), fixed_path, size, 0); /* Try to open. */ R_TRY(fsFsOpenFile(std::addressof(g_sd_filesystem), fixed_path, OpenMode_ReadWrite, std::addressof(f))); auto file_guard = SCOPE_GUARD { fsFileClose(std::addressof(f)); }; /* Try to set the size. */ R_TRY(fsFileSetSize(std::addressof(f), static_cast<s64>(size))); /* Set output. */ file_guard.Cancel(); *out = f; R_SUCCEED(); } }
10,610
C++
.cpp
211
42.383886
140
0.655522
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,192
amsmitm_initialization.cpp
Atmosphere-NX_Atmosphere/stratosphere/ams_mitm/source/amsmitm_initialization.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have 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 "amsmitm_initialization.hpp" #include "amsmitm_fs_utils.hpp" #include "amsmitm_prodinfo_utils.hpp" #include "bpc_mitm/bpc_ams_power_utils.hpp" #include "set_mitm/settings_sd_kvs.hpp" namespace ams::mitm { namespace { /* BIS key sources. */ constexpr u8 BisKeySources[4][2][0x10] = { { {0xF8, 0x3F, 0x38, 0x6E, 0x2C, 0xD2, 0xCA, 0x32, 0xA8, 0x9A, 0xB9, 0xAA, 0x29, 0xBF, 0xC7, 0x48}, {0x7D, 0x92, 0xB0, 0x3A, 0xA8, 0xBF, 0xDE, 0xE1, 0xA7, 0x4C, 0x3B, 0x6E, 0x35, 0xCB, 0x71, 0x06} }, { {0x41, 0x00, 0x30, 0x49, 0xDD, 0xCC, 0xC0, 0x65, 0x64, 0x7A, 0x7E, 0xB4, 0x1E, 0xED, 0x9C, 0x5F}, {0x44, 0x42, 0x4E, 0xDA, 0xB4, 0x9D, 0xFC, 0xD9, 0x87, 0x77, 0x24, 0x9A, 0xDC, 0x9F, 0x7C, 0xA4} }, { {0x52, 0xC2, 0xE9, 0xEB, 0x09, 0xE3, 0xEE, 0x29, 0x32, 0xA1, 0x0C, 0x1F, 0xB6, 0xA0, 0x92, 0x6C}, {0x4D, 0x12, 0xE1, 0x4B, 0x2A, 0x47, 0x4C, 0x1C, 0x09, 0xCB, 0x03, 0x59, 0xF0, 0x15, 0xF4, 0xE4} }, { {0x52, 0xC2, 0xE9, 0xEB, 0x09, 0xE3, 0xEE, 0x29, 0x32, 0xA1, 0x0C, 0x1F, 0xB6, 0xA0, 0x92, 0x6C}, {0x4D, 0x12, 0xE1, 0x4B, 0x2A, 0x47, 0x4C, 0x1C, 0x09, 0xCB, 0x03, 0x59, 0xF0, 0x15, 0xF4, 0xE4} } }; constexpr u8 BisKekSource[0x10] = { 0x34, 0xC1, 0xA0, 0xC4, 0x82, 0x58, 0xF8, 0xB4, 0xFA, 0x9E, 0x5E, 0x6A, 0xDA, 0xFC, 0x7E, 0x4F, }; void InitializeThreadFunc(void *arg); constexpr size_t InitializeThreadStackSize = 0x4000; /* Globals. */ os::Event g_init_event(os::EventClearMode_ManualClear); os::ThreadType g_initialize_thread; alignas(os::ThreadStackAlignment) u8 g_initialize_thread_stack[InitializeThreadStackSize]; /* Console-unique data backup and protection. */ FsFile g_bis_key_file; /* Emummc file protection. */ FsFile g_emummc_file; /* Maintain exclusive access to the fusee external package. */ FsFile g_stratosphere_file; FsFile g_package3_file; constexpr inline bool IsHexadecimal(const char *str) { while (*str) { if (std::isxdigit(static_cast<unsigned char>(*str))) { str++; } else { return false; } } return true; } void GetBackupFileName(char *dst, size_t dst_size, const char *serial_number, const char *fn) { if (strlen(serial_number) > 0) { util::SNPrintf(dst, dst_size, "automatic_backups/%s_%s", serial_number, fn); } else { util::SNPrintf(dst, dst_size, "automatic_backups/%s", fn); } } void CreateAutomaticBackups() { /* Create a backup directory, if one doesn't exist. */ mitm::fs::CreateAtmosphereSdDirectory("/automatic_backups"); /* Initialize PRODINFO and get a reference for the device. */ char device_reference[0x40] = {}; ON_SCOPE_EXIT { std::memset(device_reference, 0, sizeof(device_reference)); }; mitm::SaveProdInfoBackupsAndWipeMemory(device_reference, sizeof(device_reference)); /* Backup BIS keys. */ { u64 key_generation = 0; if (hos::GetVersion() >= hos::Version_5_0_0) { R_ABORT_UNLESS(spl::GetConfig(std::addressof(key_generation), spl::ConfigItem::DeviceUniqueKeyGeneration)); } u8 bis_keys[4][2][0x10]; std::memset(bis_keys, 0xCC, sizeof(bis_keys)); ON_SCOPE_EXIT { std::memset(bis_keys, 0xCC, sizeof(bis_keys)); }; /* TODO: Clean this up. */ for (size_t partition = 0; partition < 4; partition++) { if (partition == 0) { for (size_t i = 0; i < 2; i++) { R_ABORT_UNLESS(spl::GenerateSpecificAesKey(bis_keys[partition][i], 0x10, BisKeySources[partition][i], 0x10, key_generation, i)); } } else { const u32 option = (partition == 3 && spl::IsRecoveryBoot()) ? 0x4 : 0x1; spl::AccessKey access_key; R_ABORT_UNLESS(spl::GenerateAesKek(std::addressof(access_key), BisKekSource, 0x10, key_generation, option)); for (size_t i = 0; i < 2; i++) { R_ABORT_UNLESS(spl::GenerateAesKey(bis_keys[partition][i], 0x10, access_key, BisKeySources[partition][i], 0x10)); } } } char bis_keys_backup_name[ams::fs::EntryNameLengthMax + 1]; GetBackupFileName(bis_keys_backup_name, sizeof(bis_keys_backup_name), device_reference, "BISKEYS.bin"); mitm::fs::CreateAtmosphereSdFile(bis_keys_backup_name, sizeof(bis_keys), ams::fs::CreateOption_None); R_ABORT_UNLESS(mitm::fs::OpenAtmosphereSdFile(std::addressof(g_bis_key_file), bis_keys_backup_name, ams::fs::OpenMode_ReadWrite)); R_ABORT_UNLESS(fsFileSetSize(std::addressof(g_bis_key_file), sizeof(bis_keys))); R_ABORT_UNLESS(fsFileWrite(std::addressof(g_bis_key_file), 0, bis_keys, sizeof(bis_keys), FsWriteOption_Flush)); /* NOTE: g_bis_key_file is intentionally not closed here. This prevents any other process from opening it. */ } /* Open a reference to the fusee external package. */ /* As upcoming/current atmosphere releases may contain more than one zip which users much choose between, */ /* maintaining an open reference prevents cleanly the issue of "automatic" updaters selecting the incorrect */ /* zip, and encourages good updating hygiene -- atmosphere should not be updated on SD while HOS is alive. */ { R_ABORT_UNLESS(mitm::fs::OpenSdFile(std::addressof(g_package3_file), "/atmosphere/package3", ams::fs::OpenMode_Read)); R_ABORT_UNLESS(mitm::fs::OpenSdFile(std::addressof(g_stratosphere_file), "/atmosphere/stratosphere.romfs", ams::fs::OpenMode_Read)); } } /* Initialization implementation */ void InitializeThreadFunc(void *) { /* Wait for the SD card to be ready. */ cfg::WaitSdCardInitialized(); /* Open global SD card file system, so that other threads can begin using the SD. */ mitm::fs::OpenGlobalSdCardFileSystem(); /* Mount the sd card at a convenient mountpoint. */ ams::fs::MountSdCard(ams::fs::impl::SdCardFileSystemMountName); /* Initialize the reboot manager (load a payload off the SD). */ /* Discard result, since it doesn't need to succeed. */ mitm::bpc::LoadRebootPayload(); /* Backup Calibration Binary and BIS keys. */ CreateAutomaticBackups(); /* If we're emummc, persist a write-handle to prevent other processes from touching the image. */ if (emummc::IsActive()) { if (const char *emummc_file_path = emummc::GetFilePath(); emummc_file_path != nullptr) { char emummc_path[ams::fs::EntryNameLengthMax + 1]; util::SNPrintf(emummc_path, sizeof(emummc_path), "%s/eMMC", emummc_file_path); mitm::fs::OpenSdFile(std::addressof(g_emummc_file), emummc_path, ams::fs::OpenMode_Read); } /* NOTE: due to an Atmosphere bug, NS accesses to the Nintendo dir accessed /Nintendo/Nintendo */ /* instead of /Nintendo. This logic is potentially temporary, and fixes the case where this would have happened. */ { auto HasDir = [](const char *p) -> bool { bool res{}; R_ABORT_UNLESS(ams::fs::HasDirectory(std::addressof(res), p)); return res; }; auto HasFile = [](const char *p) -> bool { bool res{}; R_ABORT_UNLESS(ams::fs::HasFile(std::addressof(res), p)); return res; }; char emummc_path[ams::fs::EntryNameLengthMax + 1]; char emummc_bug_path[ams::fs::EntryNameLengthMax + 1]; util::SNPrintf(emummc_path, sizeof(emummc_path), "%s:/%s", ams::fs::impl::SdCardFileSystemMountName, emummc::GetNintendoDirPath()); util::SNPrintf(emummc_bug_path, sizeof(emummc_bug_path), "%s:/%s/Nintendo", ams::fs::impl::SdCardFileSystemMountName, emummc::GetNintendoDirPath()); if (HasDir(emummc_bug_path)) { /* Ensure Contents directory exists for normal emummc. */ /* NOTE: Allowed to fail on already-exists. */ util::SNPrintf(emummc_path, sizeof(emummc_path), "%s:/%s/Contents", ams::fs::impl::SdCardFileSystemMountName, emummc::GetNintendoDirPath()); ams::fs::CreateDirectory(emummc_path); /* Fix Contents/private */ util::SNPrintf(emummc_path, sizeof(emummc_path), "%s:/%s/Contents/private", ams::fs::impl::SdCardFileSystemMountName, emummc::GetNintendoDirPath()); util::SNPrintf(emummc_bug_path, sizeof(emummc_bug_path), "%s:/%s/Nintendo/Contents/private", ams::fs::impl::SdCardFileSystemMountName, emummc::GetNintendoDirPath()); if (HasFile(emummc_bug_path) && !HasFile(emummc_path)) { R_ABORT_UNLESS(ams::fs::RenameFile(emummc_bug_path, emummc_path)); } /* Fix Contents/private1 */ util::SNPrintf(emummc_path, sizeof(emummc_path), "%s:/%s/Contents/private1", ams::fs::impl::SdCardFileSystemMountName, emummc::GetNintendoDirPath()); util::SNPrintf(emummc_bug_path, sizeof(emummc_bug_path), "%s:/%s/Nintendo/Contents/private1", ams::fs::impl::SdCardFileSystemMountName, emummc::GetNintendoDirPath()); if (HasFile(emummc_bug_path) && !HasFile(emummc_path)) { R_ABORT_UNLESS(ams::fs::RenameFile(emummc_bug_path, emummc_path)); } /* Delete bug directory. */ util::SNPrintf(emummc_bug_path, sizeof(emummc_bug_path), "%s:/%s/Nintendo", ams::fs::impl::SdCardFileSystemMountName, emummc::GetNintendoDirPath()); R_ABORT_UNLESS(ams::fs::DeleteDirectoryRecursively(emummc_bug_path)); } } } /* Connect to set:sys. */ R_ABORT_UNLESS(setInitialize()); R_ABORT_UNLESS(setsysInitialize()); /* Load settings off the SD card. */ settings::fwdbg::InitializeSdCardKeyValueStore(); /* Ensure that we reboot using the user's preferred method. */ R_ABORT_UNLESS(mitm::bpc::DetectPreferredRebootFunctionality()); /* Signal to waiters that we are ready. */ g_init_event.Signal(); } } void StartInitialize() { /* Initialize prodinfo. */ mitm::InitializeProdInfoManagement(); /* Launch initialize thread. */ R_ABORT_UNLESS(os::CreateThread(std::addressof(g_initialize_thread), InitializeThreadFunc, nullptr, g_initialize_thread_stack, sizeof(g_initialize_thread_stack), AMS_GET_SYSTEM_THREAD_PRIORITY(mitm, InitializeThread))); os::SetThreadNamePointer(std::addressof(g_initialize_thread), AMS_GET_SYSTEM_THREAD_NAME(mitm, InitializeThread)); os::StartThread(std::addressof(g_initialize_thread)); } bool IsInitialized() { return g_init_event.TryWait(); } void WaitInitialized() { g_init_event.Wait(); } }
12,642
C++
.cpp
201
48.830846
227
0.587804
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,193
amsmitm_module_management.cpp
Atmosphere-NX_Atmosphere/stratosphere/ams_mitm/source/amsmitm_module_management.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have 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 "amsmitm_module_management.hpp" #include "amsmitm_module.hpp" #include "fs_mitm/fsmitm_module.hpp" #include "set_mitm/setmitm_module.hpp" #include "bpc_mitm/bpcmitm_module.hpp" #include "bpc_mitm/bpc_ams_module.hpp" #include "ns_mitm/nsmitm_module.hpp" #include "dns_mitm/dnsmitm_module.hpp" #include "sysupdater/sysupdater_module.hpp" #include "mitm_pm/mitm_pm_module.hpp" namespace ams::mitm { namespace { enum ModuleId : u32 { ModuleId_FsMitm, ModuleId_SetMitm, ModuleId_BpcMitm, ModuleId_BpcAms, ModuleId_NsMitm, ModuleId_DnsMitm, ModuleId_Sysupdater, ModuleId_PmService, ModuleId_Count, }; struct ModuleDefinition { ThreadFunc main; void *stack_mem; s32 priority; u32 stack_size; }; template<class M> constexpr ModuleDefinition GetModuleDefinition() { using Traits = ModuleTraits<M>; return ModuleDefinition { .main = Traits::ThreadFunction, .stack_mem = Traits::Stack, .priority = Traits::ThreadPriority, .stack_size = static_cast<u32>(Traits::StackSize), }; } ams::os::ThreadType g_module_threads[ModuleId_Count]; constexpr ModuleDefinition g_module_definitions[ModuleId_Count] = { GetModuleDefinition<fs::MitmModule>(), GetModuleDefinition<settings::MitmModule>(), GetModuleDefinition<bpc::MitmModule>(), GetModuleDefinition<bpc_ams::MitmModule>(), GetModuleDefinition<ns::MitmModule>(), GetModuleDefinition<socket::resolver::MitmModule>(), GetModuleDefinition<sysupdater::MitmModule>(), GetModuleDefinition<pm::MitmModule>(), }; } void LaunchAllModules() { /* Create thread for each module. */ for (u32 i = 0; i < static_cast<u32>(ModuleId_Count); i++) { const ModuleDefinition &cur_module = g_module_definitions[i]; R_ABORT_UNLESS(os::CreateThread(g_module_threads + i, cur_module.main, nullptr, cur_module.stack_mem, cur_module.stack_size, cur_module.priority)); } /* Start thread for each module. */ for (u32 i = 0; i < static_cast<u32>(ModuleId_Count); i++) { os::StartThread(g_module_threads + i); } } void WaitAllModules() { /* Wait on thread for each module. */ for (u32 i = 0; i < static_cast<u32>(ModuleId_Count); i++) { os::WaitThread(g_module_threads + i); } } }
3,346
C++
.cpp
85
31.247059
159
0.634011
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,194
bpcmitm_module.cpp
Atmosphere-NX_Atmosphere/stratosphere/ams_mitm/source/bpc_mitm/bpcmitm_module.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "../amsmitm_initialization.hpp" #include "bpcmitm_module.hpp" #include "bpc_mitm_service.hpp" namespace ams::mitm::bpc { namespace { enum PortIndex { PortIndex_Mitm, PortIndex_Count, }; constexpr sm::ServiceName MitmServiceName = sm::ServiceName::Encode("bpc"); constexpr sm::ServiceName DeprecatedMitmServiceName = sm::ServiceName::Encode("bpc:c"); constexpr size_t MitmServiceMaxSessions = 13; constexpr size_t MaxSessions = MitmServiceMaxSessions; struct ServerOptions { static constexpr size_t PointerBufferSize = sf::hipc::DefaultServerManagerOptions::PointerBufferSize; static constexpr size_t MaxDomains = sf::hipc::DefaultServerManagerOptions::MaxDomains; static constexpr size_t MaxDomainObjects = sf::hipc::DefaultServerManagerOptions::MaxDomainObjects; static constexpr bool CanDeferInvokeRequest = sf::hipc::DefaultServerManagerOptions::CanDeferInvokeRequest; static constexpr bool CanManageMitmServers = true; }; class ServerManager final : public sf::hipc::ServerManager<PortIndex_Count, ServerOptions, MaxSessions> { private: virtual Result OnNeedsToAccept(int port_index, Server *server) override; }; ServerManager g_server_manager; Result ServerManager::OnNeedsToAccept(int port_index, Server *server) { /* Acknowledge the mitm session. */ std::shared_ptr<::Service> fsrv; sm::MitmProcessInfo client_info; server->AcknowledgeMitmSession(std::addressof(fsrv), std::addressof(client_info)); switch (port_index) { case PortIndex_Mitm: R_RETURN(this->AcceptMitmImpl(server, sf::CreateSharedObjectEmplaced<impl::IBpcMitmInterface, BpcMitmService>(decltype(fsrv)(fsrv), client_info), fsrv)); AMS_UNREACHABLE_DEFAULT_CASE(); } } } void MitmModule::ThreadFunction(void *) { /* Wait until initialization is complete. */ mitm::WaitInitialized(); /* Create bpc mitm. */ const sm::ServiceName service_name = (hos::GetVersion() >= hos::Version_2_0_0) ? MitmServiceName : DeprecatedMitmServiceName; R_ABORT_UNLESS((g_server_manager.RegisterMitmServer<BpcMitmService>(PortIndex_Mitm, service_name))); /* Loop forever, servicing our services. */ g_server_manager.LoopProcess(); } }
3,207
C++
.cpp
63
42.888889
173
0.684783
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,195
bpc_mitm_service.cpp
Atmosphere-NX_Atmosphere/stratosphere/ams_mitm/source/bpc_mitm/bpc_mitm_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 "bpc_mitm_service.hpp" #include "bpc_ams_power_utils.hpp" namespace ams::mitm::bpc { Result BpcMitmService::RebootSystem() { R_UNLESS(bpc::IsRebootManaged(), sm::mitm::ResultShouldForwardToSession()); bpc::RebootSystem(); R_SUCCEED(); } Result BpcMitmService::ShutdownSystem() { bpc::ShutdownSystem(); R_SUCCEED(); } }
1,051
C++
.cpp
29
32.689655
83
0.720039
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,196
bpc_ams_power_utils.cpp
Atmosphere-NX_Atmosphere/stratosphere/ams_mitm/source/bpc_mitm/bpc_ams_power_utils.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "bpc_ams_power_utils.hpp" #include "../amsmitm_fs_utils.hpp" namespace ams::mitm::bpc { namespace { /* Convenience definitions. */ constexpr uintptr_t IramBase = 0x40000000ull; constexpr uintptr_t IramPayloadBase = 0x40010000ull; constexpr size_t IramSize = 0x40000; constexpr size_t IramPayloadMaxSize = 0x24000; constexpr size_t IramFatalErrorContextOffset = 0x2E000; /* Helper enum. */ enum class RebootType : u32 { Standard, ToRcm, ToPayload, ByPmic, }; /* Globals. */ alignas(os::MemoryPageSize) u8 g_work_page[os::MemoryPageSize]; alignas(os::MemoryPageSize) u8 g_reboot_payload[IramPayloadMaxSize]; RebootType g_reboot_type = RebootType::ToRcm; /* Helpers. */ void ClearIram() { /* Make page CCs. */ std::memset(g_work_page, 0xCC, sizeof(g_work_page)); /* Overwrite all of IRAM with CCs. */ for (size_t ofs = 0; ofs < IramSize; ofs += sizeof(g_work_page)) { exosphere::CopyToIram(IramBase + ofs, g_work_page, sizeof(g_work_page)); } } void DoRebootToPayload() { /* Ensure clean IRAM state. */ ClearIram(); /* Copy in payload. */ for (size_t ofs = 0; ofs < sizeof(g_reboot_payload); ofs += sizeof(g_work_page)) { std::memcpy(g_work_page, g_reboot_payload + ofs, std::min(sizeof(g_reboot_payload) - ofs, sizeof(g_work_page))); exosphere::CopyToIram(IramPayloadBase + ofs, g_work_page, sizeof(g_work_page)); } exosphere::ForceRebootToIramPayload(); } void DoRebootToFatalError(const ams::FatalErrorContext *ctx) { /* Ensure clean IRAM state. */ ClearIram(); /* Copy in payload. */ for (size_t ofs = 0; ofs < sizeof(g_reboot_payload); ofs += sizeof(g_work_page)) { std::memcpy(g_work_page, g_reboot_payload + ofs, std::min(sizeof(g_reboot_payload) - ofs, sizeof(g_work_page))); exosphere::CopyToIram(IramPayloadBase + ofs, g_work_page, sizeof(g_work_page)); } /* Copy in fatal error context, if relevant. */ if (ctx != nullptr) { std::memset(g_work_page, 0xCC, sizeof(g_work_page)); std::memcpy(g_work_page, ctx, sizeof(*ctx)); exosphere::CopyToIram(IramPayloadBase + IramFatalErrorContextOffset, g_work_page, sizeof(g_work_page)); } exosphere::ForceRebootToFatalError(); } } /* Power utilities. */ bool IsRebootManaged() { return g_reboot_type != RebootType::Standard; } void RebootSystem() { switch (g_reboot_type) { case RebootType::ByPmic: exosphere::ForceRebootByPmic(); break; case RebootType::ToRcm: exosphere::ForceRebootToRcm(); break; case RebootType::ToPayload: default: /* This should never be called with ::Standard */ DoRebootToPayload(); break; } } void ShutdownSystem() { exosphere::ForceShutdown(); } /* Atmosphere power utilities. */ void RebootForFatalError(const ams::FatalErrorContext *ctx) { DoRebootToFatalError(ctx); } void SetRebootPayload(const void *payload, size_t payload_size) { /* Mariko does not support reboot-to-payload. */ if (spl::GetSocType() == spl::SocType_Mariko) { return; } /* Clear payload buffer */ std::memset(g_reboot_payload, 0xCC, sizeof(g_reboot_payload)); /* Ensure valid. */ AMS_ABORT_UNLESS(payload != nullptr && payload_size <= sizeof(g_reboot_payload)); /* Copy in payload. */ std::memcpy(g_reboot_payload, payload, payload_size); /* Note to the secure monitor that we have a payload. */ spl::smc::AsyncOperationKey dummy; spl::smc::SetConfig(std::addressof(dummy), spl::ConfigItem::ExospherePayloadAddress, nullptr, 0, g_reboot_payload); /* NOTE: Preferred reboot type may be overrwritten when parsed from settings during boot. */ g_reboot_type = RebootType::ToPayload; } Result LoadRebootPayload() { /* Mariko does not support reboot-to-payload. */ R_SUCCEED_IF(spl::GetSocType() == spl::SocType_Mariko) /* Clear payload buffer */ std::memset(g_reboot_payload, 0xCC, sizeof(g_reboot_payload)); /* Open payload file. */ FsFile payload_file; R_TRY(fs::OpenAtmosphereSdFile(std::addressof(payload_file), "/reboot_payload.bin", ams::fs::OpenMode_Read)); ON_SCOPE_EXIT { fsFileClose(std::addressof(payload_file)); }; /* Read payload file. Discard result. */ { size_t actual_size; fsFileRead(std::addressof(payload_file), 0, g_reboot_payload, sizeof(g_reboot_payload), FsReadOption_None, std::addressof(actual_size)); } /* NOTE: Preferred reboot type will be parsed from settings later on. */ g_reboot_type = RebootType::ToPayload; R_SUCCEED(); } Result DetectPreferredRebootFunctionality() { char reboot_type[0x40] = {}; settings::fwdbg::GetSettingsItemValue(reboot_type, sizeof(reboot_type) - 1, "atmosphere", "power_menu_reboot_function"); if (strcasecmp(reboot_type, "stock") == 0 || strcasecmp(reboot_type, "normal") == 0 || strcasecmp(reboot_type, "standard") == 0) { g_reboot_type = RebootType::Standard; } else if (strcasecmp(reboot_type, "rcm") == 0) { g_reboot_type = RebootType::ToRcm; } else if (strcasecmp(reboot_type, "payload") == 0) { g_reboot_type = RebootType::ToPayload; } /* TODO: Should we actually allow control over this on mariko? */ if (spl::GetSocType() == spl::SocType_Mariko) { g_reboot_type = RebootType::ByPmic; } R_SUCCEED(); } }
6,842
C++
.cpp
150
36.146667
148
0.608774
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,197
bpc_ams_module.cpp
Atmosphere-NX_Atmosphere/stratosphere/ams_mitm/source/bpc_mitm/bpc_ams_module.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "../amsmitm_initialization.hpp" #include "bpc_ams_module.hpp" #include "bpc_ams_service.hpp" namespace ams::mitm::bpc_ams { namespace { constexpr sm::ServiceName AtmosphereServiceName = sm::ServiceName::Encode("bpc:ams"); constexpr size_t AtmosphereMaxSessions = 4; constexpr size_t MaxServers = 1; constexpr size_t MaxSessions = AtmosphereMaxSessions; using ServerOptions = sf::hipc::DefaultServerManagerOptions; sf::hipc::ServerManager<MaxServers, ServerOptions, MaxSessions> g_server_manager; constinit sf::UnmanagedServiceObject<bpc::impl::IAtmosphereInterface, bpc::AtmosphereService> g_ams_service_object; } void MitmModule::ThreadFunction(void *) { /* Create bpc:ams. */ { os::NativeHandle bpcams_h; R_ABORT_UNLESS(svc::ManageNamedPort(&bpcams_h, AtmosphereServiceName.name, AtmosphereMaxSessions)); g_server_manager.RegisterObjectForServer(g_ams_service_object.GetShared(), bpcams_h); } /* Loop forever, servicing our services. */ g_server_manager.LoopProcess(); } }
1,813
C++
.cpp
40
40.05
123
0.71542
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,198
bpc_ams_service.cpp
Atmosphere-NX_Atmosphere/stratosphere/ams_mitm/source/bpc_mitm/bpc_ams_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 "../amsmitm_initialization.hpp" #include "bpc_ams_service.hpp" #include "bpc_ams_power_utils.hpp" namespace ams::mitm::bpc { namespace { bool g_set_initial_payload = false; } void AtmosphereService::RebootToFatalError(const ams::FatalErrorContext &ctx) { bpc::RebootForFatalError(std::addressof(ctx)); } void AtmosphereService::SetRebootPayload(const ams::sf::InBuffer &payload) { /* Set the reboot payload. */ bpc::SetRebootPayload(payload.GetPointer(), payload.GetSize()); /* If this is being called for the first time (by boot sysmodule), */ /* Then we should kick off the rest of init. */ if (!g_set_initial_payload) { g_set_initial_payload = true; /* Start the initialization process. */ ::ams::mitm::StartInitialize(); } } }
1,536
C++
.cpp
38
35.552632
83
0.695097
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,199
settings_sd_kvs.cpp
Atmosphere-NX_Atmosphere/stratosphere/ams_mitm/source/set_mitm/settings_sd_kvs.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have 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 "../amsmitm_fs_utils.hpp" #include "settings_sd_kvs.hpp" namespace ams::settings::fwdbg { namespace { struct SdKeyValueStoreEntry { const char *name; const char *key; void *value; size_t value_size; constexpr inline bool HasValue() const { return this->value != nullptr; } constexpr inline void GetNameAndKey(char *dst) const { size_t offset = 0; for (size_t i = 0; i < std::strlen(this->name); i++) { dst[offset++] = this->name[i]; } dst[offset++] = '!'; for (size_t i = 0; i < std::strlen(this->key); i++) { dst[offset++] = this->key[i]; } dst[offset] = 0; } }; static_assert(util::is_pod<SdKeyValueStoreEntry>::value); constexpr inline bool operator==(const SdKeyValueStoreEntry &lhs, const SdKeyValueStoreEntry &rhs) { if (lhs.HasValue() != rhs.HasValue()) { return false; } return lhs.HasValue() && std::strcmp(lhs.name, rhs.name) == 0 && std::strcmp(lhs.key, rhs.key) == 0; } inline bool operator<(const SdKeyValueStoreEntry &lhs, const SdKeyValueStoreEntry &rhs) { AMS_ABORT_UNLESS(lhs.HasValue()); AMS_ABORT_UNLESS(rhs.HasValue()); char lhs_name_key[SettingsNameLengthMax + 1 + SettingsItemKeyLengthMax + 1]; char rhs_name_key[SettingsNameLengthMax + 1 + SettingsItemKeyLengthMax + 1]; lhs.GetNameAndKey(lhs_name_key); rhs.GetNameAndKey(rhs_name_key); return std::strcmp(lhs_name_key, rhs_name_key) < 0; } constexpr size_t MaxEntries = 0x200; constexpr size_t SettingsItemValueStorageSize = 0x10000; SettingsName g_names[MaxEntries]; SettingsItemKey g_item_keys[MaxEntries]; u8 g_value_storage[SettingsItemValueStorageSize]; size_t g_allocated_value_storage_size; SdKeyValueStoreEntry g_entries[MaxEntries]; size_t g_num_entries; constexpr bool IsValidSettingsFormat(const char *str, size_t len) { AMS_ABORT_UNLESS(str != nullptr); if (len > 0 && str[len - 1] == '.') { return false; } for (size_t i = 0; i < len; i++) { const char c = str[i]; if ('a' <= c && c <= 'z') { continue; } if ('0' <= c && c <= '9') { continue; } if (c == '-' || c == '.' || c == '_') { continue; } return false; } return true; } constexpr bool IsHexadecimal(const char *str) { while (*str) { if (std::isxdigit(static_cast<unsigned char>(*str))) { str++; } else { return false; } } return true; } constexpr inline char hextoi(char c) { if ('a' <= c && c <= 'f') return c - 'a' + 0xA; if ('A' <= c && c <= 'F') return c - 'A' + 0xA; if ('0' <= c && c <= '9') return c - '0'; return 0; } Result ValidateSettingsName(const char *name) { R_UNLESS(name != nullptr, settings::ResultNullSettingsName()); const size_t len = strnlen(name, SettingsNameLengthMax + 1); R_UNLESS(len > 0, settings::ResultEmptySettingsName()); R_UNLESS(len <= SettingsNameLengthMax, settings::ResultTooLongSettingsName()); R_UNLESS(IsValidSettingsFormat(name, len), settings::ResultInvalidFormatSettingsName()); R_SUCCEED(); } Result ValidateSettingsItemKey(const char *key) { R_UNLESS(key != nullptr, settings::ResultNullSettingsName()); const size_t len = strnlen(key, SettingsItemKeyLengthMax + 1); R_UNLESS(len > 0, settings::ResultEmptySettingsItemKey()); R_UNLESS(len <= SettingsNameLengthMax, settings::ResultTooLongSettingsItemKey()); R_UNLESS(IsValidSettingsFormat(key, len), settings::ResultInvalidFormatSettingsItemKey()); R_SUCCEED(); } Result AllocateValue(void **out, size_t size) { R_UNLESS(g_allocated_value_storage_size + size <= sizeof(g_value_storage), settings::ResultSettingsItemValueAllocationFailed()); *out = g_value_storage + g_allocated_value_storage_size; g_allocated_value_storage_size += size; R_SUCCEED(); } Result FindSettingsName(const char **out, const char *name) { for (auto &stored : g_names) { if (std::strcmp(stored.value, name) == 0) { *out = stored.value; R_SUCCEED(); } else if (std::strcmp(stored.value, "") == 0) { *out = stored.value; std::strcpy(stored.value, name); R_SUCCEED(); } } R_THROW(settings::ResultSettingsItemKeyAllocationFailed()); } Result FindSettingsItemKey(const char **out, const char *key) { for (auto &stored : g_item_keys) { if (std::strcmp(stored.value, key) == 0) { *out = stored.value; R_SUCCEED(); } else if (std::strcmp(stored.value, "") == 0) { std::strcpy(stored.value, key); *out = stored.value; R_SUCCEED(); } } R_THROW(settings::ResultSettingsItemKeyAllocationFailed()); } template<typename T> Result ParseSettingsItemIntegralValue(SdKeyValueStoreEntry &out, const char *value_str) { R_TRY(AllocateValue(std::addressof(out.value), sizeof(T))); out.value_size = sizeof(T); T value = static_cast<T>(strtoul(value_str, nullptr, 0)); std::memcpy(out.value, std::addressof(value), sizeof(T)); R_SUCCEED(); } Result GetEntry(SdKeyValueStoreEntry **out, const char *name, const char *key) { /* Validate name/key. */ R_TRY(ValidateSettingsName(name)); R_TRY(ValidateSettingsItemKey(key)); u8 dummy_value = 0; SdKeyValueStoreEntry test_entry { .name = name, .key = key, .value = std::addressof(dummy_value), .value_size = sizeof(dummy_value) }; auto *begin = g_entries; auto *end = begin + g_num_entries; auto it = std::lower_bound(begin, end, test_entry); R_UNLESS(it != end, settings::ResultSettingsItemNotFound()); R_UNLESS(*it == test_entry, settings::ResultSettingsItemNotFound()); *out = std::addressof(*it); R_SUCCEED(); } Result ParseSettingsItemValueImpl(const char *name, const char *key, const char *val_tup) { const char *delimiter = strchr(val_tup, '!'); const char *value_str = delimiter + 1; const char *type = val_tup; R_UNLESS(delimiter != nullptr, settings::ResultInvalidFormatSettingsItemValue()); while (std::isspace(static_cast<unsigned char>(*type)) && type != delimiter) { type++; } const size_t type_len = delimiter - type; const size_t value_len = strlen(value_str); R_UNLESS(type_len > 0, settings::ResultInvalidFormatSettingsItemValue()); R_UNLESS(value_len > 0, settings::ResultInvalidFormatSettingsItemValue()); /* Create new value. */ SdKeyValueStoreEntry new_value = {}; /* Find name and key. */ R_TRY(FindSettingsName(std::addressof(new_value.name), name)); R_TRY(FindSettingsItemKey(std::addressof(new_value.key), key)); if (strncasecmp(type, "str", type_len) == 0 || strncasecmp(type, "string", type_len) == 0) { const size_t size = value_len + 1; R_TRY(AllocateValue(std::addressof(new_value.value), size)); std::memcpy(new_value.value, value_str, size); new_value.value_size = size; } else if (strncasecmp(type, "hex", type_len) == 0 || strncasecmp(type, "bytes", type_len) == 0) { R_UNLESS(value_len > 0, settings::ResultInvalidFormatSettingsItemValue()); R_UNLESS(value_len % 2 == 0, settings::ResultInvalidFormatSettingsItemValue()); R_UNLESS(IsHexadecimal(value_str), settings::ResultInvalidFormatSettingsItemValue()); const size_t size = value_len / 2; R_TRY(AllocateValue(std::addressof(new_value.value), size)); new_value.value_size = size; u8 *data = reinterpret_cast<u8 *>(new_value.value); for (size_t i = 0; i < size; i++) { data[i >> 1] = hextoi(value_str[i]) << (4 * (i & 1)); } } else if (strncasecmp(type, "u8", type_len) == 0) { R_TRY((ParseSettingsItemIntegralValue<u8>(new_value, value_str))); } else if (strncasecmp(type, "u16", type_len) == 0) { R_TRY((ParseSettingsItemIntegralValue<u16>(new_value, value_str))); } else if (strncasecmp(type, "u32", type_len) == 0) { R_TRY((ParseSettingsItemIntegralValue<u32>(new_value, value_str))); } else if (strncasecmp(type, "u64", type_len) == 0) { R_TRY((ParseSettingsItemIntegralValue<u64>(new_value, value_str))); } else { R_THROW(settings::ResultInvalidFormatSettingsItemValue()); } /* Insert the entry. */ bool inserted = false; for (auto &entry : g_entries) { if (!entry.HasValue() || entry == new_value) { entry = new_value; inserted = true; break; } } R_UNLESS(inserted, settings::ResultSettingsItemValueAllocationFailed()); R_SUCCEED(); } Result ParseSettingsItemValue(const char *name, const char *key, const char *value) { R_TRY(ValidateSettingsName(name)); R_TRY(ValidateSettingsItemKey(key)); R_RETURN(ParseSettingsItemValueImpl(name, key, value)); } static int SystemSettingsIniHandler(void *user, const char *name, const char *key, const char *value) { Result *parse_res = reinterpret_cast<Result *>(user); /* Once we fail to parse a value, don't parse further. */ if (R_FAILED(*parse_res)) { return 0; } *parse_res = ParseSettingsItemValue(name, key, value); return R_SUCCEEDED(*parse_res) ? 1 : 0; } Result LoadSdCardKeyValueStore() { /* Open file. */ /* It's okay if the file isn't readable/present, because we already loaded defaults. */ std::unique_ptr<ams::fs::fsa::IFile> file; { FsFile f; R_SUCCEED_IF(R_FAILED(ams::mitm::fs::OpenAtmosphereSdFile(std::addressof(f), "/config/system_settings.ini", fs::OpenMode_Read))); file = std::make_unique<ams::fs::RemoteFile>(f); } AMS_ABORT_UNLESS(file != nullptr); Result parse_result = ResultSuccess(); util::ini::ParseFile(file.get(), std::addressof(parse_result), SystemSettingsIniHandler); R_TRY(parse_result); R_SUCCEED(); } void LoadDefaultCustomSettings() { /* Disable uploading error reports to Nintendo. */ R_ABORT_UNLESS(ParseSettingsItemValue("eupld", "upload_enabled", "u8!0x0")); /* Enable USB 3.0 superspeed for homebrew */ R_ABORT_UNLESS(ParseSettingsItemValue("usb", "usb30_force_enabled", spl::IsUsb30ForceEnabled() ? "u8!0x1" : "u8!0x0")); /* Control whether RO should ease its validation of NROs. */ /* (note: this is normally not necessary, and ips patches can be used.) */ R_ABORT_UNLESS(ParseSettingsItemValue("ro", "ease_nro_restriction", "u8!0x1")); /* Control whether lm should log to the SD card. */ /* Note that this setting does nothing when log manager is not enabled. */ R_ABORT_UNLESS(ParseSettingsItemValue("lm", "enable_sd_card_logging", "u8!0x1")); /* Control the output directory for SD card logs. */ /* Note that this setting does nothing when log manager is not enabled/sd card logging is not enabled. */ R_ABORT_UNLESS(ParseSettingsItemValue("lm", "sd_card_log_output_directory", "str!atmosphere/binlogs")); /* Control whether erpt reports should always be preserved, instead of automatically cleaning periodically. */ /* 0 = Disabled, 1 = Enabled */ R_ABORT_UNLESS(ParseSettingsItemValue("erpt", "disable_automatic_report_cleanup", "u8!0x0")); /* Atmosphere custom settings. */ /* Reboot from fatal automatically after some number of milliseconds. */ /* If field is not present or 0, fatal will wait indefinitely for user input. */ R_ABORT_UNLESS(ParseSettingsItemValue("atmosphere", "fatal_auto_reboot_interval", "u64!0x0")); /* Make the power menu's "reboot" button reboot to payload. */ /* Set to "normal" for normal reboot, "rcm" for rcm reboot. */ R_ABORT_UNLESS(ParseSettingsItemValue("atmosphere", "power_menu_reboot_function", "str!payload")); /* Enable writing to BIS partitions for HBL. */ /* This is probably undesirable for normal usage. */ R_ABORT_UNLESS(ParseSettingsItemValue("atmosphere", "enable_hbl_bis_write", "u8!0x0")); /* Controls whether dmnt cheats should be toggled on or off by */ /* default. 1 = toggled on by default, 0 = toggled off by default. */ R_ABORT_UNLESS(ParseSettingsItemValue("atmosphere", "dmnt_cheats_enabled_by_default", "u8!0x1")); /* Controls whether dmnt should always save cheat toggle state */ /* for restoration on new game launch. 1 = always save toggles, */ /* 0 = only save toggles if toggle file exists. */ R_ABORT_UNLESS(ParseSettingsItemValue("atmosphere", "dmnt_always_save_cheat_toggles", "u8!0x0")); /* Controls whether fs.mitm should redirect save files */ /* to directories on the sd card. */ /* 0 = Do not redirect, 1 = Redirect. */ /* NOTE: EXPERIMENTAL */ /* If you do not know what you are doing, do not touch this yet. */ R_ABORT_UNLESS(ParseSettingsItemValue("atmosphere", "fsmitm_redirect_saves_to_sd", "u8!0x0")); /* Controls whether am sees system settings "DebugModeFlag" as */ /* enabled or disabled. */ /* 0 = Disabled (not debug mode), 1 = Enabled (debug mode) */ R_ABORT_UNLESS(ParseSettingsItemValue("atmosphere", "enable_am_debug_mode", "u8!0x0")); /* Controls whether dns.mitm is enabled. */ /* 0 = Disabled, 1 = Enabled */ R_ABORT_UNLESS(ParseSettingsItemValue("atmosphere", "enable_dns_mitm", "u8!0x1")); /* Controls whether dns.mitm uses the default redirections in addition to */ /* whatever is specified in the user's hosts file. */ /* 0 = Disabled (use hosts file contents), 1 = Enabled (use defaults and hosts file contents) */ R_ABORT_UNLESS(ParseSettingsItemValue("atmosphere", "add_defaults_to_dns_hosts", "u8!0x1")); /* Controls whether dns.mitm logs to the sd card for debugging. */ /* 0 = Disabled, 1 = Enabled */ R_ABORT_UNLESS(ParseSettingsItemValue("atmosphere", "enable_dns_mitm_debug_log", "u8!0x0")); /* Controls whether htc is enabled. */ /* TODO: Change this to default 1 when tma2 is ready for inclusion in atmosphere releases. */ /* 0 = Disabled, 1 = Enabled */ R_ABORT_UNLESS(ParseSettingsItemValue("atmosphere", "enable_htc", "u8!0x0")); /* Controls whether atmosphere's dmnt.gen2 gdbstub should run as a standalone via sockets. */ /* Note that this setting is ignored (and treated as 0) when htc is enabled. */ /* Note that this setting may disappear in the future. */ /* 0 = Disabled, 1 = Enabled */ R_ABORT_UNLESS(ParseSettingsItemValue("atmosphere", "enable_standalone_gdbstub", "u8!0x0")); /* Controls whether atmosphere's log manager is enabled. */ /* Note that this setting is ignored (and treated as 1) when htc is enabled. */ /* 0 = Disabled, 1 = Enabled */ R_ABORT_UNLESS(ParseSettingsItemValue("atmosphere", "enable_log_manager", "u8!0x0")); /* Controls whether the bluetooth pairing database is redirected to the SD card (shared across sysmmc/all emummcs) */ /* NOTE: On <13.0.0, the database size was 10 instead of 20; booting pre-13.0.0 will truncate the database. */ /* 0 = Disabled, 1 = Enabled */ R_ABORT_UNLESS(ParseSettingsItemValue("atmosphere", "enable_external_bluetooth_db", "u8!0x0")); /* Hbloader custom settings. */ /* Controls the size of the homebrew heap when running as applet. */ /* If set to zero, all available applet memory is used as heap. */ /* The default is zero. */ R_ABORT_UNLESS(ParseSettingsItemValue("hbloader", "applet_heap_size", "u64!0x0")); /* Controls the amount of memory to reserve when running as applet */ /* for usage by other applets. This setting has no effect if */ /* applet_heap_size is non-zero. The default is 0x8600000. */ R_ABORT_UNLESS(ParseSettingsItemValue("hbloader", "applet_heap_reservation_size", "u64!0x8600000")); } } void InitializeSdCardKeyValueStore() { /* Load in hardcoded defaults. */ /* These will be overwritten if present on the SD card. */ LoadDefaultCustomSettings(); /* Parse custom settings off the SD card. */ R_ABORT_UNLESS(LoadSdCardKeyValueStore()); /* Determine how many custom settings are present. */ for (size_t i = 0; i < util::size(g_entries); i++) { if (!g_entries[i].HasValue()) { g_num_entries = i; break; } } /* Ensure that the custom settings entries are sorted. */ if (g_num_entries) { std::sort(g_entries, g_entries + g_num_entries); } } Result GetSdCardKeyValueStoreSettingsItemValueSize(size_t *out_size, const char *name, const char *key) { SdKeyValueStoreEntry *entry = nullptr; R_TRY(GetEntry(std::addressof(entry), name, key)); *out_size = entry->value_size; R_SUCCEED(); } Result GetSdCardKeyValueStoreSettingsItemValue(size_t *out_size, void *dst, size_t dst_size, const char *name, const char *key) { R_UNLESS(dst != nullptr, settings::ResultNullSettingsItemValueBuffer()); SdKeyValueStoreEntry *entry = nullptr; R_TRY(GetEntry(std::addressof(entry), name, key)); const size_t size = std::min(entry->value_size, dst_size); if (size > 0) { std::memcpy(dst, entry->value, size); } *out_size = size; R_SUCCEED(); } }
20,645
C++
.cpp
371
42.908356
146
0.575725
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,200
setmitm_module.cpp
Atmosphere-NX_Atmosphere/stratosphere/ams_mitm/source/set_mitm/setmitm_module.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "../amsmitm_initialization.hpp" #include "setmitm_module.hpp" #include "set_mitm_service.hpp" #include "setsys_mitm_service.hpp" namespace ams::mitm::settings { namespace { enum PortIndex { PortIndex_SetMitm, PortIndex_SetSysMitm, PortIndex_Count, }; constexpr sm::ServiceName SetMitmServiceName = sm::ServiceName::Encode("set"); constexpr sm::ServiceName SetSysMitmServiceName = sm::ServiceName::Encode("set:sys"); struct ServerOptions { static constexpr size_t PointerBufferSize = 0x200; static constexpr size_t MaxDomains = 0; static constexpr size_t MaxDomainObjects = 0; static constexpr bool CanDeferInvokeRequest = false; static constexpr bool CanManageMitmServers = true; }; constexpr size_t MaxSessions = 60; class ServerManager final : public sf::hipc::ServerManager<PortIndex_Count, ServerOptions, MaxSessions> { private: virtual Result OnNeedsToAccept(int port_index, Server *server) override; }; ServerManager g_server_manager; Result ServerManager::OnNeedsToAccept(int port_index, Server *server) { /* Acknowledge the mitm session. */ std::shared_ptr<::Service> fsrv; sm::MitmProcessInfo client_info; server->AcknowledgeMitmSession(std::addressof(fsrv), std::addressof(client_info)); switch (port_index) { case PortIndex_SetMitm: R_RETURN(this->AcceptMitmImpl(server, sf::CreateSharedObjectEmplaced<ISetMitmInterface, SetMitmService>(decltype(fsrv)(fsrv), client_info), fsrv)); case PortIndex_SetSysMitm: R_RETURN(this->AcceptMitmImpl(server, sf::CreateSharedObjectEmplaced<ISetSysMitmInterface, SetSysMitmService>(decltype(fsrv)(fsrv), client_info), fsrv)); AMS_UNREACHABLE_DEFAULT_CASE(); } } } void MitmModule::ThreadFunction(void *) { /* Wait until initialization is complete. */ mitm::WaitInitialized(); /* Create mitm servers. */ R_ABORT_UNLESS((g_server_manager.RegisterMitmServer<SetMitmService>(PortIndex_SetMitm, SetMitmServiceName))); R_ABORT_UNLESS((g_server_manager.RegisterMitmServer<SetSysMitmService>(PortIndex_SetSysMitm, SetSysMitmServiceName))); /* Loop forever, servicing our services. */ g_server_manager.LoopProcess(); } }
3,216
C++
.cpp
66
40.439394
173
0.677193
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,201
setsys_mitm_service.cpp
Atmosphere-NX_Atmosphere/stratosphere/ams_mitm/source/set_mitm/setsys_mitm_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 "setsys_mitm_service.hpp" #include "settings_sd_kvs.hpp" #include "setsys_shim.h" namespace ams::mitm::settings { using namespace ams::settings; namespace { constexpr const char ExternalBluetoothDatabasePath[] = "@Sdcard:/atmosphere/bluetooth_devices.db"; 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_UNLIKELY(g_cached_firmware_version)) { return; } /* Mount firmware version data archive. */ { R_ABORT_UNLESS(ams::fs::MountSystemData("sysver", ncm::SystemDataId::SystemVersion)); ON_SCOPE_EXIT { ams::fs::Unmount("sysver"); }; /* Firmware version file must exist. */ ams::fs::FileHandle file; R_ABORT_UNLESS(ams::fs::OpenFile(std::addressof(file), "sysver:/file", fs::OpenMode_Read)); ON_SCOPE_EXIT { ams::fs::CloseFile(file); }; /* Must be possible to read firmware version from file. */ R_ABORT_UNLESS(ams::fs::ReadFile(file, 0, std::addressof(g_firmware_version), sizeof(g_firmware_version))); g_ams_firmware_version = g_firmware_version; } /* Modify the atmosphere firmware version to display a custom version string. */ { const auto api_info = exosphere::GetApiInfo(); const char emummc_char = emummc::IsActive() ? 'E' : 'S'; /* NOTE: We have carefully accounted for the size of the string we print. */ /* No truncation occurs assuming two-digits for all version number components. */ char display_version[sizeof(g_ams_firmware_version.display_version)]; util::SNPrintf(display_version, sizeof(display_version), "%s|AMS %u.%u.%u|%c", g_ams_firmware_version.display_version, api_info.GetMajorVersion(), api_info.GetMinorVersion(), api_info.GetMicroVersion(), emummc_char); std::memcpy(g_ams_firmware_version.display_version, display_version, sizeof(display_version)); } g_cached_firmware_version = true; } Result GetFirmwareVersionImpl(settings::FirmwareVersion *out, const sm::MitmProcessInfo &client_info) { /* Ensure that we have the firmware version cached. */ CacheFirmwareVersion(); /* We want to give a special firmware version to the home menu title, and nothing else. */ /* This means qlaunch + maintenance menu, and nothing else. */ if (client_info.program_id == ncm::SystemAppletId::Qlaunch || client_info.program_id == ncm::SystemAppletId::MaintenanceMenu) { *out = g_ams_firmware_version; } else { *out = g_firmware_version; } R_SUCCEED(); } bool IsExternalBluetoothDatabaseEnabled() { u8 en = 0; settings::fwdbg::GetSettingsItemValue(std::addressof(en), sizeof(en), "atmosphere", "enable_external_bluetooth_db"); return en; } bool HasExternalBluetoothDatabase() { bool file_exists; R_ABORT_UNLESS(fs::HasFile(std::addressof(file_exists), ExternalBluetoothDatabasePath)); return file_exists; } Result ReadExternalBluetoothDatabase(s32 *entries_read, settings::BluetoothDevicesSettings *db, size_t db_max_size) { /* Open the external database file. */ fs::FileHandle file; R_TRY(fs::OpenFile(std::addressof(file), ExternalBluetoothDatabasePath, fs::OpenMode_Read)); ON_SCOPE_EXIT { fs::CloseFile(file); }; /* Read the number of database entries stored in external database. */ u64 total_entries; R_TRY(fs::ReadFile(file, 0, std::addressof(total_entries), sizeof(total_entries))); u64 db_offset = sizeof(total_entries); if (total_entries > db_max_size) { /* Pairings are stored from least to most recent. Add offset to skip the older entries that won't fit. */ db_offset += (total_entries - db_max_size) * sizeof(settings::BluetoothDevicesSettings); /* Cap number of database entries read to size of database on this firmware. */ total_entries = db_max_size; } /* Read database entries. */ R_TRY(fs::ReadFile(file, db_offset, db, total_entries * sizeof(settings::BluetoothDevicesSettings))); /* Convert entries to the old format if running on a firmware below 13.0.0. */ if (hos::GetVersion() < hos::Version_13_0_0) { for (size_t i = 0; i < total_entries; ++i) { /* Copy the newer name field to the older one. */ util::TSNPrintf(db[i].name, sizeof(db[i].name), "%s", db[i].name2); /* Clear the newer name field. */ std::memset(db[i].name2, 0, sizeof(db[i].name2)); } } /* Set the output. */ *entries_read = static_cast<s32>(total_entries); R_SUCCEED(); } Result StoreExternalBluetoothDatabase(const settings::BluetoothDevicesSettings *db, u64 total_entries) { /* Open the external database file. */ fs::FileHandle file; R_TRY(fs::OpenFile(std::addressof(file), ExternalBluetoothDatabasePath, fs::OpenMode_Write)); ON_SCOPE_EXIT { fs::CloseFile(file); }; /* Ensure the file is the appropriate size for the number of entries. */ R_TRY(fs::SetFileSize(file, sizeof(total_entries) + total_entries * sizeof(settings::BluetoothDevicesSettings))); /* Write the number of database entries. */ R_TRY(fs::WriteFile(file, 0, std::addressof(total_entries), sizeof(total_entries), fs::WriteOption::None)); /* Write the database entries. */ u64 db_offset = sizeof(total_entries); if (hos::GetVersion() < hos::Version_13_0_0) { /* Convert entries to the new format if running on a firmware below 13.0.0. */ for (size_t i = 0; i < total_entries; ++i) { /* Make a copy of the current database entry. */ settings::BluetoothDevicesSettings tmp = db[i]; /* Copy the older name field to the newer one. */ util::TSNPrintf(tmp.name2, sizeof(tmp.name2), "%s", tmp.name); /* Clear the original name field. */ std::memset(tmp.name, 0, sizeof(tmp.name)); /* Write the converted database entry. */ R_TRY(fs::WriteFile(file, db_offset, std::addressof(tmp), sizeof(settings::BluetoothDevicesSettings), fs::WriteOption::None)); /* Advance to the next database entry. */ db_offset += sizeof(settings::BluetoothDevicesSettings); } /* Flush the data we've written. */ R_TRY(fs::FlushFile(file)); } else { /* We can just write the database to the file. */ R_TRY(fs::WriteFile(file, db_offset, db, total_entries * sizeof(settings::BluetoothDevicesSettings), fs::WriteOption::Flush)); } R_SUCCEED(); } } Result SetSysMitmService::GetFirmwareVersion(sf::Out<settings::FirmwareVersion> out) { R_TRY(GetFirmwareVersionImpl(out.GetPointer(), m_client_info)); /* GetFirmwareVersion sanitizes the revision fields. */ out.GetPointer()->revision_major = 0; out.GetPointer()->revision_minor = 0; R_SUCCEED(); } Result SetSysMitmService::GetFirmwareVersion2(sf::Out<settings::FirmwareVersion> out) { R_RETURN(GetFirmwareVersionImpl(out.GetPointer(), m_client_info)); } Result SetSysMitmService::SetBluetoothDevicesSettings(const sf::InMapAliasArray<settings::BluetoothDevicesSettings> &settings) { /* We only want to perform additional logic when the external database setting is enabled. */ R_UNLESS(IsExternalBluetoothDatabaseEnabled(), sm::mitm::ResultShouldForwardToSession()); /* Create the external database if it doesn't exist. */ if (!HasExternalBluetoothDatabase()) { R_TRY(fs::CreateFile(ExternalBluetoothDatabasePath, 0)); } /* Backup the local database to the sd card. */ R_TRY(StoreExternalBluetoothDatabase(settings.GetPointer(), settings.GetSize())); /* Ensure that the updated database is stored to the system save as usual. */ static_assert(sizeof(settings::BluetoothDevicesSettings) == sizeof(::SetSysBluetoothDevicesSettings)); R_TRY(setsysSetBluetoothDevicesSettingsFwd(m_forward_service.get(), reinterpret_cast<const ::SetSysBluetoothDevicesSettings *>(settings.GetPointer()), settings.GetSize())); R_SUCCEED(); } Result SetSysMitmService::GetBluetoothDevicesSettings(sf::Out<s32> out_count, const sf::OutMapAliasArray<settings::BluetoothDevicesSettings> &out) { /* We only want to perform additional logic when the external database setting is enabled. */ R_UNLESS(IsExternalBluetoothDatabaseEnabled(), sm::mitm::ResultShouldForwardToSession()); if (!HasExternalBluetoothDatabase()) { /* Fetch the local database from the system save. */ static_assert(sizeof(settings::BluetoothDevicesSettings) == sizeof(::SetSysBluetoothDevicesSettings)); R_TRY(setsysGetBluetoothDevicesSettingsFwd(m_forward_service.get(), out_count.GetPointer(), reinterpret_cast<::SetSysBluetoothDevicesSettings *>(out.GetPointer()), out.GetSize())); /* Create the external database file. */ R_TRY(fs::CreateFile(ExternalBluetoothDatabasePath, 0)); /* Backup the local database to the sd card. */ R_TRY(StoreExternalBluetoothDatabase(out.GetPointer(), out_count.GetValue())); } else { /* Read the external database from the sd card. */ R_TRY(ReadExternalBluetoothDatabase(out_count.GetPointer(), out.GetPointer(), out.GetSize())); } R_SUCCEED(); } Result SetSysMitmService::GetSettingsItemValueSize(sf::Out<u64> out_size, const settings::SettingsName &name, const settings::SettingsItemKey &key) { R_TRY_CATCH(settings::fwdbg::GetSdCardKeyValueStoreSettingsItemValueSize(out_size.GetPointer(), name.value, key.value)) { R_CATCH_RETHROW(sf::impl::ResultRequestContextChanged) R_CONVERT_ALL(sm::mitm::ResultShouldForwardToSession()); } R_END_TRY_CATCH; R_SUCCEED(); } Result SetSysMitmService::GetSettingsItemValue(sf::Out<u64> out_size, const sf::OutBuffer &out, const settings::SettingsName &name, const settings::SettingsItemKey &key) { R_TRY_CATCH(settings::fwdbg::GetSdCardKeyValueStoreSettingsItemValue(out_size.GetPointer(), out.GetPointer(), out.GetSize(), name.value, key.value)) { R_CATCH_RETHROW(sf::impl::ResultRequestContextChanged) R_CONVERT_ALL(sm::mitm::ResultShouldForwardToSession()); } R_END_TRY_CATCH; R_SUCCEED(); } Result SetSysMitmService::GetDebugModeFlag(sf::Out<bool> out) { /* If we're not processing for am, just return the real flag value. */ R_UNLESS(m_client_info.program_id == ncm::SystemProgramId::Am, sm::mitm::ResultShouldForwardToSession()); /* Retrieve the user configuration. */ u8 en = 0; settings::fwdbg::GetSettingsItemValue(std::addressof(en), sizeof(en), "atmosphere", "enable_am_debug_mode"); out.SetValue(en != 0); R_SUCCEED(); } }
12,835
C++
.cpp
210
49.452381
232
0.634801
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,202
settings_fwdbg_api_override.cpp
Atmosphere-NX_Atmosphere/stratosphere/ams_mitm/source/set_mitm/settings_fwdbg_api_override.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "settings_sd_kvs.hpp" namespace ams::settings::fwdbg { size_t GetSettingsItemValueSize(const char *name, const char *key) { u64 size = 0; if (R_SUCCEEDED(GetSdCardKeyValueStoreSettingsItemValueSize(&size, name, key))) { return size; } R_ABORT_UNLESS(setsysGetSettingsItemValueSize(name, key, &size)); return size; } size_t GetSettingsItemValue(void *dst, size_t dst_size, const char *name, const char *key) { u64 size = 0; if (R_SUCCEEDED(GetSdCardKeyValueStoreSettingsItemValue(&size, dst, dst_size, name, key))) { return size; } R_ABORT_UNLESS(setsysGetSettingsItemValue(name, key, dst, dst_size, &size)); return size; } }
1,425
C++
.cpp
35
35.657143
100
0.700434
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,203
set_mitm_service.cpp
Atmosphere-NX_Atmosphere/stratosphere/ams_mitm/source/set_mitm/set_mitm_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 "set_mitm_service.hpp" #include "set_shim.h" namespace ams::mitm::settings { using namespace ams::settings; namespace { constinit os::ProcessId g_application_process_id = os::InvalidProcessId; constinit cfg::OverrideLocale g_application_locale; constinit bool g_valid_language; constinit bool g_valid_region; } SetMitmService::SetMitmService(std::shared_ptr<::Service> &&s, const sm::MitmProcessInfo &c) : sf::MitmServiceImplBase(std::forward<std::shared_ptr<::Service>>(s), c) { if (m_client_info.program_id == ncm::SystemProgramId::Ns) { os::ProcessId application_process_id; if (R_SUCCEEDED(ams::pm::dmnt::GetApplicationProcessId(std::addressof(application_process_id))) && g_application_process_id == application_process_id) { m_locale = g_application_locale; m_is_valid_language = g_valid_language; m_is_valid_region = g_valid_region; m_got_locale = true; } else { this->InvalidateLocale(); } } else { this->InvalidateLocale(); } } Result SetMitmService::EnsureLocale() { /* Optimization: if locale has already been gotten, we can stop. */ if (AMS_LIKELY(m_got_locale)) { R_SUCCEED(); } std::scoped_lock lk(m_lock); const bool is_ns = m_client_info.program_id == ncm::SystemProgramId::Ns; if (!m_got_locale) { ncm::ProgramId program_id = m_client_info.program_id; os::ProcessId application_process_id = os::InvalidProcessId; if (is_ns) { /* When NS asks for a locale, refresh to get the current application locale. */ R_TRY(ams::pm::dmnt::GetApplicationProcessId(std::addressof(application_process_id))); R_TRY(ams::pm::info::GetProgramId(std::addressof(program_id), application_process_id)); } m_locale = cfg::GetOverrideLocale(program_id); m_is_valid_language = settings::IsValidLanguageCode(m_locale.language_code); m_is_valid_region = settings::IsValidRegionCode(m_locale.region_code); m_got_locale = true; if (is_ns) { g_application_locale = m_locale; g_valid_language = m_is_valid_language; g_valid_region = m_is_valid_region; g_application_process_id = application_process_id; } } R_SUCCEED(); } void SetMitmService::InvalidateLocale() { std::scoped_lock lk(m_lock); std::memset(std::addressof(m_locale), 0xCC, sizeof(m_locale)); m_is_valid_language = false; m_is_valid_region = false; m_got_locale = false; } Result SetMitmService::GetLanguageCode(sf::Out<settings::LanguageCode> out) { this->EnsureLocale(); /* If there's no override locale, just use the actual one. */ if (AMS_UNLIKELY(!m_is_valid_language)) { static_assert(sizeof(u64) == sizeof(settings::LanguageCode)); R_TRY(setGetLanguageCodeFwd(m_forward_service.get(), reinterpret_cast<u64 *>(std::addressof(m_locale.language_code)))); m_is_valid_language = true; if (m_client_info.program_id == ncm::SystemProgramId::Ns) { g_application_locale.language_code = m_locale.language_code; g_valid_language = true; } } out.SetValue(m_locale.language_code); R_SUCCEED(); } Result SetMitmService::GetRegionCode(sf::Out<settings::RegionCode> out) { this->EnsureLocale(); /* If there's no override locale, just use the actual one. */ if (AMS_UNLIKELY(!m_is_valid_region)) { static_assert(sizeof(::SetRegion) == sizeof(settings::RegionCode)); R_TRY(setGetRegionCodeFwd(m_forward_service.get(), reinterpret_cast<::SetRegion *>(std::addressof(m_locale.region_code)))); m_is_valid_region = true; if (m_client_info.program_id == ncm::SystemProgramId::Ns) { g_application_locale.region_code = m_locale.region_code; g_valid_region = true; } } out.SetValue(m_locale.region_code); R_SUCCEED(); } }
5,112
C++
.cpp
107
38.242991
172
0.6112
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,204
dnsmitm_host_redirection.cpp
Atmosphere-NX_Atmosphere/stratosphere/ams_mitm/source/dns_mitm/dnsmitm_host_redirection.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have 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 "../amsmitm_fs_utils.hpp" #include "dnsmitm_debug.hpp" #include "dnsmitm_host_redirection.hpp" #include "socket_allocator.hpp" namespace ams::mitm::socket::resolver { namespace { /* https://github.com/clibs/wildcardcmp */ constexpr int wildcardcmp(const char *pattern, const char *string) { const char *w = nullptr; /* last `*` */ const char *s = nullptr; /* last checked char */ /* malformed */ if (!pattern || !string) return 0; /* loop 1 char at a time */ while (1) { if (!*string) { if (!*pattern) return 1; if ('*' == *pattern) return 1; if (!s || !*s) return 0; string = s++; pattern = w; continue; } else { if (*pattern != *string) { if ('*' == *pattern) { w = ++pattern; s = string; /* "*" -> "foobar" */ if (*pattern) continue; return 1; } else if (w) { string++; /* "*ooba*" -> "foobar" */ continue; } return 0; } } string++; pattern++; } return 1; } constexpr const char DefaultHostsFile[] = "# Nintendo telemetry servers\n" "127.0.0.1 receive-%.dg.srv.nintendo.net receive-%.er.srv.nintendo.net\n"; constinit os::SdkMutex g_redirection_lock; std::vector<std::pair<std::string, ams::socket::InAddrT>> g_redirection_list; void RemoveRedirection(const char *hostname) { for (auto it = g_redirection_list.begin(); it != g_redirection_list.end(); ++it) { if (std::strcmp(it->first.c_str(), hostname) == 0) { g_redirection_list.erase(it); break; } } } void AddRedirection(const char *hostname, ams::socket::InAddrT addr) { RemoveRedirection(hostname); g_redirection_list.emplace(g_redirection_list.begin(), std::string(hostname), addr); } constinit char g_specific_emummc_hosts_path[0x40] = {}; void ParseHostsFile(const char *file_data) { /* Get the environment identifier from settings. */ const auto env = ams::nsd::impl::device::GetEnvironmentIdentifierFromSettings(); const auto env_len = std::strlen(env.value); /* Parse the file. */ enum class State { IgnoredLine, BeginLine, Ip1, IpDot1, Ip2, IpDot2, Ip3, IpDot3, Ip4, WhiteSpace, HostName, }; ams::socket::InAddrT current_address{}; char current_hostname[0x200]; u32 work{}; State state = State::BeginLine; for (const char *cur = file_data; *cur != '\x00'; ++cur) { const char c = *cur; switch (state) { case State::IgnoredLine: if (c == '\n') { state = State::BeginLine; } break; case State::BeginLine: if (std::isdigit(static_cast<unsigned char>(c))) { current_address = 0; work = static_cast<u32>(c - '0'); state = State::Ip1; } else if (c == '\n') { state = State::BeginLine; } else { state = State::IgnoredLine; } break; case State::Ip1: if (std::isdigit(static_cast<unsigned char>(c))) { work *= 10; work += static_cast<u32>(c - '0'); } else if (c == '.') { current_address |= (work & 0xFF) << 0; work = 0; state = State::IpDot1; } else { state = State::IgnoredLine; } break; case State::IpDot1: if (std::isdigit(static_cast<unsigned char>(c))) { work = static_cast<u32>(c - '0'); state = State::Ip2; } else { state = State::IgnoredLine; } break; case State::Ip2: if (std::isdigit(static_cast<unsigned char>(c))) { work *= 10; work += static_cast<u32>(c - '0'); } else if (c == '.') { current_address |= (work & 0xFF) << 8; work = 0; state = State::IpDot2; } else { state = State::IgnoredLine; } break; case State::IpDot2: if (std::isdigit(static_cast<unsigned char>(c))) { work = static_cast<u32>(c - '0'); state = State::Ip3; } else { state = State::IgnoredLine; } break; case State::Ip3: if (std::isdigit(static_cast<unsigned char>(c))) { work *= 10; work += static_cast<u32>(c - '0'); } else if (c == '.') { current_address |= (work & 0xFF) << 16; work = 0; state = State::IpDot3; } else { state = State::IgnoredLine; } break; case State::IpDot3: if (std::isdigit(static_cast<unsigned char>(c))) { work = static_cast<u32>(c - '0'); state = State::Ip4; } else { state = State::IgnoredLine; } break; case State::Ip4: if (std::isdigit(static_cast<unsigned char>(c))) { work *= 10; work += static_cast<u32>(c - '0'); } else if (c == ' ' || c == '\t') { current_address |= (work & 0xFF) << 24; work = 0; state = State::WhiteSpace; } else { state = State::IgnoredLine; } break; case State::WhiteSpace: if (c == '\n') { state = State::BeginLine; } else if (c != ' ' && c != '\r' && c != '\t') { if (c == '%') { std::memcpy(current_hostname, env.value, env_len); work = env_len; } else { current_hostname[0] = c; work = 1; } state = State::HostName; } break; case State::HostName: if (c == ' ' || c == '\r' || c == '\n' || c == '\t') { AMS_ABORT_UNLESS(work < sizeof(current_hostname)); current_hostname[work] = '\x00'; AddRedirection(current_hostname, current_address); work = 0; if (c == '\n') { state = State::BeginLine; } else { state = State::WhiteSpace; } } else if (c == '%') { AMS_ABORT_UNLESS(work < sizeof(current_hostname) - env_len); std::memcpy(current_hostname + work, env.value, env_len); work += env_len; } else { AMS_ABORT_UNLESS(work < sizeof(current_hostname) - 1); current_hostname[work++] = c; } } } if (state == State::HostName) { AMS_ABORT_UNLESS(work < sizeof(current_hostname)); current_hostname[work] = '\x00'; AddRedirection(current_hostname, current_address); } } void Log(::FsFile &f, const char *fmt, ...) __attribute__((format(printf, 2, 3))); void Log(::FsFile &f, const char *fmt, ...) { char log_buf[0x100]; int len = 0; { std::va_list vl; va_start(vl, fmt); len = util::VSNPrintf(log_buf, sizeof(log_buf), fmt, vl); va_end(vl); } s64 ofs; R_ABORT_UNLESS(::fsFileGetSize(std::addressof(f), std::addressof(ofs))); R_ABORT_UNLESS(::fsFileWrite(std::addressof(f), ofs, log_buf, len, FsWriteOption_Flush)); } const char *SelectHostsFile(::FsFile &log_file) { Log(log_file, "Selecting hosts file...\n"); const bool is_emummc = emummc::IsActive(); const u32 emummc_id = emummc::GetActiveId(); util::SNPrintf(g_specific_emummc_hosts_path, sizeof(g_specific_emummc_hosts_path), "/hosts/emummc_%04x.txt", emummc_id); if (is_emummc) { if (mitm::fs::HasAtmosphereSdFile(g_specific_emummc_hosts_path)) { return g_specific_emummc_hosts_path; } Log(log_file, "Skipping %s because it does not exist...\n", g_specific_emummc_hosts_path); if (mitm::fs::HasAtmosphereSdFile("/hosts/emummc.txt")) { return "/hosts/emummc.txt"; } Log(log_file, "Skipping %s because it does not exist...\n", "/hosts/emummc.txt"); } else { if (mitm::fs::HasAtmosphereSdFile("/hosts/sysmmc.txt")) { return "/hosts/sysmmc.txt"; } Log(log_file, "Skipping %s because it does not exist...\n", "/hosts/sysmmc.txt"); } return "/hosts/default.txt"; } bool ShouldAddDefaultResolverRedirections() { u8 en = 0; if (settings::fwdbg::GetSettingsItemValue(std::addressof(en), sizeof(en), "atmosphere", "add_defaults_to_dns_hosts") == sizeof(en)) { return (en != 0); } return false; } } void InitializeResolverRedirections() { /* Get whether we should add defaults. */ const bool add_defaults = ShouldAddDefaultResolverRedirections(); /* Acquire exclusive access to the map. */ std::scoped_lock lk(g_redirection_lock); /* Clear the redirections map. */ g_redirection_list.clear(); /* Open log file. */ ::FsFile log_file; mitm::fs::DeleteAtmosphereSdFile("/logs/dns_mitm_startup.log"); mitm::fs::CreateAtmosphereSdDirectory("/logs"); R_ABORT_UNLESS(mitm::fs::CreateAtmosphereSdFile("/logs/dns_mitm_startup.log", 0, ams::fs::CreateOption_None)); R_ABORT_UNLESS(mitm::fs::OpenAtmosphereSdFile(std::addressof(log_file), "/logs/dns_mitm_startup.log", ams::fs::OpenMode_ReadWrite | ams::fs::OpenMode_AllowAppend)); ON_SCOPE_EXIT { ::fsFileClose(std::addressof(log_file)); }; Log(log_file, "DNS Mitm:\n"); /* If a default hosts file doesn't exist on the sd card, create one. */ if (!mitm::fs::HasAtmosphereSdFile("/hosts/default.txt")) { Log(log_file, "Creating /hosts/default.txt because it does not exist.\n"); mitm::fs::CreateAtmosphereSdDirectory("/hosts"); R_ABORT_UNLESS(mitm::fs::CreateAtmosphereSdFile("/hosts/default.txt", sizeof(DefaultHostsFile) - 1, ams::fs::CreateOption_None)); ::FsFile default_file; R_ABORT_UNLESS(mitm::fs::OpenAtmosphereSdFile(std::addressof(default_file), "/hosts/default.txt", ams::fs::OpenMode_ReadWrite)); R_ABORT_UNLESS(::fsFileWrite(std::addressof(default_file), 0, DefaultHostsFile, sizeof(DefaultHostsFile) - 1, ::FsWriteOption_Flush)); ::fsFileClose(std::addressof(default_file)); } /* If we should, add the defaults. */ if (add_defaults) { Log(log_file, "Adding defaults to redirection list.\n"); ParseHostsFile(DefaultHostsFile); } /* Select the hosts file. */ const char *hosts_path = SelectHostsFile(log_file); Log(log_file, "Selected %s\n", hosts_path); /* Load the hosts file. */ { char *hosts_file_data = nullptr; ON_SCOPE_EXIT { if (hosts_file_data != nullptr) { ams::Free(hosts_file_data); } }; { ::FsFile hosts_file; R_ABORT_UNLESS(mitm::fs::OpenAtmosphereSdFile(std::addressof(hosts_file), hosts_path, ams::fs::OpenMode_Read)); ON_SCOPE_EXIT { ::fsFileClose(std::addressof(hosts_file)); }; /* Get the hosts file size. */ s64 hosts_size; R_ABORT_UNLESS(::fsFileGetSize(std::addressof(hosts_file), std::addressof(hosts_size))); /* Validate we can read the file. */ AMS_ABORT_UNLESS(0 <= hosts_size && hosts_size < 0x8000); /* Read the data. */ hosts_file_data = static_cast<char *>(ams::Malloc(0x8000)); AMS_ABORT_UNLESS(hosts_file_data != nullptr); u64 br; R_ABORT_UNLESS(::fsFileRead(std::addressof(hosts_file), 0, hosts_file_data, hosts_size, ::FsReadOption_None, std::addressof(br))); AMS_ABORT_UNLESS(br == static_cast<u64>(hosts_size)); /* Null-terminate. */ hosts_file_data[hosts_size] = '\x00'; } /* Parse the hosts file. */ ParseHostsFile(hosts_file_data); } /* Print the redirections. */ Log(log_file, "Redirections:\n"); for (const auto &[host, address] : g_redirection_list) { Log(log_file, " `%s` -> %u.%u.%u.%u\n", host.c_str(), (address >> 0) & 0xFF, (address >> 8) & 0xFF, (address >> 16) & 0xFF, (address >> 24) & 0xFF); } } bool GetRedirectedHostByName(ams::socket::InAddrT *out, const char *hostname) { std::scoped_lock lk(g_redirection_lock); for (const auto &[host, address] : g_redirection_list) { if (wildcardcmp(host.c_str(), hostname)) { *out = address; return true; } } return false; } }
16,664
C++
.cpp
349
29.819484
172
0.444759
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,205
dnsmitm_resolver_impl.cpp
Atmosphere-NX_Atmosphere/stratosphere/ams_mitm/source/dns_mitm/dnsmitm_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 "dnsmitm_resolver_impl.hpp" #include "dnsmitm_debug.hpp" #include "dnsmitm_host_redirection.hpp" #include "serializer/serializer.hpp" #include "sfdnsres_shim.h" namespace ams::mitm::socket::resolver { ssize_t SerializeRedirectedHostEnt(u8 * const dst, size_t dst_size, const char *hostname, ams::socket::InAddrT redirect_addr) { struct in_addr addr = { .s_addr = redirect_addr }; struct in_addr *addr_list[2] = { std::addressof(addr), nullptr }; struct hostent ent = { .h_name = const_cast<char *>(hostname), .h_aliases = nullptr, .h_addrtype = AF_INET, .h_length = sizeof(u32), .h_addr_list = (char **)addr_list, }; const auto result = serializer::DNSSerializer::ToBuffer(dst, dst_size, ent); AMS_ABORT_UNLESS(result >= 0); return result; } ssize_t SerializeRedirectedAddrInfo(u8 * const dst, size_t dst_size, const char *hostname, ams::socket::InAddrT redirect_addr, u16 redirect_port, const struct addrinfo *hint) { AMS_UNUSED(hostname); struct addrinfo ai = { .ai_flags = 0, .ai_family = AF_UNSPEC, .ai_socktype = 0, .ai_protocol = 0, .ai_addrlen = 0, .ai_canonname = nullptr, .ai_next = nullptr, }; if (hint != nullptr) { ai = *hint; } switch (ai.ai_family) { case AF_UNSPEC: ai.ai_family = AF_INET; break; case AF_INET: ai.ai_family = AF_INET; break; case AF_INET6: AMS_ABORT("Redirected INET6 not supported"); break; AMS_UNREACHABLE_DEFAULT_CASE(); } if (ai.ai_socktype == 0) { ai.ai_socktype = SOCK_STREAM; } if (ai.ai_protocol == 0) { ai.ai_protocol = IPPROTO_TCP; } const struct sockaddr_in sin = { .sin_family = AF_INET, .sin_port = ams::socket::InetHtons(redirect_port), .sin_addr = { .s_addr = redirect_addr }, .sin_zero = {}, }; ai.ai_addrlen = sizeof(sin); ai.ai_addr = (struct sockaddr *)(std::addressof(sin)); const auto result = serializer::DNSSerializer::ToBuffer(dst, dst_size, ai); AMS_ABORT_UNLESS(result >= 0); return result; } Result ResolverImpl::GetHostByNameRequest(u32 cancel_handle, const sf::ClientProcessId &client_pid, bool use_nsd_resolve, const sf::InBuffer &name, sf::Out<u32> out_host_error, sf::Out<u32> out_errno, const sf::OutBuffer &out_hostent, sf::Out<u32> out_size) { AMS_UNUSED(cancel_handle, client_pid, use_nsd_resolve); const char *hostname = reinterpret_cast<const char *>(name.GetPointer()); LogDebug("[%016lx]: GetHostByNameRequest(%s)\n", m_client_info.program_id.value, hostname); R_UNLESS(hostname != nullptr, sm::mitm::ResultShouldForwardToSession()); ams::socket::InAddrT redirect_addr = {}; R_UNLESS(GetRedirectedHostByName(std::addressof(redirect_addr), hostname), sm::mitm::ResultShouldForwardToSession()); LogDebug("[%016lx]: Redirecting %s to %u.%u.%u.%u\n", m_client_info.program_id.value, hostname, (redirect_addr >> 0) & 0xFF, (redirect_addr >> 8) & 0xFF, (redirect_addr >> 16) & 0xFF, (redirect_addr >> 24) & 0xFF); const auto size = SerializeRedirectedHostEnt(out_hostent.GetPointer(), out_hostent.GetSize(), hostname, redirect_addr); *out_host_error = 0; *out_errno = 0; *out_size = size; R_SUCCEED(); } Result ResolverImpl::GetAddrInfoRequest(u32 cancel_handle, const sf::ClientProcessId &client_pid, bool use_nsd_resolve, const sf::InBuffer &node, const sf::InBuffer &srv, const sf::InBuffer &serialized_hint, const sf::OutBuffer &out_addrinfo, sf::Out<u32> out_errno, sf::Out<s32> out_retval, sf::Out<u32> out_size) { AMS_UNUSED(cancel_handle, client_pid, use_nsd_resolve); const char *hostname = reinterpret_cast<const char *>(node.GetPointer()); LogDebug("[%016lx]: GetAddrInfoRequest(%s, %s)\n", m_client_info.program_id.value, reinterpret_cast<const char *>(node.GetPointer()), reinterpret_cast<const char *>(srv.GetPointer())); R_UNLESS(hostname != nullptr, sm::mitm::ResultShouldForwardToSession()); ams::socket::InAddrT redirect_addr = {}; R_UNLESS(GetRedirectedHostByName(std::addressof(redirect_addr), hostname), sm::mitm::ResultShouldForwardToSession()); u16 port = 0; if (srv.GetPointer() != nullptr) { for (const char *cur = reinterpret_cast<const char *>(srv.GetPointer()); *cur != 0; ++cur) { AMS_ABORT_UNLESS(std::isdigit(static_cast<unsigned char>(*cur))); port *= 10; port += *cur - '0'; } } LogDebug("[%016lx]: Redirecting %s:%u to %u.%u.%u.%u\n", m_client_info.program_id.value, hostname, port, (redirect_addr >> 0) & 0xFF, (redirect_addr >> 8) & 0xFF, (redirect_addr >> 16) & 0xFF, (redirect_addr >> 24) & 0xFF); const bool use_hint = serialized_hint.GetPointer() != nullptr; struct addrinfo hint = {}; if (use_hint) { AMS_ABORT_UNLESS(serializer::DNSSerializer::FromBuffer(hint, serialized_hint.GetPointer(), serialized_hint.GetSize()) >= 0); } ON_SCOPE_EXIT { if (use_hint) { serializer::FreeAddrInfo(hint); } }; const auto size = SerializeRedirectedAddrInfo(out_addrinfo.GetPointer(), out_addrinfo.GetSize(), hostname, redirect_addr, port, use_hint ? std::addressof(hint) : nullptr); *out_retval = 0; *out_errno = 0; *out_size = size; R_SUCCEED(); } Result ResolverImpl::GetHostByNameRequestWithOptions(const sf::ClientProcessId &client_pid, const sf::InAutoSelectBuffer &name, const sf::OutAutoSelectBuffer &out_hostent, sf::Out<u32> out_size, u32 options_version, const sf::InAutoSelectBuffer &options, u32 num_options, sf::Out<s32> out_host_error, sf::Out<s32> out_errno) { AMS_UNUSED(client_pid, options_version, options, num_options); const char *hostname = reinterpret_cast<const char *>(name.GetPointer()); LogDebug("[%016lx]: GetHostByNameRequestWithOptions(%s)\n", m_client_info.program_id.value, hostname); R_UNLESS(hostname != nullptr, sm::mitm::ResultShouldForwardToSession()); ams::socket::InAddrT redirect_addr = {}; R_UNLESS(GetRedirectedHostByName(std::addressof(redirect_addr), hostname), sm::mitm::ResultShouldForwardToSession()); LogDebug("[%016lx]: Redirecting %s to %u.%u.%u.%u\n", m_client_info.program_id.value, hostname, (redirect_addr >> 0) & 0xFF, (redirect_addr >> 8) & 0xFF, (redirect_addr >> 16) & 0xFF, (redirect_addr >> 24) & 0xFF); const auto size = SerializeRedirectedHostEnt(out_hostent.GetPointer(), out_hostent.GetSize(), hostname, redirect_addr); *out_host_error = 0; *out_errno = 0; *out_size = size; R_SUCCEED(); } Result ResolverImpl::GetAddrInfoRequestWithOptions(const sf::ClientProcessId &client_pid, const sf::InBuffer &node, const sf::InBuffer &srv, const sf::InBuffer &serialized_hint, const sf::OutAutoSelectBuffer &out_addrinfo, sf::Out<u32> out_size, sf::Out<s32> out_retval, u32 options_version, const sf::InAutoSelectBuffer &options, u32 num_options, sf::Out<s32> out_host_error, sf::Out<s32> out_errno) { AMS_UNUSED(client_pid, options_version, options, num_options); const char *hostname = reinterpret_cast<const char *>(node.GetPointer()); LogDebug("[%016lx]: GetAddrInfoRequestWithOptions(%s, %s)\n", m_client_info.program_id.value, hostname, reinterpret_cast<const char *>(srv.GetPointer())); R_UNLESS(hostname != nullptr, sm::mitm::ResultShouldForwardToSession()); ams::socket::InAddrT redirect_addr = {}; R_UNLESS(GetRedirectedHostByName(std::addressof(redirect_addr), hostname), sm::mitm::ResultShouldForwardToSession()); u16 port = 0; if (srv.GetPointer() != nullptr) { for (const char *cur = reinterpret_cast<const char *>(srv.GetPointer()); *cur != 0; ++cur) { AMS_ABORT_UNLESS(std::isdigit(static_cast<unsigned char>(*cur))); port *= 10; port += *cur - '0'; } } LogDebug("[%016lx]: Redirecting %s:%u to %u.%u.%u.%u\n", m_client_info.program_id.value, hostname, port, (redirect_addr >> 0) & 0xFF, (redirect_addr >> 8) & 0xFF, (redirect_addr >> 16) & 0xFF, (redirect_addr >> 24) & 0xFF); const bool use_hint = serialized_hint.GetPointer() != nullptr; struct addrinfo hint = {}; if (use_hint) { AMS_ABORT_UNLESS(serializer::DNSSerializer::FromBuffer(hint, serialized_hint.GetPointer(), serialized_hint.GetSize()) >= 0); } ON_SCOPE_EXIT { if (use_hint) { serializer::FreeAddrInfo(hint); } }; const auto size = SerializeRedirectedAddrInfo(out_addrinfo.GetPointer(), out_addrinfo.GetSize(), hostname, redirect_addr, port, use_hint ? std::addressof(hint) : nullptr); *out_retval = 0; *out_host_error = 0; *out_errno = 0; *out_size = size; R_SUCCEED(); } Result ResolverImpl::AtmosphereReloadHostsFile() { /* Perform a hosts file reload. */ InitializeResolverRedirections(); R_SUCCEED(); } }
10,191
C++
.cpp
165
52.818182
406
0.635716
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,206
dnsmitm_module.cpp
Atmosphere-NX_Atmosphere/stratosphere/ams_mitm/source/dns_mitm/dnsmitm_module.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "../amsmitm_initialization.hpp" #include "dnsmitm_module.hpp" #include "dnsmitm_debug.hpp" #include "dnsmitm_resolver_impl.hpp" #include "dnsmitm_host_redirection.hpp" namespace ams::mitm::socket::resolver { namespace { enum PortIndex { PortIndex_Mitm, PortIndex_Count, }; constexpr sm::ServiceName DnsMitmServiceName = sm::ServiceName::Encode("sfdnsres"); constexpr size_t MaxSessions = 30; struct ServerOptions { static constexpr size_t PointerBufferSize = sf::hipc::DefaultServerManagerOptions::PointerBufferSize; static constexpr size_t MaxDomains = sf::hipc::DefaultServerManagerOptions::MaxDomains; static constexpr size_t MaxDomainObjects = sf::hipc::DefaultServerManagerOptions::MaxDomainObjects; static constexpr bool CanDeferInvokeRequest = sf::hipc::DefaultServerManagerOptions::CanDeferInvokeRequest; static constexpr bool CanManageMitmServers = true; }; class ServerManager final : public sf::hipc::ServerManager<PortIndex_Count, ServerOptions, MaxSessions> { private: virtual Result OnNeedsToAccept(int port_index, Server *server) override; }; alignas(os::MemoryPageSize) constinit u8 g_resolver_allocator_buffer[16_KB]; ServerManager g_server_manager; Result ServerManager::OnNeedsToAccept(int port_index, Server *server) { /* Acknowledge the mitm session. */ std::shared_ptr<::Service> fsrv; sm::MitmProcessInfo client_info; server->AcknowledgeMitmSession(std::addressof(fsrv), std::addressof(client_info)); switch (port_index) { case PortIndex_Mitm: R_RETURN(this->AcceptMitmImpl(server, sf::CreateSharedObjectEmplaced<IResolver, ResolverImpl>(decltype(fsrv)(fsrv), client_info), fsrv)); AMS_UNREACHABLE_DEFAULT_CASE(); } } constexpr size_t TotalThreads = 8; static_assert(TotalThreads >= 1, "TotalThreads"); constexpr size_t NumExtraThreads = TotalThreads - 1; constexpr size_t ThreadStackSize = mitm::ModuleTraits<socket::resolver::MitmModule>::StackSize; alignas(os::MemoryPageSize) u8 g_extra_thread_stacks[NumExtraThreads][ThreadStackSize]; os::ThreadType g_extra_threads[NumExtraThreads]; void LoopServerThread(void *) { /* Loop forever, servicing our services. */ g_server_manager.LoopProcess(); } void ProcessForServerOnAllThreads() { /* Initialize threads. */ if constexpr (NumExtraThreads > 0) { const s32 priority = os::GetThreadCurrentPriority(os::GetCurrentThread()); for (size_t i = 0; i < NumExtraThreads; i++) { R_ABORT_UNLESS(os::CreateThread(g_extra_threads + i, LoopServerThread, nullptr, g_extra_thread_stacks[i], ThreadStackSize, priority)); } } /* Start extra threads. */ if constexpr (NumExtraThreads > 0) { for (size_t i = 0; i < NumExtraThreads; i++) { os::StartThread(g_extra_threads + i); } } /* Loop this thread. */ LoopServerThread(nullptr); /* Wait for extra threads to finish. */ if constexpr (NumExtraThreads > 0) { for (size_t i = 0; i < NumExtraThreads; i++) { os::WaitThread(g_extra_threads + i); } } } bool ShouldMitmDns() { u8 en = 0; if (settings::fwdbg::GetSettingsItemValue(std::addressof(en), sizeof(en), "atmosphere", "enable_dns_mitm") == sizeof(en)) { return (en != 0); } return false; } bool ShouldEnableDebugLog() { u8 en = 0; if (settings::fwdbg::GetSettingsItemValue(std::addressof(en), sizeof(en), "atmosphere", "enable_dns_mitm_debug_log") == sizeof(en)) { return (en != 0); } return false; } } void MitmModule::ThreadFunction(void *) { /* Wait until initialization is complete. */ mitm::WaitInitialized(); /* If we shouldn't mitm dns, don't do anything at all. */ if (!ShouldMitmDns()) { return; } /* Initialize the socket allocator. */ ams::socket::InitializeAllocatorForInternal(g_resolver_allocator_buffer, sizeof(g_resolver_allocator_buffer)); /* Initialize debug. */ resolver::InitializeDebug(ShouldEnableDebugLog()); /* Initialize redirection map. */ resolver::InitializeResolverRedirections(); /* Create mitm servers. */ R_ABORT_UNLESS((g_server_manager.RegisterMitmServer<ResolverImpl>(PortIndex_Mitm, DnsMitmServiceName))); /* Loop forever, servicing our services. */ ProcessForServerOnAllThreads(); } }
5,745
C++
.cpp
120
37.783333
157
0.628842
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,207
dnsmitm_debug.cpp
Atmosphere-NX_Atmosphere/stratosphere/ams_mitm/source/dns_mitm/dnsmitm_debug.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have 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 "../amsmitm_fs_utils.hpp" #include "dnsmitm_debug.hpp" namespace ams::mitm::socket::resolver { namespace { constinit os::SdkMutex g_log_mutex; constinit bool g_log_enabled; constinit ::FsFile g_log_file; constinit s64 g_log_ofs; constinit char g_log_buf[0x400]; } void InitializeDebug(bool enable_log) { { std::scoped_lock lk(g_log_mutex); g_log_enabled = enable_log; if (g_log_enabled) { /* Create the logs directory. */ mitm::fs::CreateAtmosphereSdDirectory("/logs"); /* Create the log file. */ mitm::fs::CreateAtmosphereSdFile("/logs/dns_mitm_debug.log", 0, ams::fs::CreateOption_None); /* Open the log file. */ R_ABORT_UNLESS(mitm::fs::OpenAtmosphereSdFile(std::addressof(g_log_file), "/logs/dns_mitm_debug.log", ams::fs::OpenMode_ReadWrite | ams::fs::OpenMode_AllowAppend)); /* Get the current log offset. */ R_ABORT_UNLESS(::fsFileGetSize(std::addressof(g_log_file), std::addressof(g_log_ofs))); } } /* Start a new log. */ LogDebug("\n---\n"); } void LogDebug(const char *fmt, ...) { std::scoped_lock lk(g_log_mutex); if (g_log_enabled) { int len = 0; { std::va_list vl; va_start(vl, fmt); len = util::VSNPrintf(g_log_buf, sizeof(g_log_buf), fmt, vl); va_end(vl); } R_ABORT_UNLESS(::fsFileWrite(std::addressof(g_log_file), g_log_ofs, g_log_buf, len, FsWriteOption_Flush)); g_log_ofs += len; } } }
2,422
C++
.cpp
59
32.389831
180
0.597015
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,208
serializer_impls_sockaddrin_4.cpp
Atmosphere-NX_Atmosphere/stratosphere/ams_mitm/source/dns_mitm/serializer/serializer_impls_sockaddrin_4.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have 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 "../dnsmitm_debug.hpp" #include "../socket_allocator.hpp" #include "serializer.hpp" namespace ams::mitm::socket::resolver::serializer { namespace { template<typename T> concept IsSockAddrIn = std::same_as<T, ams::socket::SockAddrIn> || std::same_as<T, struct sockaddr_in>; template<typename T> requires IsSockAddrIn<T> size_t SizeOfImpl(const T &in) { size_t rc = 0; rc += sizeof(u16); rc += sizeof(u16); rc += DNSSerializer::SizeOf(in.sin_addr); rc += sizeof(in.sin_zero); return rc; } template<typename T> requires IsSockAddrIn<T> ssize_t ToBufferImpl(u8 * const dst, size_t dst_size, const T &in) { ssize_t rc = -1; u8 *cur = dst; if ((rc = DNSSerializer::CheckToBufferArguments(cur, dst_size, sizeof(in), __LINE__)) == -1) { return rc; } const u16 sin_family = static_cast<u16>(in.sin_family); if ((rc = DNSSerializer::ToBuffer(cur, dst_size - (cur - dst), sin_family)) == -1) { return rc; } cur += rc; const u16 sin_port = static_cast<u16>(in.sin_port); if ((rc = DNSSerializer::ToBuffer(cur, dst_size - (cur - dst), sin_port)) == -1) { return rc; } cur += rc; const u32 s_addr = static_cast<u32>(in.sin_addr.s_addr); if ((rc = DNSSerializer::ToBuffer(cur, dst_size - (cur - dst), s_addr)) == -1) { return rc; } cur += rc; if (dst_size - (cur - dst) < sizeof(in.sin_zero)) { rc = -1; return rc; } std::memcpy(cur, in.sin_zero, sizeof(in.sin_zero)); cur += sizeof(in.sin_zero); rc = cur - dst; return rc; } template<typename T> requires IsSockAddrIn<T> ssize_t FromBufferImpl(T &out, const u8 *src, size_t src_size) { ssize_t rc = -1; const u8 *cur = src; u16 sin_family; if ((rc = DNSSerializer::FromBuffer(sin_family, cur, src_size - (cur - src))) == -1) { return rc; } out.sin_family = static_cast<decltype(out.sin_family)>(sin_family); cur += rc; u16 sin_port; if ((rc = DNSSerializer::FromBuffer(sin_port, cur, src_size - (cur - src))) == -1) { return rc; } out.sin_port = static_cast<decltype(out.sin_port)>(sin_port); cur += rc; u32 s_addr; if ((rc = DNSSerializer::FromBuffer(s_addr, cur, src_size - (cur - src))) == -1) { return rc; } out.sin_addr.s_addr = static_cast<decltype(out.sin_addr.s_addr)>(s_addr); cur += rc; if (src_size - (cur - src) < sizeof(out.sin_zero)) { rc = -1; return rc; } std::memcpy(out.sin_zero, cur, sizeof(out.sin_zero)); cur += sizeof(out.sin_zero); rc = cur - src; return rc; } } template<> size_t DNSSerializer::SizeOf(const struct sockaddr_in &in) { return SizeOfImpl(in); } template<> size_t DNSSerializer::SizeOf(const ams::socket::SockAddrIn &in) { return SizeOfImpl(in); } template<> ssize_t DNSSerializer::ToBuffer(u8 * const dst, size_t dst_size, const struct sockaddr_in &in) { return ToBufferImpl(dst, dst_size, in); } template<> ssize_t DNSSerializer::ToBuffer(u8 * const dst, size_t dst_size, const ams::socket::SockAddrIn &in) { return ToBufferImpl(dst, dst_size, in); } template<> ssize_t DNSSerializer::FromBuffer(struct sockaddr_in &out, const u8 *src, size_t src_size) { return FromBufferImpl(out, src, src_size); } template<> ssize_t DNSSerializer::FromBuffer(struct ams::socket::SockAddrIn &out, const u8 *src, size_t src_size) { return FromBufferImpl(out, src, src_size); } }
4,817
C++
.cpp
114
32.298246
119
0.561805
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,209
serializer_impls_addrinfo.cpp
Atmosphere-NX_Atmosphere/stratosphere/ams_mitm/source/dns_mitm/serializer/serializer_impls_addrinfo.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have 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 "../dnsmitm_debug.hpp" #include "../socket_allocator.hpp" #include "serializer.hpp" namespace ams::mitm::socket::resolver::serializer { namespace { constexpr inline u32 AddrInfoMagic = 0xBEEFCAFE; template<typename T> concept IsAddrInfo = std::same_as<T, ams::socket::AddrInfo> || std::same_as<T, struct addrinfo>; template<typename T> requires IsAddrInfo<T> using SockAddrType = typename std::conditional<std::same_as<T, ams::socket::AddrInfo>, ams::socket::SockAddr, struct sockaddr>::type; template<typename T> requires IsAddrInfo<T> using SockAddrInType = typename std::conditional<std::same_as<T, ams::socket::AddrInfo>, ams::socket::SockAddrIn, struct sockaddr_in>::type; template<typename T> requires IsAddrInfo<T> using SockAddrIn6Type = typename std::conditional<std::same_as<T, ams::socket::AddrInfo>, struct sockaddr_in6, struct sockaddr_in6>::type; template<typename T> requires IsAddrInfo<T> constexpr bool IsAfInet(const auto ai_family) { if constexpr (std::same_as<T, ams::socket::AddrInfo>) { return ai_family == ams::socket::Family::Af_Inet; } else { return ai_family == AF_INET; } } template<typename T> requires IsAddrInfo<T> constexpr bool IsAfInet6(const auto ai_family) { if constexpr (std::same_as<T, ams::socket::AddrInfo>) { return ai_family == ams::socket::Family::Af_Inet6; } else { return ai_family == AF_INET; } } template<typename T> requires IsAddrInfo<T> void FreeAddrInfoImpl(T &addr_info) { T *next = nullptr; for (T *cur = std::addressof(addr_info); cur != nullptr; cur = next) { next = cur->ai_next; if (cur->ai_addr != nullptr) { if (IsAfInet<T>(cur->ai_family)) { ams::socket::impl::Free(reinterpret_cast<SockAddrInType<T> *>(cur->ai_addr)); } else if (IsAfInet6<T>(cur->ai_family)) { ams::socket::impl::Free(reinterpret_cast<SockAddrIn6Type<T> *>(cur->ai_addr)); } else { ams::socket::impl::Free(cur->ai_addr); } cur->ai_addr = nullptr; } if (cur->ai_canonname != nullptr) { ams::socket::impl::Free(cur->ai_canonname); cur->ai_canonname = nullptr; } if (cur != std::addressof(addr_info)) { ams::socket::impl::Free(cur); } } } template<typename T> requires IsAddrInfo<T> size_t AddrInfoSingleSizeOf(const T *addr_info) { size_t rc = 6 * sizeof(u32); if (addr_info->ai_addr == nullptr) { rc += sizeof(u32); } else if (IsAfInet<T>(addr_info->ai_family)) { rc += DNSSerializer::SizeOf(*reinterpret_cast<SockAddrInType<T> *>(addr_info->ai_addr)); } else if (IsAfInet6<T>(addr_info->ai_family)) { rc += DNSSerializer::SizeOf(*reinterpret_cast<SockAddrIn6Type<T> *>(addr_info->ai_addr)); } else if (addr_info->ai_addrlen == 0) { rc += sizeof(u32); } else { rc += addr_info->ai_addrlen; } if (addr_info->ai_canonname != nullptr) { rc += DNSSerializer::SizeOf(static_cast<const char *>(addr_info->ai_canonname)); } else { rc += sizeof(u8); } if (addr_info->ai_next == nullptr) { rc += sizeof(u32); } return rc; } template<typename T> requires IsAddrInfo<T> size_t SizeOfImpl(const T &in) { size_t rc = 0; for (const T *addr_info = std::addressof(in); addr_info != nullptr; addr_info = addr_info->ai_next) { rc += AddrInfoSingleSizeOf(addr_info); } return rc; } template<typename T> requires IsAddrInfo<T> ssize_t ToBufferInternalImpl(u8 * const dst, size_t dst_size, const T &addr_info) { ssize_t rc = -1; u8 *cur = dst; { const u32 value = AddrInfoMagic; if ((rc = DNSSerializer::ToBuffer(cur, dst_size - (cur - dst), value)) == -1) { return rc; } cur += rc; } { const u32 value = static_cast<u32>(addr_info.ai_flags); if ((rc = DNSSerializer::ToBuffer(cur, dst_size - (cur - dst), value)) == -1) { return rc; } cur += rc; } { const u32 value = static_cast<u32>(addr_info.ai_family); if ((rc = DNSSerializer::ToBuffer(cur, dst_size - (cur - dst), value)) == -1) { return rc; } cur += rc; } { const u32 value = static_cast<u32>(addr_info.ai_socktype); if ((rc = DNSSerializer::ToBuffer(cur, dst_size - (cur - dst), value)) == -1) { return rc; } cur += rc; } { const u32 value = static_cast<u32>(addr_info.ai_protocol); if ((rc = DNSSerializer::ToBuffer(cur, dst_size - (cur - dst), value)) == -1) { return rc; } cur += rc; } { const u32 value = static_cast<u32>(addr_info.ai_addrlen); if ((rc = DNSSerializer::ToBuffer(cur, dst_size - (cur - dst), value)) == -1) { return rc; } cur += rc; } { if (addr_info.ai_addr == nullptr || addr_info.ai_addrlen == 0) { const u32 value = 0; if ((rc = DNSSerializer::ToBuffer(cur, dst_size - (cur - dst), value)) == -1) { return rc; } } else if (IsAfInet<T>(addr_info.ai_family)) { if ((rc = DNSSerializer::ToBuffer(cur, dst_size - (cur - dst), *reinterpret_cast<SockAddrInType<T> *>(addr_info.ai_addr))) == -1) { return rc; } } else if (IsAfInet6<T>(addr_info.ai_family)) { if ((rc = DNSSerializer::ToBuffer(cur, dst_size - (cur - dst), *reinterpret_cast<SockAddrIn6Type<T> *>(addr_info.ai_addr))) == -1) { return rc; } } else { if (dst_size - (cur - dst) < addr_info.ai_addrlen) { rc = -1; return rc; } /* NOTE: This is clearly a nintendo bug, see the accompanying note in FromBufferInternalImpl */ std::memmove(cur, std::addressof(addr_info.ai_addr), addr_info.ai_addrlen); rc = addr_info.ai_addrlen; } cur += rc; } { if ((rc = DNSSerializer::ToBuffer(cur, dst_size - (cur - dst), addr_info.ai_canonname)) == -1) { return rc; } cur += rc; } if (addr_info.ai_next == nullptr) { const u32 value = 0; if ((rc = DNSSerializer::ToBuffer(cur, dst_size - (cur - dst), value)) == -1) { return rc; } cur += rc; } rc = cur - dst; return rc; } template<typename T> requires IsAddrInfo<T> ssize_t ToBufferImpl(u8 * const dst, size_t dst_size, const T &in) { ssize_t rc = -1; u8 *cur = dst; std::memset(dst, 0, dst_size); const size_t required = DNSSerializer::SizeOf(in); if ((rc = DNSSerializer::CheckToBufferArguments(cur, dst_size, required, __LINE__)) == -1) { return rc; } for (const T *addr_info = std::addressof(in); addr_info != nullptr; addr_info = addr_info->ai_next) { if ((rc = ToBufferInternalImpl(cur, dst_size, *addr_info)) == -1) { return rc; } cur += rc; } rc = cur - dst; return rc; } template<typename T> requires IsAddrInfo<T> ssize_t FromBufferInternalImpl(T &out, const u8 *src, size_t src_size) { ssize_t rc = -1; const u8 *cur = src; std::memset(std::addressof(out), 0, sizeof(out)); ON_SCOPE_EXIT { if (rc < 0) { FreeAddrInfo(out); } }; u32 tmp_value; { if ((rc = DNSSerializer::FromBuffer(tmp_value, cur, src_size - (cur - src))) == -1) { return rc; } else if (tmp_value != AddrInfoMagic) { return rc; } cur += rc; } { if ((rc = DNSSerializer::FromBuffer(tmp_value, cur, src_size - (cur - src))) == -1) { return rc; } out.ai_flags = static_cast<decltype(out.ai_flags)>(tmp_value); cur += rc; } { if ((rc = DNSSerializer::FromBuffer(tmp_value, cur, src_size - (cur - src))) == -1) { return rc; } out.ai_family = static_cast<decltype(out.ai_family)>(tmp_value); cur += rc; } { if ((rc = DNSSerializer::FromBuffer(tmp_value, cur, src_size - (cur - src))) == -1) { return rc; } out.ai_socktype = static_cast<decltype(out.ai_socktype)>(tmp_value); cur += rc; } { if ((rc = DNSSerializer::FromBuffer(tmp_value, cur, src_size - (cur - src))) == -1) { return rc; } out.ai_protocol = static_cast<decltype(out.ai_protocol)>(tmp_value); cur += rc; } { if ((rc = DNSSerializer::FromBuffer(tmp_value, cur, src_size - (cur - src))) == -1) { return rc; } out.ai_addrlen = static_cast<decltype(out.ai_addrlen)>(tmp_value); cur += rc; } { if (out.ai_addrlen == 0) { if ((rc = DNSSerializer::FromBuffer(tmp_value, cur, src_size - (cur - src))) == -1) { return rc; } if (tmp_value != 0) { rc = -1; return rc; } out.ai_addr = nullptr; } else if (IsAfInet<T>(out.ai_family)) { out.ai_addr = static_cast<SockAddrType<T> *>(ams::socket::impl::Alloc(sizeof(SockAddrInType<T>))); if (out.ai_addr == nullptr) { rc = -1; return rc; } std::memset(out.ai_addr, 0, sizeof(SockAddrInType<T>)); if ((rc = DNSSerializer::FromBuffer(*reinterpret_cast<SockAddrInType<T> *>(out.ai_addr), cur, src_size - (cur - src))) == -1) { return rc; } } else if (IsAfInet6<T>(out.ai_family)) { out.ai_addr = static_cast<SockAddrType<T> *>(ams::socket::impl::Alloc(sizeof(SockAddrIn6Type<T>))); if (out.ai_addr == nullptr) { rc = -1; return rc; } std::memset(out.ai_addr, 0, sizeof(SockAddrIn6Type<T>)); if ((rc = DNSSerializer::FromBuffer(*reinterpret_cast<SockAddrIn6Type<T> *>(out.ai_addr), cur, src_size - (cur - src))) == -1) { return rc; } } else { out.ai_addr = static_cast<decltype(out.ai_addr)>(ams::socket::impl::Alloc(out.ai_addrlen)); if (out.ai_addr == nullptr) { rc = -1; return rc; } /* NOTE: This is *clearly* a nintendo bug. */ /* They obviously intend to copy to the buffer they just allocated, but instead they copy to the addrinfo structure itself. */ /* Probably &out.ai_addr instead of &out.ai_addr[0]? Either way, we'll implement what they do, but... */ std::memcpy(std::addressof(out.ai_addr), cur, out.ai_addrlen); rc = out.ai_addrlen; } cur += rc; } { if ((rc = DNSSerializer::FromBuffer(out.ai_canonname, cur, src_size - (cur - src))) == -1) { return rc; } cur += rc; } { if ((rc = DNSSerializer::FromBuffer(tmp_value, cur, src_size - (cur - src))) == -1) { return rc; } else if (tmp_value == 0) { out.ai_next = nullptr; cur += rc; } else if (tmp_value == AddrInfoMagic) { out.ai_next = static_cast<T *>(ams::socket::impl::Alloc(sizeof(T))); if (out.ai_next == nullptr) { rc = -1; return rc; } std::memset(out.ai_next, 0, sizeof(T)); } else { rc = -1; return rc; } } rc = cur - src; return rc; } template<typename T> requires IsAddrInfo<T> ssize_t FromBufferImpl(T &out, const u8 *src, size_t src_size) { ssize_t rc = 0; const u8 *cur = src; const size_t required = DNSSerializer::SizeOf(out); if (src_size < required) { ams::socket::SetLastError(ams::socket::Errno::ENoSpc); rc = -1; return rc; } for (T *addr_info = std::addressof(out); addr_info != nullptr; addr_info = addr_info->ai_next) { if ((rc = FromBufferInternalImpl(*addr_info, cur, src_size - (cur - src))) == -1) { rc = -1; return rc; } cur += rc; } rc = cur - src; return rc; } } template<> size_t DNSSerializer::SizeOf(const struct addrinfo &in) { return SizeOfImpl(in); } template<> size_t DNSSerializer::SizeOf(const ams::socket::AddrInfo &in) { return SizeOfImpl(in); } template<> ssize_t DNSSerializer::ToBuffer(u8 * const dst, size_t dst_size, const ams::socket::AddrInfo &in) { return ToBufferImpl(dst, dst_size, in); } template<> ssize_t DNSSerializer::ToBuffer(u8 * const dst, size_t dst_size, const struct addrinfo &in) { return ToBufferImpl(dst, dst_size, in); } template<> ssize_t DNSSerializer::FromBuffer(ams::socket::AddrInfo &out, const u8 *src, size_t src_size) { return FromBufferImpl(out, src, src_size); } template<> ssize_t DNSSerializer::FromBuffer(struct addrinfo &out, const u8 *src, size_t src_size) { return FromBufferImpl(out, src, src_size); } void FreeAddrInfo(ams::socket::AddrInfo &addr_info) { return FreeAddrInfoImpl(addr_info); } void FreeAddrInfo(struct addrinfo &addr_info) { return FreeAddrInfoImpl(addr_info); } }
16,797
C++
.cpp
374
29.858289
152
0.475326
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,210
serializer_impls_in_addr.cpp
Atmosphere-NX_Atmosphere/stratosphere/ams_mitm/source/dns_mitm/serializer/serializer_impls_in_addr.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have 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 "../dnsmitm_debug.hpp" #include "../socket_allocator.hpp" #include "serializer.hpp" namespace ams::mitm::socket::resolver::serializer { namespace { template<typename T> concept IsInAddr = std::same_as<T, ams::socket::InAddr> || std::same_as<T, struct in_addr>; template<typename T> requires IsInAddr<T> size_t SizeOfImpl(const T &) { return sizeof(u32); } template<typename T> requires IsInAddr<T> size_t SizeOfImpl(const T **in, u32 &out_count) { size_t rc = sizeof(u32); out_count = 0; if (in != nullptr) { for (const T ** cur_addr = in; *cur_addr != nullptr; ++cur_addr) { ++out_count; rc += sizeof(u32); } } return rc; } template<typename T> requires IsInAddr<T> ssize_t ToBufferImpl(u8 * const dst, size_t dst_size, const T &in) { ssize_t rc = -1; u8 *cur = dst; const u32 val = DNSSerializer::InternalHton(in.s_addr); if ((rc = DNSSerializer::CheckToBufferArguments(cur, dst_size, sizeof(in), __LINE__)) == -1) { return rc; } std::memcpy(cur, std::addressof(val), sizeof(val)); rc += sizeof(val); return rc; } template<typename T> requires IsInAddr<T> ssize_t FromBufferImpl(T &out, const u8 *src, size_t src_size) { ssize_t rc = -1; if (src_size < sizeof(out)) { return rc; } std::memset(std::addressof(out), 0, sizeof(out)); out.s_addr = DNSSerializer::InternalNtoh(*reinterpret_cast<const u32 *>(src)); rc = sizeof(u32); return rc; } template<typename T> requires IsInAddr<T> ssize_t ToBufferImpl(u8 * const dst, size_t dst_size, T **arr) { ssize_t rc = -1; u8 *cur = dst; if (arr == nullptr && dst_size < sizeof(u32)) { return rc; } else if (arr == nullptr) { const u32 null = 0; if ((rc = DNSSerializer::ToBuffer(cur, dst_size - (cur - dst), null)) == -1) { return rc; } cur += rc; } else { u32 count = 0; for (auto *tmp = arr; *tmp != nullptr; ++tmp) { ++count; } if ((rc = DNSSerializer::CheckToBufferArguments(cur, dst_size, (count + 1) * sizeof(**arr), __LINE__)) == -1) { return rc; } if ((rc = DNSSerializer::ToBuffer(cur, dst_size - (cur - dst), count)) == -1) { return rc; } cur += rc; rc = 0; for (auto i = 0; arr[i] != nullptr; ++i) { const T addr = *arr[i]; if ((rc = DNSSerializer::ToBuffer(cur, dst_size - (cur - dst), addr)) == -1) { return rc; } cur += rc; } rc = cur - dst; } return rc; } template<typename T> requires IsInAddr<T> ssize_t FromBufferImpl(T **&out, const u8 *src, size_t src_size) { ssize_t rc = -1; const u8 *cur = src; out = nullptr; ON_SCOPE_EXIT { if (rc == -1 && out != nullptr) { for (auto i = 0; out[i] != nullptr; ++i) { ams::socket::impl::Free(out[i]); out[i] = nullptr; } ams::socket::impl::Free(out); out = nullptr; } }; if (src == nullptr) { rc = 0; return rc; } else if (src_size == 0) { rc = 0; return rc; } u32 count = 0; if ((rc = DNSSerializer::FromBuffer(count, cur, src_size)) == -1) { return rc; } cur += rc; if (count == 0) { return rc; } out = static_cast<T **>(ams::socket::impl::Alloc((count + 1) * sizeof(T *))); if (out == nullptr) { rc = -1; return rc; } std::memset(out, 0, (count + 1) * sizeof(T *)); for (u32 i = 0; i < count; ++i) { out[i] = static_cast<T *>(ams::socket::impl::Alloc(sizeof(T))); if (out[i] == nullptr) { rc = -1; return rc; } u32 s_addr = 0; if ((rc = DNSSerializer::FromBuffer(s_addr, cur, src_size - (cur - src))) == -1) { return rc; } out[i]->s_addr = s_addr; cur += rc; } out[count] = nullptr; rc = cur - src; return rc; } } template<> size_t DNSSerializer::SizeOf(const struct in_addr &in) { return SizeOfImpl(in); } template<> size_t DNSSerializer::SizeOf(const ams::socket::InAddr &in) { return SizeOfImpl(in); } template<> size_t DNSSerializer::SizeOf(const struct in_addr **in, u32 &out_count) { return SizeOfImpl(in, out_count); } template<> size_t DNSSerializer::SizeOf(const ams::socket::InAddr **in, u32 &out_count) { return SizeOfImpl(in, out_count); } template<> ssize_t DNSSerializer::ToBuffer(u8 * const dst, size_t dst_size, const struct in_addr &in) { return ToBufferImpl(dst, dst_size, in); } template<> ssize_t DNSSerializer::ToBuffer(u8 * const dst, size_t dst_size, const ams::socket::InAddr &in) { return ToBufferImpl(dst, dst_size, in); } template<> ssize_t DNSSerializer::FromBuffer(struct in_addr &out, const u8 *src, size_t src_size) { return FromBufferImpl(out, src, src_size); } template<> ssize_t DNSSerializer::FromBuffer(struct ams::socket::InAddr &out, const u8 *src, size_t src_size) { return FromBufferImpl(out, src, src_size); } template<> ssize_t DNSSerializer::ToBuffer(u8 * const dst, size_t dst_size, struct in_addr **arr) { return ToBufferImpl(dst, dst_size, arr); } template<> ssize_t DNSSerializer::ToBuffer(u8 * const dst, size_t dst_size, ams::socket::InAddr **arr) { return ToBufferImpl(dst, dst_size, arr); } template<> ssize_t DNSSerializer::FromBuffer(struct in_addr **&out, const u8 *src, size_t src_size) { return FromBufferImpl(out, src, src_size); } template<> ssize_t DNSSerializer::FromBuffer(struct ams::socket::InAddr **&out, const u8 *src, size_t src_size) { return FromBufferImpl(out, src, src_size); } }
7,684
C++
.cpp
189
28.703704
127
0.50517
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,211
serializer_impls_hostent.cpp
Atmosphere-NX_Atmosphere/stratosphere/ams_mitm/source/dns_mitm/serializer/serializer_impls_hostent.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have 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 "../dnsmitm_debug.hpp" #include "../socket_allocator.hpp" #include "serializer.hpp" namespace ams::mitm::socket::resolver::serializer { namespace { template<typename T> concept IsHostEnt = std::same_as<T, ams::socket::HostEnt> || std::same_as<T, struct hostent>; template<typename T> requires IsHostEnt<T> using InAddrType = typename std::conditional<std::same_as<T, ams::socket::HostEnt>, ams::socket::InAddr, struct in_addr>::type; template<typename T> requires IsHostEnt<T> constexpr bool IsAfInet(const auto h_addrtype) { if constexpr (std::same_as<T, ams::socket::HostEnt>) { return h_addrtype == ams::socket::Family::Af_Inet; } else { return h_addrtype == AF_INET; } } template<typename T> requires IsHostEnt<T> constexpr bool IsAfInet6(const auto h_addrtype) { if constexpr (std::same_as<T, ams::socket::HostEnt>) { return h_addrtype == ams::socket::Family::Af_Inet6; } else { return h_addrtype == AF_INET; } } template<typename T> requires IsHostEnt<T> size_t SizeOfImpl(const T &in) { size_t rc = 0; u32 dummy = 0; rc += DNSSerializer::SizeOf((const char *)(in.h_name)); rc += DNSSerializer::SizeOf((const char **)(in.h_aliases), dummy); rc += sizeof(u32); rc += sizeof(u32); rc += DNSSerializer::SizeOf((const InAddrType<T> **)(in.h_addr_list), dummy); return rc; } template<typename T> requires IsHostEnt<T> ssize_t ToBufferImpl(u8 * const dst, size_t dst_size, const T &in) { ssize_t rc = -1; u8 *cur = dst; const size_t required = DNSSerializer::SizeOf(in); if ((rc = DNSSerializer::CheckToBufferArguments(cur, dst_size, required, __LINE__)) == -1) { return rc; } if ((rc = DNSSerializer::ToBuffer(cur, dst_size - (cur - dst), in.h_name)) == -1) { return rc; } cur += rc; if ((rc = DNSSerializer::ToBuffer(cur, dst_size - (cur - dst), in.h_aliases)) == -1) { return rc; } cur += rc; const u16 h_addrtype = static_cast<u16>(in.h_addrtype); if ((rc = DNSSerializer::ToBuffer(cur, dst_size - (cur - dst), h_addrtype)) == -1) { return rc; } cur += rc; const u16 h_length = in.h_length; if ((rc = DNSSerializer::ToBuffer(cur, dst_size - (cur - dst), h_length)) == -1) { return rc; } cur += rc; if (IsAfInet<T>(in.h_addrtype)) { if ((rc = DNSSerializer::ToBuffer(cur, dst_size - (cur - dst), (InAddrType<T> **)(in.h_addr_list))) == -1) { return rc; } } else if (IsAfInet6<T>(in.h_addrtype)) { if ((rc = DNSSerializer::ToBuffer(cur, dst_size - (cur - dst), (InAddrType<T> **)(in.h_addr_list))) == -1) { return rc; } } else { const u32 null = 0; if ((rc = DNSSerializer::ToBuffer(cur, dst_size - (cur - dst), null)) == -1) { return rc; } } cur += rc; rc = cur - dst; return rc; } template<typename T> requires IsHostEnt<T> ssize_t FromBufferImpl(T &out, const u8 *src, size_t src_size) { ssize_t rc = -1; const u8 *cur = src; std::memset(std::addressof(out), 0, sizeof(out)); ON_SCOPE_EXIT { if (rc < 0) { FreeHostent(out); } }; if ((rc = DNSSerializer::FromBuffer(out.h_name, cur, src_size - (cur - src))) == -1) { return rc; } cur += rc; if ((rc = DNSSerializer::FromBuffer(out.h_aliases, cur, src_size - (cur - src))) == -1) { return rc; } cur += rc; u16 h_addrtype = 0; if ((rc = DNSSerializer::FromBuffer(h_addrtype, cur, src_size - (cur - src))) == -1) { return rc; } out.h_addrtype = static_cast<decltype(out.h_addrtype)>(h_addrtype); cur += rc; u16 h_length = 0; if ((rc = DNSSerializer::FromBuffer(h_length, cur, src_size - (cur - src))) == -1) { return rc; } out.h_length = h_length; cur += rc; InAddrType<T> **addrs = nullptr; if ((rc = DNSSerializer::FromBuffer(addrs, cur, src_size - (cur - src))) == -1) { return rc; } out.h_addr_list = (char **)addrs; cur += rc; rc = cur - src; return rc; } template<typename T> requires IsHostEnt<T> void FreeHostentImpl(T &ent) { if (ent.h_name != nullptr) { ams::socket::impl::Free(ent.h_name); ent.h_name = nullptr; } if (ent.h_aliases != nullptr) { u32 i = 0; for (char *str = ent.h_aliases[i]; str != nullptr; str = ent.h_aliases[++i]) { ams::socket::impl::Free(str); ent.h_aliases[i] = nullptr; } ams::socket::impl::Free(ent.h_aliases); ent.h_aliases = nullptr; } if (ent.h_addr_list != nullptr) { AMS_ASSERT(ent.h_length == sizeof(u32)); if (ent.h_length == sizeof(u32)) { auto **addr_list = reinterpret_cast<InAddrType<T> **>(ent.h_addr_list); u32 i = 0; for (auto *addr = addr_list[i]; addr != nullptr; addr = addr_list[++i]) { ams::socket::impl::Free(addr); addr_list[i] = nullptr; } ams::socket::impl::Free(ent.h_addr_list); ent.h_addr_list = nullptr; } } std::memset(std::addressof(ent), 0, sizeof(ent)); } } template<> size_t DNSSerializer::SizeOf(const struct hostent &in) { return SizeOfImpl(in); } template<> ssize_t DNSSerializer::ToBuffer(u8 * const dst, size_t dst_size, const struct hostent &in) { return ToBufferImpl(dst, dst_size, in); } template<> ssize_t DNSSerializer::FromBuffer(struct hostent &out, const u8 *src, size_t src_size) { return FromBufferImpl(out, src, src_size); } template<> size_t DNSSerializer::SizeOf(const ams::socket::HostEnt &in) { return SizeOfImpl(in); } template<> ssize_t DNSSerializer::ToBuffer(u8 * const dst, size_t dst_size, const ams::socket::HostEnt &in) { return ToBufferImpl(dst, dst_size, in); } template<> ssize_t DNSSerializer::FromBuffer(ams::socket::HostEnt &out, const u8 *src, size_t src_size) { return FromBufferImpl(out, src, src_size); } void FreeHostent(ams::socket::HostEnt &ent) { return FreeHostentImpl(ent); } void FreeHostent(struct hostent &ent) { return FreeHostentImpl(ent); } }
8,157
C++
.cpp
191
30.790576
135
0.518995
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,212
serializer_impls_string.cpp
Atmosphere-NX_Atmosphere/stratosphere/ams_mitm/source/dns_mitm/serializer/serializer_impls_string.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have 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 "../dnsmitm_debug.hpp" #include "../socket_allocator.hpp" #include "serializer.hpp" namespace ams::mitm::socket::resolver::serializer { template<> size_t DNSSerializer::SizeOf(const char *str) { if (str == nullptr) { return sizeof(char); } return std::strlen(str) + 1; } template<> size_t DNSSerializer::SizeOf(const char **str, u32 &out_count) { size_t rc = sizeof(u32); out_count = 0; if (str != nullptr) { for (const char **cur = str; *cur != nullptr; ++cur) { ++out_count; rc += SizeOf(*cur); } } return rc; } template<> ssize_t DNSSerializer::ToBuffer(u8 * const dst, size_t dst_size, char *str) { ssize_t rc = -1; u8 *cur = dst; if (str == nullptr && dst_size == 0) { return -1; } else if (str == nullptr) { *cur = '\x00'; return 1; } else if ((rc = SizeOf(static_cast<const char *>(str))) == 0) { *cur = '\x00'; return 1; } else if (CheckToBufferArguments(cur, dst_size, rc + 1, __LINE__) == -1) { return -1; } std::memmove(cur, str, rc); return rc; } template<> ssize_t DNSSerializer::FromBuffer(char *&out, const u8 *src, size_t src_size) { size_t len = 0; if (src == nullptr) { return 0; } else if (src_size == 0) { return 0; } else if (src_size < (len = SizeOf(reinterpret_cast<const char *>(src)))) { return 1; } else if (src[0] == '\x00') { return 1; } out = static_cast<char *>(ams::socket::impl::Alloc(len)); if (out == nullptr) { return -1; } std::memmove(out, src, len); return len; } template<> ssize_t DNSSerializer::ToBuffer(u8 * const dst, size_t dst_size, char **str) { ssize_t rc = -1; u8 *cur = dst; u32 count = 0; if (dst_size == 0) { return -1; } const size_t total_size = SizeOf(const_cast<const char **>(str), count); AMS_UNUSED(total_size); if ((rc = CheckToBufferArguments(cur, dst_size, sizeof(u32), __LINE__)) == -1) { return rc; } else if ((rc = ToBuffer(cur, dst_size, count)) == -1) { return rc; } cur += rc; dst_size -= rc; if (str != nullptr) { for (char **cur_str = str; *cur_str != nullptr; ++cur_str) { const auto tmp = ToBuffer(cur, dst_size, *cur_str); if (tmp == -1) { return rc; } cur += tmp; dst_size -= tmp; rc += tmp; } } rc = cur - dst; return rc; } template<> ssize_t DNSSerializer::FromBuffer(char **&out, const u8 *src, size_t src_size) { ssize_t rc = -1; const u8 *cur = src; u32 count = 0; out = nullptr; ON_SCOPE_EXIT { if (rc < 0 && out != nullptr) { u32 i = 0; for (char *str = *out; str != nullptr; str = out[++i]) { ams::socket::impl::Free(str); } ams::socket::impl::Free(out); out = nullptr; } }; if (src == nullptr) { rc = 0; return rc; } else if (src_size == 0) { rc = 0; return rc; } else if ((rc = FromBuffer(count, cur, src_size)) == -1) { rc = -1; return rc; } cur += rc; out = static_cast<char **>(ams::socket::impl::Alloc((count + 1) * sizeof(char *))); if (out == nullptr) { rc = -1; return rc; } std::memset(out, 0, (count + 1) * sizeof(char *)); u32 i; for (i = 0; i < count; ++i) { const size_t len = std::strlen(reinterpret_cast<const char *>(cur)); out[i] = static_cast<char *>(ams::socket::impl::Alloc(len + 1)); if (out[i] == nullptr) { rc = -1; return rc; } std::memmove(out[i], cur, len + 1); cur += len + 1; } out[i] = nullptr; rc = cur - src; return rc; } }
5,125
C++
.cpp
150
24.42
95
0.486552
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,213
serializer.cpp
Atmosphere-NX_Atmosphere/stratosphere/ams_mitm/source/dns_mitm/serializer/serializer.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have 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 "../dnsmitm_debug.hpp" #include "serializer.hpp" namespace ams::mitm::socket::resolver::serializer { ssize_t DNSSerializer::CheckToBufferArguments(const u8 *dst, size_t dst_size, size_t required, int error_id) { /* TODO: Logging, using error_id */ AMS_UNUSED(error_id); if (dst == nullptr) { return -1; } else if (dst_size < required) { return -1; } return 0; } u32 DNSSerializer::InternalHton(const u32 &v) { return ams::socket::InetHtonl(v); } u16 DNSSerializer::InternalHton(const u16 &v) { return ams::socket::InetHtons(v); } u32 DNSSerializer::InternalNtoh(const u32 &v) { return ams::socket::InetNtohl(v); } u16 DNSSerializer::InternalNtoh(const u16 &v) { return ams::socket::InetNtohs(v); } }
1,526
C++
.cpp
42
31.333333
114
0.678426
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,214
serializer_impls_sockaddrin_6.cpp
Atmosphere-NX_Atmosphere/stratosphere/ams_mitm/source/dns_mitm/serializer/serializer_impls_sockaddrin_6.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have 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 "../dnsmitm_debug.hpp" #include "../socket_allocator.hpp" #include "serializer.hpp" namespace ams::mitm::socket::resolver::serializer { namespace { template<typename T> concept IsSockAddrIn6 = std::same_as<T, struct sockaddr_in6>; template<typename T> requires IsSockAddrIn6<T> size_t SizeOfImpl(const T &in) { size_t rc = 0; rc += sizeof(u16); rc += sizeof(u16); rc += sizeof(u32); rc += DNSSerializer::SizeOf(in.sin6_addr); rc += sizeof(u32); return rc; } template<typename T> requires IsSockAddrIn6<T> ssize_t ToBufferImpl(u8 * const dst, size_t dst_size, const T &in) { ssize_t rc = -1; u8 *cur = dst; if ((rc = DNSSerializer::CheckToBufferArguments(cur, dst_size, sizeof(in), __LINE__)) == -1) { return rc; } const u16 sin6_family = static_cast<u16>(in.sin6_family); if ((rc = DNSSerializer::ToBuffer(cur, dst_size - (cur - dst), sin6_family)) == -1) { return rc; } cur += rc; const u16 sin6_port = static_cast<u16>(in.sin6_port); if ((rc = DNSSerializer::ToBuffer(cur, dst_size - (cur - dst), sin6_port)) == -1) { return rc; } cur += rc; const u32 sin6_flowinfo = static_cast<u32>(in.sin6_flowinfo); if ((rc = DNSSerializer::ToBuffer(cur, dst_size - (cur - dst), sin6_flowinfo)) == -1) { return rc; } cur += rc; std::memcpy(cur, std::addressof(in.sin6_addr), sizeof(in.sin6_addr)); cur += sizeof(in.sin6_addr); const u32 sin6_scope_id = static_cast<u32>(in.sin6_scope_id); if ((rc = DNSSerializer::ToBuffer(cur, dst_size - (cur - dst), sin6_scope_id)) == -1) { return rc; } cur += rc; rc = cur - dst; return rc; } template<typename T> requires IsSockAddrIn6<T> ssize_t FromBufferImpl(T &out, const u8 *src, size_t src_size) { ssize_t rc = -1; const u8 *cur = src; u16 sin6_family; if ((rc = DNSSerializer::FromBuffer(sin6_family, cur, src_size - (cur - src))) == -1) { return rc; } out.sin6_family = static_cast<decltype(out.sin6_family)>(sin6_family); cur += rc; u16 sin6_port; if ((rc = DNSSerializer::FromBuffer(sin6_port, cur, src_size - (cur - src))) == -1) { return rc; } out.sin6_port = static_cast<decltype(out.sin6_port)>(sin6_port); cur += rc; u32 sin6_flowinfo; if ((rc = DNSSerializer::FromBuffer(sin6_flowinfo, cur, src_size - (cur - src))) == -1) { return rc; } out.sin6_flowinfo = static_cast<decltype(out.sin6_flowinfo)>(sin6_flowinfo); cur += rc; std::memcpy(std::addressof(out.sin6_addr), cur, sizeof(out.sin6_addr)); cur += sizeof(out.sin6_addr); u32 sin6_scope_id; if ((rc = DNSSerializer::FromBuffer(sin6_scope_id, cur, src_size - (cur - src))) == -1) { return rc; } out.sin6_scope_id = static_cast<decltype(out.sin6_scope_id)>(sin6_scope_id); cur += rc; rc = cur - src; return rc; } } template<> size_t DNSSerializer::SizeOf(const struct sockaddr_in6 &in) { return SizeOfImpl(in); } template<> ssize_t DNSSerializer::ToBuffer(u8 * const dst, size_t dst_size, const struct sockaddr_in6 &in) { return ToBufferImpl(dst, dst_size, in); } template<> ssize_t DNSSerializer::FromBuffer(struct sockaddr_in6 &out, const u8 *src, size_t src_size) { return FromBufferImpl(out, src, src_size); } }
4,682
C++
.cpp
109
32.688073
112
0.560783
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,215
serializer_impls_ints.cpp
Atmosphere-NX_Atmosphere/stratosphere/ams_mitm/source/dns_mitm/serializer/serializer_impls_ints.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have 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 "../dnsmitm_debug.hpp" #include "serializer.hpp" namespace ams::mitm::socket::resolver::serializer { template<> ssize_t DNSSerializer::ToBuffer(u8 * const dst, size_t dst_size, const u16 &in) { /* Convert the value. */ u8 *cur = dst; const u16 val = InternalHton(in); /* Check arguments. */ ssize_t rc = -1; if ((rc = CheckToBufferArguments(cur, dst_size, sizeof(u16), __LINE__)) == -1) { return rc; } std::memcpy(cur, std::addressof(val), sizeof(u16)); rc += sizeof(u16); return rc; } template<> ssize_t DNSSerializer::FromBuffer(u16 &out, const u8 *src, size_t src_size) { if (src_size < sizeof(u16)) { return -1; } out = InternalNtoh(*reinterpret_cast<const u16 *>(src)); return sizeof(u16); } template<> ssize_t DNSSerializer::ToBuffer(u8 * const dst, size_t dst_size, const u32 &in) { /* Convert the value. */ u8 *cur = dst; const u32 val = InternalHton(in); /* Check arguments. */ ssize_t rc = -1; if ((rc = CheckToBufferArguments(cur, dst_size, sizeof(u32), __LINE__)) == -1) { return rc; } std::memcpy(cur, std::addressof(val), sizeof(u32)); rc += sizeof(u32); return rc; } template<> ssize_t DNSSerializer::FromBuffer(u32 &out, const u8 *src, size_t src_size) { if (src_size < sizeof(u32)) { return -1; } out = InternalNtoh(*reinterpret_cast<const u32 *>(src)); return sizeof(u32); } }
2,421
C++
.cpp
60
31.683333
96
0.582446
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,216
fsmitm_romfs.cpp
Atmosphere-NX_Atmosphere/stratosphere/ams_mitm/source/fs_mitm/fsmitm_romfs.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have 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 "../amsmitm_fs_utils.hpp" #include "fsmitm_romfs.hpp" #include "fsmitm_layered_romfs_storage.hpp" namespace ams::mitm::fs { using namespace ams::fs; namespace romfs { namespace { struct ApplicationWithDynamicHeapInfo { ncm::ProgramId program_id; size_t dynamic_app_heap_size; size_t dynamic_system_heap_size; }; constexpr const ApplicationWithDynamicHeapInfo ApplicationsWithDynamicHeap[] = { /* Animal Crossing: New Horizons. */ /* Requirement ~24 MB. */ /* No particular heap sensitivity. */ { 0x01006F8002326000, 16_MB, 0_MB }, /* Fire Emblem: Engage. */ /* Requirement ~32+ MB. */ /* No particular heap sensitivity. */ { 0x0100A6301214E000, 16_MB, 0_MB }, /* The Legend of Zelda: Tears of the Kingdom. */ /* Requirement ~48 MB. */ /* Game is highly sensitive to memory stolen from application heap. */ /* 1.0.0 tolerates no more than 16 MB stolen. 1.1.0 no more than 12 MB. */ { 0x0100F2C0115B6000, 10_MB, 8_MB }, }; constexpr size_t GetDynamicAppHeapSize(ncm::ProgramId program_id) { for (const auto &info : ApplicationsWithDynamicHeap) { if (info.program_id == program_id) { return info.dynamic_app_heap_size; } } return 0; } constexpr size_t GetDynamicSysHeapSize(ncm::ProgramId program_id) { for (const auto &info : ApplicationsWithDynamicHeap) { if (info.program_id == program_id) { return info.dynamic_system_heap_size; } } return 0; } template<auto MapImpl, auto UnmapImpl> struct DynamicHeap { uintptr_t heap_address{}; size_t heap_size{}; size_t outstanding_allocations{}; util::TypedStorage<mem::StandardAllocator> heap{}; os::SdkMutex release_heap_lock{}; constexpr DynamicHeap() = default; void Map() { if (this->heap_address == 0) { /* NOTE: Lock not necessary, because this is the only location which do 0 -> non-zero. */ R_ABORT_UNLESS(MapImpl(std::addressof(this->heap_address), this->heap_size)); AMS_ABORT_UNLESS(this->heap_address != 0); /* Create heap. */ util::ConstructAt(this->heap, reinterpret_cast<void *>(this->heap_address), this->heap_size); } } void TryRelease() { if (this->outstanding_allocations == 0) { std::scoped_lock lk(this->release_heap_lock); if (this->heap_address != 0) { util::DestroyAt(this->heap); this->heap = {}; R_ABORT_UNLESS(UnmapImpl(this->heap_address, this->heap_size)); this->heap_address = 0; } } } void *Allocate(size_t size) { void * const ret = util::GetReference(this->heap).Allocate(size); if (AMS_LIKELY(ret != nullptr)) { ++this->outstanding_allocations; } return ret; } bool TryFree(void *p) { if (this->IsAllocated(p)) { --this->outstanding_allocations; util::GetReference(this->heap).Free(p); return true; } else { return false; } } bool IsAllocated(void *p) const { const uintptr_t address = reinterpret_cast<uintptr_t>(p); return this->heap_address != 0 && (this->heap_address <= address && address < this->heap_address + this->heap_size); } void Reset() { /* This should require no remaining allocations. */ AMS_ABORT_UNLESS(this->outstanding_allocations == 0); /* Free the heap. */ this->TryRelease(); AMS_ABORT_UNLESS(this->heap_address == 0); /* Clear the heap size. */ this->heap_size = 0; } }; Result MapByHeap(uintptr_t *out, size_t size) { R_TRY(os::SetMemoryHeapSize(size)); R_RETURN(os::AllocateMemoryBlock(out, size)); } Result UnmapByHeap(uintptr_t address, size_t size) { os::FreeMemoryBlock(address, size); R_RETURN(os::SetMemoryHeapSize(0)); } /* Dynamic allocation globals. */ constinit os::SdkMutex g_romfs_build_lock; constinit ncm::ProgramId g_dynamic_heap_program_id{}; constinit bool g_building_from_dynamic_heap = false; constinit DynamicHeap<os::AllocateUnsafeMemory, os::FreeUnsafeMemory> g_dynamic_app_heap; constinit DynamicHeap<MapByHeap, UnmapByHeap> g_dynamic_sys_heap; void InitializeDynamicHeapForBuildRomfs(ncm::ProgramId program_id) { if (program_id == g_dynamic_heap_program_id && g_dynamic_app_heap.heap_size > 0) { /* This romfs will build out of dynamic heap. */ g_building_from_dynamic_heap = true; g_dynamic_app_heap.Map(); if (g_dynamic_sys_heap.heap_size > 0) { g_dynamic_sys_heap.Map(); } } } void FinalizeDynamicHeapForBuildRomfs() { /* We are definitely no longer building out of dynamic heap. */ g_building_from_dynamic_heap = false; g_dynamic_app_heap.TryRelease(); } } void *AllocateTracked(AllocationType type, size_t size) { AMS_UNUSED(type); if (g_building_from_dynamic_heap) { void *ret = g_dynamic_app_heap.Allocate(size); if (ret == nullptr && g_dynamic_sys_heap.heap_address != 0) { ret = g_dynamic_sys_heap.Allocate(size); } if (ret == nullptr) { ret = std::malloc(size); } return ret; } else { return std::malloc(size); } } void FreeTracked(AllocationType type, void *p, size_t size) { AMS_UNUSED(type); AMS_UNUSED(size); if (g_dynamic_app_heap.TryFree(p)) { if (!g_building_from_dynamic_heap) { g_dynamic_app_heap.TryRelease(); } } else if (g_dynamic_sys_heap.TryFree(p)) { if (!g_building_from_dynamic_heap) { g_dynamic_sys_heap.TryRelease(); } } else { std::free(p); } } namespace { constexpr u32 EmptyEntry = 0xFFFFFFFF; constexpr size_t FilePartitionOffset = 0x200; struct Header { s64 header_size; s64 dir_hash_table_ofs; s64 dir_hash_table_size; s64 dir_table_ofs; s64 dir_table_size; s64 file_hash_table_ofs; s64 file_hash_table_size; s64 file_table_ofs; s64 file_table_size; s64 file_partition_ofs; }; static_assert(util::is_pod<Header>::value && sizeof(Header) == 0x50); struct DirectoryEntry { u32 parent; u32 sibling; u32 child; u32 file; u32 hash; u32 name_size; char name[]; }; static_assert(util::is_pod<DirectoryEntry>::value && sizeof(DirectoryEntry) == 0x18); struct FileEntry { u32 parent; u32 sibling; s64 offset; s64 size; u32 hash; u32 name_size; char name[]; }; static_assert(util::is_pod<FileEntry>::value && sizeof(FileEntry) == 0x20); class DynamicTableCache { NON_COPYABLE(DynamicTableCache); NON_MOVEABLE(DynamicTableCache); private: static constexpr size_t MaxCachedSize = (1_MB / 4); private: size_t m_cache_bitsize; size_t m_cache_size; protected: void *m_cache; protected: DynamicTableCache(size_t sz) { m_cache_size = util::CeilingPowerOfTwo(std::min(sz, MaxCachedSize)); m_cache = AllocateTracked(AllocationType_TableCache, m_cache_size); while (m_cache == nullptr) { m_cache_size >>= 1; AMS_ABORT_UNLESS(m_cache_size >= 16_KB); m_cache = AllocateTracked(AllocationType_TableCache, m_cache_size); } m_cache_bitsize = util::CountTrailingZeros(m_cache_size); } ~DynamicTableCache() { FreeTracked(AllocationType_TableCache, m_cache, m_cache_size); } ALWAYS_INLINE size_t GetCacheSize() const { return static_cast<size_t>(1) << m_cache_bitsize; } }; class HashTableStorage : public DynamicTableCache { public: HashTableStorage(size_t sz) : DynamicTableCache(sz) { /* ... */ } ALWAYS_INLINE u32 *GetBuffer() { return reinterpret_cast<u32 *>(m_cache); } ALWAYS_INLINE size_t GetBufferSize() const { return DynamicTableCache::GetCacheSize(); } }; template<typename Entry> class TableReader : public DynamicTableCache { NON_COPYABLE(TableReader); NON_MOVEABLE(TableReader); private: static constexpr size_t FallbackCacheSize = 1_KB; private: ams::fs::IStorage *m_storage; size_t m_offset; size_t m_size; size_t m_cache_idx; u8 m_fallback_cache[FallbackCacheSize]; private: ALWAYS_INLINE bool Read(size_t ofs, void *dst, size_t size) { R_TRY_CATCH(m_storage->Read(m_offset + ofs, dst, size)) { R_CATCH(fs::ResultNcaExternalKeyNotFound) { return false; } } R_END_TRY_CATCH_WITH_ABORT_UNLESS; return true; } ALWAYS_INLINE bool ReloadCacheImpl(size_t idx) { const size_t rel_ofs = idx * this->GetCacheSize(); AMS_ABORT_UNLESS(rel_ofs < m_size); const size_t new_cache_size = std::min(m_size - rel_ofs, this->GetCacheSize()); if (!this->Read(rel_ofs, m_cache, new_cache_size)) { return false; } m_cache_idx = idx; return true; } ALWAYS_INLINE bool ReloadCache(size_t idx) { if (m_cache_idx != idx) { if (!this->ReloadCacheImpl(idx)) { return false; } } return true; } ALWAYS_INLINE size_t GetCacheIndex(u32 ofs) { return ofs / this->GetCacheSize(); } public: TableReader(ams::fs::IStorage *s, size_t ofs, size_t sz) : DynamicTableCache(sz), m_storage(s), m_offset(ofs), m_size(sz), m_cache_idx(0) { AMS_ABORT_UNLESS(m_cache != nullptr); this->ReloadCacheImpl(0); } const Entry *GetEntry(u32 entry_offset) { if (!this->ReloadCache(this->GetCacheIndex(entry_offset))) { return nullptr; } const size_t ofs = entry_offset % this->GetCacheSize(); const Entry *entry = reinterpret_cast<const Entry *>(reinterpret_cast<uintptr_t>(m_cache) + ofs); if (AMS_UNLIKELY(this->GetCacheIndex(entry_offset) != this->GetCacheIndex(entry_offset + sizeof(Entry) + entry->name_size + sizeof(u32)))) { if (!this->Read(entry_offset, m_fallback_cache, std::min(m_size - entry_offset, FallbackCacheSize))) { return nullptr; } entry = reinterpret_cast<const Entry *>(m_fallback_cache); } return entry; } }; template<typename Entry> class TableWriter : public DynamicTableCache { NON_COPYABLE(TableWriter); NON_MOVEABLE(TableWriter); private: static constexpr size_t FallbackCacheSize = 1_KB; private: ::FsFile *m_file; size_t m_offset; size_t m_size; size_t m_cache_idx; u8 m_fallback_cache[FallbackCacheSize]; size_t m_fallback_cache_entry_offset; size_t m_fallback_cache_entry_size; bool m_cache_dirty; bool m_fallback_cache_dirty; private: ALWAYS_INLINE void Read(size_t ofs, void *dst, size_t sz) { u64 read_size; R_ABORT_UNLESS(fsFileRead(m_file, m_offset + ofs, dst, sz, 0, std::addressof(read_size))); AMS_ABORT_UNLESS(read_size == sz); } ALWAYS_INLINE void Write(size_t ofs, const void *src, size_t sz) { R_ABORT_UNLESS(fsFileWrite(m_file, m_offset + ofs, src, sz, FsWriteOption_None)); } ALWAYS_INLINE void Flush() { AMS_ABORT_UNLESS(!(m_cache_dirty && m_fallback_cache_dirty)); if (m_cache_dirty) { const size_t ofs = m_cache_idx * this->GetCacheSize(); this->Write(ofs, m_cache, std::min(m_size - ofs, this->GetCacheSize())); m_cache_dirty = false; } if (m_fallback_cache_dirty) { this->Write(m_fallback_cache_entry_offset, m_fallback_cache, m_fallback_cache_entry_size); m_fallback_cache_dirty = false; } } ALWAYS_INLINE size_t GetCacheIndex(u32 ofs) { return ofs / this->GetCacheSize(); } ALWAYS_INLINE void RefreshCacheImpl() { const size_t cur_cache = m_cache_idx * this->GetCacheSize(); this->Read(cur_cache, m_cache, std::min(m_size - cur_cache, this->GetCacheSize())); } ALWAYS_INLINE void RefreshCache(u32 entry_offset) { if (size_t idx = this->GetCacheIndex(entry_offset); idx != m_cache_idx || m_fallback_cache_dirty) { this->Flush(); m_cache_idx = idx; this->RefreshCacheImpl(); } } public: TableWriter(::FsFile *f, size_t ofs, size_t sz) : DynamicTableCache(sz), m_file(f), m_offset(ofs), m_size(sz), m_cache_idx(0), m_fallback_cache_entry_offset(), m_fallback_cache_entry_size(), m_cache_dirty(), m_fallback_cache_dirty() { AMS_ABORT_UNLESS(m_cache != nullptr); std::memset(m_cache, 0, this->GetCacheSize()); std::memset(m_fallback_cache, 0, sizeof(m_fallback_cache)); for (size_t cur = 0; cur < m_size; cur += this->GetCacheSize()) { this->Write(cur, m_cache, std::min(m_size - cur, this->GetCacheSize())); } } ~TableWriter() { this->Flush(); } Entry *GetEntry(u32 entry_offset, u32 name_len) { this->RefreshCache(entry_offset); const size_t ofs = entry_offset % this->GetCacheSize(); Entry *entry = reinterpret_cast<Entry *>(reinterpret_cast<uintptr_t>(m_cache) + ofs); if (ofs + sizeof(Entry) + util::AlignUp(name_len, sizeof(u32)) > this->GetCacheSize()) { this->Flush(); m_fallback_cache_entry_offset = entry_offset; m_fallback_cache_entry_size = sizeof(Entry) + util::AlignUp(name_len, sizeof(u32)); this->Read(m_fallback_cache_entry_offset, m_fallback_cache, m_fallback_cache_entry_size); entry = reinterpret_cast<Entry *>(m_fallback_cache); m_fallback_cache_dirty = true; } else { m_cache_dirty = true; } return entry; } }; using DirectoryTableWriter = TableWriter<DirectoryEntry>; using FileTableWriter = TableWriter<FileEntry>; constexpr inline u32 CalculatePathHash(u32 parent, const char *path, u32 start, size_t path_len) { u32 hash = parent ^ 123456789; for (size_t i = 0; i < path_len; i++) { hash = (hash >> 5) | (hash << 27); hash ^= static_cast<unsigned char>(path[start + i]); } return hash; } constexpr inline size_t GetHashTableSize(size_t num_entries) { if (num_entries < 3) { return 3; } else if (num_entries < 19) { return num_entries | 1; } else { size_t count = num_entries; while ((count % 2 == 0) || (count % 3 == 0) || (count % 5 == 0) || (count % 7 == 0) || (count % 11 == 0) || (count % 13 == 0) || (count % 17 == 0)) { count++; } return count; } } 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); parent->GetPath(g_fs_romfs_path_buffer); R_ABORT_UNLESS(mitm::fs::OpenAtmosphereRomfsDirectory(out, program_id, g_fs_romfs_path_buffer, mode, fs)); } } Builder::Builder(ncm::ProgramId pr_id) : m_program_id(pr_id), m_num_dirs(0), m_num_files(0), m_dir_table_size(0), m_file_table_size(0), m_dir_hash_table_size(0), m_file_hash_table_size(0), m_file_partition_size(0) { /* Ensure only one romfs is built at any time. */ g_romfs_build_lock.Lock(); /* If we should be using dynamic heap, turn it on. */ InitializeDynamicHeapForBuildRomfs(m_program_id); auto res = m_directories.emplace(std::unique_ptr<BuildDirectoryContext>(AllocateTyped<BuildDirectoryContext>(AllocationType_BuildDirContext, BuildDirectoryContext::RootTag{}))); AMS_ABORT_UNLESS(res.second); m_root = res.first->get(); m_num_dirs = 1; m_dir_table_size = 0x18; } Builder::~Builder() { /* If we have nothing remaining in dynamic heap, release it. */ FinalizeDynamicHeapForBuildRomfs(); /* Release the romfs build lock. */ g_romfs_build_lock.Unlock(); } void Builder::AddDirectory(BuildDirectoryContext **out, BuildDirectoryContext *parent_ctx, std::unique_ptr<BuildDirectoryContext> child_ctx) { /* Set parent context member. */ child_ctx->parent = parent_ctx; /* Check if the directory already exists. */ auto existing = m_directories.find(child_ctx); if (existing != m_directories.end()) { *out = existing->get(); return; } /* Add a new directory. */ m_num_dirs++; m_dir_table_size += sizeof(DirectoryEntry) + util::AlignUp(child_ctx->path_len, 4); *out = child_ctx.get(); m_directories.emplace(std::move(child_ctx)); } void Builder::AddFile(BuildDirectoryContext *parent_ctx, std::unique_ptr<BuildFileContext> file_ctx) { /* Set parent context member. */ file_ctx->parent = parent_ctx; /* Check if the file already exists. */ if (m_files.find(file_ctx) != m_files.end()) { return; } /* Add a new file. */ m_num_files++; m_file_table_size += sizeof(FileEntry) + util::AlignUp(file_ctx->path_len, 4); m_files.emplace(std::move(file_ctx)); } void Builder::VisitDirectory(FsFileSystem *fs, BuildDirectoryContext *parent) { FsDir dir; /* Get number of child directories. */ s64 num_child_dirs = 0; { OpenFileSystemRomfsDirectory(std::addressof(dir), m_program_id, parent, OpenDirectoryMode_Directory, fs); ON_SCOPE_EXIT { fsDirClose(std::addressof(dir)); }; R_ABORT_UNLESS(fsDirGetEntryCount(std::addressof(dir), std::addressof(num_child_dirs))); } AMS_ABORT_UNLESS(num_child_dirs >= 0); { BuildDirectoryContext **child_dirs = num_child_dirs != 0 ? reinterpret_cast<BuildDirectoryContext **>(AllocateTracked(AllocationType_DirPointerArray, sizeof(BuildDirectoryContext *) * num_child_dirs)) : nullptr; AMS_ABORT_UNLESS(num_child_dirs == 0 || child_dirs != nullptr); ON_SCOPE_EXIT { if (child_dirs != nullptr) { FreeTracked(AllocationType_DirPointerArray, child_dirs, sizeof(BuildDirectoryContext *) * num_child_dirs); } }; s64 cur_child_dir_ind = 0; { OpenFileSystemRomfsDirectory(std::addressof(dir), m_program_id, parent, OpenDirectoryMode_All, fs); ON_SCOPE_EXIT { fsDirClose(std::addressof(dir)); }; s64 read_entries = 0; while (true) { R_ABORT_UNLESS(fsDirRead(std::addressof(dir), std::addressof(read_entries), 1, std::addressof(m_dir_entry))); if (read_entries != 1) { break; } AMS_ABORT_UNLESS(m_dir_entry.type == FsDirEntryType_Dir || m_dir_entry.type == FsDirEntryType_File); if (m_dir_entry.type == FsDirEntryType_Dir) { AMS_ABORT_UNLESS(child_dirs != nullptr); BuildDirectoryContext *real_child = nullptr; this->AddDirectory(std::addressof(real_child), parent, std::unique_ptr<BuildDirectoryContext>(AllocateTyped<BuildDirectoryContext>(AllocationType_BuildDirContext, m_dir_entry.name, strlen(m_dir_entry.name)))); AMS_ABORT_UNLESS(real_child != nullptr); child_dirs[cur_child_dir_ind++] = real_child; AMS_ABORT_UNLESS(cur_child_dir_ind <= num_child_dirs); } else /* if (m_dir_entry.type == FsDirEntryType_File) */ { this->AddFile(parent, std::unique_ptr<BuildFileContext>(AllocateTyped<BuildFileContext>(AllocationType_BuildFileContext, m_dir_entry.name, strlen(m_dir_entry.name), m_dir_entry.file_size, 0, m_cur_source_type))); } } } AMS_ABORT_UNLESS(num_child_dirs == cur_child_dir_ind); for (s64 i = 0; i < num_child_dirs; i++) { this->VisitDirectory(fs, child_dirs[i]); } } } class DirectoryTableReader : public TableReader<DirectoryEntry> { public: DirectoryTableReader(ams::fs::IStorage *s, size_t ofs, size_t sz) : TableReader(s, ofs, sz) { /* ... */ } }; class FileTableReader : public TableReader<FileEntry> { public: FileTableReader(ams::fs::IStorage *s, size_t ofs, size_t sz) : TableReader(s, ofs, sz) { /* ... */ } }; void Builder::VisitDirectory(BuildDirectoryContext *parent, u32 parent_offset, DirectoryTableReader &dir_table, FileTableReader &file_table) { const DirectoryEntry *parent_entry = dir_table.GetEntry(parent_offset); if (AMS_UNLIKELY(parent_entry == nullptr)) { return; } u32 cur_file_offset = parent_entry->file; while (cur_file_offset != EmptyEntry) { const FileEntry *cur_file = file_table.GetEntry(cur_file_offset); if (AMS_UNLIKELY(cur_file == nullptr)) { return; } this->AddFile(parent, std::unique_ptr<BuildFileContext>(AllocateTyped<BuildFileContext>(AllocationType_BuildFileContext, cur_file->name, cur_file->name_size, cur_file->size, cur_file->offset, m_cur_source_type))); cur_file_offset = cur_file->sibling; } u32 cur_child_offset = parent_entry->child; while (cur_child_offset != EmptyEntry) { BuildDirectoryContext *real_child = nullptr; u32 next_child_offset = 0; { const DirectoryEntry *cur_child = dir_table.GetEntry(cur_child_offset); if (AMS_UNLIKELY(cur_child == nullptr)) { return; } this->AddDirectory(std::addressof(real_child), parent, std::unique_ptr<BuildDirectoryContext>(AllocateTyped<BuildDirectoryContext>(AllocationType_BuildDirContext, cur_child->name, cur_child->name_size))); AMS_ABORT_UNLESS(real_child != nullptr); next_child_offset = cur_child->sibling; __asm__ __volatile__("" ::: "memory"); } this->VisitDirectory(real_child, cur_child_offset, dir_table, file_table); cur_child_offset = next_child_offset; } } void Builder::AddSdFiles() { /* Open Sd Card filesystem. */ FsFileSystem sd_filesystem; R_ABORT_UNLESS(fsOpenSdCardFileSystem(std::addressof(sd_filesystem))); ON_SCOPE_EXIT { fsFsClose(std::addressof(sd_filesystem)); }; /* If there is no romfs folder on the SD, don't bother continuing. */ { FsDir dir; if (R_FAILED(mitm::fs::OpenAtmosphereRomfsDirectory(std::addressof(dir), m_program_id, m_root->path, OpenDirectoryMode_Directory, std::addressof(sd_filesystem)))) { return; } fsDirClose(std::addressof(dir)); } m_cur_source_type = DataSourceType::LooseSdFile; this->VisitDirectory(std::addressof(sd_filesystem), m_root); } void Builder::AddStorageFiles(ams::fs::IStorage *storage, DataSourceType source_type) { Header header; R_ABORT_UNLESS(storage->Read(0, std::addressof(header), sizeof(Header))); AMS_ABORT_UNLESS(header.header_size == sizeof(Header)); /* Read tables. */ DirectoryTableReader dir_table(storage, header.dir_table_ofs, header.dir_table_size); FileTableReader file_table(storage, header.file_table_ofs, header.file_table_size); m_cur_source_type = source_type; this->VisitDirectory(m_root, 0x0, dir_table, file_table); } void Builder::Build(SourceInfoVector *out_infos) { /* Clear output. */ out_infos->clear(); /* Open an SD card filesystem. */ FsFileSystem sd_filesystem; R_ABORT_UNLESS(fsOpenSdCardFileSystem(std::addressof(sd_filesystem))); ON_SCOPE_EXIT { fsFsClose(std::addressof(sd_filesystem)); }; /* Calculate hash table sizes. */ const size_t num_dir_hash_table_entries = GetHashTableSize(m_num_dirs); const size_t num_file_hash_table_entries = GetHashTableSize(m_num_files); m_dir_hash_table_size = sizeof(u32) * num_dir_hash_table_entries; m_file_hash_table_size = sizeof(u32) * num_file_hash_table_entries; /* Allocate metadata, make pointers. */ Header *header = reinterpret_cast<Header *>(AllocateTracked(AllocationType_Memory, sizeof(Header))); std::memset(header, 0x00, sizeof(*header)); /* Open metadata file. */ const size_t metadata_size = m_dir_hash_table_size + m_dir_table_size + m_file_hash_table_size + m_file_table_size; FsFile metadata_file; R_ABORT_UNLESS(mitm::fs::CreateAndOpenAtmosphereSdFile(std::addressof(metadata_file), m_program_id, "romfs_metadata.bin", metadata_size)); /* Ensure later hash tables will have correct defaults. */ static_assert(EmptyEntry == 0xFFFFFFFF); /* Emplace metadata source info. */ out_infos->emplace_back(0, sizeof(*header), DataSourceType::Memory, header); /* Process Files. */ { u32 entry_offset = 0; BuildFileContext *cur_file = nullptr; BuildFileContext *prev_file = nullptr; for (const auto &it : m_files) { cur_file = it.get(); /* By default, pad to 0x10 alignment. */ m_file_partition_size = util::AlignUp(m_file_partition_size, 0x10); /* Check if extra padding is present in original source, preserve it to make our life easier. */ const bool is_storage_or_file = cur_file->source_type == DataSourceType::Storage || cur_file->source_type == DataSourceType::File; if (prev_file != nullptr && prev_file->source_type == cur_file->source_type && is_storage_or_file) { const s64 expected = m_file_partition_size - prev_file->offset + prev_file->orig_offset; if (expected != cur_file->orig_offset) { AMS_ABORT_UNLESS(expected <= cur_file->orig_offset); m_file_partition_size += cur_file->orig_offset - expected; } } /* Calculate offsets. */ cur_file->offset = m_file_partition_size; m_file_partition_size += cur_file->size; cur_file->entry_offset = entry_offset; entry_offset += sizeof(FileEntry) + util::AlignUp(cur_file->path_len, 4); /* Save current file as prev for next iteration. */ prev_file = cur_file; } /* Assign deferred parent/sibling ownership. */ for (auto it = m_files.rbegin(); it != m_files.rend(); it++) { cur_file = it->get(); cur_file->sibling = cur_file->parent->file; cur_file->parent->file = cur_file; } } /* Process Directories. */ { u32 entry_offset = 0; BuildDirectoryContext *cur_dir = nullptr; for (const auto &it : m_directories) { cur_dir = it.get(); cur_dir->entry_offset = entry_offset; entry_offset += sizeof(DirectoryEntry) + util::AlignUp(cur_dir->path_len, 4); } /* Assign deferred parent/sibling ownership. */ for (auto it = m_directories.rbegin(); it != m_directories.rend(); it++) { cur_dir = it->get(); if (cur_dir == m_root) { continue; } cur_dir->sibling = cur_dir->parent->child; cur_dir->parent->child = cur_dir; } } /* Set all files' hash value = hash index. */ for (const auto &it : m_files) { BuildFileContext *cur_file = it.get(); cur_file->hash_value = CalculatePathHash(cur_file->parent->entry_offset, cur_file->path, 0, cur_file->path_len) % num_file_hash_table_entries; } /* Set all directories' hash value = hash index. */ for (const auto &it : m_directories) { BuildDirectoryContext *cur_dir = it.get(); cur_dir->hash_value = CalculatePathHash(cur_dir == m_root ? 0 : cur_dir->parent->entry_offset, cur_dir->path, 0, cur_dir->path_len) % num_dir_hash_table_entries; } /* Write hash tables. */ { HashTableStorage hash_table_storage(std::max(m_dir_hash_table_size, m_file_hash_table_size)); u32 *hash_table = hash_table_storage.GetBuffer(); size_t hash_table_size = hash_table_storage.GetBufferSize(); /* Write the file hash table. */ for (size_t ofs = 0; ofs < m_file_hash_table_size; ofs += hash_table_size) { std::memset(hash_table, 0xFF, hash_table_size); const u32 ofs_ind = ofs / sizeof(u32); const u32 end_ind = (ofs + hash_table_size) / sizeof(u32); for (const auto &it : m_files) { BuildFileContext *cur_file = it.get(); if (cur_file->HasHashMark()) { continue; } if (const auto hash_ind = cur_file->hash_value; ofs_ind <= hash_ind && hash_ind < end_ind) { cur_file->hash_value = hash_table[hash_ind - ofs_ind]; hash_table[hash_ind - ofs_ind] = cur_file->entry_offset; cur_file->SetHashMark(); } } R_ABORT_UNLESS(fsFileWrite(std::addressof(metadata_file), m_dir_hash_table_size + m_dir_table_size + ofs, hash_table, std::min(m_file_hash_table_size - ofs, hash_table_size), FsWriteOption_None)); } /* Write the directory hash table. */ for (size_t ofs = 0; ofs < m_dir_hash_table_size; ofs += hash_table_size) { std::memset(hash_table, 0xFF, hash_table_size); const u32 ofs_ind = ofs / sizeof(u32); const u32 end_ind = (ofs + hash_table_size) / sizeof(u32); for (const auto &it : m_directories) { BuildDirectoryContext *cur_dir = it.get(); if (cur_dir->HasHashMark()) { continue; } if (const auto hash_ind = cur_dir->hash_value; ofs_ind <= hash_ind && hash_ind < end_ind) { cur_dir->hash_value = hash_table[hash_ind - ofs_ind]; hash_table[hash_ind - ofs_ind] = cur_dir->entry_offset; cur_dir->SetHashMark(); } } R_ABORT_UNLESS(fsFileWrite(std::addressof(metadata_file), ofs, hash_table, std::min(m_dir_hash_table_size - ofs, hash_table_size), FsWriteOption_None)); } } /* Replace sibling pointers with sibling entry_offsets, so that we can de-allocate as we go. */ { /* Set all directories sibling and file pointers. */ for (const auto &it : m_directories) { BuildDirectoryContext *cur_dir = it.get(); cur_dir->ClearHashMark(); cur_dir->sibling_offset = (cur_dir->sibling == nullptr) ? EmptyEntry : cur_dir->sibling->entry_offset; cur_dir->child_offset = (cur_dir->child == nullptr) ? EmptyEntry : cur_dir->child->entry_offset; cur_dir->file_offset = (cur_dir->file == nullptr) ? EmptyEntry : cur_dir->file->entry_offset; cur_dir->parent_offset = cur_dir == m_root ? 0 : cur_dir->parent->entry_offset; } /* Replace all files' sibling pointers. */ for (const auto &it : m_files) { BuildFileContext *cur_file = it.get(); cur_file->ClearHashMark(); cur_file->sibling_offset = (cur_file->sibling == nullptr) ? EmptyEntry : cur_file->sibling->entry_offset; } } /* Write the file table. */ { FileTableWriter file_table(std::addressof(metadata_file), m_dir_hash_table_size + m_dir_table_size + m_file_hash_table_size, m_file_table_size); for (auto it = m_files.begin(); it != m_files.end(); it = m_files.erase(it)) { BuildFileContext *cur_file = it->get(); FileEntry *cur_entry = file_table.GetEntry(cur_file->entry_offset, cur_file->path_len); /* Set entry fields. */ cur_entry->parent = cur_file->parent->entry_offset; cur_entry->sibling = cur_file->sibling_offset; cur_entry->offset = cur_file->offset; cur_entry->size = cur_file->size; cur_entry->hash = cur_file->hash_value; /* Set name. */ const u32 name_size = cur_file->path_len; cur_entry->name_size = name_size; if (name_size) { std::memcpy(cur_entry->name, cur_file->path, name_size); for (size_t i = name_size; i < util::AlignUp(name_size, 4); i++) { cur_entry->name[i] = 0; } } /* Emplace a source. */ switch (cur_file->source_type) { case DataSourceType::Storage: case DataSourceType::File: { /* Try to compact if possible. */ auto &back = out_infos->back(); if (back.source_type == cur_file->source_type) { back.size = cur_file->offset + FilePartitionOffset + cur_file->size - back.virtual_offset; } else { out_infos->emplace_back(cur_file->offset + FilePartitionOffset, cur_file->size, cur_file->source_type, cur_file->orig_offset + FilePartitionOffset); } } break; case DataSourceType::LooseSdFile: { char full_path[fs::EntryNameLengthMax + 1]; const size_t path_needed_size = cur_file->GetPathLength() + 1; AMS_ABORT_UNLESS(path_needed_size <= sizeof(full_path)); cur_file->GetPath(full_path); FreeTracked(AllocationType_FileName, cur_file->path, cur_file->path_len + 1); cur_file->path = nullptr; char *new_path = static_cast<char *>(AllocateTracked(AllocationType_FullPath, path_needed_size)); std::memcpy(new_path, full_path, path_needed_size); out_infos->emplace_back(cur_file->offset + FilePartitionOffset, cur_file->size, cur_file->source_type, new_path); } break; AMS_UNREACHABLE_DEFAULT_CASE(); } } } /* Write the directory table. */ { DirectoryTableWriter dir_table(std::addressof(metadata_file), m_dir_hash_table_size, m_dir_table_size); for (auto it = m_directories.begin(); it != m_directories.end(); it = m_directories.erase(it)) { BuildDirectoryContext *cur_dir = it->get(); DirectoryEntry *cur_entry = dir_table.GetEntry(cur_dir->entry_offset, cur_dir->path_len); /* Set entry fields. */ cur_entry->parent = cur_dir->parent_offset; cur_entry->sibling = cur_dir->sibling_offset; cur_entry->child = cur_dir->child_offset; cur_entry->file = cur_dir->file_offset; cur_entry->hash = cur_dir->hash_value; /* Set name. */ const u32 name_size = cur_dir->path_len; cur_entry->name_size = name_size; if (name_size) { std::memcpy(cur_entry->name, cur_dir->path, name_size); for (size_t i = name_size; i < util::AlignUp(name_size, 4); i++) { cur_entry->name[i] = 0; } } } } /* Delete maps. */ m_root = nullptr; m_directories.clear(); m_files.clear(); /* Set header fields. */ header->header_size = sizeof(*header); header->file_hash_table_size = m_file_hash_table_size; header->file_table_size = m_file_table_size; header->dir_hash_table_size = m_dir_hash_table_size; header->dir_table_size = m_dir_table_size; header->file_partition_ofs = FilePartitionOffset; header->dir_hash_table_ofs = util::AlignUp(FilePartitionOffset + m_file_partition_size, 4); header->dir_table_ofs = header->dir_hash_table_ofs + header->dir_hash_table_size; header->file_hash_table_ofs = header->dir_table_ofs + header->dir_table_size; header->file_table_ofs = header->file_hash_table_ofs + header->file_hash_table_size; /* Save metadata to the SD card, to save on memory space. */ { R_ABORT_UNLESS(fsFileFlush(std::addressof(metadata_file))); out_infos->emplace_back(header->dir_hash_table_ofs, metadata_size, DataSourceType::Metadata, new RemoteFile(metadata_file)); } } Result ConfigureDynamicHeap(u64 *out_size, ncm::ProgramId program_id, const cfg::OverrideStatus &status, bool is_application) { /* Baseline: use no dynamic heap. */ *out_size = 0; /* If the process is not an application, we do not care about dynamic heap. */ R_SUCCEED_IF(!is_application); /* First, we need to ensure that, if the game used dynamic heap, we clear it. */ if (g_dynamic_app_heap.heap_size > 0) { mitm::fs::FinalizeLayeredRomfsStorage(g_dynamic_heap_program_id); /* Free the heap. */ g_dynamic_app_heap.Reset(); g_dynamic_sys_heap.Reset(); } /* Next, if we aren't going to end up building a romfs, we can ignore dynamic heap. */ R_SUCCEED_IF(!status.IsProgramSpecific()); /* Only mitm if there is actually an override romfs. */ R_SUCCEED_IF(!mitm::fs::HasSdRomfsContent(program_id)); /* Next, set the new program id for dynamic heap. */ g_dynamic_heap_program_id = program_id; g_dynamic_app_heap.heap_size = GetDynamicAppHeapSize(g_dynamic_heap_program_id); g_dynamic_sys_heap.heap_size = GetDynamicSysHeapSize(g_dynamic_heap_program_id); /* Set output. */ *out_size = g_dynamic_app_heap.heap_size; R_SUCCEED(); } } }
46,971
C++
.cpp
843
37.117438
254
0.501524
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,217
fs_mitm_service.cpp
Atmosphere-NX_Atmosphere/stratosphere/ams_mitm/source/fs_mitm/fs_mitm_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 "../amsmitm_fs_utils.hpp" #include "../amsmitm_initialization.hpp" #include "fs_shim.h" #include "fs_mitm_service.hpp" #include "fsmitm_boot0storage.hpp" #include "fsmitm_calibration_binary_storage.hpp" #include "fsmitm_layered_romfs_storage.hpp" #include "fsmitm_save_utils.hpp" #include "fsmitm_readonly_layered_filesystem.hpp" namespace ams::mitm::fs { using namespace ams::fs; namespace { constexpr const ams::fs::Path AtmosphereHblWebContentDirPath = fs::MakeConstantPath("/atmosphere/hbl_html/"); constexpr const char ProgramWebContentDir[] = "/manual_html/"; constinit os::SdkMutex g_boot0_detect_lock; constinit bool g_detected_boot0_kind = false; constinit bool g_is_boot0_custom_public_key = false; constinit fssrv::impl::ProgramIndexMapInfoManager g_program_index_map_info_manager; bool IsBoot0CustomPublicKey(::FsStorage &storage) { if (AMS_UNLIKELY(!g_detected_boot0_kind)) { std::scoped_lock lk(g_boot0_detect_lock); if (AMS_LIKELY(!g_detected_boot0_kind)) { g_is_boot0_custom_public_key = DetectBoot0CustomPublicKey(storage); g_detected_boot0_kind = true; } } return g_is_boot0_custom_public_key; } bool GetSettingsItemBooleanValue(const char *name, const char *key) { u8 tmp = 0; AMS_ABORT_UNLESS(settings::fwdbg::GetSettingsItemValue(std::addressof(tmp), sizeof(tmp), name, key) == sizeof(tmp)); return (tmp != 0); } template<typename... Arguments> constexpr ALWAYS_INLINE auto MakeSharedFileSystem(Arguments &&... args) { return sf::CreateSharedObjectEmplaced<ams::fssrv::sf::IFileSystem, ams::fssrv::impl::FileSystemInterfaceAdapter>(std::forward<Arguments>(args)...); } template<typename... Arguments> constexpr ALWAYS_INLINE auto MakeSharedStorage(Arguments &&... args) { return sf::CreateSharedObjectEmplaced<ams::fssrv::sf::IStorage, ams::fssrv::impl::StorageInterfaceAdapter>(std::forward<Arguments>(args)...); } Result OpenHblWebContentFileSystem(sf::Out<sf::SharedPointer<ams::fssrv::sf::IFileSystem>> &out, ncm::ProgramId program_id) { /* Verify eligibility. */ bool is_hbl; R_UNLESS(R_SUCCEEDED(ams::pm::info::IsHblProgramId(std::addressof(is_hbl), program_id)), sm::mitm::ResultShouldForwardToSession()); R_UNLESS(is_hbl, sm::mitm::ResultShouldForwardToSession()); /* Hbl html directory must exist. */ { FsDir d; R_UNLESS(R_SUCCEEDED(mitm::fs::OpenSdDirectory(std::addressof(d), AtmosphereHblWebContentDirPath.GetString(), fs::OpenDirectoryMode_Directory)), sm::mitm::ResultShouldForwardToSession()); fsDirClose(std::addressof(d)); } /* Open the SD card using fs.mitm's session. */ FsFileSystem sd_fs; R_TRY(fsOpenSdCardFileSystem(std::addressof(sd_fs))); const sf::cmif::DomainObjectId target_object_id{serviceGetObjectId(std::addressof(sd_fs.s))}; std::unique_ptr<fs::fsa::IFileSystem> sd_ifs = std::make_unique<fs::RemoteFileSystem>(sd_fs); auto subdir_fs = std::make_unique<fssystem::SubDirectoryFileSystem>(std::move(sd_ifs)); R_TRY(subdir_fs->Initialize(AtmosphereHblWebContentDirPath)); out.SetValue(MakeSharedFileSystem(std::make_shared<fs::ReadOnlyFileSystem>(std::move(subdir_fs)), false), target_object_id); R_SUCCEED(); } Result OpenProgramSpecificWebContentFileSystem(sf::Out<sf::SharedPointer<ams::fssrv::sf::IFileSystem>> &out, ncm::ProgramId program_id, FsFileSystemType filesystem_type, Service *fwd, const fssrv::sf::Path *path, bool with_id) { /* Directory must exist. */ R_UNLESS(HasSdManualHtmlContent(program_id), sm::mitm::ResultShouldForwardToSession()); /* Open the SD card using fs.mitm's session. */ FsFileSystem sd_fs; R_TRY(fsOpenSdCardFileSystem(std::addressof(sd_fs))); const sf::cmif::DomainObjectId target_object_id{serviceGetObjectId(std::addressof(sd_fs.s))}; std::unique_ptr<fs::fsa::IFileSystem> sd_ifs = std::make_unique<fs::RemoteFileSystem>(sd_fs); /* Format the subdirectory path. */ char program_web_content_raw_path[0x100]; FormatAtmosphereSdPath(program_web_content_raw_path, sizeof(program_web_content_raw_path), program_id, ProgramWebContentDir); ams::fs::Path program_web_content_path; R_TRY(program_web_content_path.SetShallowBuffer(program_web_content_raw_path)); /* Make a new filesystem. */ { auto subdir_fs = std::make_unique<fssystem::SubDirectoryFileSystem>(std::move(sd_ifs)); R_TRY(subdir_fs->Initialize(program_web_content_path)); std::shared_ptr<fs::fsa::IFileSystem> new_fs = nullptr; /* Try to open the existing fs. */ FsFileSystem base_fs; bool opened_base_fs = false; if (with_id) { opened_base_fs = R_SUCCEEDED(fsOpenFileSystemWithIdFwd(fwd, std::addressof(base_fs), static_cast<u64>(program_id), filesystem_type, path->str)); } else { opened_base_fs = R_SUCCEEDED(fsOpenFileSystemWithPatchFwd(fwd, std::addressof(base_fs), static_cast<u64>(program_id), filesystem_type)); } if (opened_base_fs) { /* Create a layered adapter. */ new_fs = std::make_shared<ReadOnlyLayeredFileSystem>(std::move(subdir_fs), std::make_unique<fs::RemoteFileSystem>(base_fs)); } else { /* Without an existing FS, just make a read only adapter to the subdirectory. */ new_fs = std::make_shared<fs::ReadOnlyFileSystem>(std::move(subdir_fs)); } out.SetValue(MakeSharedFileSystem(std::move(new_fs), false), target_object_id); } R_SUCCEED(); } Result OpenWebContentFileSystem(sf::Out<sf::SharedPointer<ams::fssrv::sf::IFileSystem>> &out, ncm::ProgramId client_program_id, ncm::ProgramId program_id, FsFileSystemType filesystem_type, Service *fwd, const fssrv::sf::Path *path, bool with_id, bool try_program_specific) { /* Check first that we're a web applet opening web content. */ R_UNLESS(ncm::IsWebAppletId(client_program_id), sm::mitm::ResultShouldForwardToSession()); R_UNLESS(filesystem_type == FsFileSystemType_ContentManual, sm::mitm::ResultShouldForwardToSession()); /* Try to mount the HBL web filesystem. If this succeeds then we're done. */ R_SUCCEED_IF(R_SUCCEEDED(OpenHblWebContentFileSystem(out, program_id))); /* If program specific override shouldn't be attempted, fall back. */ R_UNLESS(try_program_specific, sm::mitm::ResultShouldForwardToSession()); /* If we're not opening a HBL filesystem, just try to open a generic one. */ R_RETURN(OpenProgramSpecificWebContentFileSystem(out, program_id, filesystem_type, fwd, path, with_id)); } } bool HasSdManualHtmlContent(ncm::ProgramId program_id) { /* Directory must exist. */ FsDir d; if (R_SUCCEEDED(OpenAtmosphereSdDirectory(std::addressof(d), program_id, ProgramWebContentDir, fs::OpenDirectoryMode_Directory))) { ::fsDirClose(std::addressof(d)); return true; } else { return false; } } Result FsMitmService::OpenFileSystemWithPatch(sf::Out<sf::SharedPointer<ams::fssrv::sf::IFileSystem>> out, ncm::ProgramId program_id, u32 _filesystem_type) { R_RETURN(OpenWebContentFileSystem(out, m_client_info.program_id, program_id, static_cast<FsFileSystemType>(_filesystem_type), m_forward_service.get(), nullptr, false, m_client_info.override_status.IsProgramSpecific())); } Result FsMitmService::OpenFileSystemWithId(sf::Out<sf::SharedPointer<ams::fssrv::sf::IFileSystem>> out, const fssrv::sf::Path &path, ncm::ProgramId program_id, u32 _filesystem_type) { R_RETURN(OpenWebContentFileSystem(out, m_client_info.program_id, program_id, static_cast<FsFileSystemType>(_filesystem_type), m_forward_service.get(), std::addressof(path), true, m_client_info.override_status.IsProgramSpecific())); } Result FsMitmService::OpenSdCardFileSystem(sf::Out<sf::SharedPointer<ams::fssrv::sf::IFileSystem>> out) { /* We only care about redirecting this for NS/emummc. */ R_UNLESS(m_client_info.program_id == ncm::SystemProgramId::Ns, sm::mitm::ResultShouldForwardToSession()); R_UNLESS(emummc::IsActive(), sm::mitm::ResultShouldForwardToSession()); /* Create a new SD card filesystem. */ FsFileSystem sd_fs; R_TRY(fsOpenSdCardFileSystemFwd(m_forward_service.get(), std::addressof(sd_fs))); const sf::cmif::DomainObjectId target_object_id{serviceGetObjectId(std::addressof(sd_fs.s))}; /* Return output filesystem. */ auto redir_fs = std::make_shared<fssystem::DirectoryRedirectionFileSystem>(std::make_unique<RemoteFileSystem>(sd_fs)); R_TRY(redir_fs->InitializeWithFixedPath("/Nintendo", emummc::GetNintendoDirPath())); out.SetValue(MakeSharedFileSystem(std::move(redir_fs), false), target_object_id); R_SUCCEED(); } Result FsMitmService::OpenSaveDataFileSystem(sf::Out<sf::SharedPointer<ams::fssrv::sf::IFileSystem>> out, u8 _space_id, const fs::SaveDataAttribute &attribute) { /* We only want to intercept saves for games, right now. */ const bool is_game_or_hbl = m_client_info.override_status.IsHbl() || ncm::IsApplicationId(m_client_info.program_id); R_UNLESS(is_game_or_hbl, sm::mitm::ResultShouldForwardToSession()); /* Only redirect if the appropriate system setting is set. */ R_UNLESS(GetSettingsItemBooleanValue("atmosphere", "fsmitm_redirect_saves_to_sd"), sm::mitm::ResultShouldForwardToSession()); /* Only redirect if the specific title being accessed has a redirect save flag. */ R_UNLESS(cfg::HasContentSpecificFlag(m_client_info.program_id, "redirect_save"), sm::mitm::ResultShouldForwardToSession()); /* Only redirect account savedata. */ R_UNLESS(attribute.type == fs::SaveDataType::Account, sm::mitm::ResultShouldForwardToSession()); /* Get enum type for space id. */ auto space_id = static_cast<FsSaveDataSpaceId>(_space_id); /* Verify we can open the save. */ static_assert(sizeof(fs::SaveDataAttribute) == sizeof(::FsSaveDataAttribute)); FsFileSystem save_fs; R_UNLESS(R_SUCCEEDED(fsOpenSaveDataFileSystemFwd(m_forward_service.get(), std::addressof(save_fs), space_id, reinterpret_cast<const FsSaveDataAttribute *>(std::addressof(attribute)))), sm::mitm::ResultShouldForwardToSession()); std::unique_ptr<fs::fsa::IFileSystem> save_ifs = std::make_unique<fs::RemoteFileSystem>(save_fs); /* Mount the SD card using fs.mitm's session. */ FsFileSystem sd_fs; R_TRY(fsOpenSdCardFileSystem(std::addressof(sd_fs))); const sf::cmif::DomainObjectId target_object_id{serviceGetObjectId(std::addressof(sd_fs.s))}; std::shared_ptr<fs::fsa::IFileSystem> sd_ifs = std::make_shared<fs::RemoteFileSystem>(sd_fs); /* Verify that we can open the save directory, and that it exists. */ const ncm::ProgramId application_id = attribute.program_id == ncm::InvalidProgramId ? m_client_info.program_id : attribute.program_id; char save_dir_raw_path[0x100]; R_TRY(mitm::fs::SaveUtil::GetDirectorySaveDataPath(save_dir_raw_path, sizeof(save_dir_raw_path), application_id, space_id, attribute)); ams::fs::Path save_dir_path; R_TRY(save_dir_path.SetShallowBuffer(save_dir_raw_path)); /* Check if this is the first time we're making the save. */ bool is_new_save = false; { fs::DirectoryEntryType ent; R_TRY_CATCH(sd_ifs->GetEntryType(std::addressof(ent), save_dir_path)) { R_CATCH(fs::ResultPathNotFound) { is_new_save = true; } R_CATCH_ALL() { /* ... */ } } R_END_TRY_CATCH; } /* Ensure the directory exists. */ R_TRY(fssystem::EnsureDirectory(sd_ifs.get(), save_dir_path)); /* Create directory savedata filesystem. */ auto subdir_fs = std::make_unique<fssystem::SubDirectoryFileSystem>(sd_ifs); R_TRY(subdir_fs->Initialize(save_dir_path)); std::shared_ptr<fssystem::DirectorySaveDataFileSystem> dirsave_ifs = std::make_shared<fssystem::DirectorySaveDataFileSystem>(std::move(subdir_fs)); /* Ensure correct directory savedata filesystem state. */ R_TRY(dirsave_ifs->Initialize(true, true, true)); /* If it's the first time we're making the save, copy existing savedata over. */ if (is_new_save) { /* TODO: Check error? */ fs::DirectoryEntry work_entry; constexpr const fs::Path root_path = fs::MakeConstantPath("/"); u8 savedata_copy_buffer[2_KB]; fssystem::CopyDirectoryRecursively(dirsave_ifs.get(), save_ifs.get(), root_path, root_path, std::addressof(work_entry), savedata_copy_buffer, sizeof(savedata_copy_buffer)); } /* Set output. */ out.SetValue(MakeSharedFileSystem(std::move(dirsave_ifs), false), target_object_id); R_SUCCEED(); } Result FsMitmService::OpenBisStorage(sf::Out<sf::SharedPointer<ams::fssrv::sf::IStorage>> out, u32 _bis_partition_id) { const ::FsBisPartitionId bis_partition_id = static_cast<::FsBisPartitionId>(_bis_partition_id); /* Try to open a storage for the partition. */ FsStorage bis_storage; R_TRY(fsOpenBisStorageFwd(m_forward_service.get(), std::addressof(bis_storage), bis_partition_id)); const sf::cmif::DomainObjectId target_object_id{serviceGetObjectId(std::addressof(bis_storage.s))}; const bool is_sysmodule = ncm::IsSystemProgramId(m_client_info.program_id); const bool is_hbl = m_client_info.override_status.IsHbl(); const bool can_write_bis = is_sysmodule || (is_hbl && GetSettingsItemBooleanValue("atmosphere", "enable_hbl_bis_write")); /* Allow HBL to write to boot1 (safe firm) + package2. */ /* This is needed to not break compatibility with ChoiDujourNX, which does not check for write access before beginning an update. */ /* TODO: get fixed so that this can be turned off without causing bricks :/ */ const bool is_package2 = (FsBisPartitionId_BootConfigAndPackage2Part1 <= bis_partition_id && bis_partition_id <= FsBisPartitionId_BootConfigAndPackage2Part6); const bool is_boot1 = bis_partition_id == FsBisPartitionId_BootPartition2Root; const bool can_write_bis_for_choi_support = is_hbl && (is_package2 || is_boot1); /* Set output storage. */ if (bis_partition_id == FsBisPartitionId_BootPartition1Root) { if (IsBoot0CustomPublicKey(bis_storage)) { out.SetValue(MakeSharedStorage(std::make_shared<CustomPublicKeyBoot0Storage>(bis_storage, m_client_info, spl::GetSocType())), target_object_id); } else { out.SetValue(MakeSharedStorage(std::make_shared<Boot0Storage>(bis_storage, m_client_info)), target_object_id); } } else if (bis_partition_id == FsBisPartitionId_CalibrationBinary) { out.SetValue(MakeSharedStorage(std::make_shared<CalibrationBinaryStorage>(bis_storage, m_client_info)), target_object_id); } else { if (can_write_bis || can_write_bis_for_choi_support) { /* We can write, so create a writable storage. */ out.SetValue(MakeSharedStorage(std::make_shared<RemoteStorage>(bis_storage)), target_object_id); } else { /* We can only read, so create a readable storage. */ std::unique_ptr<ams::fs::IStorage> unique_bis = std::make_unique<RemoteStorage>(bis_storage); out.SetValue(MakeSharedStorage(std::make_shared<ReadOnlyStorageAdapter>(std::move(unique_bis))), target_object_id); } } R_SUCCEED(); } Result FsMitmService::OpenDataStorageByCurrentProcess(sf::Out<sf::SharedPointer<ams::fssrv::sf::IStorage>> out) { /* Only mitm if we should override contents for the current process. */ R_UNLESS(m_client_info.override_status.IsProgramSpecific(), sm::mitm::ResultShouldForwardToSession()); /* Only mitm if there is actually an override romfs. */ R_UNLESS(mitm::fs::HasSdRomfsContent(m_client_info.program_id), sm::mitm::ResultShouldForwardToSession()); /* Try to open the process romfs. */ FsStorage data_storage; R_TRY(fsOpenDataStorageByCurrentProcessFwd(m_forward_service.get(), std::addressof(data_storage))); const sf::cmif::DomainObjectId target_object_id{serviceGetObjectId(std::addressof(data_storage.s))}; /* Get a layered storage for the process romfs. */ out.SetValue(MakeSharedStorage(GetLayeredRomfsStorage(m_client_info.program_id, data_storage, true)), target_object_id); R_SUCCEED(); } Result FsMitmService::OpenDataStorageByDataId(sf::Out<sf::SharedPointer<ams::fssrv::sf::IStorage>> out, ncm::DataId _data_id, u8 storage_id) { /* Only mitm if we should override contents for the current process. */ R_UNLESS(m_client_info.override_status.IsProgramSpecific(), sm::mitm::ResultShouldForwardToSession()); /* TODO: Decide how to handle DataId vs ProgramId for this API. */ const ncm::ProgramId data_id = {_data_id.value}; /* Only mitm if there is actually an override romfs. */ R_UNLESS(mitm::fs::HasSdRomfsContent(data_id), sm::mitm::ResultShouldForwardToSession()); /* Try to open the data id. */ FsStorage data_storage; R_TRY(fsOpenDataStorageByDataIdFwd(m_forward_service.get(), std::addressof(data_storage), static_cast<u64>(data_id), static_cast<NcmStorageId>(storage_id))); const sf::cmif::DomainObjectId target_object_id{serviceGetObjectId(std::addressof(data_storage.s))}; /* Get a layered storage for the data id. */ out.SetValue(MakeSharedStorage(GetLayeredRomfsStorage(data_id, data_storage, false)), target_object_id); R_SUCCEED(); } Result FsMitmService::OpenDataStorageWithProgramIndex(sf::Out<sf::SharedPointer<ams::fssrv::sf::IStorage>> out, u8 program_index) { /* Only mitm if we should override contents for the current process. */ R_UNLESS(m_client_info.override_status.IsProgramSpecific(), sm::mitm::ResultShouldForwardToSession()); /* Get the relevant program id. */ const ncm::ProgramId program_id = g_program_index_map_info_manager.GetProgramId(m_client_info.program_id, program_index); /* If we don't know about the program or don't have content, forward. */ R_UNLESS(program_id != ncm::InvalidProgramId, sm::mitm::ResultShouldForwardToSession()); R_UNLESS(mitm::fs::HasSdRomfsContent(program_id), sm::mitm::ResultShouldForwardToSession()); /* Try to open the process romfs. */ FsStorage data_storage; R_TRY(fsOpenDataStorageWithProgramIndexFwd(m_forward_service.get(), std::addressof(data_storage), program_index)); const sf::cmif::DomainObjectId target_object_id{serviceGetObjectId(std::addressof(data_storage.s))}; /* Get a layered storage for the process romfs. */ out.SetValue(MakeSharedStorage(GetLayeredRomfsStorage(program_id, data_storage, true)), target_object_id); R_SUCCEED(); } Result FsMitmService::RegisterProgramIndexMapInfo(const sf::InBuffer &info_buffer, s32 info_count) { /* Try to register with FS. */ R_TRY(fsRegisterProgramIndexMapInfoFwd(m_forward_service.get(), info_buffer.GetPointer(), info_buffer.GetSize(), info_count)); /* Register with ourselves. */ R_ABORT_UNLESS(g_program_index_map_info_manager.Reset(reinterpret_cast<const fs::ProgramIndexMapInfo *>(info_buffer.GetPointer()), info_count)); R_SUCCEED(); } }
21,328
C++
.cpp
302
60.380795
282
0.668608
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,218
fsmitm_module.cpp
Atmosphere-NX_Atmosphere/stratosphere/ams_mitm/source/fs_mitm/fsmitm_module.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "fsmitm_module.hpp" #include "fs_mitm_service.hpp" namespace ams::mitm::fs { namespace { enum PortIndex { PortIndex_Mitm, PortIndex_Count, }; constexpr sm::ServiceName MitmServiceName = sm::ServiceName::Encode("fsp-srv"); struct ServerOptions { static constexpr size_t PointerBufferSize = 0x800; static constexpr size_t MaxDomains = 0x40; static constexpr size_t MaxDomainObjects = 0x4000; static constexpr bool CanDeferInvokeRequest = false; static constexpr bool CanManageMitmServers = true; }; constexpr size_t MaxSessions = 61; class ServerManager final : public sf::hipc::ServerManager<PortIndex_Count, ServerOptions, MaxSessions> { private: virtual Result OnNeedsToAccept(int port_index, Server *server) override; }; ServerManager g_server_manager; Result ServerManager::OnNeedsToAccept(int port_index, Server *server) { /* Acknowledge the mitm session. */ std::shared_ptr<::Service> fsrv; sm::MitmProcessInfo client_info; server->AcknowledgeMitmSession(std::addressof(fsrv), std::addressof(client_info)); switch (port_index) { case PortIndex_Mitm: R_RETURN(this->AcceptMitmImpl(server, sf::CreateSharedObjectEmplaced<IFsMitmInterface, FsMitmService>(decltype(fsrv)(fsrv), client_info), fsrv)); AMS_UNREACHABLE_DEFAULT_CASE(); } } constexpr size_t TotalThreads = 5; static_assert(TotalThreads >= 1, "TotalThreads"); constexpr size_t NumExtraThreads = TotalThreads - 1; constexpr size_t ThreadStackSize = mitm::ModuleTraits<fs::MitmModule>::StackSize; alignas(os::MemoryPageSize) u8 g_extra_thread_stacks[NumExtraThreads][ThreadStackSize]; os::ThreadType g_extra_threads[NumExtraThreads]; void LoopServerThread(void *) { /* Loop forever, servicing our services. */ g_server_manager.LoopProcess(); } void ProcessForServerOnAllThreads() { /* Initialize threads. */ if constexpr (NumExtraThreads > 0) { const s32 priority = os::GetThreadCurrentPriority(os::GetCurrentThread()); for (size_t i = 0; i < NumExtraThreads; i++) { R_ABORT_UNLESS(os::CreateThread(g_extra_threads + i, LoopServerThread, nullptr, g_extra_thread_stacks[i], ThreadStackSize, priority)); } } /* Start extra threads. */ if constexpr (NumExtraThreads > 0) { for (size_t i = 0; i < NumExtraThreads; i++) { os::StartThread(g_extra_threads + i); } } /* Loop this thread. */ LoopServerThread(nullptr); /* Wait for extra threads to finish. */ if constexpr (NumExtraThreads > 0) { for (size_t i = 0; i < NumExtraThreads; i++) { os::WaitThread(g_extra_threads + i); } } } } void MitmModule::ThreadFunction(void *) { /* Create fs mitm. */ R_ABORT_UNLESS((g_server_manager.RegisterMitmServer<FsMitmService>(PortIndex_Mitm, MitmServiceName))); /* Process for the server. */ ProcessForServerOnAllThreads(); } }
4,160
C++
.cpp
90
36.166667
165
0.62287
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,219
fsmitm_calibration_binary_storage.cpp
Atmosphere-NX_Atmosphere/stratosphere/ams_mitm/source/fs_mitm/fsmitm_calibration_binary_storage.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "fsmitm_calibration_binary_storage.hpp" namespace ams::mitm::fs { using namespace ams::fs; namespace { constinit os::SdkMutex g_cal0_access_mutex; } Result CalibrationBinaryStorage::Read(s64 offset, void *_buffer, size_t size) { /* Acquire exclusive calibration binary access. */ std::scoped_lock lk(g_cal0_access_mutex); /* Get u8 buffer. */ u8 *buffer = static_cast<u8 *>(_buffer); /* Succeed on zero-size. */ R_SUCCEED_IF(size == 0); /* Handle the blank region. */ if (m_read_blank) { if (BlankStartOffset <= offset && offset < BlankEndOffset) { const size_t blank_size = std::min(size, static_cast<size_t>(BlankEndOffset - offset)); mitm::ReadFromBlankCalibrationBinary(offset, buffer, blank_size); size -= blank_size; buffer += blank_size; offset += blank_size; } } /* Succeed if we're done. */ R_SUCCEED_IF(size == 0); /* Handle any in-between data. */ if (BlankEndOffset <= offset && offset < FakeSecureStartOffset) { const size_t mid_size = std::min(size, static_cast<size_t>(FakeSecureStartOffset - offset)); R_TRY(Base::Read(offset, buffer, mid_size)); size -= mid_size; buffer += mid_size; offset += mid_size; } /* Succeed if we're done. */ R_SUCCEED_IF(size == 0); /* Handle the secure region. */ if (FakeSecureStartOffset <= offset && offset < FakeSecureEndOffset) { const size_t fake_size = std::min(size, static_cast<size_t>(FakeSecureEndOffset - offset)); mitm::ReadFromFakeSecureBackupStorage(offset, buffer, fake_size); size -= fake_size; buffer += fake_size; offset += fake_size; } /* Succeed if we're done. */ R_SUCCEED_IF(size == 0); /* Handle any remaining data. */ R_RETURN(Base::Read(offset, buffer, size)); } Result CalibrationBinaryStorage::Write(s64 offset, const void *_buffer, size_t size) { /* Acquire exclusive calibration binary access. */ std::scoped_lock lk(g_cal0_access_mutex); /* Get const u8 buffer. */ const u8 *buffer = static_cast<const u8 *>(_buffer); /* Succeed on zero-size. */ R_SUCCEED_IF(size == 0); /* Only allow writes if we should. */ R_UNLESS(m_allow_writes, fs::ResultUnsupportedOperation()); /* Handle the blank region. */ if (m_read_blank) { if (BlankStartOffset <= offset && offset < BlankEndOffset) { const size_t blank_size = std::min(size, static_cast<size_t>(BlankEndOffset - offset)); mitm::WriteToBlankCalibrationBinary(offset, buffer, blank_size); size -= blank_size; buffer += blank_size; offset += blank_size; } } /* Succeed if we're done. */ R_SUCCEED_IF(size == 0); /* Handle any in-between data. */ if (BlankEndOffset <= offset && offset < FakeSecureStartOffset) { const size_t mid_size = std::min(size, static_cast<size_t>(FakeSecureStartOffset - offset)); R_TRY(Base::Write(offset, buffer, mid_size)); size -= mid_size; buffer += mid_size; offset += mid_size; } /* Succeed if we're done. */ R_SUCCEED_IF(size == 0); /* Handle the secure region. */ if (FakeSecureStartOffset <= offset && offset < FakeSecureEndOffset) { const size_t fake_size = std::min(size, static_cast<size_t>(FakeSecureEndOffset - offset)); mitm::WriteToFakeSecureBackupStorage(offset, buffer, fake_size); size -= fake_size; buffer += fake_size; offset += fake_size; } /* Succeed if we're done. */ R_SUCCEED_IF(size == 0); /* Handle any remaining data. */ R_RETURN(Base::Write(offset, buffer, size)); } }
4,823
C++
.cpp
109
34.908257
104
0.591636
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,220
fsmitm_layered_romfs_storage.cpp
Atmosphere-NX_Atmosphere/stratosphere/ams_mitm/source/fs_mitm/fsmitm_layered_romfs_storage.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "../amsmitm_initialization.hpp" #include "../amsmitm_fs_utils.hpp" #include "fsmitm_layered_romfs_storage.hpp" namespace ams::mitm::fs { namespace { 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); class LayeredRomfsStorageHolder : public util::IntrusiveRedBlackTreeBaseNode<LayeredRomfsStorageHolder> { public: using RedBlackKeyType = u64; private: LayeredRomfsStorageImpl *m_impl; u32 m_reference_count; bool m_second_chance; bool m_process_romfs; public: LayeredRomfsStorageHolder(LayeredRomfsStorageImpl *impl, bool process_rom) : m_impl(impl), m_reference_count(1), m_second_chance(true), m_process_romfs(process_rom) { /* ... */ } ~LayeredRomfsStorageHolder() { delete m_impl; } constexpr LayeredRomfsStorageImpl *GetImpl() const { return m_impl; } constexpr ncm::ProgramId GetProgramId() const { return m_impl->GetProgramId(); } constexpr u32 GetReferenceCount() const { return m_reference_count; } void OpenReferenceImpl() { ++m_reference_count; } void CloseReferenceImpl() { --m_reference_count; } bool GetSecondChanceImpl() const { return m_second_chance; } void SetSecondChanceImpl(bool sc) { m_second_chance = sc; } bool IsProcessRomfs() const { return m_process_romfs; } static constexpr ALWAYS_INLINE int Compare(const RedBlackKeyType &lval, const LayeredRomfsStorageHolder &rhs) { const auto rval = rhs.GetProgramId().value; if (lval < rval) { return -1; } else if (lval == rval) { return 0; } else { return 1; } } static constexpr ALWAYS_INLINE int Compare(const LayeredRomfsStorageHolder &lhs, const LayeredRomfsStorageHolder &rhs) { return Compare(lhs.GetProgramId().value, rhs); } }; using LayeredRomfsStorageSet = typename util::IntrusiveRedBlackTreeBaseTraits<LayeredRomfsStorageHolder>::TreeType<LayeredRomfsStorageHolder>; constinit os::SdkRecursiveMutex g_storage_set_mutex; constinit LayeredRomfsStorageSet g_storage_set; constinit os::SdkMutex g_initialization_mutex; void OpenReference(LayeredRomfsStorageImpl *impl) { std::scoped_lock lk(g_storage_set_mutex); auto it = g_storage_set.find_key(impl->GetProgramId().value); AMS_ABORT_UNLESS(it != g_storage_set.end()); it->OpenReferenceImpl(); } void CloseReference(LayeredRomfsStorageImpl *impl) { std::scoped_lock lk(g_storage_set_mutex); auto it = g_storage_set.find_key(impl->GetProgramId().value); AMS_ABORT_UNLESS(it != g_storage_set.end()); AMS_ABORT_UNLESS(it->GetReferenceCount() > 0); it->CloseReferenceImpl(); } void RomfsInitializerThreadFunction(void *) { while (true) { uintptr_t storage_uptr = 0; g_req_mq.Receive(std::addressof(storage_uptr)); auto *impl = reinterpret_cast<LayeredRomfsStorageImpl *>(storage_uptr); g_ack_mq.Send(storage_uptr); std::scoped_lock lk(g_initialization_mutex); impl->InitializeImpl(); /* Close the initial reference. */ CloseReference(impl); } } void RomfsFinalizerThreadFunction(void *) { while (true) { { std::scoped_lock lk(g_storage_set_mutex); auto it = g_storage_set.begin(); while (it != g_storage_set.end()) { if (it->GetReferenceCount() > 0) { it->SetSecondChanceImpl(true); ++it; } else if (it->GetSecondChanceImpl()) { it->SetSecondChanceImpl(false); ++it; } else { auto *holder = std::addressof(*it); it = g_storage_set.erase(it); delete holder; } } } os::SleepThread(TimeSpan::FromMilliSeconds(500)); } } constexpr size_t RomfsInitializerThreadStackSize = 0x8000; os::ThreadType g_romfs_initializer_thread; os::ThreadType g_romfs_finalizer_thread; alignas(os::ThreadStackAlignment) u8 g_romfs_initializer_thread_stack[RomfsInitializerThreadStackSize]; alignas(os::ThreadStackAlignment) u8 g_romfs_finalizer_thread_stack[os::MemoryPageSize]; void RequestInitializeStorage(uintptr_t storage_uptr) { std::scoped_lock lk(g_mq_lock); if (AMS_UNLIKELY(!g_started_req_thread)) { R_ABORT_UNLESS(os::CreateThread(std::addressof(g_romfs_initializer_thread), RomfsInitializerThreadFunction, nullptr, g_romfs_initializer_thread_stack, sizeof(g_romfs_initializer_thread_stack), AMS_GET_SYSTEM_THREAD_PRIORITY(mitm_fs, RomFileSystemInitializeThread))); os::SetThreadNamePointer(std::addressof(g_romfs_initializer_thread), AMS_GET_SYSTEM_THREAD_NAME(mitm_fs, RomFileSystemInitializeThread)); os::StartThread(std::addressof(g_romfs_initializer_thread)); R_ABORT_UNLESS(os::CreateThread(std::addressof(g_romfs_finalizer_thread), RomfsFinalizerThreadFunction, nullptr, g_romfs_finalizer_thread_stack, sizeof(g_romfs_finalizer_thread_stack), AMS_GET_SYSTEM_THREAD_PRIORITY(mitm_fs, RomFileSystemInitializeThread))); os::SetThreadNamePointer(std::addressof(g_romfs_finalizer_thread), AMS_GET_SYSTEM_THREAD_NAME(mitm_fs, RomFileSystemFinalizeThread)); os::StartThread(std::addressof(g_romfs_finalizer_thread)); g_started_req_thread = true; } g_req_mq.Send(storage_uptr); uintptr_t ack = 0; g_ack_mq.Receive(std::addressof(ack)); AMS_ABORT_UNLESS(ack == storage_uptr); } class LayeredRomfsStorage : public ams::fs::IStorage { private: LayeredRomfsStorageImpl *m_impl; public: LayeredRomfsStorage(LayeredRomfsStorageImpl *impl) : m_impl(impl) { OpenReference(m_impl); } virtual ~LayeredRomfsStorage() { CloseReference(m_impl); } virtual Result Read(s64 offset, void *buffer, size_t size) override { R_RETURN(m_impl->Read(offset, buffer, size)); } virtual Result GetSize(s64 *out_size) override { R_RETURN(m_impl->GetSize(out_size)); } virtual Result Flush() override { R_RETURN(m_impl->Flush()); } virtual Result OperateRange(void *dst, size_t dst_size, ams::fs::OperationId op_id, s64 offset, s64 size, const void *src, size_t src_size) override { R_RETURN(m_impl->OperateRange(dst, dst_size, op_id, offset, size, src, src_size)); } virtual Result Write(s64 offset, const void *buffer, size_t size) override { /* TODO: Better result code? */ AMS_UNUSED(offset, buffer, size); R_THROW(ams::fs::ResultUnsupportedOperation()) } virtual Result SetSize(s64 size) override { /* TODO: Better result code? */ AMS_UNUSED(size); R_THROW(ams::fs::ResultUnsupportedOperation()) } }; } using namespace ams::fs; std::shared_ptr<ams::fs::IStorage> GetLayeredRomfsStorage(ncm::ProgramId program_id, ::FsStorage &data_storage, bool is_process_romfs) { std::scoped_lock lk(g_storage_set_mutex); /* Find an existing storage. */ if (auto it = g_storage_set.find_key(program_id.value); it != g_storage_set.end()) { return std::make_shared<LayeredRomfsStorage>(it->GetImpl()); } /* We don't have an existing storage. If we're creating process romfs, free any unreferenced process romfs. */ /* This should help prevent too much memory in use at any time. */ if (is_process_romfs) { auto it = g_storage_set.begin(); while (it != g_storage_set.end()) { if (it->GetReferenceCount() > 0 || !it->IsProcessRomfs()) { ++it; } else { auto *holder = std::addressof(*it); it = g_storage_set.erase(it); delete holder; } } } /* Create a new storage. */ LayeredRomfsStorageImpl *impl; { ::FsFile data_file; if (R_SUCCEEDED(OpenAtmosphereSdFile(std::addressof(data_file), program_id, "romfs.bin", OpenMode_Read))) { impl = new LayeredRomfsStorageImpl(std::make_unique<ReadOnlyStorageAdapter>(new RemoteStorage(data_storage)), std::make_unique<ReadOnlyStorageAdapter>(new FileStorage(new RemoteFile(data_file))), program_id); } else { impl = new LayeredRomfsStorageImpl(std::make_unique<ReadOnlyStorageAdapter>(new RemoteStorage(data_storage)), nullptr, program_id); } } /* Insert holder. Reference count will now be one. */ g_storage_set.insert(*(new LayeredRomfsStorageHolder(impl, is_process_romfs))); /* Begin initialization. When this finishes, a decref will occur. */ impl->BeginInitialize(); /* Return a new shared storage for the impl. */ return std::make_shared<LayeredRomfsStorage>(impl); } void FinalizeLayeredRomfsStorage(ncm::ProgramId program_id) { std::scoped_lock lk(g_initialization_mutex); std::scoped_lock lk2(g_storage_set_mutex); /* Find an existing storage. */ if (auto it = g_storage_set.find_key(program_id.value); it != g_storage_set.end()) { /* We need to delete the process romfs. Require invariant that it is unreferenced, by this point. */ AMS_ABORT_UNLESS(it->GetReferenceCount() == 0); auto *holder = std::addressof(*it); it = g_storage_set.erase(it); delete holder; } } LayeredRomfsStorageImpl::LayeredRomfsStorageImpl(std::unique_ptr<IStorage> s_r, std::unique_ptr<IStorage> f_r, ncm::ProgramId pr_id) : m_storage_romfs(std::move(s_r)), m_file_romfs(std::move(f_r)), m_initialize_event(os::EventClearMode_ManualClear), m_program_id(std::move(pr_id)), m_is_initialized(false), m_started_initialize(false) { /* ... */ } LayeredRomfsStorageImpl::~LayeredRomfsStorageImpl() { for (size_t i = 0; i < m_source_infos.size(); i++) { m_source_infos[i].Cleanup(); } } void LayeredRomfsStorageImpl::BeginInitialize() { AMS_ABORT_UNLESS(!m_started_initialize); RequestInitializeStorage(reinterpret_cast<uintptr_t>(this)); m_started_initialize = true; } void LayeredRomfsStorageImpl::InitializeImpl() { /* Build new virtual romfs. */ romfs::Builder builder(m_program_id); if (mitm::IsInitialized()) { builder.AddSdFiles(); } if (m_file_romfs) { builder.AddStorageFiles(m_file_romfs.get(), romfs::DataSourceType::File); } if (m_storage_romfs) { builder.AddStorageFiles(m_storage_romfs.get(), romfs::DataSourceType::Storage); } builder.Build(std::addressof(m_source_infos)); m_is_initialized = true; m_initialize_event.Signal(); } Result LayeredRomfsStorageImpl::Read(s64 offset, void *buffer, size_t size) { /* Check if we can succeed immediately. */ R_SUCCEED_IF(size == 0); /* Ensure we're initialized. */ if (!m_is_initialized) { m_initialize_event.Wait(); } /* Validate offset/size. */ const s64 virt_size = this->GetSize(); R_UNLESS(offset >= 0, fs::ResultInvalidOffset()); R_UNLESS(offset < virt_size, fs::ResultInvalidOffset()); if (static_cast<size_t>(virt_size - offset) < size) { size = static_cast<size_t>(virt_size - offset); } /* Find first source info via binary search. */ auto it = std::lower_bound(m_source_infos.begin(), m_source_infos.end(), offset); u8 *cur_dst = static_cast<u8 *>(buffer); /* Our operator < compares against start of info instead of end, so we need to subtract one from lower bound. */ it--; size_t read_so_far = 0; while (read_so_far < size) { const auto &cur_source = *it; AMS_ABORT_UNLESS(offset >= cur_source.virtual_offset); if (offset < cur_source.virtual_offset + cur_source.size) { const s64 offset_within_source = offset - cur_source.virtual_offset; const size_t cur_read_size = std::min(size - read_so_far, static_cast<size_t>(cur_source.size - offset_within_source)); switch (cur_source.source_type) { case romfs::DataSourceType::Storage: R_ABORT_UNLESS(m_storage_romfs->Read(cur_source.storage_source_info.offset + offset_within_source, cur_dst, cur_read_size)); break; case romfs::DataSourceType::File: R_ABORT_UNLESS(m_file_romfs->Read(cur_source.file_source_info.offset + offset_within_source, cur_dst, cur_read_size)); break; case romfs::DataSourceType::LooseSdFile: { FsFile file; R_ABORT_UNLESS(mitm::fs::OpenAtmosphereSdRomfsFile(std::addressof(file), m_program_id, cur_source.loose_source_info.path, OpenMode_Read)); ON_SCOPE_EXIT { fsFileClose(std::addressof(file)); }; u64 out_read = 0; R_ABORT_UNLESS(fsFileRead(std::addressof(file), offset_within_source, cur_dst, cur_read_size, FsReadOption_None, std::addressof(out_read))); AMS_ABORT_UNLESS(out_read == cur_read_size); } break; case romfs::DataSourceType::Memory: std::memcpy(cur_dst, cur_source.memory_source_info.data + offset_within_source, cur_read_size); break; case romfs::DataSourceType::Metadata: { size_t out_read = 0; R_ABORT_UNLESS(cur_source.metadata_source_info.file->Read(std::addressof(out_read), offset_within_source, cur_dst, cur_read_size)); AMS_ABORT_UNLESS(out_read == cur_read_size); } break; AMS_UNREACHABLE_DEFAULT_CASE(); } read_so_far += cur_read_size; cur_dst += cur_read_size; offset += cur_read_size; } else { /* Explicitly handle padding. */ const auto &next_source = *(++it); const size_t padding_size = static_cast<size_t>(next_source.virtual_offset - offset); std::memset(cur_dst, 0, padding_size); read_so_far += padding_size; cur_dst += padding_size; offset += padding_size; } } R_SUCCEED(); } Result LayeredRomfsStorageImpl::GetSize(s64 *out_size) { /* Ensure we're initialized. */ if (!m_is_initialized) { m_initialize_event.Wait(); } *out_size = this->GetSize(); R_SUCCEED(); } Result LayeredRomfsStorageImpl::Flush() { R_SUCCEED(); } Result LayeredRomfsStorageImpl::OperateRange(void *dst, size_t dst_size, OperationId op_id, s64 offset, s64 size, const void *src, size_t src_size) { AMS_UNUSED(offset, src, src_size); switch (op_id) { case OperationId::Invalidate: case OperationId::QueryRange: if (size == 0) { if (op_id == OperationId::QueryRange) { R_UNLESS(dst != nullptr, fs::ResultNullptrArgument()); R_UNLESS(dst_size == sizeof(QueryRangeInfo), fs::ResultInvalidSize()); reinterpret_cast<QueryRangeInfo *>(dst)->Clear(); } R_SUCCEED(); } /* TODO: How to deal with this? */ R_THROW(fs::ResultUnsupportedOperation()); default: R_THROW(fs::ResultUnsupportedOperation()); } } }
18,378
C++
.cpp
349
38.498567
340
0.569582
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,221
fsmitm_boot0storage.cpp
Atmosphere-NX_Atmosphere/stratosphere/ams_mitm/source/fs_mitm/fsmitm_boot0storage.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have 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 "fsmitm_boot0storage.hpp" namespace ams::mitm::fs { using namespace ams::fs; namespace { constinit os::SdkMutex g_boot0_access_mutex; constinit bool g_custom_public_key = false; constinit u8 g_boot0_bct_buffer[Boot0Storage::BctEndOffset]; /* Recognize special public key (https://gist.github.com/SciresM/16b63ac1d80494522bdba2c57995257c). */ /* P = 19 */ /* Q = 1696986749729493925354392349339746171297507422986462747526968361144447230710192316397327889522451749459854070558277878297255552508603806832852079596337539247651161831569525505882103311631577368514276343192042634740927726070847704397913856975832811679847928433261678072951551065705680482548543833651752439700272736498378724153330763357721354498194000536297732323628263256733931353143625854828275237159155585342783077681713929284136658773985266864804093157854331138230313706015557050002740810464618031715670281442110238274404626065924786185264268216336867948322976979393032640085259926883014490947373494538254895109731 */ /* N = 0xFF696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696969696959 */ /* E = 0x10001 */ /* D = 6512128715229088976470211610075969347035078304643231077895577077900787352712063823560162578441773733649014439616165727455431015055675770987914713980812453585413988983206576233689754710500864883529402371292948326392791238474661859182717295176679567362482790015587820446999760239570255254879359445627372805817473978644067558931078225451477635089763009580492462097185005355990612929951162366081631888011031830742459571000203341001926135389508196521518687349554188686396554248868403128728646457247197407637887195043486221295751496667162366700477934591694110831002874992896076061627516220934290742867397720103040314639313 */ constexpr const u8 CustomPublicKey[0x100] = { 0x59, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0xFF, }; } bool Boot0Storage::CanModifyBctPublicKey() { if (exosphere::IsRcmBugPatched()) { /* RCM bug patched. */ /* Only allow NS to update the BCT pubks. */ /* AutoRCM on a patched unit will cause a brick, so homebrew should NOT be allowed to write. */ return m_client_info.program_id == ncm::SystemProgramId::Ns; } else { /* RCM bug unpatched. */ /* Allow homebrew but not NS to update the BCT pubks. */ return m_client_info.override_status.IsHbl(); } } Result Boot0Storage::Read(s64 offset, void *_buffer, size_t size) { std::scoped_lock lk{g_boot0_access_mutex}; AMS_ABORT_UNLESS(!g_custom_public_key); /* Check if we have nothing to do. */ R_SUCCEED_IF(size == 0); R_RETURN(Base::Read(offset, _buffer, size)); } Result Boot0Storage::Write(s64 offset, const void *_buffer, size_t size) { std::scoped_lock lk{g_boot0_access_mutex}; AMS_ABORT_UNLESS(!g_custom_public_key); const u8 *buffer = static_cast<const u8 *>(_buffer); /* Check if we have nothing to do. */ R_SUCCEED_IF(size == 0); /* Protect the EKS region from writes. */ if (offset <= EksStart) { if (offset + size < EksStart) { /* Fall through, no need to do anything here. */ } else { if (offset + size > EksEnd) { /* Perform portion of write falling past end of keyblobs. */ const s64 diff = EksEnd - offset; R_TRY(Base::Write(EksEnd, buffer + diff, size - diff)); } /* Adjust size to avoid writing end of data. */ size = EksStart - offset; } } else if (offset < EksEnd) { /* Ignore writes falling strictly within the region. */ R_SUCCEED_IF(offset + size <= EksEnd); /* Only write past the end of the region. */ const s64 diff = EksEnd - offset; buffer += diff; size -= diff; offset = EksEnd; } /* If we have nothing to write, succeed immediately. */ R_SUCCEED_IF(size == 0); /* We want to protect AutoRCM from NS on ipatched units. If we can modify bct pubks or we're not touching any of them, proceed. */ if (this->CanModifyBctPublicKey() || offset >= BctEndOffset || (util::AlignUp(offset, BctSize) >= BctEndOffset && (offset % BctSize) >= BctPubkEnd)) { R_RETURN(Base::Write(offset, buffer, size)); } /* Handle any data written past the end of the pubk region. */ if (offset + size > BctEndOffset) { const u64 diff = BctEndOffset - offset; R_TRY(Base::Write(BctEndOffset, buffer + diff, size - diff)); size = diff; } /* Read in the current BCT region. */ R_TRY(Base::Read(0, g_boot0_bct_buffer, BctEndOffset)); /* Update the bct buffer. */ for (u64 cur_offset = offset; cur_offset < BctEndOffset && cur_offset < offset + size; cur_offset++) { const u64 cur_bct_relative_ofs = cur_offset % BctSize; if (cur_bct_relative_ofs < BctPubkStart || BctPubkEnd <= cur_bct_relative_ofs) { g_boot0_bct_buffer[cur_offset] = buffer[cur_offset - offset]; } } R_RETURN(Base::Write(0, g_boot0_bct_buffer, BctEndOffset)); } CustomPublicKeyBoot0Storage::CustomPublicKeyBoot0Storage(FsStorage &s, const sm::MitmProcessInfo &c, spl::SocType soc) : Base(s), m_client_info(c), m_soc_type(soc) { std::scoped_lock lk{g_boot0_access_mutex}; /* We're custom public key. */ g_custom_public_key = true; } Result CustomPublicKeyBoot0Storage::Read(s64 offset, void *_buffer, size_t size) { std::scoped_lock lk{g_boot0_access_mutex}; AMS_ABORT_UNLESS(g_custom_public_key); /* Check if we have nothing to do. */ R_SUCCEED_IF(size == 0); u8 *buffer = static_cast<u8 *>(_buffer); /* Check if we're reading the first BCTs for NS. */ /* If we are, we want to lie about the contents of BCT0/1 so that they validate. */ if (offset < 0x8000 && m_client_info.program_id == ncm::SystemProgramId::Ns) { R_TRY(Base::Read(0, g_boot0_bct_buffer, Boot0Storage::BctEndOffset)); /* Determine the readable size. */ const size_t readable_bct01_size = std::min<size_t>(0x8000, offset + size) - offset; std::memcpy(buffer, g_boot0_bct_buffer + 0x8000 + offset, readable_bct01_size); /* Advance. */ buffer += readable_bct01_size; offset += readable_bct01_size; size -= readable_bct01_size; } /* Check if we have nothing to do. */ R_SUCCEED_IF(size == 0); /* Perform whatever remains of the read. */ R_RETURN(Base::Read(offset, buffer, size)); } Result CustomPublicKeyBoot0Storage::Write(s64 offset, const void *_buffer, size_t size) { std::scoped_lock lk{g_boot0_access_mutex}; AMS_ABORT_UNLESS(g_custom_public_key); const u8 *buffer = static_cast<const u8 *>(_buffer); /* Check if we have nothing to do. */ R_SUCCEED_IF(size == 0); /* Drop writes to the first BCTs. */ if (offset < 0x8000) { /* Determine the writable size. */ const size_t writable_bct01_size = std::min<size_t>(0x8000, offset + size) - offset; /* Advance. */ buffer += writable_bct01_size; offset += writable_bct01_size; size -= writable_bct01_size; } /* Check if we have nothing to do. */ R_SUCCEED_IF(size == 0); /* Similarly, we want to drop writes to the end of boot0, where custom bootloader lives. */ R_SUCCEED_IF(offset >= 0x380000); if (offset + size >= 0x380000) { size = 0x380000 - offset; } /* On erista, we want to protect the EKS region. */ if (m_soc_type == spl::SocType_Erista) { if (offset <= Boot0Storage::EksStart) { if (offset + size < Boot0Storage::EksStart) { /* Fall through, no need to do anything here. */ } else { if (offset + size > Boot0Storage::EksEnd) { /* Perform portion of write falling past end of keyblobs. */ const s64 diff = Boot0Storage::EksEnd - offset; R_TRY(Base::Write(Boot0Storage::EksEnd, buffer + diff, size - diff)); } /* Adjust size to avoid writing end of data. */ size = Boot0Storage::EksStart - offset; } } else if (offset < Boot0Storage::EksEnd) { /* Ignore writes falling strictly within the region. */ R_SUCCEED_IF(offset + size <= Boot0Storage::EksEnd); /* Only write past the end of the region. */ const s64 diff = Boot0Storage::EksEnd - offset; buffer += diff; size -= diff; offset = Boot0Storage::EksEnd; } } /* If we have nothing to write, succeed immediately. */ R_SUCCEED_IF(size == 0); /* Perform whatever remains of the write. */ R_RETURN(Base::Write(offset, buffer, size)); } bool DetectBoot0CustomPublicKey(::FsStorage &storage) { /* Determine public key offset. */ const size_t bct_pubk_offset = spl::GetSocType() == spl::SocType_Mariko ? 0x10 : 0x210; u8 work_buffer[0x400]; /* Read BCT-Normal-Main. */ R_ABORT_UNLESS(::fsStorageRead(std::addressof(storage), 0, work_buffer, sizeof(work_buffer))); /* Check for custom public key. */ if (std::memcmp(work_buffer + bct_pubk_offset, CustomPublicKey, sizeof(CustomPublicKey)) != 0) { return false; } /* Read BCT-Safe-Main. */ R_ABORT_UNLESS(::fsStorageRead(std::addressof(storage), 0x4000, work_buffer, sizeof(work_buffer))); /* Check for custom public key. */ if (std::memcmp(work_buffer + bct_pubk_offset, CustomPublicKey, sizeof(CustomPublicKey)) != 0) { return false; } return true; } }
13,169
C++
.cpp
216
50.314815
634
0.639668
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,222
fsmitm_save_utils.cpp
Atmosphere-NX_Atmosphere/stratosphere/ams_mitm/source/fs_mitm/fsmitm_save_utils.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "fsmitm_save_utils.hpp" namespace ams::mitm::fs { using namespace ams::fs; namespace { Result GetSaveDataSpaceIdString(const char **out_str, u8 space_id) { switch (static_cast<SaveDataSpaceId>(space_id)) { case SaveDataSpaceId::System: case SaveDataSpaceId::ProperSystem: *out_str = "sys"; break; case SaveDataSpaceId::User: *out_str = "user"; break; case SaveDataSpaceId::SdSystem: *out_str = "sd_sys"; break; case SaveDataSpaceId::Temporary: *out_str = "temp"; break; case SaveDataSpaceId::SdUser: *out_str = "sd_user"; break; case SaveDataSpaceId::SafeMode: *out_str = "safe"; break; default: R_THROW(fs::ResultInvalidSaveDataSpaceId()); } R_SUCCEED(); } Result GetSaveDataTypeString(const char **out_str, SaveDataType save_data_type) { switch (save_data_type) { case SaveDataType::System: *out_str = "system"; break; case SaveDataType::Account: *out_str = "account"; break; case SaveDataType::Bcat: *out_str = "bcat"; break; case SaveDataType::Device: *out_str = "device"; break; case SaveDataType::Temporary: *out_str = "temp"; break; case SaveDataType::Cache: *out_str = "cache"; break; case SaveDataType::SystemBcat: *out_str = "system_bcat"; break; default: /* TODO: Better result? */ R_THROW(fs::ResultInvalidArgument()); } R_SUCCEED(); } constexpr inline bool IsEmptyAccountId(const UserId &uid) { return uid == InvalidUserId; } } Result SaveUtil::GetDirectorySaveDataPath(char *dst, size_t dst_size, ncm::ProgramId program_id, u8 space_id, const fs::SaveDataAttribute &attribute) { /* Saves should be separate for emunand vs sysnand. */ const char *emummc_str = emummc::IsActive() ? "emummc" : "sysmmc"; /* Get space_id, save_data_type strings. */ const char *space_id_str, *save_type_str; R_TRY(GetSaveDataSpaceIdString(&space_id_str, space_id)); R_TRY(GetSaveDataTypeString(&save_type_str, attribute.type)); /* Initialize the path. */ const bool is_system = attribute.system_save_data_id != InvalidSystemSaveDataId && IsEmptyAccountId(attribute.user_id); size_t out_path_len; if (is_system) { out_path_len = static_cast<size_t>(util::SNPrintf(dst, dst_size, "/atmosphere/saves/%s/%s/%s/%016lx", emummc_str, space_id_str, save_type_str, attribute.system_save_data_id)); } else { out_path_len = static_cast<size_t>(util::SNPrintf(dst, dst_size, "/atmosphere/saves/%s/%s/%s/%016lx/%016lx%016lx", emummc_str, space_id_str, save_type_str, static_cast<u64>(program_id), attribute.user_id.data[1], attribute.user_id.data[0])); } R_UNLESS(out_path_len < dst_size, fs::ResultTooLongPath()); R_SUCCEED(); } }
4,324
C++
.cpp
98
31.346939
253
0.551781
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,223
sysupdater_fs_utils.cpp
Atmosphere-NX_Atmosphere/stratosphere/ams_mitm/source/sysupdater/sysupdater_fs_utils.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "sysupdater_fs_utils.hpp" namespace ams::mitm::sysupdater { namespace { constexpr inline const char * const NcaExtension = ".nca"; constexpr inline const char * const NspExtension = ".nsp"; constexpr inline const size_t NcaExtensionSize = 4; constexpr inline const size_t NspExtensionSize = 4; constexpr const ams::fs::PathFlags SdCardContentMetaPathNormalizePathFlags = [] { fs::PathFlags flags{}; flags.AllowMountName(); return flags; }(); static_assert(NcaExtensionSize == NspExtensionSize); constexpr inline const size_t NcaNspExtensionSize = NcaExtensionSize; Result CheckNcaOrNsp(const char **path) { /* Ensure that the path is currently at the mount name delimeter. */ R_UNLESS(util::Strncmp(*path, ams::fs::impl::MountNameDelimiter, util::Strnlen(ams::fs::impl::MountNameDelimiter, ams::fs::EntryNameLengthMax)) == 0, fs::ResultPathNotFound()); /* Advance past the :. */ static_assert(ams::fs::impl::MountNameDelimiter[0] == ':'); *path += 1; /* Ensure path is long enough for the extension. */ const size_t path_len = util::Strnlen(*path, ams::fs::EntryNameLengthMax); R_UNLESS(path_len > NcaNspExtensionSize, fs::ResultPathNotFound()); /* Get the extension. */ const char * const extension = *path + path_len - NcaNspExtensionSize; /* Ensure nca or nsp. */ const bool is_nca = util::Strnicmp(extension, NcaExtension, NcaNspExtensionSize) == 0; const bool is_nsp = util::Strnicmp(extension, NspExtension, NcaNspExtensionSize) == 0; R_UNLESS(is_nca || is_nsp, fs::ResultPathNotFound()); R_SUCCEED(); } Result ParseMountName(const char **path, std::shared_ptr<ams::fs::fsa::IFileSystem> *out) { /* The equivalent function here supports all the common mount names; we'll only support the SD card, system content storage. */ if (const auto mount_len = util::Strnlen(ams::fs::impl::SdCardFileSystemMountName, ams::fs::MountNameLengthMax); util::Strncmp(*path, ams::fs::impl::SdCardFileSystemMountName, mount_len) == 0) { /* Advance the path. */ *path += mount_len; /* Open the SD card. This uses libnx bindings. */ FsFileSystem fs; R_TRY(fsOpenSdCardFileSystem(std::addressof(fs))); /* Allocate a new filesystem wrapper. */ auto fsa = std::make_shared<ams::fs::RemoteFileSystem>(fs); R_UNLESS(fsa != nullptr, fs::ResultAllocationMemoryFailedInSdCardA()); /* Set the output fs. */ *out = std::move(fsa); } else if (const auto mount_len = util::Strnlen(ams::fs::impl::ContentStorageSystemMountName, ams::fs::MountNameLengthMax); util::Strncmp(*path, ams::fs::impl::ContentStorageSystemMountName, mount_len) == 0) { /* Advance the path. */ *path += mount_len; /* Open the system content storage. This uses libnx bindings. */ FsFileSystem fs; R_TRY(fsOpenContentStorageFileSystem(std::addressof(fs), FsContentStorageId_System)); /* Allocate a new filesystem wrapper. */ auto fsa = std::make_shared<ams::fs::RemoteFileSystem>(fs); R_UNLESS(fsa != nullptr, fs::ResultAllocationMemoryFailedInContentStorageA()); /* Set the output fs. */ *out = std::move(fsa); } else { R_THROW(fs::ResultPathNotFound()); } /* Ensure that there's something that could be a mount name delimiter. */ R_UNLESS(util::Strnlen(*path, fs::EntryNameLengthMax) != 0, fs::ResultPathNotFound()); R_SUCCEED(); } Result ParseNsp(const char **path, std::shared_ptr<ams::fs::fsa::IFileSystem> *out, std::shared_ptr<ams::fs::fsa::IFileSystem> base_fs) { const char *work_path = *path; /* Advance to the nsp extension. */ while (true) { if (util::Strnicmp(work_path, NspExtension, NspExtensionSize) == 0) { if (work_path[NspExtensionSize] == '\x00' || work_path[NspExtensionSize] == '/') { break; } work_path += NspExtensionSize; } else { R_UNLESS(*work_path != '\x00', fs::ResultPathNotFound()); work_path += 1; } } /* Advance past the extension. */ work_path += NspExtensionSize; /* Get the nsp path. */ ams::fs::Path nsp_path; R_TRY(nsp_path.InitializeWithNormalization(*path, work_path - *path)); /* Open the file storage. */ std::shared_ptr<ams::fs::FileStorageBasedFileSystem> file_storage = fssystem::AllocateShared<ams::fs::FileStorageBasedFileSystem>(); R_UNLESS(file_storage != nullptr, fs::ResultAllocationMemoryFailedInNcaFileSystemServiceImplA()); R_TRY(file_storage->Initialize(std::move(base_fs), nsp_path, ams::fs::OpenMode_Read)); /* Create a partition fs. */ R_TRY(fssystem::GetFileSystemCreatorInterfaces()->partition_fs_creator->Create(out, std::move(file_storage))); /* Update the path. */ *path = work_path; R_SUCCEED(); } Result ParseNca(const char **path, std::shared_ptr<fssystem::NcaReader> *out, std::shared_ptr<ams::fs::fsa::IFileSystem> base_fs) { /* Open the file storage. */ std::shared_ptr<ams::fs::FileStorageBasedFileSystem> file_storage = fssystem::AllocateShared<ams::fs::FileStorageBasedFileSystem>(); R_UNLESS(file_storage != nullptr, fs::ResultAllocationMemoryFailedInNcaFileSystemServiceImplB()); /* Get the nca path. */ ams::fs::Path nca_path; R_TRY(nca_path.InitializeWithNormalization(*path)); R_TRY(file_storage->Initialize(std::move(base_fs), nca_path, ams::fs::OpenMode_Read)); /* Create the nca reader. */ std::shared_ptr<fssystem::NcaReader> nca_reader; R_TRY(fssystem::GetFileSystemCreatorInterfaces()->storage_on_nca_creator->CreateNcaReader(std::addressof(nca_reader), file_storage)); /* NOTE: Here Nintendo validates program ID, but this does not need checking in the meta case. */ /* Set output reader. */ *out = std::move(nca_reader); R_SUCCEED(); } Result OpenMetaStorage(std::shared_ptr<ams::fs::IStorage> *out, std::shared_ptr<fssystem::IAsynchronousAccessSplitter> *out_splitter, std::shared_ptr<fssystem::NcaReader> nca_reader, fssystem::NcaFsHeader::FsType *out_fs_type) { /* Ensure the nca is a meta nca. */ R_UNLESS(nca_reader->GetContentType() == fssystem::NcaHeader::ContentType::Meta, fs::ResultPreconditionViolation()); /* We only support SD card ncas, so ensure this isn't a gamecard nca. */ R_UNLESS(nca_reader->GetDistributionType() != fssystem::NcaHeader::DistributionType::GameCard, fs::ResultPermissionDenied()); /* Here Nintendo would call GetPartitionIndex(), but we don't need to, because it's meta. */ constexpr int MetaPartitionIndex = 0; /* Open fs header reader. */ fssystem::NcaFsHeaderReader fs_header_reader; R_TRY(fssystem::GetFileSystemCreatorInterfaces()->storage_on_nca_creator->Create(out, out_splitter, std::addressof(fs_header_reader), std::move(nca_reader), MetaPartitionIndex)); /* Set the output fs type. */ *out_fs_type = fs_header_reader.GetFsType(); R_SUCCEED(); } Result OpenContentMetaFileSystem(std::shared_ptr<ams::fs::fsa::IFileSystem> *out, const char *path) { /* Parse the mount name to get a filesystem. */ const char *cur_path = path; std::shared_ptr<ams::fs::fsa::IFileSystem> base_fs; R_TRY(ParseMountName(std::addressof(cur_path), std::addressof(base_fs))); /* Ensure the path is an nca or nsp. */ R_TRY(CheckNcaOrNsp(std::addressof(cur_path))); /* Try to parse as nsp. */ std::shared_ptr<ams::fs::fsa::IFileSystem> nsp_fs; if (R_SUCCEEDED(ParseNsp(std::addressof(cur_path), std::addressof(nsp_fs), base_fs))) { /* nsp target is only allowed for type package, and we're assuming type meta. */ R_UNLESS(*path != '\x00', fs::ResultInvalidArgument()); /* Use the nsp fs as the base fs. */ base_fs = std::move(nsp_fs); } /* Parse as nca. */ std::shared_ptr<fssystem::NcaReader> nca_reader; R_TRY(ParseNca(std::addressof(cur_path), std::addressof(nca_reader), std::move(base_fs))); /* Open meta storage. */ std::shared_ptr<ams::fs::IStorage> storage; std::shared_ptr<fssystem::IAsynchronousAccessSplitter> splitter; fssystem::NcaFsHeader::FsType fs_type = static_cast<fssystem::NcaFsHeader::FsType>(~0); R_TRY(OpenMetaStorage(std::addressof(storage), std::addressof(splitter), std::move(nca_reader), std::addressof(fs_type))); /* Open the appropriate interface. */ const auto * const creator_intfs = fssystem::GetFileSystemCreatorInterfaces(); switch (fs_type) { case fssystem::NcaFsHeader::FsType::PartitionFs: R_RETURN(creator_intfs->partition_fs_creator->Create(out, std::move(storage))); case fssystem::NcaFsHeader::FsType::RomFs: R_RETURN(creator_intfs->rom_fs_creator->Create(out, std::move(storage))); default: R_THROW(fs::ResultInvalidNcaFileSystemType()); } } } bool PathView::HasPrefix(util::string_view prefix) const { return m_path.compare(0, prefix.length(), prefix) == 0; } bool PathView::HasSuffix(util::string_view suffix) const { return m_path.compare(m_path.length() - suffix.length(), suffix.length(), suffix) == 0; } util::string_view PathView::GetFileName() const { auto pos = m_path.find_last_of("/"); return pos != util::string_view::npos ? m_path.substr(pos + 1) : m_path; } Result MountSdCardContentMeta(const char *mount_name, const char *path, ams::fs::ContentAttributes attr) { /* TODO: What does attributes actually get used for? */ AMS_UNUSED(attr); /* Sanitize input. */ /* NOTE: This is an internal API, so we won't bother with mount name sanitization. */ R_UNLESS(path != nullptr, fs::ResultInvalidPath()); /* Normalize the path. */ char normalized_path[fs::EntryNameLengthMax + 1]; R_TRY(ams::fs::PathFormatter::Normalize(normalized_path, sizeof(normalized_path), path, std::strlen(path) + 1, SdCardContentMetaPathNormalizePathFlags)); /* Open the filesystem. */ std::shared_ptr<ams::fs::fsa::IFileSystem> fs; R_TRY(OpenContentMetaFileSystem(std::addressof(fs), normalized_path)); /* Create a holder for the fs. */ std::unique_ptr unique_fs = std::make_unique<fssystem::ForwardingFileSystem>(std::move(fs)); R_UNLESS(unique_fs != nullptr, fs::ResultAllocationMemoryFailedNew()); /* Register the fs. */ R_RETURN(ams::fs::fsa::Register(mount_name, std::move(unique_fs))); } }
12,412
C++
.cpp
199
50.437186
236
0.617195
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false