From 0a58e803be72e53b33efaaa1db4a2649a26c5b2f Mon Sep 17 00:00:00 2001 From: Michael Scire Date: Wed, 20 Oct 2021 20:53:42 -0700 Subject: [PATCH] kern/test: add wip qemu-virt board support to mesosphere --- libraries/config/board/qemu/virt/board.mk | 5 + libraries/config/common.mk | 15 + libraries/libmesosphere/Makefile | 12 + .../mesosphere/arch/arm64/kern_cpu.hpp | 2 + .../arch/arm64/kern_k_interrupt_name.hpp | 4 + .../generic/kern_k_device_page_table.hpp | 8 +- .../board/qemu/virt/kern_cpu_map.hpp | 33 + .../board/qemu/virt/kern_k_memory_layout.hpp | 24 + .../kern_k_memory_region_device_types.inc | 20 + .../board/qemu/virt/kern_k_system_control.hpp | 85 + .../include/mesosphere/kern_debug_log.hpp | 2 + .../mesosphere/kern_k_memory_layout.hpp | 2 + .../include/mesosphere/kern_select_cpu.hpp | 10 + .../mesosphere/kern_select_system_control.hpp | 7 + .../board/nintendo/nx/kern_secure_monitor.cpp | 18 +- .../board/qemu/virt/kern_k_system_control.cpp | 464 + .../board/qemu/virt/kern_secure_monitor.cpp | 171 + .../board/qemu/virt/kern_secure_monitor.hpp | 76 + .../libmesosphere/source/kern_debug_log.cpp | 10 + .../source/kern_debug_log_impl.arch.arm64.s | 27 + .../kern_debug_log_impl.board.qemu_virt.cpp | 50 + .../source/kern_debug_log_impl.hpp | 1 + .../kern_k_memory_layout.board.qemu_virt.cpp | 137 + .../svc/svc_stratosphere_shims.hpp | 5 + .../init/init_libnx_shim.os.horizon.cpp | 5 + .../source/init/init_system_module.cpp | 4 + .../qemu/virt/svc_hardware_constants.hpp | 23 + .../svc/svc_select_hardware_constants.hpp | 9 +- mesosphere/Makefile | 38 +- mesosphere/build_mesosphere.py | 32 +- mesosphere/kernel/Makefile | 12 + mesosphere/kernel_ldr/Makefile | 12 + tests/Licensing/Catch2-LICENSE.txt | 23 + tests/TestSvc/Makefile | 107 + tests/TestSvc/TestSvc.json | 128 + tests/TestSvc/source/catch.hpp | 17959 ++++++++++++++++ tests/TestSvc/source/test_main.cpp | 93 + tests/TestSvc/source/test_set_heap_size.cpp | 153 + tests/TestSvc/source/test_sleep_thread.cpp | 37 + 39 files changed, 19796 insertions(+), 27 deletions(-) create mode 100644 libraries/config/board/qemu/virt/board.mk create mode 100644 libraries/libmesosphere/include/mesosphere/board/qemu/virt/kern_cpu_map.hpp create mode 100644 libraries/libmesosphere/include/mesosphere/board/qemu/virt/kern_k_memory_layout.hpp create mode 100644 libraries/libmesosphere/include/mesosphere/board/qemu/virt/kern_k_memory_region_device_types.inc create mode 100644 libraries/libmesosphere/include/mesosphere/board/qemu/virt/kern_k_system_control.hpp create mode 100644 libraries/libmesosphere/source/board/qemu/virt/kern_k_system_control.cpp create mode 100644 libraries/libmesosphere/source/board/qemu/virt/kern_secure_monitor.cpp create mode 100644 libraries/libmesosphere/source/board/qemu/virt/kern_secure_monitor.hpp create mode 100644 libraries/libmesosphere/source/kern_debug_log_impl.arch.arm64.s create mode 100644 libraries/libmesosphere/source/kern_debug_log_impl.board.qemu_virt.cpp create mode 100644 libraries/libmesosphere/source/kern_k_memory_layout.board.qemu_virt.cpp create mode 100644 libraries/libvapours/include/vapours/svc/board/qemu/virt/svc_hardware_constants.hpp create mode 100644 tests/Licensing/Catch2-LICENSE.txt create mode 100644 tests/TestSvc/Makefile create mode 100644 tests/TestSvc/TestSvc.json create mode 100644 tests/TestSvc/source/catch.hpp create mode 100644 tests/TestSvc/source/test_main.cpp create mode 100644 tests/TestSvc/source/test_set_heap_size.cpp create mode 100644 tests/TestSvc/source/test_sleep_thread.cpp diff --git a/libraries/config/board/qemu/virt/board.mk b/libraries/config/board/qemu/virt/board.mk new file mode 100644 index 000000000..752aad417 --- /dev/null +++ b/libraries/config/board/qemu/virt/board.mk @@ -0,0 +1,5 @@ +export ATMOSPHERE_DEFINES += -DATMOSPHERE_BOARD_QEMU_VIRT -D__SWITCH__ +export ATMOSPHERE_SETTINGS += +export ATMOSPHERE_CFLAGS += +export ATMOSPHERE_CXXFLAGS += +export ATMOSPHERE_ASFLAGS += \ No newline at end of file diff --git a/libraries/config/common.mk b/libraries/config/common.mk index 3fd7c1cad..460f7d9ea 100644 --- a/libraries/config/common.mk +++ b/libraries/config/common.mk @@ -52,6 +52,21 @@ export ATMOSPHERE_OS_NAME := horizon export ATMOSPHERE_CPU_EXTENSIONS := endif +else ifeq ($(ATMOSPHERE_BOARD),qemu-virt) + + +ifeq ($(ATMOSPHERE_CPU),arm-cortex-a57) +export ATMOSPHERE_ARCH_DIR := arm64 +export ATMOSPHERE_BOARD_DIR := qemu/virt +export ATMOSPHERE_OS_DIR := horizon + +export ATMOSPHERE_ARCH_NAME := arm64 +export ATMOSPHERE_BOARD_NAME := qemu_virt +export ATMOSPHERE_OS_NAME := horizon + +export ATMOSPHERE_CPU_EXTENSIONS := arm_crypto_extension aarch64_crypto_extension +endif + endif ifeq ($(ATMOSPHERE_CPU),arm-cortex-a57) diff --git a/libraries/libmesosphere/Makefile b/libraries/libmesosphere/Makefile index c60cc8650..6a996f156 100644 --- a/libraries/libmesosphere/Makefile +++ b/libraries/libmesosphere/Makefile @@ -104,6 +104,18 @@ $(eval $(call ATMOSPHERE_ADD_TARGET, audit, $(TARGET)_audit.a, \ ATMOSPHERE_BUILD_SETTINGS="-DMESOSPHERE_BUILD_FOR_AUDITING" \ )) +$(eval $(call ATMOSPHERE_ADD_TARGET, qemu_virt_release, $(TARGET)_qemu_virt.a, \ + ATMOSPHERE_BUILD_SETTINGS="" \ +)) + +$(eval $(call ATMOSPHERE_ADD_TARGET, qemu_virt_debug, $(TARGET)_qemu_virt_debug.a, \ + ATMOSPHERE_BUILD_SETTINGS="-DMESOSPHERE_BUILD_FOR_DEBUGGING" \ +)) + +$(eval $(call ATMOSPHERE_ADD_TARGET, qemu_virt_audit, $(TARGET)_qemu_virt_audit.a, \ + ATMOSPHERE_BUILD_SETTINGS="-DMESOSPHERE_BUILD_FOR_AUDITING" \ +)) + #--------------------------------------------------------------------------------- -include $(ATMOSPHERE_BOARD_NAME)_$(ATMOSPHERE_ARCH_NAME).mk diff --git a/libraries/libmesosphere/include/mesosphere/arch/arm64/kern_cpu.hpp b/libraries/libmesosphere/include/mesosphere/arch/arm64/kern_cpu.hpp index c06c4e30d..353824372 100644 --- a/libraries/libmesosphere/include/mesosphere/arch/arm64/kern_cpu.hpp +++ b/libraries/libmesosphere/include/mesosphere/arch/arm64/kern_cpu.hpp @@ -30,6 +30,8 @@ namespace ams::kern::arch::arm64::cpu { #if defined(ATMOSPHERE_BOARD_NINTENDO_NX) constexpr inline size_t NumCores = 4; +#elif defined(ATMOSPHERE_BOARD_QEMU_VIRT) + constexpr inline size_t NumCores = 4; #else #error "Unknown Board for cpu::NumCores" #endif diff --git a/libraries/libmesosphere/include/mesosphere/arch/arm64/kern_k_interrupt_name.hpp b/libraries/libmesosphere/include/mesosphere/arch/arm64/kern_k_interrupt_name.hpp index cbe6e1ea3..6503b4e1e 100644 --- a/libraries/libmesosphere/include/mesosphere/arch/arm64/kern_k_interrupt_name.hpp +++ b/libraries/libmesosphere/include/mesosphere/arch/arm64/kern_k_interrupt_name.hpp @@ -36,6 +36,10 @@ namespace ams::kern::arch::arm64 { KInterruptName_SecurePhysicalTimer = 29, KInterruptName_NonSecurePhysicalTimer = 30, KInterruptName_LegacyNIrq = 31, + #elif defined(ATMOSPHERE_BOARD_QEMU_VIRT) + KInterruptName_VirtualTimer = 27, + KInterruptName_SecurePhysicalTimer = 29, + KInterruptName_NonSecurePhysicalTimer = 30, #endif #if defined(ATMOSPHERE_BOARD_NINTENDO_NX) diff --git a/libraries/libmesosphere/include/mesosphere/board/generic/kern_k_device_page_table.hpp b/libraries/libmesosphere/include/mesosphere/board/generic/kern_k_device_page_table.hpp index cc9404a41..0fb09b4ef 100644 --- a/libraries/libmesosphere/include/mesosphere/board/generic/kern_k_device_page_table.hpp +++ b/libraries/libmesosphere/include/mesosphere/board/generic/kern_k_device_page_table.hpp @@ -44,13 +44,13 @@ namespace ams::kern::board::generic { return ams::kern::svc::ResultNotImplemented(); } - Result ALWAYS_INLINE Map(size_t *out_mapped_size, const KPageGroup &pg, KDeviceVirtualAddress device_address, ams::svc::MemoryPermission device_perm, bool refresh_mappings) { - MESOSPHERE_UNUSED(out_mapped_size, pg, device_address, device_perm, refresh_mappings); + Result ALWAYS_INLINE Map(KProcessPageTable *page_table, KProcessAddress process_address, size_t size, KDeviceVirtualAddress device_address, ams::svc::MemoryPermission device_perm, bool is_aligned) { + MESOSPHERE_UNUSED(page_table, process_address, size, device_address, device_perm, is_aligned); return ams::kern::svc::ResultNotImplemented(); } - Result ALWAYS_INLINE Unmap(const KPageGroup &pg, KDeviceVirtualAddress device_address) { - MESOSPHERE_UNUSED(pg, device_address); + Result ALWAYS_INLINE Unmap(KProcessPageTable *page_table, KProcessAddress process_address, size_t size, KDeviceVirtualAddress device_address) { + MESOSPHERE_UNUSED(page_table, process_address, size, device_address); return ams::kern::svc::ResultNotImplemented(); } diff --git a/libraries/libmesosphere/include/mesosphere/board/qemu/virt/kern_cpu_map.hpp b/libraries/libmesosphere/include/mesosphere/board/qemu/virt/kern_cpu_map.hpp new file mode 100644 index 000000000..ec3335466 --- /dev/null +++ b/libraries/libmesosphere/include/mesosphere/board/qemu/virt/kern_cpu_map.hpp @@ -0,0 +1,33 @@ +/* + * Copyright (c) Atmosphère-NX + * + * This program is free software; you can redistribute it and/or modify it + * under the terms and conditions of the GNU General Public License, + * version 2, as published by the Free Software Foundation. + * + * This program is distributed in the hope it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +#pragma once +#include + +namespace ams::kern::board::qemu::virt::impl::cpu { + + /* Virtual to Physical core map. */ + constexpr inline const s32 VirtualToPhysicalCoreMap[BITSIZEOF(u64)] = { + 0, 1, 2, 3, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 3, + }; + +} diff --git a/libraries/libmesosphere/include/mesosphere/board/qemu/virt/kern_k_memory_layout.hpp b/libraries/libmesosphere/include/mesosphere/board/qemu/virt/kern_k_memory_layout.hpp new file mode 100644 index 000000000..003f74570 --- /dev/null +++ b/libraries/libmesosphere/include/mesosphere/board/qemu/virt/kern_k_memory_layout.hpp @@ -0,0 +1,24 @@ +/* + * Copyright (c) Atmosphère-NX + * + * This program is free software; you can redistribute it and/or modify it + * under the terms and conditions of the GNU General Public License, + * version 2, as published by the Free Software Foundation. + * + * This program is distributed in the hope it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +#pragma once +#include + +namespace ams::kern { + + constexpr inline size_t MainMemorySize = 4_GB; + constexpr inline size_t MainMemorySizeMax = 8_GB; + +} diff --git a/libraries/libmesosphere/include/mesosphere/board/qemu/virt/kern_k_memory_region_device_types.inc b/libraries/libmesosphere/include/mesosphere/board/qemu/virt/kern_k_memory_region_device_types.inc new file mode 100644 index 000000000..3d64f0407 --- /dev/null +++ b/libraries/libmesosphere/include/mesosphere/board/qemu/virt/kern_k_memory_region_device_types.inc @@ -0,0 +1,20 @@ +/* + * Copyright (c) Atmosphère-NX + * + * This program is free software; you can redistribute it and/or modify it + * under the terms and conditions of the GNU General Public License, + * version 2, as published by the Free Software Foundation. + * + * This program is distributed in the hope it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/* All architectures must define NumBoardDeviceRegions. */ +constexpr inline const auto NumBoardDeviceRegions = 0; + /* UNUSED: .Derive(NumBoardDeviceRegions, 0); */ + diff --git a/libraries/libmesosphere/include/mesosphere/board/qemu/virt/kern_k_system_control.hpp b/libraries/libmesosphere/include/mesosphere/board/qemu/virt/kern_k_system_control.hpp new file mode 100644 index 000000000..d1d1fa212 --- /dev/null +++ b/libraries/libmesosphere/include/mesosphere/board/qemu/virt/kern_k_system_control.hpp @@ -0,0 +1,85 @@ +/* + * Copyright (c) Atmosphère-NX + * + * This program is free software; you can redistribute it and/or modify it + * under the terms and conditions of the GNU General Public License, + * version 2, as published by the Free Software Foundation. + * + * This program is distributed in the hope it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +#pragma once +#include + +namespace ams::kern { + + struct InitialProcessBinaryLayout; + +} + +namespace ams::kern::board::qemu::virt { + + class KSystemControl { + public: + class Init { + public: + /* Initialization. */ + static size_t GetIntendedMemorySize(); + static KPhysicalAddress GetKernelPhysicalBaseAddress(uintptr_t base_address); + static void GetInitialProcessBinaryLayout(InitialProcessBinaryLayout *out); + static bool ShouldIncreaseThreadResourceLimit(); + static void CpuOn(u64 core_id, uintptr_t entrypoint, uintptr_t arg); + static size_t GetApplicationPoolSize(); + static size_t GetAppletPoolSize(); + static size_t GetMinimumNonSecureSystemPoolSize(); + static u8 GetDebugLogUartPort(); + + /* Randomness. */ + static void GenerateRandomBytes(void *dst, size_t size); + static u64 GenerateRandomRange(u64 min, u64 max); + }; + public: + /* Initialization. */ + static NOINLINE void InitializePhase1(); + static NOINLINE void InitializePhase2(); + static NOINLINE u32 GetCreateProcessMemoryPool(); + + /* Randomness. */ + static void GenerateRandomBytes(void *dst, size_t size); + static u64 GenerateRandomRange(u64 min, u64 max); + static u64 GenerateRandomU64(); + + /* Privileged Access. */ + static void ReadWriteRegisterPrivileged(u32 *out, ams::svc::PhysicalAddress address, u32 mask, u32 value); + static Result ReadWriteRegister(u32 *out, ams::svc::PhysicalAddress address, u32 mask, u32 value); + + static ALWAYS_INLINE u32 ReadRegisterPrivileged(ams::svc::PhysicalAddress address) { + u32 v; + ReadWriteRegisterPrivileged(std::addressof(v), address, 0x00000000u, 0); + return v; + } + + static ALWAYS_INLINE void WriteRegisterPrivileged(ams::svc::PhysicalAddress address, u32 value) { + u32 v; + ReadWriteRegisterPrivileged(std::addressof(v), address, 0xFFFFFFFFu, value); + } + + /* Power management. */ + static void SleepSystem(); + static NORETURN void StopSystem(void *arg = nullptr); + + /* User access. */ + static void CallSecureMonitorFromUser(ams::svc::lp64::SecureMonitorArguments *args); + + /* Secure Memory. */ + static size_t CalculateRequiredSecureMemorySize(size_t size, u32 pool); + static Result AllocateSecureMemory(KVirtualAddress *out, size_t size, u32 pool); + static void FreeSecureMemory(KVirtualAddress address, size_t size, u32 pool); + }; + +} \ No newline at end of file diff --git a/libraries/libmesosphere/include/mesosphere/kern_debug_log.hpp b/libraries/libmesosphere/include/mesosphere/kern_debug_log.hpp index 8253b1a24..51b83596e 100644 --- a/libraries/libmesosphere/include/mesosphere/kern_debug_log.hpp +++ b/libraries/libmesosphere/include/mesosphere/kern_debug_log.hpp @@ -43,6 +43,8 @@ namespace ams::kern { #ifdef ATMOSPHERE_BOARD_NINTENDO_NX #define MESOSPHERE_DEBUG_LOG_USE_UART + #elif defined(ATMOSPHERE_BOARD_QEMU_VIRT) + #define MESOSPHERE_DEBUG_LOG_USE_SEMIHOSTING #else #error "Unknown board for Default Debug Log Source" #endif diff --git a/libraries/libmesosphere/include/mesosphere/kern_k_memory_layout.hpp b/libraries/libmesosphere/include/mesosphere/kern_k_memory_layout.hpp index 66ee75ab6..5ac2a5908 100644 --- a/libraries/libmesosphere/include/mesosphere/kern_k_memory_layout.hpp +++ b/libraries/libmesosphere/include/mesosphere/kern_k_memory_layout.hpp @@ -20,6 +20,8 @@ #if defined(ATMOSPHERE_BOARD_NINTENDO_NX) #include +#elif defined(ATMOSPHERE_BOARD_QEMU_VIRT) + #include #else #error "Unknown board for KMemoryLayout" #endif diff --git a/libraries/libmesosphere/include/mesosphere/kern_select_cpu.hpp b/libraries/libmesosphere/include/mesosphere/kern_select_cpu.hpp index 8cf08533b..799a2fb3f 100644 --- a/libraries/libmesosphere/include/mesosphere/kern_select_cpu.hpp +++ b/libraries/libmesosphere/include/mesosphere/kern_select_cpu.hpp @@ -39,6 +39,16 @@ } +#elif defined(ATMOSPHERE_BOARD_QEMU_VIRT) + + #include + + namespace ams::kern::cpu { + + using namespace ams::kern::board::qemu::virt::impl::cpu; + + } + #else #error "Unknown board for CPU Map" #endif diff --git a/libraries/libmesosphere/include/mesosphere/kern_select_system_control.hpp b/libraries/libmesosphere/include/mesosphere/kern_select_system_control.hpp index cb1bb4d9a..0ea19592d 100644 --- a/libraries/libmesosphere/include/mesosphere/kern_select_system_control.hpp +++ b/libraries/libmesosphere/include/mesosphere/kern_select_system_control.hpp @@ -23,6 +23,13 @@ using ams::kern::board::nintendo::nx::KSystemControl; } +#elif defined(ATMOSPHERE_BOARD_QEMU_VIRT) + #include + + namespace ams::kern { + using ams::kern::board::qemu::virt::KSystemControl; + } + #else #error "Unknown board for KSystemControl" #endif diff --git a/libraries/libmesosphere/source/board/nintendo/nx/kern_secure_monitor.cpp b/libraries/libmesosphere/source/board/nintendo/nx/kern_secure_monitor.cpp index 112524fae..2ec4cbe2c 100644 --- a/libraries/libmesosphere/source/board/nintendo/nx/kern_secure_monitor.cpp +++ b/libraries/libmesosphere/source/board/nintendo/nx/kern_secure_monitor.cpp @@ -25,7 +25,23 @@ namespace ams::kern::board::nintendo::nx::smc { }; enum UserFunctionId : u32 { - UserFunctionId_SetConfig = 0xC3000401, + UserFunctionId_SetConfig = 0xC3000401, + UserFunctionId_GetConfigUser = 0xC3000002, + UserFunctionId_GetResult = 0xC3000003, + UserFunctionId_GetResultData = 0xC3000404, + UserFunctionId_ModularExponentiate = 0xC3000E05, + UserFunctionId_GenerateRandomBytes = 0xC3000006, + UserFunctionId_GenerateAesKek = 0xC3000007, + UserFunctionId_LoadAesKey = 0xC3000008, + UserFunctionId_ComputeAes = 0xC3000009, + UserFunctionId_GenerateSpecificAesKey = 0xC300000A, + UserFunctionId_ComputeCmac = 0xC300040B, + UserFunctionId_ReencryptDeviceUniqueData = 0xC300D60C, + UserFunctionId_DecryptDeviceUniqueData = 0xC300100D, + UserFunctionId_ModularExponentiateByStorageKey = 0xC300060F, + UserFunctionId_PrepareEsDeviceUniqueKey = 0xC3000610, + UserFunctionId_LoadPreparedAesKey = 0xC3000011, + UserFunctionId_PrepareEsCommonTitleKey = 0xC3000012, }; enum FunctionId : u32 { diff --git a/libraries/libmesosphere/source/board/qemu/virt/kern_k_system_control.cpp b/libraries/libmesosphere/source/board/qemu/virt/kern_k_system_control.cpp new file mode 100644 index 000000000..53526eece --- /dev/null +++ b/libraries/libmesosphere/source/board/qemu/virt/kern_k_system_control.cpp @@ -0,0 +1,464 @@ +/* + * Copyright (c) Atmosphère-NX + * + * This program is free software; you can redistribute it and/or modify it + * under the terms and conditions of the GNU General Public License, + * version 2, as published by the Free Software Foundation. + * + * This program is distributed in the hope it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +#include +#include "kern_secure_monitor.hpp" + +namespace ams::kern::board::qemu::virt { + + namespace { + + constexpr uintptr_t DramPhysicalAddress = 0x40000000; + constexpr size_t SecureAlignment = 128_KB; + + /* Global variables for secure memory. */ + constexpr size_t SecureAppletMemorySize = 4_MB; + constinit KSpinLock g_secure_applet_lock; + constinit bool g_secure_applet_memory_used = false; + constinit KVirtualAddress g_secure_applet_memory_address = Null; + + constinit KSpinLock g_secure_region_lock; + constinit bool g_secure_region_used = false; + constinit KPhysicalAddress g_secure_region_phys_addr = Null; + constinit size_t g_secure_region_size = 0; + + /* Global variables for randomness. */ + constinit bool g_initialized_random_generator; + constinit util::TinyMT g_random_generator; + constinit KSpinLock g_random_lock; + + ALWAYS_INLINE u64 GenerateRandomU64FromGenerator() { + return g_random_generator.GenerateRandomU64(); + } + + template + ALWAYS_INLINE u64 GenerateUniformRange(u64 min, u64 max, F f) { + /* Handle the case where the difference is too large to represent. */ + if (max == std::numeric_limits::max() && min == std::numeric_limits::min()) { + return f(); + } + + /* Iterate until we get a value in range. */ + const u64 range_size = ((max + 1) - min); + const u64 effective_max = (std::numeric_limits::max() / range_size) * range_size; + while (true) { + if (const u64 rnd = f(); rnd < effective_max) { + return min + (rnd % range_size); + } + } + } + + + /* TODO */ + + ALWAYS_INLINE size_t GetRealMemorySizeForInit() { + return 4_GB; + } + + bool SetSecureRegion(KPhysicalAddress phys_addr, size_t size) { + /* Ensure address and size are aligned. */ + if (!util::IsAligned(GetInteger(phys_addr), SecureAlignment)) { + return false; + } + if (!util::IsAligned(size, SecureAlignment)) { + return false; + } + + /* Disable interrupts and acquire the secure region lock. */ + KScopedInterruptDisable di; + KScopedSpinLock lk(g_secure_region_lock); + + /* If size is non-zero, we're allocating the secure region. Otherwise, we're freeing it. */ + if (size != 0) { + /* Verify that the secure region is free. */ + if (g_secure_region_used) { + return false; + } + + /* Set the secure region. */ + g_secure_region_used = true; + g_secure_region_phys_addr = phys_addr; + g_secure_region_size = size; + } else { + /* Verify that the secure region is in use. */ + if (!g_secure_region_used) { + return false; + } + + /* Verify that the address being freed is the secure region. */ + if (phys_addr != g_secure_region_phys_addr) { + return false; + } + + /* Clear the secure region. */ + g_secure_region_used = false; + g_secure_region_phys_addr = Null; + g_secure_region_size = 0; + } + + // /* Configure the carveout with the secure monitor. */ + // smc::ConfigureCarveout(1, GetInteger(phys_addr), size); + + return true; + } + + Result AllocateSecureMemoryForApplet(KVirtualAddress *out, size_t size) { + /* Verify that the size is valid. */ + R_UNLESS(util::IsAligned(size, PageSize), svc::ResultInvalidSize()); + R_UNLESS(size <= SecureAppletMemorySize, svc::ResultOutOfMemory()); + + /* Disable interrupts and acquire the secure applet lock. */ + KScopedInterruptDisable di; + KScopedSpinLock lk(g_secure_applet_lock); + + /* Check that memory is reserved for secure applet use. */ + MESOSPHERE_ABORT_UNLESS(g_secure_applet_memory_address != Null); + + /* Verify that the secure applet memory isn't already being used. */ + R_UNLESS(!g_secure_applet_memory_used, svc::ResultOutOfMemory()); + + /* Return the secure applet memory. */ + g_secure_applet_memory_used = true; + *out = g_secure_applet_memory_address; + + return ResultSuccess(); + } + + void FreeSecureMemoryForApplet(KVirtualAddress address, size_t size) { + /* Disable interrupts and acquire the secure applet lock. */ + KScopedInterruptDisable di; + KScopedSpinLock lk(g_secure_applet_lock); + + /* Verify that the memory being freed is correct. */ + MESOSPHERE_ABORT_UNLESS(address == g_secure_applet_memory_address); + MESOSPHERE_ABORT_UNLESS(size <= SecureAppletMemorySize); + MESOSPHERE_ABORT_UNLESS(util::IsAligned(size, PageSize)); + MESOSPHERE_ABORT_UNLESS(g_secure_applet_memory_used); + + /* Release the secure applet memory. */ + g_secure_applet_memory_used = false; + } + + void EnsureRandomGeneratorSeeded() { + if (AMS_UNLIKELY(!g_initialized_random_generator)) { + u64 seed = UINT64_C(0xF5F5F5F5F5F5F5F5); + g_random_generator.Initialize(reinterpret_cast(std::addressof(seed)), sizeof(seed) / sizeof(u32)); + g_initialized_random_generator = true; + } + } + + } + + /* Initialization. */ + size_t KSystemControl::Init::GetIntendedMemorySize() { + return 4_GB; + } + + KPhysicalAddress KSystemControl::Init::GetKernelPhysicalBaseAddress(uintptr_t base_address) { + const size_t real_dram_size = GetRealMemorySizeForInit(); + const size_t intended_dram_size = KSystemControl::Init::GetIntendedMemorySize(); + if (intended_dram_size * 2 < real_dram_size) { + return base_address; + } else { + return base_address + ((real_dram_size - intended_dram_size) / 2); + } + } + + void KSystemControl::Init::GetInitialProcessBinaryLayout(InitialProcessBinaryLayout *out) { + *out = { + .address = GetInteger(GetKernelPhysicalBaseAddress(DramPhysicalAddress)) + GetIntendedMemorySize() - KTraceBufferSize - InitialProcessBinarySizeMax, + ._08 = 0, + }; + } + + + bool KSystemControl::Init::ShouldIncreaseThreadResourceLimit() { + return true; + } + + + size_t KSystemControl::Init::GetApplicationPoolSize() { + /* Get the base pool size. */ + const size_t base_pool_size = 3285_MB; + + /* Return (possibly) adjusted size. */ + return base_pool_size; + } + + size_t KSystemControl::Init::GetAppletPoolSize() { + /* Get the base pool size. */ + const size_t base_pool_size = 507_MB; + + /* Return (possibly) adjusted size. */ + constexpr size_t ExtraSystemMemoryForAtmosphere = 40_MB; + return base_pool_size - ExtraSystemMemoryForAtmosphere - KTraceBufferSize; + } + + size_t KSystemControl::Init::GetMinimumNonSecureSystemPoolSize() { + return 0x29C8000; + } + + void KSystemControl::Init::CpuOn(u64 core_id, uintptr_t entrypoint, uintptr_t arg) { + smc::init::CpuOn(core_id, entrypoint, arg); + } + + /* Randomness for Initialization. */ + void KSystemControl::Init::GenerateRandomBytes(void *dst, size_t size) { + EnsureRandomGeneratorSeeded(); + + u8 *dst_8 = static_cast(dst); + while (size > 0) { + const u64 random = GenerateRandomU64FromGenerator(); + std::memcpy(dst_8, std::addressof(random), std::min(size, sizeof(u64))); + size -= std::min(size, sizeof(u64)); + } + } + + u64 KSystemControl::Init::GenerateRandomRange(u64 min, u64 max) { + EnsureRandomGeneratorSeeded(); + + return GenerateUniformRange(min, max, GenerateRandomU64FromGenerator); + } + + /* System Initialization. */ + void KSystemControl::InitializePhase1() { + /* Set IsDebugMode. */ + { + KTargetSystem::SetIsDebugMode(true); + + /* If debug mode, we want to initialize uart logging. */ + KTargetSystem::EnableDebugLogging(true); + KDebugLog::Initialize(); + } + + /* Set Kernel Configuration. */ + { + KTargetSystem::EnableDebugMemoryFill(false); + KTargetSystem::EnableUserExceptionHandlers(true); + KTargetSystem::EnableDynamicResourceLimits(true); + KTargetSystem::EnableUserPmuAccess(false); + } + + /* Set Kernel Debugging. */ + { + /* NOTE: This is used to restrict access to SvcKernelDebug/SvcChangeKernelTraceState. */ + /* Mesosphere may wish to not require this, as we'd ideally keep ProgramVerification enabled for userland. */ + KTargetSystem::EnableKernelDebugging(true); + } + + /* System ResourceLimit initialization. */ + { + /* Construct the resource limit object. */ + KResourceLimit &sys_res_limit = Kernel::GetSystemResourceLimit(); + KAutoObject::Create(std::addressof(sys_res_limit)); + sys_res_limit.Initialize(); + + /* Set the initial limits. */ + const auto [total_memory_size, kernel_memory_size] = KMemoryLayout::GetTotalAndKernelMemorySizes(); + const auto &slab_counts = init::GetSlabResourceCounts(); + MESOSPHERE_R_ABORT_UNLESS(sys_res_limit.SetLimitValue(ams::svc::LimitableResource_PhysicalMemoryMax, total_memory_size)); + MESOSPHERE_R_ABORT_UNLESS(sys_res_limit.SetLimitValue(ams::svc::LimitableResource_ThreadCountMax, slab_counts.num_KThread)); + MESOSPHERE_R_ABORT_UNLESS(sys_res_limit.SetLimitValue(ams::svc::LimitableResource_EventCountMax, slab_counts.num_KEvent)); + MESOSPHERE_R_ABORT_UNLESS(sys_res_limit.SetLimitValue(ams::svc::LimitableResource_TransferMemoryCountMax, slab_counts.num_KTransferMemory)); + MESOSPHERE_R_ABORT_UNLESS(sys_res_limit.SetLimitValue(ams::svc::LimitableResource_SessionCountMax, slab_counts.num_KSession)); + + /* Reserve system memory. */ + MESOSPHERE_ABORT_UNLESS(sys_res_limit.Reserve(ams::svc::LimitableResource_PhysicalMemoryMax, kernel_memory_size)); + } + } + + void KSystemControl::InitializePhase2() { + /* Reserve secure applet memory. */ + if (GetTargetFirmware() >= TargetFirmware_5_0_0) { + MESOSPHERE_ABORT_UNLESS(g_secure_applet_memory_address == Null); + MESOSPHERE_ABORT_UNLESS(Kernel::GetSystemResourceLimit().Reserve(ams::svc::LimitableResource_PhysicalMemoryMax, SecureAppletMemorySize)); + + constexpr auto SecureAppletAllocateOption = KMemoryManager::EncodeOption(KMemoryManager::Pool_System, KMemoryManager::Direction_FromFront); + const KPhysicalAddress secure_applet_memory_phys_addr = Kernel::GetMemoryManager().AllocateAndOpenContinuous(SecureAppletMemorySize / PageSize, 1, SecureAppletAllocateOption); + MESOSPHERE_ABORT_UNLESS(secure_applet_memory_phys_addr != Null); + + g_secure_applet_memory_address = KMemoryLayout::GetLinearVirtualAddress(secure_applet_memory_phys_addr); + } + + /* Initialize KTrace. */ + if constexpr (IsKTraceEnabled) { + const auto &ktrace = KMemoryLayout::GetKernelTraceBufferRegion(); + KTrace::Initialize(ktrace.GetAddress(), ktrace.GetSize()); + } + } + + u32 KSystemControl::GetCreateProcessMemoryPool() { + return KMemoryManager::Pool_Unsafe; + } + + /* Privileged Access. */ + void KSystemControl::ReadWriteRegisterPrivileged(u32 *out, ams::svc::PhysicalAddress address, u32 mask, u32 value) { + MESOSPHERE_UNUSED(out, address, mask, value); + MESOSPHERE_UNIMPLEMENTED(); + } + + Result KSystemControl::ReadWriteRegister(u32 *out, ams::svc::PhysicalAddress address, u32 mask, u32 value) { + MESOSPHERE_UNUSED(out, address, mask, value); + MESOSPHERE_UNIMPLEMENTED(); + } + + /* Randomness. */ + void KSystemControl::GenerateRandomBytes(void *dst, size_t size) { + KScopedInterruptDisable intr_disable; + KScopedSpinLock lk(g_random_lock); + + u8 *dst_8 = static_cast(dst); + while (size > 0) { + const u64 random = GenerateRandomU64FromGenerator(); + std::memcpy(dst_8, std::addressof(random), std::min(size, sizeof(u64))); + size -= std::min(size, sizeof(u64)); + } + } + + u64 KSystemControl::GenerateRandomRange(u64 min, u64 max) { + KScopedInterruptDisable intr_disable; + KScopedSpinLock lk(g_random_lock); + + return GenerateUniformRange(min, max, GenerateRandomU64FromGenerator); + } + + u64 KSystemControl::GenerateRandomU64() { + KScopedInterruptDisable intr_disable; + KScopedSpinLock lk(g_random_lock); + + return GenerateRandomU64FromGenerator(); + } + + void KSystemControl::SleepSystem() { + MESOSPHERE_LOG("SleepSystem() was called\n"); + MESOSPHERE_UNIMPLEMENTED(); + } + + void KSystemControl::StopSystem(void *arg) { + MESOSPHERE_UNUSED(arg); + AMS_INFINITE_LOOP(); + } + + /* User access. */ + void KSystemControl::CallSecureMonitorFromUser(ams::svc::lp64::SecureMonitorArguments *args) { + /* Get the function id for the current call. */ + u64 function_id = args->r[0]; + + /* We'll need to map in pages if arguments are pointers. Prepare page groups to do so. */ + auto &page_table = GetCurrentProcess().GetPageTable(); + auto *bim = page_table.GetBlockInfoManager(); + + constexpr size_t MaxMappedRegisters = 7; + std::array page_groups = { KPageGroup(bim), KPageGroup(bim), KPageGroup(bim), KPageGroup(bim), KPageGroup(bim), KPageGroup(bim), KPageGroup(bim), }; + + for (size_t i = 0; i < MaxMappedRegisters; i++) { + const size_t reg_id = i + 1; + if (function_id & (1ul << (8 + reg_id))) { + /* Create and open a new page group for the address. */ + KVirtualAddress virt_addr = args->r[reg_id]; + + if (R_SUCCEEDED(page_table.MakeAndOpenPageGroup(std::addressof(page_groups[i]), util::AlignDown(GetInteger(virt_addr), PageSize), 1, KMemoryState_None, KMemoryState_None, KMemoryPermission_UserReadWrite, KMemoryPermission_UserReadWrite, KMemoryAttribute_None, KMemoryAttribute_None))) { + /* Translate the virtual address to a physical address. */ + const auto it = page_groups[i].begin(); + MESOSPHERE_ASSERT(it != page_groups[i].end()); + MESOSPHERE_ASSERT(it->GetNumPages() == 1); + + args->r[reg_id] = GetInteger(it->GetAddress()) | (GetInteger(virt_addr) & (PageSize - 1)); + } else { + /* If we couldn't map, we should clear the address. */ + args->r[reg_id] = 0; + } + } + } + + /* Invoke the secure monitor. */ + smc::CallSecureMonitorFromUser(args); + + /* Make sure that we close any pages that we opened. */ + for (size_t i = 0; i < MaxMappedRegisters; i++) { + page_groups[i].Close(); + } + } + + /* Secure Memory. */ + size_t KSystemControl::CalculateRequiredSecureMemorySize(size_t size, u32 pool) { + if (pool == KMemoryManager::Pool_Applet) { + return 0; + } + return size; + } + + Result KSystemControl::AllocateSecureMemory(KVirtualAddress *out, size_t size, u32 pool) { + /* Applet secure memory is handled separately. */ + if (pool == KMemoryManager::Pool_Applet) { + return AllocateSecureMemoryForApplet(out, size); + } + + /* Ensure the size is aligned. */ + const size_t alignment = (pool == KMemoryManager::Pool_System ? PageSize : SecureAlignment); + R_UNLESS(util::IsAligned(size, alignment), svc::ResultInvalidSize()); + + /* Allocate the memory. */ + const size_t num_pages = size / PageSize; + const KPhysicalAddress paddr = Kernel::GetMemoryManager().AllocateAndOpenContinuous(num_pages, alignment / PageSize, KMemoryManager::EncodeOption(static_cast(pool), KMemoryManager::Direction_FromFront)); + R_UNLESS(paddr != Null, svc::ResultOutOfMemory()); + + /* Ensure we don't leak references to the memory on error. */ + auto mem_guard = SCOPE_GUARD { Kernel::GetMemoryManager().Close(paddr, num_pages); }; + + /* If the memory isn't already secure, set it as secure. */ + if (pool != KMemoryManager::Pool_System) { + /* Set the secure region. */ + R_UNLESS(SetSecureRegion(paddr, size), svc::ResultOutOfMemory()); + } + + /* We succeeded. */ + mem_guard.Cancel(); + *out = KPageTable::GetHeapVirtualAddress(paddr); + return ResultSuccess(); + } + + void KSystemControl::FreeSecureMemory(KVirtualAddress address, size_t size, u32 pool) { + /* Applet secure memory is handled separately. */ + if (pool == KMemoryManager::Pool_Applet) { + return FreeSecureMemoryForApplet(address, size); + } + + /* Ensure the size is aligned. */ + const size_t alignment = (pool == KMemoryManager::Pool_System ? PageSize : SecureAlignment); + MESOSPHERE_ABORT_UNLESS(util::IsAligned(GetInteger(address), alignment)); + MESOSPHERE_ABORT_UNLESS(util::IsAligned(size, alignment)); + + /* If the memory isn't secure system, reset the secure region. */ + if (pool != KMemoryManager::Pool_System) { + /* Check that the size being freed is the current secure region size. */ + MESOSPHERE_ABORT_UNLESS(g_secure_region_size == size); + + /* Get the physical address. */ + const KPhysicalAddress paddr = KPageTable::GetHeapPhysicalAddress(address); + MESOSPHERE_ABORT_UNLESS(paddr != Null); + + /* Check that the memory being freed is the current secure region. */ + MESOSPHERE_ABORT_UNLESS(paddr == g_secure_region_phys_addr); + + /* Free the secure region. */ + MESOSPHERE_ABORT_UNLESS(SetSecureRegion(paddr, 0)); + } + + /* Close the secure region's pages. */ + Kernel::GetMemoryManager().Close(KPageTable::GetHeapPhysicalAddress(address), size / PageSize); + } + +} \ No newline at end of file diff --git a/libraries/libmesosphere/source/board/qemu/virt/kern_secure_monitor.cpp b/libraries/libmesosphere/source/board/qemu/virt/kern_secure_monitor.cpp new file mode 100644 index 000000000..c4fa1c380 --- /dev/null +++ b/libraries/libmesosphere/source/board/qemu/virt/kern_secure_monitor.cpp @@ -0,0 +1,171 @@ +/* + * Copyright (c) Atmosphère-NX + * + * This program is free software; you can redistribute it and/or modify it + * under the terms and conditions of the GNU General Public License, + * version 2, as published by the Free Software Foundation. + * + * This program is distributed in the hope it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +#include +#include "kern_secure_monitor.hpp" + +namespace ams::kern::board::qemu::virt::smc { + + namespace { + + struct SecureMonitorArguments { + u64 x[8]; + }; + + enum UserFunctionId : u32 { + UserFunctionId_SetConfig = 0xC3000401, + UserFunctionId_GetConfig = 0xC3000002, + UserFunctionId_GetResult = 0xC3000003, + UserFunctionId_GetResultData = 0xC3000404, + UserFunctionId_ModularExponentiate = 0xC3000E05, + UserFunctionId_GenerateRandomBytes = 0xC3000006, + UserFunctionId_GenerateAesKek = 0xC3000007, + UserFunctionId_LoadAesKey = 0xC3000008, + UserFunctionId_ComputeAes = 0xC3000009, + UserFunctionId_GenerateSpecificAesKey = 0xC300000A, + UserFunctionId_ComputeCmac = 0xC300040B, + UserFunctionId_ReencryptDeviceUniqueData = 0xC300D60C, + UserFunctionId_DecryptDeviceUniqueData = 0xC300100D, + UserFunctionId_ModularExponentiateByStorageKey = 0xC300060F, + UserFunctionId_PrepareEsDeviceUniqueKey = 0xC3000610, + UserFunctionId_LoadPreparedAesKey = 0xC3000011, + UserFunctionId_PrepareEsCommonTitleKey = 0xC3000012, + }; + + enum FunctionId : u32 { + FunctionId_CpuSuspend = 0xC4000001, + FunctionId_CpuOff = 0x84000002, + FunctionId_CpuOn = 0xC4000003, + }; + + void CallPrivilegedSecureMonitorFunction(SecureMonitorArguments &args) { + /* Load arguments into registers. */ + register u64 x0 asm("x0") = args.x[0]; + register u64 x1 asm("x1") = args.x[1]; + register u64 x2 asm("x2") = args.x[2]; + register u64 x3 asm("x3") = args.x[3]; + register u64 x4 asm("x4") = args.x[4]; + register u64 x5 asm("x5") = args.x[5]; + register u64 x6 asm("x6") = args.x[6]; + register u64 x7 asm("x7") = args.x[7]; + + /* Actually make the call. */ + { + /* Disable interrupts while making the call. */ + KScopedInterruptDisable intr_disable; + + { + /* Backup the current thread pointer. */ + const uintptr_t current_thread_pointer_value = cpu::GetCurrentThreadPointerValue(); + + __asm__ __volatile__("smc #0" + : "+r"(x0), "+r"(x1), "+r"(x2), "+r"(x3), "+r"(x4), "+r"(x5), "+r"(x6), "+r"(x7) + : + : "x8", "x9", "x10", "x11", "x12", "x13", "x14", "x15", "x16", "x17", "x18", "cc", "memory" + ); + + /* Restore the current thread pointer into X18. */ + cpu::SetCurrentThreadPointerValue(current_thread_pointer_value); + + /* Store arguments to output. */ + args.x[0] = x0; + args.x[1] = x1; + args.x[2] = x2; + args.x[3] = x3; + args.x[4] = x4; + args.x[5] = x5; + args.x[6] = x6; + args.x[7] = x7; + } + } + } + + void CallPrivilegedSecureMonitorFunctionForInit(SecureMonitorArguments &args) { + /* Load arguments into registers. */ + register u64 x0 asm("x0") = args.x[0]; + register u64 x1 asm("x1") = args.x[1]; + register u64 x2 asm("x2") = args.x[2]; + register u64 x3 asm("x3") = args.x[3]; + register u64 x4 asm("x4") = args.x[4]; + register u64 x5 asm("x5") = args.x[5]; + register u64 x6 asm("x6") = args.x[6]; + register u64 x7 asm("x7") = args.x[7]; + + /* Actually make the call. */ + __asm__ __volatile__("smc #0" + : "+r"(x0), "+r"(x1), "+r"(x2), "+r"(x3), "+r"(x4), "+r"(x5), "+r"(x6), "+r"(x7) + : + : "x8", "x9", "x10", "x11", "x12", "x13", "x14", "x15", "x16", "x17", "x18", "cc", "memory" + ); + + /* Store arguments to output. */ + args.x[0] = x0; + args.x[1] = x1; + args.x[2] = x2; + args.x[3] = x3; + args.x[4] = x4; + args.x[5] = x5; + args.x[6] = x6; + args.x[7] = x7; + } + + /* Global lock for generate random bytes. */ + KSpinLock g_generate_random_lock; + + } + + /* SMC functionality needed for init. */ + namespace init { + + void CpuOn(u64 core_id, uintptr_t entrypoint, uintptr_t arg) { + SecureMonitorArguments args = { FunctionId_CpuOn, core_id, entrypoint, arg }; + CallPrivilegedSecureMonitorFunctionForInit(args); + } + + } + + void CpuOn(u64 core_id, uintptr_t entrypoint, uintptr_t arg) { + SecureMonitorArguments args = { FunctionId_CpuOn, core_id, static_cast(entrypoint), static_cast(arg) }; + CallPrivilegedSecureMonitorFunction(args); + MESOSPHERE_ABORT_UNLESS((static_cast(args.x[0]) == SmcResult::Success)); + } + + void CallSecureMonitorFromUser(ams::svc::lp64::SecureMonitorArguments *args) { + MESOSPHERE_LOG("Received SMC [%p %p %p %p %p %p %p %p] from %s\n", reinterpret_cast(args->r[0]), reinterpret_cast(args->r[1]), reinterpret_cast(args->r[2]), reinterpret_cast(args->r[3]), reinterpret_cast(args->r[4]), reinterpret_cast(args->r[5]), reinterpret_cast(args->r[6]), reinterpret_cast(args->r[7]), GetCurrentProcess().GetName()); + + switch (args->r[0]) { + case UserFunctionId_GetConfig: + { + switch (static_cast(args->r[1])) { + case ConfigItem::ExosphereApiVersion: + args->r[1] = (static_cast(ATMOSPHERE_RELEASE_VERSION_MAJOR & 0xFF) << 56) | + (static_cast(ATMOSPHERE_RELEASE_VERSION_MINOR & 0xFF) << 48) | + (static_cast(ATMOSPHERE_RELEASE_VERSION_MICRO & 0xFF) << 40) | + (static_cast(13) << 32) | + (static_cast(GetTargetFirmware()) << 0); + break; + default: + MESOSPHERE_PANIC("Unhandled GetConfig\n"); + } + + args->r[0] = static_cast(SmcResult::Success); + } + break; + default: + MESOSPHERE_PANIC("Unhandled SMC [%p %p %p %p %p %p %p %p]", reinterpret_cast(args->r[0]), reinterpret_cast(args->r[1]), reinterpret_cast(args->r[2]), reinterpret_cast(args->r[3]), reinterpret_cast(args->r[4]), reinterpret_cast(args->r[5]), reinterpret_cast(args->r[6]), reinterpret_cast(args->r[7])); + } + } + +} \ No newline at end of file diff --git a/libraries/libmesosphere/source/board/qemu/virt/kern_secure_monitor.hpp b/libraries/libmesosphere/source/board/qemu/virt/kern_secure_monitor.hpp new file mode 100644 index 000000000..869624007 --- /dev/null +++ b/libraries/libmesosphere/source/board/qemu/virt/kern_secure_monitor.hpp @@ -0,0 +1,76 @@ +/* + * Copyright (c) Atmosphère-NX + * + * This program is free software; you can redistribute it and/or modify it + * under the terms and conditions of the GNU General Public License, + * version 2, as published by the Free Software Foundation. + * + * This program is distributed in the hope it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +#pragma once +#include + +namespace ams::kern::board::qemu::virt::smc { + + enum class ConfigItem : u32 { + /* Standard config items. */ + DisableProgramVerification = 1, + DramId = 2, + SecurityEngineIrqNumber = 3, + Version = 4, + HardwareType = 5, + IsRetail = 6, + IsRecoveryBoot = 7, + DeviceId = 8, + BootReason = 9, + MemoryMode = 10, + IsDebugMode = 11, + KernelConfiguration = 12, + IsChargerHiZModeEnabled = 13, + IsQuest = 14, + RegulatorType = 15, + DeviceUniqueKeyGeneration = 16, + Package2Hash = 17, + + /* Extension config items for exosphere. */ + ExosphereApiVersion = 65000, + ExosphereNeedsReboot = 65001, + ExosphereNeedsShutdown = 65002, + ExosphereGitCommitHash = 65003, + ExosphereHasRcmBugPatch = 65004, + ExosphereBlankProdInfo = 65005, + ExosphereAllowCalWrites = 65006, + ExosphereEmummcType = 65007, + ExospherePayloadAddress = 65008, + ExosphereLogConfiguration = 65009, + ExosphereForceEnableUsb30 = 65010, + ExosphereSupportedHosVersion = 65011, + }; + + enum class SmcResult { + Success = 0, + NotImplemented = 1, + InvalidArgument = 2, + InProgress = 3, + NoAsyncOperation = 4, + InvalidAsyncOperation = 5, + NotPermitted = 6, + }; + + void CpuOn(u64 core_id, uintptr_t entrypoint, uintptr_t arg); + + void CallSecureMonitorFromUser(ams::svc::lp64::SecureMonitorArguments *args); + + namespace init { + + void CpuOn(u64 core_id, uintptr_t entrypoint, uintptr_t arg); + + } + +} \ No newline at end of file diff --git a/libraries/libmesosphere/source/kern_debug_log.cpp b/libraries/libmesosphere/source/kern_debug_log.cpp index 6ff3df949..5f296b65b 100644 --- a/libraries/libmesosphere/source/kern_debug_log.cpp +++ b/libraries/libmesosphere/source/kern_debug_log.cpp @@ -32,6 +32,9 @@ namespace ams::kern { return; } + #if defined(MESOSPHERE_DEBUG_LOG_USE_SEMIHOSTING) + KDebugLogImpl::PutStringBySemihosting(str); + #else while (*str) { /* Get a character. */ const char c = *(str++); @@ -44,6 +47,7 @@ namespace ams::kern { } KDebugLogImpl::Flush(); + #endif } #if defined(MESOSPHERE_ENABLE_DEBUG_PRINT) @@ -54,6 +58,11 @@ namespace ams::kern { return ResultSuccess(); } + #if defined(MESOSPHERE_DEBUG_LOG_USE_SEMIHOSTING) + /* TODO: should we do this properly? */ + KDebugLogImpl::PutStringBySemihosting(user_str.GetUnsafePointer()); + MESOSPHERE_UNUSED(len); + #else for (size_t i = 0; i < len; ++i) { /* Get a character. */ char c; @@ -67,6 +76,7 @@ namespace ams::kern { } KDebugLogImpl::Flush(); + #endif return ResultSuccess(); } diff --git a/libraries/libmesosphere/source/kern_debug_log_impl.arch.arm64.s b/libraries/libmesosphere/source/kern_debug_log_impl.arch.arm64.s new file mode 100644 index 000000000..e7d4423e3 --- /dev/null +++ b/libraries/libmesosphere/source/kern_debug_log_impl.arch.arm64.s @@ -0,0 +1,27 @@ +/* + * Copyright (c) Atmosphère-NX + * + * This program is free software; you can redistribute it and/or modify it + * under the terms and conditions of the GNU General Public License, + * version 2, as published by the Free Software Foundation. + * + * This program is distributed in the hope it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/* ams::kern::KDebugLogImpl::PutStringBySemihosting(const char *str) */ +.section .text._ZN3ams4kern13KDebugLogImpl22PutStringBySemihostingEPKc, "ax", %progbits +.global _ZN3ams4kern13KDebugLogImpl22PutStringBySemihostingEPKc +.type _ZN3ams4kern13KDebugLogImpl22PutStringBySemihostingEPKc, %function +.balign 0x10 +_ZN3ams4kern13KDebugLogImpl22PutStringBySemihostingEPKc: + mov x1, x0 + mov x0, #0x4 + hlt #0xF000 + ret + diff --git a/libraries/libmesosphere/source/kern_debug_log_impl.board.qemu_virt.cpp b/libraries/libmesosphere/source/kern_debug_log_impl.board.qemu_virt.cpp new file mode 100644 index 000000000..a71b904d4 --- /dev/null +++ b/libraries/libmesosphere/source/kern_debug_log_impl.board.qemu_virt.cpp @@ -0,0 +1,50 @@ +/* + * Copyright (c) Atmosphère-NX + * + * This program is free software; you can redistribute it and/or modify it + * under the terms and conditions of the GNU General Public License, + * version 2, as published by the Free Software Foundation. + * + * This program is distributed in the hope it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +#include +#include "kern_debug_log_impl.hpp" + +namespace ams::kern { + +#if defined(MESOSPHERE_DEBUG_LOG_USE_SEMIHOSTING) + + bool KDebugLogImpl::Initialize() { + return true; + } + + void KDebugLogImpl::PutChar(char c) { + /* TODO */ + AMS_UNUSED(c); + } + + void KDebugLogImpl::Flush() { + /* ... */ + } + + void KDebugLogImpl::Save() { + /* ... */ + } + + void KDebugLogImpl::Restore() { + /* ... */ + } + +#else + + #error "Unknown Debug device!" + +#endif + +} diff --git a/libraries/libmesosphere/source/kern_debug_log_impl.hpp b/libraries/libmesosphere/source/kern_debug_log_impl.hpp index fb065c532..a34591db4 100644 --- a/libraries/libmesosphere/source/kern_debug_log_impl.hpp +++ b/libraries/libmesosphere/source/kern_debug_log_impl.hpp @@ -21,6 +21,7 @@ namespace ams::kern { class KDebugLogImpl { public: static NOINLINE bool Initialize(); + static NOINLINE void PutStringBySemihosting(const char *s); static NOINLINE void PutChar(char c); static NOINLINE void Flush(); diff --git a/libraries/libmesosphere/source/kern_k_memory_layout.board.qemu_virt.cpp b/libraries/libmesosphere/source/kern_k_memory_layout.board.qemu_virt.cpp new file mode 100644 index 000000000..578761d65 --- /dev/null +++ b/libraries/libmesosphere/source/kern_k_memory_layout.board.qemu_virt.cpp @@ -0,0 +1,137 @@ +/* + * Copyright (c) Atmosphère-NX + * + * This program is free software; you can redistribute it and/or modify it + * under the terms and conditions of the GNU General Public License, + * version 2, as published by the Free Software Foundation. + * + * This program is distributed in the hope it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +#include + +namespace ams::kern { + + namespace { + + constexpr uintptr_t DramPhysicalAddress = 0x40000000; + constexpr size_t ReservedEarlyDramSize = 0x00080000; + + constexpr size_t CarveoutAlignment = 0x20000; + constexpr size_t CarveoutSizeMax = 512_MB - CarveoutAlignment; + + template requires (std::same_as && ...) + constexpr ALWAYS_INLINE KMemoryRegionType GetMemoryRegionType(KMemoryRegionType base, T... attr) { + return util::FromUnderlying(util::ToUnderlying(base) | (util::ToUnderlying(attr) | ...)); + } + + void InsertPoolPartitionRegionIntoBothTrees(size_t start, size_t size, KMemoryRegionType phys_type, KMemoryRegionType virt_type, u32 &cur_attr) { + const u32 attr = cur_attr++; + MESOSPHERE_INIT_ABORT_UNLESS(KMemoryLayout::GetPhysicalMemoryRegionTree().Insert(start, size, phys_type, attr)); + const KMemoryRegion *phys = KMemoryLayout::GetPhysicalMemoryRegionTree().FindByTypeAndAttribute(phys_type, attr); + MESOSPHERE_INIT_ABORT_UNLESS(phys != nullptr); + MESOSPHERE_INIT_ABORT_UNLESS(phys->GetEndAddress() != 0); + MESOSPHERE_INIT_ABORT_UNLESS(KMemoryLayout::GetVirtualMemoryRegionTree().Insert(phys->GetPairAddress(), size, virt_type, attr)); + } + + } + + namespace init { + + void SetupDevicePhysicalMemoryRegions() { + MESOSPHERE_INIT_ABORT_UNLESS(KMemoryLayout::GetPhysicalMemoryRegionTree().Insert(0x08000000, 0x10000, GetMemoryRegionType(KMemoryRegionType_InterruptDistributor, KMemoryRegionAttr_ShouldKernelMap))); + MESOSPHERE_INIT_ABORT_UNLESS(KMemoryLayout::GetPhysicalMemoryRegionTree().Insert(0x08010000, 0x10000, GetMemoryRegionType(KMemoryRegionType_InterruptCpuInterface, KMemoryRegionAttr_ShouldKernelMap))); + } + + void SetupDramPhysicalMemoryRegions() { + const size_t intended_memory_size = KSystemControl::Init::GetIntendedMemorySize(); + const KPhysicalAddress physical_memory_base_address = KSystemControl::Init::GetKernelPhysicalBaseAddress(DramPhysicalAddress); + + /* Insert blocks into the tree. */ + MESOSPHERE_INIT_ABORT_UNLESS(KMemoryLayout::GetPhysicalMemoryRegionTree().Insert(GetInteger(physical_memory_base_address), intended_memory_size, KMemoryRegionType_Dram)); + MESOSPHERE_INIT_ABORT_UNLESS(KMemoryLayout::GetPhysicalMemoryRegionTree().Insert(GetInteger(physical_memory_base_address), ReservedEarlyDramSize, KMemoryRegionType_DramReservedEarly)); + + /* Insert the KTrace block at the end of Dram, if KTrace is enabled. */ + static_assert(!IsKTraceEnabled || KTraceBufferSize > 0); + if constexpr (IsKTraceEnabled) { + const KPhysicalAddress ktrace_buffer_phys_addr = physical_memory_base_address + intended_memory_size - KTraceBufferSize; + MESOSPHERE_INIT_ABORT_UNLESS(KMemoryLayout::GetPhysicalMemoryRegionTree().Insert(GetInteger(ktrace_buffer_phys_addr), KTraceBufferSize, KMemoryRegionType_KernelTraceBuffer)); + } + } + + void SetupPoolPartitionMemoryRegions() { + /* Start by identifying the extents of the DRAM memory region. */ + const auto dram_extents = KMemoryLayout::GetMainMemoryPhysicalExtents(); + MESOSPHERE_INIT_ABORT_UNLESS(dram_extents.GetEndAddress() != 0); + + /* Determine the end of the pool region. */ + const uintptr_t pool_end = dram_extents.GetEndAddress() - KTraceBufferSize; + + /* Find the start of the kernel DRAM region. */ + const KMemoryRegion *kernel_dram_region = KMemoryLayout::GetPhysicalMemoryRegionTree().FindFirstDerived(KMemoryRegionType_DramKernelBase); + MESOSPHERE_INIT_ABORT_UNLESS(kernel_dram_region != nullptr); + + const uintptr_t kernel_dram_start = kernel_dram_region->GetAddress(); + MESOSPHERE_INIT_ABORT_UNLESS(util::IsAligned(kernel_dram_start, CarveoutAlignment)); + + /* Find the start of the pool partitions region. */ + const KMemoryRegion *pool_partitions_region = KMemoryLayout::GetPhysicalMemoryRegionTree().FindByTypeAndAttribute(KMemoryRegionType_DramPoolPartition, 0); + MESOSPHERE_INIT_ABORT_UNLESS(pool_partitions_region != nullptr); + const uintptr_t pool_partitions_start = pool_partitions_region->GetAddress(); + + /* Setup the pool partition layouts. */ + /* Get Application and Applet pool sizes. */ + const size_t application_pool_size = KSystemControl::Init::GetApplicationPoolSize(); + const size_t applet_pool_size = KSystemControl::Init::GetAppletPoolSize(); + const size_t unsafe_system_pool_min_size = KSystemControl::Init::GetMinimumNonSecureSystemPoolSize(); + + /* Decide on starting addresses for our pools. */ + const uintptr_t application_pool_start = pool_end - application_pool_size; + const uintptr_t applet_pool_start = application_pool_start - applet_pool_size; + const uintptr_t unsafe_system_pool_start = std::min(kernel_dram_start + CarveoutSizeMax, util::AlignDown(applet_pool_start - unsafe_system_pool_min_size, CarveoutAlignment)); + const size_t unsafe_system_pool_size = applet_pool_start - unsafe_system_pool_start; + + /* We want to arrange application pool depending on where the middle of dram is. */ + const uintptr_t dram_midpoint = (dram_extents.GetAddress() + dram_extents.GetEndAddress()) / 2; + u32 cur_pool_attr = 0; + size_t total_overhead_size = 0; + if (dram_extents.GetEndAddress() <= dram_midpoint || dram_midpoint <= application_pool_start) { + InsertPoolPartitionRegionIntoBothTrees(application_pool_start, application_pool_size, KMemoryRegionType_DramApplicationPool, KMemoryRegionType_VirtualDramApplicationPool, cur_pool_attr); + total_overhead_size += KMemoryManager::CalculateManagementOverheadSize(application_pool_size); + } else { + const size_t first_application_pool_size = dram_midpoint - application_pool_start; + const size_t second_application_pool_size = application_pool_start + application_pool_size - dram_midpoint; + InsertPoolPartitionRegionIntoBothTrees(application_pool_start, first_application_pool_size, KMemoryRegionType_DramApplicationPool, KMemoryRegionType_VirtualDramApplicationPool, cur_pool_attr); + InsertPoolPartitionRegionIntoBothTrees(dram_midpoint, second_application_pool_size, KMemoryRegionType_DramApplicationPool, KMemoryRegionType_VirtualDramApplicationPool, cur_pool_attr); + total_overhead_size += KMemoryManager::CalculateManagementOverheadSize(first_application_pool_size); + total_overhead_size += KMemoryManager::CalculateManagementOverheadSize(second_application_pool_size); + } + + /* Insert the applet pool. */ + InsertPoolPartitionRegionIntoBothTrees(applet_pool_start, applet_pool_size, KMemoryRegionType_DramAppletPool, KMemoryRegionType_VirtualDramAppletPool, cur_pool_attr); + total_overhead_size += KMemoryManager::CalculateManagementOverheadSize(applet_pool_size); + + /* Insert the nonsecure system pool. */ + InsertPoolPartitionRegionIntoBothTrees(unsafe_system_pool_start, unsafe_system_pool_size, KMemoryRegionType_DramSystemNonSecurePool, KMemoryRegionType_VirtualDramSystemNonSecurePool, cur_pool_attr); + total_overhead_size += KMemoryManager::CalculateManagementOverheadSize(unsafe_system_pool_size); + + /* Insert the pool management region. */ + total_overhead_size += KMemoryManager::CalculateManagementOverheadSize((unsafe_system_pool_start - pool_partitions_start) - total_overhead_size); + const uintptr_t pool_management_start = unsafe_system_pool_start - total_overhead_size; + const size_t pool_management_size = total_overhead_size; + u32 pool_management_attr = 0; + InsertPoolPartitionRegionIntoBothTrees(pool_management_start, pool_management_size, KMemoryRegionType_DramPoolManagement, KMemoryRegionType_VirtualDramPoolManagement, pool_management_attr); + + /* Insert the system pool. */ + const uintptr_t system_pool_size = pool_management_start - pool_partitions_start; + InsertPoolPartitionRegionIntoBothTrees(pool_partitions_start, system_pool_size, KMemoryRegionType_DramSystemPool, KMemoryRegionType_VirtualDramSystemPool, cur_pool_attr); + } + + } + +} \ No newline at end of file diff --git a/libraries/libstratosphere/include/stratosphere/svc/svc_stratosphere_shims.hpp b/libraries/libstratosphere/include/stratosphere/svc/svc_stratosphere_shims.hpp index 50bc3dce2..1ffb3cda6 100644 --- a/libraries/libstratosphere/include/stratosphere/svc/svc_stratosphere_shims.hpp +++ b/libraries/libstratosphere/include/stratosphere/svc/svc_stratosphere_shims.hpp @@ -26,6 +26,11 @@ return ::svcSetHeapSize(reinterpret_cast(out_address), size); } + ALWAYS_INLINE Result SetHeapSize(uintptr_t *out_address, ::ams::svc::Size size) { + static_assert(sizeof(::ams::svc::Address) == sizeof(uintptr_t)); + return ::svcSetHeapSize(reinterpret_cast(out_address), size); + } + ALWAYS_INLINE Result SetMemoryPermission(::ams::svc::Address address, ::ams::svc::Size size, ::ams::svc::MemoryPermission perm) { return ::svcSetMemoryPermission(reinterpret_cast(static_cast(address)), size, static_cast(perm)); } diff --git a/libraries/libstratosphere/source/init/init_libnx_shim.os.horizon.cpp b/libraries/libstratosphere/source/init/init_libnx_shim.os.horizon.cpp index 5f2d21285..4a36bb94e 100644 --- a/libraries/libstratosphere/source/init/init_libnx_shim.os.horizon.cpp +++ b/libraries/libstratosphere/source/init/init_libnx_shim.os.horizon.cpp @@ -38,6 +38,8 @@ namespace ams { namespace init { + void InitializeSystemModuleBeforeConstructors(); + void InitializeSystemModule(); void FinalizeSystemModule(); @@ -66,6 +68,9 @@ extern "C" void __libnx_initheap(void) { extern "C" void __appInit(void) { /* The very first thing all stratosphere code must do is initialize the os library. */ ::ams::hos::InitializeForStratosphere(); + + /* Perform pre-C++ constructor init. */ + ::ams::init::InitializeSystemModuleBeforeConstructors(); } extern "C" void __appExit(void) { diff --git a/libraries/libstratosphere/source/init/init_system_module.cpp b/libraries/libstratosphere/source/init/init_system_module.cpp index 75ccce4ac..0f64a1079 100644 --- a/libraries/libstratosphere/source/init/init_system_module.cpp +++ b/libraries/libstratosphere/source/init/init_system_module.cpp @@ -17,6 +17,10 @@ namespace ams::init { + WEAK_SYMBOL void InitializeSystemModuleBeforeConstructors() { + /* This should only be used in exceptional circumstances. */ + } + WEAK_SYMBOL void InitializeSystemModule() { /* TODO: What should we do here, if anything? */ /* Nintendo does nndiagStartup(); nn::diag::InitializeSystemProcessAbortObserver(); */ diff --git a/libraries/libvapours/include/vapours/svc/board/qemu/virt/svc_hardware_constants.hpp b/libraries/libvapours/include/vapours/svc/board/qemu/virt/svc_hardware_constants.hpp new file mode 100644 index 000000000..5160803a2 --- /dev/null +++ b/libraries/libvapours/include/vapours/svc/board/qemu/virt/svc_hardware_constants.hpp @@ -0,0 +1,23 @@ +/* + * Copyright (c) Atmosphère-NX + * + * This program is free software; you can redistribute it and/or modify it + * under the terms and conditions of the GNU General Public License + * version 2, as published by the Free Software Foundation. + * + * This program is distributed in the hope it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +#pragma once +#include + +namespace ams::svc::board::qemu::virt { + + constexpr inline const s64 TicksPerSecond = 19'200'000; + +} diff --git a/libraries/libvapours/include/vapours/svc/svc_select_hardware_constants.hpp b/libraries/libvapours/include/vapours/svc/svc_select_hardware_constants.hpp index e02784a84..ccd6db318 100644 --- a/libraries/libvapours/include/vapours/svc/svc_select_hardware_constants.hpp +++ b/libraries/libvapours/include/vapours/svc/svc_select_hardware_constants.hpp @@ -24,8 +24,15 @@ using namespace ams::svc::board::nintendo::nx; } +#elif defined(ATMOSPHERE_BOARD_QEMU_VIRT) + + #include + namespace ams::svc { + using namespace ams::svc::board::qemu::virt; + } + #else - #error "Unknown board for svc::DeviceName" + #error "Unknown board for svc Hardware Constants" #endif diff --git a/mesosphere/Makefile b/mesosphere/Makefile index d168d278e..451a68a3e 100644 --- a/mesosphere/Makefile +++ b/mesosphere/Makefile @@ -8,29 +8,47 @@ ATMOSPHERE_BUILD_CONFIGS += $(strip $1) $(strip $1): mesosphere$(strip $2).bin mesosphere$(strip $2).bin: kernel/kernel$(strip $2).bin kernel_ldr/kernel_ldr$(strip $2).bin - @python build_mesosphere.py kernel_ldr/kernel_ldr$(strip $2).bin kernel/kernel$(strip $2).bin mesosphere$(strip $2).bin + @python build_mesosphere.py kernel_ldr/kernel_ldr$(strip $2).bin kernel/kernel$(strip $2).bin mesosphere$(strip $2).bin $(4) @echo "Built mesosphere$(strip $2).bin..." kernel/kernel$(strip $2).bin: check_libmeso$(strip $1) - @$$(MAKE) -C kernel $(strip $1) + @$$(MAKE) -C kernel $(strip $1) $(3) kernel_ldr/kernel_ldr$(strip $2).bin: check_libmeso$(strip $1) - @$$(MAKE) -C kernel_ldr $(strip $1) + @$$(MAKE) -C kernel_ldr $(strip $1) $(3) check_libmeso$(strip $1): - @$$(MAKE) -C ../libraries/libmesosphere $(strip $1) + @$$(MAKE) -C ../libraries/libmesosphere $(strip $1) $(3) clean-$(strip $1): - @$$(MAKE) -C ../libraries/libmesosphere clean-$(strip $1) - @$$(MAKE) -C kernel clean-$(strip $1) - @$$(MAKE) -C kernel_ldr clean-$(strip $1) + @$$(MAKE) -C ../libraries/libmesosphere clean-$(strip $1) $(3) + @$$(MAKE) -C kernel clean-$(strip $1) $(3) + @$$(MAKE) -C kernel_ldr clean-$(strip $1) $(3) @rm -f mesosphere$(strip $2).bin endef -$(eval $(call ATMOSPHERE_ADD_TARGET, release, ,)) -$(eval $(call ATMOSPHERE_ADD_TARGET, debug, _debug,)) -$(eval $(call ATMOSPHERE_ADD_TARGET, audit, _audit,)) +$(eval $(call ATMOSPHERE_ADD_TARGET, release, ,,)) +$(eval $(call ATMOSPHERE_ADD_TARGET, debug, _debug,,)) +$(eval $(call ATMOSPHERE_ADD_TARGET, audit, _audit,,)) + +$(eval $(call ATMOSPHERE_ADD_TARGET, qemu_virt_release, _qemu_virt, \ + ATMOSPHERE_BOARD="qemu-virt" \ + ATMOSPHERE_CPU="arm-cortex-a57" \ + , ../tests/TestSvc/TestSvc.kip \ +)) + +$(eval $(call ATMOSPHERE_ADD_TARGET, qemu_virt_debug, _qemu_virt_debug, \ + ATMOSPHERE_BOARD="qemu-virt" \ + ATMOSPHERE_CPU="arm-cortex-a57" \ + , ../tests/TestSvc/TestSvc.kip \ +)) + +$(eval $(call ATMOSPHERE_ADD_TARGET, qemu_virt_audit, _qemu_virt_audit, \ + ATMOSPHERE_BOARD="qemu-virt" \ + ATMOSPHERE_CPU="arm-cortex-a57" \ + , ../tests/TestSvc/TestSvc.kip \ +)) clean: @$(MAKE) -C ../libraries/libmesosphere clean diff --git a/mesosphere/build_mesosphere.py b/mesosphere/build_mesosphere.py index be51da4f0..5b9dd4f7b 100644 --- a/mesosphere/build_mesosphere.py +++ b/mesosphere/build_mesosphere.py @@ -10,8 +10,8 @@ def align_up(val, algn): return val - (val % algn) def main(argc, argv): - if argc != 4: - print('Usage: %s kernel_ldr.bin kernel.bin output.bin' % argv[0]) + if argc < 4: + print('Usage: %s kernel_ldr.bin kernel.bin output.bin [initial_process.kip ...]' % argv[0]) return 1 with open(argv[1], 'rb') as f: kernel_ldr = f.read() @@ -30,16 +30,25 @@ def main(argc, argv): kernel += b'\x00' * (kernel_end - len(kernel)) assert (kernel_end == len(kernel)) - embedded_ini = b'' - try: - with open('ini.bin', 'rb') as f: - embedded_ini = f.read() - except: - pass + embedded_kips = b'' + num_kips = 0 + for kip_file in argv[4:]: + try: + with open(kip_file, 'rb') as f: + data = f.read() + if data.startswith(b'KIP1'): + embedded_kips += data + num_kips += 1 + except: + pass + if num_kips > 0: + embedded_ini_header = pk('<4sIII', b'INI1', len(embedded_kips) + 0x10, num_kips, 0) + else: + embedded_ini_header = b'' embedded_ini_offset = align_up(kernel_end, 0x1000) - embedded_ini_end = embedded_ini_offset + len(embedded_ini) # TODO: Create and embed an INI, eventually. + embedded_ini_end = embedded_ini_offset + len(embedded_ini_header) + len(embedded_kips) - kernel_ldr_offset = align_up(embedded_ini_end, 0x1000) + (0x1000 if len(embedded_ini) == 0 else 0) + kernel_ldr_offset = align_up(embedded_ini_end, 0x1000) + (0x1000 if len(embedded_ini_header) == 0 else 0) kernel_ldr_end = kernel_ldr_offset + len(kernel_ldr) mesosphere_end = align_up(kernel_ldr_end, 0x1000) @@ -48,7 +57,8 @@ def main(argc, argv): f.write(pk(' +# if (defined(TARGET_OS_OSX) && TARGET_OS_OSX == 1) || \ + (defined(TARGET_OS_MAC) && TARGET_OS_MAC == 1) +# define CATCH_PLATFORM_MAC +# elif (defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE == 1) +# define CATCH_PLATFORM_IPHONE +# endif + +#elif defined(linux) || defined(__linux) || defined(__linux__) +# define CATCH_PLATFORM_LINUX + +#elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) || defined(__MINGW32__) +# define CATCH_PLATFORM_WINDOWS +#endif + +// end catch_platform.h + +#ifdef CATCH_IMPL +# ifndef CLARA_CONFIG_MAIN +# define CLARA_CONFIG_MAIN_NOT_DEFINED +# define CLARA_CONFIG_MAIN +# endif +#endif + +// start catch_user_interfaces.h + +namespace Catch { + unsigned int rngSeed(); +} + +// end catch_user_interfaces.h +// start catch_tag_alias_autoregistrar.h + +// start catch_common.h + +// start catch_compiler_capabilities.h + +// Detect a number of compiler features - by compiler +// The following features are defined: +// +// CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported? +// CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported? +// CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported? +// CATCH_CONFIG_DISABLE_EXCEPTIONS : Are exceptions enabled? +// **************** +// Note to maintainers: if new toggles are added please document them +// in configuration.md, too +// **************** + +// In general each macro has a _NO_ form +// (e.g. CATCH_CONFIG_NO_POSIX_SIGNALS) which disables the feature. +// Many features, at point of detection, define an _INTERNAL_ macro, so they +// can be combined, en-mass, with the _NO_ forms later. + +#ifdef __cplusplus + +# if (__cplusplus >= 201402L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201402L) +# define CATCH_CPP14_OR_GREATER +# endif + +# if (__cplusplus >= 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) +# define CATCH_CPP17_OR_GREATER +# endif + +#endif + +// Only GCC compiler should be used in this block, so other compilers trying to +// mask themselves as GCC should be ignored. +#if defined(__GNUC__) && !defined(__clang__) && !defined(__ICC) && !defined(__CUDACC__) && !defined(__LCC__) +# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic push" ) +# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic pop" ) + +# define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__) + +#endif + +#if defined(__clang__) + +# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic push" ) +# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic pop" ) + +// As of this writing, IBM XL's implementation of __builtin_constant_p has a bug +// which results in calls to destructors being emitted for each temporary, +// without a matching initialization. In practice, this can result in something +// like `std::string::~string` being called on an uninitialized value. +// +// For example, this code will likely segfault under IBM XL: +// ``` +// REQUIRE(std::string("12") + "34" == "1234") +// ``` +// +// Therefore, `CATCH_INTERNAL_IGNORE_BUT_WARN` is not implemented. +# if !defined(__ibmxl__) && !defined(__CUDACC__) +# define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__) /* NOLINT(cppcoreguidelines-pro-type-vararg, hicpp-vararg) */ +# endif + +# define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ + _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \ + _Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"") + +# define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \ + _Pragma( "clang diagnostic ignored \"-Wparentheses\"" ) + +# define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \ + _Pragma( "clang diagnostic ignored \"-Wunused-variable\"" ) + +# define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \ + _Pragma( "clang diagnostic ignored \"-Wgnu-zero-variadic-macro-arguments\"" ) + +# define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ + _Pragma( "clang diagnostic ignored \"-Wunused-template\"" ) + +#endif // __clang__ + +//////////////////////////////////////////////////////////////////////////////// +// Assume that non-Windows platforms support posix signals by default +#if !defined(CATCH_PLATFORM_WINDOWS) + #define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS +#endif + +//////////////////////////////////////////////////////////////////////////////// +// We know some environments not to support full POSIX signals +#if defined(__CYGWIN__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(__DJGPP__) + #define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS +#endif + +#ifdef __OS400__ +# define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS +# define CATCH_CONFIG_COLOUR_NONE +#endif + +//////////////////////////////////////////////////////////////////////////////// +// Android somehow still does not support std::to_string +#if defined(__ANDROID__) +# define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING +# define CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE +#endif + +//////////////////////////////////////////////////////////////////////////////// +// Not all Windows environments support SEH properly +#if defined(__MINGW32__) +# define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH +#endif + +//////////////////////////////////////////////////////////////////////////////// +// PS4 +#if defined(__ORBIS__) +# define CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE +#endif + +//////////////////////////////////////////////////////////////////////////////// +// Cygwin +#ifdef __CYGWIN__ + +// Required for some versions of Cygwin to declare gettimeofday +// see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin +# define _BSD_SOURCE +// some versions of cygwin (most) do not support std::to_string. Use the libstd check. +// https://gcc.gnu.org/onlinedocs/gcc-4.8.2/libstdc++/api/a01053_source.html line 2812-2813 +# if !((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) \ + && !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF)) + +# define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING + +# endif +#endif // __CYGWIN__ + +//////////////////////////////////////////////////////////////////////////////// +// Visual C++ +#if defined(_MSC_VER) + +# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION __pragma( warning(push) ) +# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION __pragma( warning(pop) ) + +// Universal Windows platform does not support SEH +// Or console colours (or console at all...) +# if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) +# define CATCH_CONFIG_COLOUR_NONE +# else +# define CATCH_INTERNAL_CONFIG_WINDOWS_SEH +# endif + +// MSVC traditional preprocessor needs some workaround for __VA_ARGS__ +// _MSVC_TRADITIONAL == 0 means new conformant preprocessor +// _MSVC_TRADITIONAL == 1 means old traditional non-conformant preprocessor +# if !defined(__clang__) // Handle Clang masquerading for msvc +# if !defined(_MSVC_TRADITIONAL) || (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL) +# define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR +# endif // MSVC_TRADITIONAL +# endif // __clang__ + +#endif // _MSC_VER + +#if defined(_REENTRANT) || defined(_MSC_VER) +// Enable async processing, as -pthread is specified or no additional linking is required +# define CATCH_INTERNAL_CONFIG_USE_ASYNC +#endif // _MSC_VER + +//////////////////////////////////////////////////////////////////////////////// +// Check if we are compiled with -fno-exceptions or equivalent +#if defined(__EXCEPTIONS) || defined(__cpp_exceptions) || defined(_CPPUNWIND) +# define CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED +#endif + +//////////////////////////////////////////////////////////////////////////////// +// DJGPP +#ifdef __DJGPP__ +# define CATCH_INTERNAL_CONFIG_NO_WCHAR +#endif // __DJGPP__ + +//////////////////////////////////////////////////////////////////////////////// +// Embarcadero C++Build +#if defined(__BORLANDC__) + #define CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN +#endif + +//////////////////////////////////////////////////////////////////////////////// + +// Use of __COUNTER__ is suppressed during code analysis in +// CLion/AppCode 2017.2.x and former, because __COUNTER__ is not properly +// handled by it. +// Otherwise all supported compilers support COUNTER macro, +// but user still might want to turn it off +#if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L ) + #define CATCH_INTERNAL_CONFIG_COUNTER +#endif + +//////////////////////////////////////////////////////////////////////////////// + +// RTX is a special version of Windows that is real time. +// This means that it is detected as Windows, but does not provide +// the same set of capabilities as real Windows does. +#if defined(UNDER_RTSS) || defined(RTX64_BUILD) + #define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH + #define CATCH_INTERNAL_CONFIG_NO_ASYNC + #define CATCH_CONFIG_COLOUR_NONE +#endif + +#if !defined(_GLIBCXX_USE_C99_MATH_TR1) +#define CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER +#endif + +// Various stdlib support checks that require __has_include +#if defined(__has_include) + // Check if string_view is available and usable + #if __has_include() && defined(CATCH_CPP17_OR_GREATER) + # define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW + #endif + + // Check if optional is available and usable + # if __has_include() && defined(CATCH_CPP17_OR_GREATER) + # define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL + # endif // __has_include() && defined(CATCH_CPP17_OR_GREATER) + + // Check if byte is available and usable + # if __has_include() && defined(CATCH_CPP17_OR_GREATER) + # include + # if defined(__cpp_lib_byte) && (__cpp_lib_byte > 0) + # define CATCH_INTERNAL_CONFIG_CPP17_BYTE + # endif + # endif // __has_include() && defined(CATCH_CPP17_OR_GREATER) + + // Check if variant is available and usable + # if __has_include() && defined(CATCH_CPP17_OR_GREATER) + # if defined(__clang__) && (__clang_major__ < 8) + // work around clang bug with libstdc++ https://bugs.llvm.org/show_bug.cgi?id=31852 + // fix should be in clang 8, workaround in libstdc++ 8.2 + # include + # if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9) + # define CATCH_CONFIG_NO_CPP17_VARIANT + # else + # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT + # endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9) + # else + # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT + # endif // defined(__clang__) && (__clang_major__ < 8) + # endif // __has_include() && defined(CATCH_CPP17_OR_GREATER) +#endif // defined(__has_include) + +#if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER) +# define CATCH_CONFIG_COUNTER +#endif +#if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && !defined(CATCH_CONFIG_WINDOWS_SEH) && !defined(CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH) +# define CATCH_CONFIG_WINDOWS_SEH +#endif +// This is set by default, because we assume that unix compilers are posix-signal-compatible by default. +#if defined(CATCH_INTERNAL_CONFIG_POSIX_SIGNALS) && !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_POSIX_SIGNALS) +# define CATCH_CONFIG_POSIX_SIGNALS +#endif +// This is set by default, because we assume that compilers with no wchar_t support are just rare exceptions. +#if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_WCHAR) +# define CATCH_CONFIG_WCHAR +#endif + +#if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING) +# define CATCH_CONFIG_CPP11_TO_STRING +#endif + +#if defined(CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_NO_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_CPP17_OPTIONAL) +# define CATCH_CONFIG_CPP17_OPTIONAL +#endif + +#if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW) +# define CATCH_CONFIG_CPP17_STRING_VIEW +#endif + +#if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && !defined(CATCH_CONFIG_CPP17_VARIANT) +# define CATCH_CONFIG_CPP17_VARIANT +#endif + +#if defined(CATCH_INTERNAL_CONFIG_CPP17_BYTE) && !defined(CATCH_CONFIG_NO_CPP17_BYTE) && !defined(CATCH_CONFIG_CPP17_BYTE) +# define CATCH_CONFIG_CPP17_BYTE +#endif + +#if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT) +# define CATCH_INTERNAL_CONFIG_NEW_CAPTURE +#endif + +#if defined(CATCH_INTERNAL_CONFIG_NEW_CAPTURE) && !defined(CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NEW_CAPTURE) +# define CATCH_CONFIG_NEW_CAPTURE +#endif + +#if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) +# define CATCH_CONFIG_DISABLE_EXCEPTIONS +#endif + +#if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_POLYFILL_ISNAN) +# define CATCH_CONFIG_POLYFILL_ISNAN +#endif + +#if defined(CATCH_INTERNAL_CONFIG_USE_ASYNC) && !defined(CATCH_INTERNAL_CONFIG_NO_ASYNC) && !defined(CATCH_CONFIG_NO_USE_ASYNC) && !defined(CATCH_CONFIG_USE_ASYNC) +# define CATCH_CONFIG_USE_ASYNC +#endif + +#if defined(CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_NO_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_ANDROID_LOGWRITE) +# define CATCH_CONFIG_ANDROID_LOGWRITE +#endif + +#if defined(CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_NO_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_GLOBAL_NEXTAFTER) +# define CATCH_CONFIG_GLOBAL_NEXTAFTER +#endif + +// Even if we do not think the compiler has that warning, we still have +// to provide a macro that can be used by the code. +#if !defined(CATCH_INTERNAL_START_WARNINGS_SUPPRESSION) +# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION +#endif +#if !defined(CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION) +# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION +#endif +#if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS) +# define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS +#endif +#if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS) +# define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS +#endif +#if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS) +# define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS +#endif +#if !defined(CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS) +# define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS +#endif + +// The goal of this macro is to avoid evaluation of the arguments, but +// still have the compiler warn on problems inside... +#if !defined(CATCH_INTERNAL_IGNORE_BUT_WARN) +# define CATCH_INTERNAL_IGNORE_BUT_WARN(...) +#endif + +#if defined(__APPLE__) && defined(__apple_build_version__) && (__clang_major__ < 10) +# undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS +#elif defined(__clang__) && (__clang_major__ < 5) +# undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS +#endif + +#if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS) +# define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS +#endif + +#if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) +#define CATCH_TRY if ((true)) +#define CATCH_CATCH_ALL if ((false)) +#define CATCH_CATCH_ANON(type) if ((false)) +#else +#define CATCH_TRY try +#define CATCH_CATCH_ALL catch (...) +#define CATCH_CATCH_ANON(type) catch (type) +#endif + +#if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) +#define CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR +#endif + +// end catch_compiler_capabilities.h +#define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line +#define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) +#ifdef CATCH_CONFIG_COUNTER +# define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ ) +#else +# define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ ) +#endif + +#include +#include +#include + +// We need a dummy global operator<< so we can bring it into Catch namespace later +struct Catch_global_namespace_dummy {}; +std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy); + +namespace Catch { + + struct CaseSensitive { enum Choice { + Yes, + No + }; }; + + class NonCopyable { + NonCopyable( NonCopyable const& ) = delete; + NonCopyable( NonCopyable && ) = delete; + NonCopyable& operator = ( NonCopyable const& ) = delete; + NonCopyable& operator = ( NonCopyable && ) = delete; + + protected: + NonCopyable(); + virtual ~NonCopyable(); + }; + + struct SourceLineInfo { + + SourceLineInfo() = delete; + SourceLineInfo( char const* _file, std::size_t _line ) noexcept + : file( _file ), + line( _line ) + {} + + SourceLineInfo( SourceLineInfo const& other ) = default; + SourceLineInfo& operator = ( SourceLineInfo const& ) = default; + SourceLineInfo( SourceLineInfo&& ) noexcept = default; + SourceLineInfo& operator = ( SourceLineInfo&& ) noexcept = default; + + bool empty() const noexcept { return file[0] == '\0'; } + bool operator == ( SourceLineInfo const& other ) const noexcept; + bool operator < ( SourceLineInfo const& other ) const noexcept; + + char const* file; + std::size_t line; + }; + + std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ); + + // Bring in operator<< from global namespace into Catch namespace + // This is necessary because the overload of operator<< above makes + // lookup stop at namespace Catch + using ::operator<<; + + // Use this in variadic streaming macros to allow + // >> +StreamEndStop + // as well as + // >> stuff +StreamEndStop + struct StreamEndStop { + std::string operator+() const; + }; + template + T const& operator + ( T const& value, StreamEndStop ) { + return value; + } +} + +#define CATCH_INTERNAL_LINEINFO \ + ::Catch::SourceLineInfo( __FILE__, static_cast( __LINE__ ) ) + +// end catch_common.h +namespace Catch { + + struct RegistrarForTagAliases { + RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo ); + }; + +} // end namespace Catch + +#define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \ + CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ + CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ + namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \ + CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION + +// end catch_tag_alias_autoregistrar.h +// start catch_test_registry.h + +// start catch_interfaces_testcase.h + +#include + +namespace Catch { + + class TestSpec; + + struct ITestInvoker { + virtual void invoke () const = 0; + virtual ~ITestInvoker(); + }; + + class TestCase; + struct IConfig; + + struct ITestCaseRegistry { + virtual ~ITestCaseRegistry(); + virtual std::vector const& getAllTests() const = 0; + virtual std::vector const& getAllTestsSorted( IConfig const& config ) const = 0; + }; + + bool isThrowSafe( TestCase const& testCase, IConfig const& config ); + bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ); + std::vector filterTests( std::vector const& testCases, TestSpec const& testSpec, IConfig const& config ); + std::vector const& getAllTestCasesSorted( IConfig const& config ); + +} + +// end catch_interfaces_testcase.h +// start catch_stringref.h + +#include +#include +#include +#include + +namespace Catch { + + /// A non-owning string class (similar to the forthcoming std::string_view) + /// Note that, because a StringRef may be a substring of another string, + /// it may not be null terminated. + class StringRef { + public: + using size_type = std::size_t; + using const_iterator = const char*; + + private: + static constexpr char const* const s_empty = ""; + + char const* m_start = s_empty; + size_type m_size = 0; + + public: // construction + constexpr StringRef() noexcept = default; + + StringRef( char const* rawChars ) noexcept; + + constexpr StringRef( char const* rawChars, size_type size ) noexcept + : m_start( rawChars ), + m_size( size ) + {} + + StringRef( std::string const& stdString ) noexcept + : m_start( stdString.c_str() ), + m_size( stdString.size() ) + {} + + explicit operator std::string() const { + return std::string(m_start, m_size); + } + + public: // operators + auto operator == ( StringRef const& other ) const noexcept -> bool; + auto operator != (StringRef const& other) const noexcept -> bool { + return !(*this == other); + } + + auto operator[] ( size_type index ) const noexcept -> char { + assert(index < m_size); + return m_start[index]; + } + + public: // named queries + constexpr auto empty() const noexcept -> bool { + return m_size == 0; + } + constexpr auto size() const noexcept -> size_type { + return m_size; + } + + // Returns the current start pointer. If the StringRef is not + // null-terminated, throws std::domain_exception + auto c_str() const -> char const*; + + public: // substrings and searches + // Returns a substring of [start, start + length). + // If start + length > size(), then the substring is [start, size()). + // If start > size(), then the substring is empty. + auto substr( size_type start, size_type length ) const noexcept -> StringRef; + + // Returns the current start pointer. May not be null-terminated. + auto data() const noexcept -> char const*; + + constexpr auto isNullTerminated() const noexcept -> bool { + return m_start[m_size] == '\0'; + } + + public: // iterators + constexpr const_iterator begin() const { return m_start; } + constexpr const_iterator end() const { return m_start + m_size; } + }; + + auto operator += ( std::string& lhs, StringRef const& sr ) -> std::string&; + auto operator << ( std::ostream& os, StringRef const& sr ) -> std::ostream&; + + constexpr auto operator "" _sr( char const* rawChars, std::size_t size ) noexcept -> StringRef { + return StringRef( rawChars, size ); + } +} // namespace Catch + +constexpr auto operator "" _catch_sr( char const* rawChars, std::size_t size ) noexcept -> Catch::StringRef { + return Catch::StringRef( rawChars, size ); +} + +// end catch_stringref.h +// start catch_preprocessor.hpp + + +#define CATCH_RECURSION_LEVEL0(...) __VA_ARGS__ +#define CATCH_RECURSION_LEVEL1(...) CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(__VA_ARGS__))) +#define CATCH_RECURSION_LEVEL2(...) CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(__VA_ARGS__))) +#define CATCH_RECURSION_LEVEL3(...) CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(__VA_ARGS__))) +#define CATCH_RECURSION_LEVEL4(...) CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(__VA_ARGS__))) +#define CATCH_RECURSION_LEVEL5(...) CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(__VA_ARGS__))) + +#ifdef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR +#define INTERNAL_CATCH_EXPAND_VARGS(...) __VA_ARGS__ +// MSVC needs more evaluations +#define CATCH_RECURSION_LEVEL6(...) CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(__VA_ARGS__))) +#define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL6(CATCH_RECURSION_LEVEL6(__VA_ARGS__)) +#else +#define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL5(__VA_ARGS__) +#endif + +#define CATCH_REC_END(...) +#define CATCH_REC_OUT + +#define CATCH_EMPTY() +#define CATCH_DEFER(id) id CATCH_EMPTY() + +#define CATCH_REC_GET_END2() 0, CATCH_REC_END +#define CATCH_REC_GET_END1(...) CATCH_REC_GET_END2 +#define CATCH_REC_GET_END(...) CATCH_REC_GET_END1 +#define CATCH_REC_NEXT0(test, next, ...) next CATCH_REC_OUT +#define CATCH_REC_NEXT1(test, next) CATCH_DEFER ( CATCH_REC_NEXT0 ) ( test, next, 0) +#define CATCH_REC_NEXT(test, next) CATCH_REC_NEXT1(CATCH_REC_GET_END test, next) + +#define CATCH_REC_LIST0(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ ) +#define CATCH_REC_LIST1(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0) ) ( f, peek, __VA_ARGS__ ) +#define CATCH_REC_LIST2(f, x, peek, ...) f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ ) + +#define CATCH_REC_LIST0_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ ) +#define CATCH_REC_LIST1_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0_UD) ) ( f, userdata, peek, __VA_ARGS__ ) +#define CATCH_REC_LIST2_UD(f, userdata, x, peek, ...) f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ ) + +// Applies the function macro `f` to each of the remaining parameters, inserts commas between the results, +// and passes userdata as the first parameter to each invocation, +// e.g. CATCH_REC_LIST_UD(f, x, a, b, c) evaluates to f(x, a), f(x, b), f(x, c) +#define CATCH_REC_LIST_UD(f, userdata, ...) CATCH_RECURSE(CATCH_REC_LIST2_UD(f, userdata, __VA_ARGS__, ()()(), ()()(), ()()(), 0)) + +#define CATCH_REC_LIST(f, ...) CATCH_RECURSE(CATCH_REC_LIST2(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0)) + +#define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param) +#define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO## __VA_ARGS__ +#define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__ +#define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF +#define INTERNAL_CATCH_STRINGIZE(...) INTERNAL_CATCH_STRINGIZE2(__VA_ARGS__) +#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR +#define INTERNAL_CATCH_STRINGIZE2(...) #__VA_ARGS__ +#define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) +#else +// MSVC is adding extra space and needs another indirection to expand INTERNAL_CATCH_NOINTERNAL_CATCH_DEF +#define INTERNAL_CATCH_STRINGIZE2(...) INTERNAL_CATCH_STRINGIZE3(__VA_ARGS__) +#define INTERNAL_CATCH_STRINGIZE3(...) #__VA_ARGS__ +#define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) (INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) + 1) +#endif + +#define INTERNAL_CATCH_MAKE_NAMESPACE2(...) ns_##__VA_ARGS__ +#define INTERNAL_CATCH_MAKE_NAMESPACE(name) INTERNAL_CATCH_MAKE_NAMESPACE2(name) + +#define INTERNAL_CATCH_REMOVE_PARENS(...) INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF __VA_ARGS__) + +#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR +#define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) decltype(get_wrapper()) +#define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__)) +#else +#define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) INTERNAL_CATCH_EXPAND_VARGS(decltype(get_wrapper())) +#define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__))) +#endif + +#define INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(...)\ + CATCH_REC_LIST(INTERNAL_CATCH_MAKE_TYPE_LIST,__VA_ARGS__) + +#define INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_0) INTERNAL_CATCH_REMOVE_PARENS(_0) +#define INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_0, _1) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_1) +#define INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_0, _1, _2) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_1, _2) +#define INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_0, _1, _2, _3) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_1, _2, _3) +#define INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_0, _1, _2, _3, _4) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_1, _2, _3, _4) +#define INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_0, _1, _2, _3, _4, _5) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_1, _2, _3, _4, _5) +#define INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_0, _1, _2, _3, _4, _5, _6) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_1, _2, _3, _4, _5, _6) +#define INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_0, _1, _2, _3, _4, _5, _6, _7) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_1, _2, _3, _4, _5, _6, _7) +#define INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_1, _2, _3, _4, _5, _6, _7, _8) +#define INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9) +#define INTERNAL_CATCH_REMOVE_PARENS_11_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10) + +#define INTERNAL_CATCH_VA_NARGS_IMPL(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N + +#define INTERNAL_CATCH_TYPE_GEN\ + template struct TypeList {};\ + template\ + constexpr auto get_wrapper() noexcept -> TypeList { return {}; }\ + template class...> struct TemplateTypeList{};\ + template class...Cs>\ + constexpr auto get_wrapper() noexcept -> TemplateTypeList { return {}; }\ + template\ + struct append;\ + template\ + struct rewrap;\ + template class, typename...>\ + struct create;\ + template class, typename>\ + struct convert;\ + \ + template \ + struct append { using type = T; };\ + template< template class L1, typename...E1, template class L2, typename...E2, typename...Rest>\ + struct append, L2, Rest...> { using type = typename append, Rest...>::type; };\ + template< template class L1, typename...E1, typename...Rest>\ + struct append, TypeList, Rest...> { using type = L1; };\ + \ + template< template class Container, template class List, typename...elems>\ + struct rewrap, List> { using type = TypeList>; };\ + template< template class Container, template class List, class...Elems, typename...Elements>\ + struct rewrap, List, Elements...> { using type = typename append>, typename rewrap, Elements...>::type>::type; };\ + \ + template