id
int64
0
755k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
6,623
i2c_driver_client_api.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/i2c/driver/i2c_driver_client_api.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "impl/i2c_driver_core.hpp" namespace ams::i2c::driver { void Initialize() { return impl::InitializeDrivers(); } void Finalize() { return impl::FinalizeDrivers(); } }
875
C++
.cpp
25
31.96
76
0.730178
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,624
i2c_driver_bus_api.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/i2c/driver/i2c_driver_bus_api.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "impl/i2c_driver_core.hpp" namespace ams::i2c::driver { namespace { constexpr inline int DefaultRetryCount = 3; constexpr inline TimeSpan DefaultRetryInterval = TimeSpan::FromMilliSeconds(5); Result OpenSessionImpl(I2cSession *out, I2cDeviceProperty *device) { /* Construct the session. */ auto *session = std::construct_at(std::addressof(impl::GetI2cSessionImpl(*out)), DefaultRetryCount, DefaultRetryInterval); ON_RESULT_FAILURE { std::destroy_at(session); }; /* Open the session. */ R_RETURN(session->Open(device, ddsf::AccessMode_ReadWrite)); } } Result OpenSession(I2cSession *out, DeviceCode device_code) { AMS_ASSERT(out != nullptr); /* Find the device. */ I2cDeviceProperty *device = nullptr; R_TRY(impl::FindDevice(std::addressof(device), device_code)); AMS_ASSERT(device != nullptr); /* Open the session. */ R_RETURN(OpenSessionImpl(out, device)); } void CloseSession(I2cSession &session) { std::destroy_at(std::addressof(impl::GetOpenI2cSessionImpl(session))); } Result Send(I2cSession &session, const void *src, size_t src_size, TransactionOption option) { AMS_ASSERT(src != nullptr); AMS_ABORT_UNLESS(src_size > 0); R_RETURN(impl::GetOpenI2cSessionImpl(session).Send(src, src_size, option)); } Result Receive(void *dst, size_t dst_size, I2cSession &session, TransactionOption option) { AMS_ASSERT(dst != nullptr); AMS_ABORT_UNLESS(dst_size > 0); R_RETURN(impl::GetOpenI2cSessionImpl(session).Receive(dst, dst_size, option)); } Result ExecuteCommandList(void *dst, size_t dst_size, I2cSession &session, const void *src, size_t src_size) { AMS_ASSERT(src != nullptr); AMS_ASSERT(dst != nullptr); AMS_ABORT_UNLESS(src_size > 0); AMS_ABORT_UNLESS(dst_size > 0); R_RETURN(impl::GetOpenI2cSessionImpl(session).ExecuteCommandList(dst, dst_size, src, src_size)); } Result SetRetryPolicy(I2cSession &session, int max_retry_count, int retry_interval_us) { AMS_ASSERT(max_retry_count > 0); AMS_ASSERT(retry_interval_us > 0); R_RETURN(impl::GetOpenI2cSessionImpl(session).SetRetryPolicy(max_retry_count, retry_interval_us)); } }
3,047
C++
.cpp
64
41
134
0.684335
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,625
i2c_driver_core.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/i2c/driver/impl/i2c_driver_core.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "i2c_driver_core.hpp" namespace ams::i2c::driver::impl { namespace { constinit os::SdkMutex g_init_mutex; constinit int g_init_count = 0; i2c::driver::II2cDriver::List &GetI2cDriverList() { AMS_FUNCTION_LOCAL_STATIC_CONSTINIT(i2c::driver::II2cDriver::List, s_driver_list); return s_driver_list; } ddsf::DeviceCodeEntryManager &GetDeviceCodeEntryManager() { AMS_FUNCTION_LOCAL_STATIC(ddsf::DeviceCodeEntryManager, s_device_code_entry_manager, ddsf::GetDeviceCodeEntryHolderMemoryResource()); return s_device_code_entry_manager; } } void InitializeDrivers() { std::scoped_lock lk(g_init_mutex); /* Initialize all registered drivers, if this is our first initialization. */ if ((g_init_count++) == 0) { for (auto &driver : GetI2cDriverList()) { driver.SafeCastTo<II2cDriver>().InitializeDriver(); } } } void FinalizeDrivers() { std::scoped_lock lk(g_init_mutex); /* If we have no remaining sessions, close. */ if ((--g_init_count) == 0) { /* Reset all device code entries. */ GetDeviceCodeEntryManager().Reset(); /* Finalize all drivers. */ for (auto &driver : GetI2cDriverList()) { driver.SafeCastTo<II2cDriver>().FinalizeDriver(); } } } void RegisterDriver(II2cDriver *driver) { AMS_ASSERT(driver != nullptr); GetI2cDriverList().push_back(*driver); } void UnregisterDriver(II2cDriver *driver) { AMS_ASSERT(driver != nullptr); if (driver->IsLinkedToList()) { auto &list = GetI2cDriverList(); list.erase(list.iterator_to(*driver)); } } Result RegisterDeviceCode(DeviceCode device_code, I2cDeviceProperty *device) { AMS_ASSERT(device != nullptr); R_TRY(GetDeviceCodeEntryManager().Add(device_code, device)); R_SUCCEED(); } bool UnregisterDeviceCode(DeviceCode device_code) { return GetDeviceCodeEntryManager().Remove(device_code); } Result FindDevice(I2cDeviceProperty **out, DeviceCode device_code) { /* Validate output. */ AMS_ASSERT(out != nullptr); /* Find the device. */ ddsf::IDevice *device; R_TRY(GetDeviceCodeEntryManager().FindDevice(std::addressof(device), device_code)); /* Set output. */ *out = device->SafeCastToPointer<I2cDeviceProperty>(); R_SUCCEED(); } Result FindDeviceByBusIndexAndAddress(I2cDeviceProperty **out, i2c::I2cBus bus_index, u16 slave_address) { /* Validate output. */ AMS_ASSERT(out != nullptr); /* Convert the bus index to a device code. */ const DeviceCode device_code = ConvertToDeviceCode(bus_index); /* Find the device. */ bool found = false; GetDeviceCodeEntryManager().ForEachEntry([&](ddsf::DeviceCodeEntry &entry) -> bool { /* Convert the entry to an I2cDeviceProperty. */ auto &device = entry.GetDevice().SafeCastTo<I2cDeviceProperty>(); auto &driver = device.GetDriver().SafeCastTo<II2cDriver>(); /* Check if the device is the one we're looking for. */ if (driver.GetDeviceCode() == device_code && device.GetAddress() == slave_address) { found = true; *out = std::addressof(device); return false; } return true; }); /* Check that we found the pad. */ R_UNLESS(found, ddsf::ResultDeviceCodeNotFound()); R_SUCCEED(); } }
4,386
C++
.cpp
104
33.778846
145
0.630317
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,626
i2c_i2c_session_impl.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/i2c/driver/impl/i2c_i2c_session_impl.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "i2c_driver_core.hpp" #include "../../impl/i2c_command_list_format.hpp" namespace ams::i2c::driver::impl { namespace { constexpr TransactionOption EncodeTransactionOption(bool start, bool stop) { return static_cast<TransactionOption>((start ? util::ToUnderlying(TransactionOption_StartCondition) : 0) | (stop ? util::ToUnderlying(TransactionOption_StopCondition) : 0)); } } Result I2cSessionImpl::Open(I2cDeviceProperty *device, ddsf::AccessMode access_mode) { AMS_ASSERT(device != nullptr); /* Check if we're the device's first session. */ const bool first = !device->HasAnyOpenSession(); /* Open the session. */ R_TRY(ddsf::OpenSession(device, this, access_mode)); auto guard = SCOPE_GUARD { ddsf::CloseSession(this); }; /* If we're the first session, initialize the device. */ if (first) { R_TRY(device->GetDriver().SafeCastTo<II2cDriver>().InitializeDevice(device)); } /* We're opened. */ guard.Cancel(); R_SUCCEED(); } void I2cSessionImpl::Close() { /* If we're not open, do nothing. */ if (!this->IsOpen()) { return; } /* Get the device. */ auto &device = this->GetDevice().SafeCastTo<I2cDeviceProperty>(); /* Close the session. */ ddsf::CloseSession(this); /* If there are no remaining sessions, finalize the device. */ if (!device.HasAnyOpenSession()) { device.GetDriver().SafeCastTo<II2cDriver>().FinalizeDevice(std::addressof(device)); } } Result I2cSessionImpl::SendHandler(const u8 **cur_cmd, u8 **cur_dst) { AMS_UNUSED(cur_dst); /* Read the header bytes. */ const util::BitPack8 hdr0{*((*cur_cmd)++)}; const util::BitPack8 hdr1{*((*cur_cmd)++)}; /* Decode the header. */ const bool start = hdr0.Get<i2c::impl::SendCommandFormat::StartCondition>(); const bool stop = hdr0.Get<i2c::impl::SendCommandFormat::StopCondition>(); const size_t size = hdr1.Get<i2c::impl::SendCommandFormat::Size>(); /* Execute the transaction. */ R_TRY(this->ExecuteTransactionWithRetry(nullptr, Command::Send, *cur_cmd, size, EncodeTransactionOption(start, stop))); /* Advance. */ *cur_cmd += size; R_SUCCEED(); } Result I2cSessionImpl::ReceiveHandler(const u8 **cur_cmd, u8 **cur_dst) { /* Read the header bytes. */ const util::BitPack8 hdr0{*((*cur_cmd)++)}; const util::BitPack8 hdr1{*((*cur_cmd)++)}; /* Decode the header. */ const bool start = hdr0.Get<i2c::impl::ReceiveCommandFormat::StartCondition>(); const bool stop = hdr0.Get<i2c::impl::ReceiveCommandFormat::StopCondition>(); const size_t size = hdr1.Get<i2c::impl::ReceiveCommandFormat::Size>(); /* Execute the transaction. */ R_TRY(this->ExecuteTransactionWithRetry(*cur_dst, Command::Receive, nullptr, size, EncodeTransactionOption(start, stop))); /* Advance. */ *cur_dst += size; R_SUCCEED(); } Result I2cSessionImpl::ExtensionHandler(const u8 **cur_cmd, u8 **cur_dst) { AMS_UNUSED(cur_dst); /* Read the header bytes. */ const util::BitPack8 hdr0{*((*cur_cmd)++)}; /* Execute the subcommand. */ switch (hdr0.Get<i2c::impl::CommonCommandFormat::SubCommandId>()) { case i2c::impl::SubCommandId_Sleep: { const util::BitPack8 param{*((*cur_cmd)++)}; os::SleepThread(TimeSpan::FromMicroSeconds(param.Get<i2c::impl::SleepCommandFormat::MicroSeconds>())); } break; AMS_UNREACHABLE_DEFAULT_CASE(); } R_SUCCEED(); } Result I2cSessionImpl::ExecuteTransactionWithRetry(void *dst, Command command, const void *src, size_t size, TransactionOption option) { /* Get the device. */ auto &device = GetDevice().SafeCastTo<I2cDeviceProperty>(); /* Repeatedly try to execute the transaction. */ int retry_count = 0; while (true) { /* Execute the transaction. */ Result result; switch (command) { case Command::Send: result = device.GetDriver().SafeCastTo<II2cDriver>().Send(std::addressof(device), src, size, option); break; case Command::Receive: result = device.GetDriver().SafeCastTo<II2cDriver>().Receive(dst, size, std::addressof(device), option); break; AMS_UNREACHABLE_DEFAULT_CASE(); } /* If we timed out, retry up to our max retry count. */ R_TRY_CATCH(result) { R_CATCH(i2c::ResultTimeout) { if ((++retry_count) <= m_max_retry_count) { os::SleepThread(m_retry_interval); continue; } R_THROW(i2c::ResultBusBusy()); } } R_END_TRY_CATCH; R_SUCCEED(); } } Result I2cSessionImpl::Send(const void *src, size_t src_size, TransactionOption option) { /* Acquire exclusive access to the device. */ std::scoped_lock lk(this->GetDevice().SafeCastTo<I2cDeviceProperty>().GetDriver().SafeCastTo<II2cDriver>().GetTransactionOrderMutex()); R_RETURN(this->ExecuteTransactionWithRetry(nullptr, Command::Send, src, src_size, option)); } Result I2cSessionImpl::Receive(void *dst, size_t dst_size, TransactionOption option) { /* Acquire exclusive access to the device. */ std::scoped_lock lk(this->GetDevice().SafeCastTo<I2cDeviceProperty>().GetDriver().SafeCastTo<II2cDriver>().GetTransactionOrderMutex()); R_RETURN(this->ExecuteTransactionWithRetry(dst, Command::Receive, nullptr, dst_size, option)); } Result I2cSessionImpl::ExecuteCommandList(void *dst, size_t dst_size, const void *src, size_t src_size) { AMS_UNUSED(dst_size); /* Acquire exclusive access to the device. */ std::scoped_lock lk(this->GetDevice().SafeCastTo<I2cDeviceProperty>().GetDriver().SafeCastTo<II2cDriver>().GetTransactionOrderMutex()); /* Prepare to process the command list. */ const u8 * cur_u8 = static_cast<const u8 *>(src); const u8 * const end_u8 = cur_u8 + src_size; u8 * dst_u8 = static_cast<u8 *>(dst); /* Process commands. */ while (cur_u8 < end_u8) { const util::BitPack8 hdr{*cur_u8}; switch (hdr.Get<i2c::impl::CommonCommandFormat::CommandId>()) { case i2c::impl::CommandId_Send: R_TRY(this->SendHandler(std::addressof(cur_u8), std::addressof(dst_u8))); break; case i2c::impl::CommandId_Receive: R_TRY(this->ReceiveHandler(std::addressof(cur_u8), std::addressof(dst_u8))); break; case i2c::impl::CommandId_Extension: R_TRY(this->ExtensionHandler(std::addressof(cur_u8), std::addressof(dst_u8))); break; AMS_UNREACHABLE_DEFAULT_CASE(); } } R_SUCCEED(); } Result I2cSessionImpl::SetRetryPolicy(int mr, int interval_us) { m_max_retry_count = mr; m_retry_interval = TimeSpan::FromMicroSeconds(interval_us); R_SUCCEED(); } }
8,083
C++
.cpp
160
41.0625
185
0.618812
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,627
i2c_driver_api.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/i2c/driver/board/nintendo/nx/i2c_driver_api.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "impl/i2c_bus_manager.hpp" #include "impl/i2c_device_property_manager.hpp" namespace ams::i2c::driver::board::nintendo::nx { namespace { struct I2cDeviceDefinition { DeviceCode device_code; u8 slave_address; }; struct I2cBusDefinition { DeviceCode device_code; dd::PhysicalAddress registers_phys_addr; size_t registers_size; SpeedMode speed_mode; os::InterruptName interrupt_name; const I2cDeviceDefinition *devices; size_t num_devices; constexpr bool IsPowerBus() const { return this->device_code == DeviceCode_I2c5; } }; #include "i2c_bus_device_map.inc" void CheckSpeedMode(SpeedMode speed_mode) { switch (speed_mode) { case SpeedMode_Standard: break; case SpeedMode_Fast: break; case SpeedMode_FastPlus: break; case SpeedMode_HighSpeed: break; AMS_UNREACHABLE_DEFAULT_CASE(); } } void Initialize(impl::I2cBusAccessorManager &bus_manager, impl::I2cDevicePropertyManager &device_manager) { /* Create an accessor for each bus. */ for (const auto &bus_def : I2cBusList) { /* Check that the speed mode is valid. */ CheckSpeedMode(bus_def.speed_mode); /* Find the bus. */ auto *bus = bus_manager.Find([&bus_def](const auto &it) { return it.GetRegistersPhysicalAddress() == bus_def.registers_phys_addr; }); /* If the bus doesn't exist, create it. */ if (bus == nullptr) { /* Allocate the bus. */ bus = bus_manager.Allocate(); /* Initialize the bus. */ bus->Initialize(bus_def.registers_phys_addr, bus_def.registers_size, bus_def.interrupt_name, bus_def.IsPowerBus(), bus_def.speed_mode); /* Register the bus. */ i2c::driver::RegisterDriver(bus); } /* Set the bus's device code. */ bus->RegisterDeviceCode(bus_def.device_code); /* Allocate and register the devices for the bus. */ for (size_t i = 0; i < bus_def.num_devices; ++i) { /* Get the device definition. */ const auto &entry = bus_def.devices[i]; /* Allocate the device. */ I2cDeviceProperty *device = device_manager.Allocate(entry.slave_address, AddressingMode_SevenBit); /* Register the device with our bus. */ bus->RegisterDevice(device); /* Register the device code with our driver. */ R_ABORT_UNLESS(i2c::driver::RegisterDeviceCode(entry.device_code, device)); } } } constinit util::TypedStorage<impl::I2cBusAccessorManager> g_bus_accessor_manager = {}; constinit util::TypedStorage<impl::I2cDevicePropertyManager> g_device_manager = {}; } void Initialize() { /* Initialize managers. */ util::ConstructAt(g_bus_accessor_manager, ddsf::GetMemoryResource()); util::ConstructAt(g_device_manager, ddsf::GetMemoryResource()); return Initialize(util::GetReference(g_bus_accessor_manager), util::GetReference(g_device_manager)); } }
4,218
C++
.cpp
89
35.516854
155
0.589968
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,628
i2c_bus_accessor.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/i2c/driver/board/nintendo/nx/impl/i2c_bus_accessor.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "i2c_bus_accessor.hpp" namespace ams::i2c::driver::board::nintendo::nx::impl { namespace { constexpr inline TimeSpan Timeout = TimeSpan::FromMilliSeconds(100); #define IO_PACKET_BITS_MASK(NAME) REG_NAMED_BITS_MASK (_IMPL_IO_PACKET_, NAME) #define IO_PACKET_BITS_VALUE(NAME, VALUE) REG_NAMED_BITS_VALUE (_IMPL_IO_PACKET_, NAME, VALUE) #define IO_PACKET_BITS_ENUM(NAME, ENUM) REG_NAMED_BITS_ENUM (_IMPL_IO_PACKET_, NAME, ENUM) #define IO_PACKET_BITS_ENUM_SEL(NAME, __COND__, TRUE_ENUM, FALSE_ENUM) REG_NAMED_BITS_ENUM_SEL(_IMPL_IO_PACKET_, NAME, __COND__, TRUE_ENUM, FALSE_ENUM) #define DEFINE_IO_PACKET_REG(NAME, __OFFSET__, __WIDTH__) REG_DEFINE_NAMED_REG (_IMPL_IO_PACKET_, NAME, __OFFSET__, __WIDTH__) #define DEFINE_IO_PACKET_REG_BIT_ENUM(NAME, __OFFSET__, ZERO, ONE) REG_DEFINE_NAMED_BIT_ENUM (_IMPL_IO_PACKET_, NAME, __OFFSET__, ZERO, ONE) #define DEFINE_IO_PACKET_REG_TWO_BIT_ENUM(NAME, __OFFSET__, ZERO, ONE, TWO, THREE) REG_DEFINE_NAMED_TWO_BIT_ENUM (_IMPL_IO_PACKET_, NAME, __OFFSET__, ZERO, ONE, TWO, THREE) #define DEFINE_IO_PACKET_REG_THREE_BIT_ENUM(NAME, __OFFSET__, ZERO, ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN) REG_DEFINE_NAMED_THREE_BIT_ENUM(_IMPL_IO_PACKET_, NAME, __OFFSET__, ZERO, ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN) #define DEFINE_IO_PACKET_REG_FOUR_BIT_ENUM(NAME, __OFFSET__, ZERO, ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, ELEVEN, TWELVE, THIRTEEN, FOURTEEN, FIFTEEN) REG_DEFINE_NAMED_FOUR_BIT_ENUM (_IMPL_IO_PACKET_, NAME, __OFFSET__, ZERO, ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, ELEVEN, TWELVE, THIRTEEN, FOURTEEN, FIFTEEN) DEFINE_IO_PACKET_REG_THREE_BIT_ENUM(HEADER_WORD0_PKT_TYPE, 0, REQUEST, RESPONSE, INTERRUPT, STOP, RSVD4, RSVD5, RSVD6, RSVD7); DEFINE_IO_PACKET_REG_FOUR_BIT_ENUM(HEADER_WORD0_PROTOCOL, 4, RSVD0, I2C, RSVD2, RSVD3, RSVD4, RSVD5, RSVD6, RSVD7, RSVD8, RSVD9, RSVD10, RSVD11, RSVD12, RSVD13, RSVD14, RSVD15) DEFINE_IO_PACKET_REG(HEADER_WORD0_CONTROLLER_ID, 12, 4); DEFINE_IO_PACKET_REG(HEADER_WORD0_PKT_ID, 16, 8); DEFINE_IO_PACKET_REG_TWO_BIT_ENUM(HEADER_WORD0_PROT_HDR_SZ, 28, 1_WORD, 2_WORD, 3_WORD, 4_WORD); DEFINE_IO_PACKET_REG(HEADER_WORD1_PAYLOAD_SIZE, 0, 12); DEFINE_IO_PACKET_REG(PROTOCOL_HEADER_SLAVE_ADDR, 0, 10); DEFINE_IO_PACKET_REG(PROTOCOL_HEADER_HS_MASTER_ADDR, 12, 3); DEFINE_IO_PACKET_REG_BIT_ENUM(PROTOCOL_HEADER_CONTINUE_XFER, 15, USE_REPEAT_START_TOP, CONTINUE); DEFINE_IO_PACKET_REG_BIT_ENUM(PROTOCOL_HEADER_REPEAT_START_STOP, 16, STOP_CONDITION, REPEAT_START_CONDITION); DEFINE_IO_PACKET_REG_BIT_ENUM(PROTOCOL_HEADER_IE, 17, DISABLE, ENABLE); DEFINE_IO_PACKET_REG_BIT_ENUM(PROTOCOL_HEADER_ADDRESS_MODE, 18, SEVEN_BIT, TEN_BIT); DEFINE_IO_PACKET_REG_BIT_ENUM(PROTOCOL_HEADER_READ_WRITE, 19, WRITE, READ); DEFINE_IO_PACKET_REG_BIT_ENUM(PROTOCOL_HEADER_SEND_START_BYTE, 20, DISABLE, ENABLE); DEFINE_IO_PACKET_REG_BIT_ENUM(PROTOCOL_HEADER_CONTINUE_ON_NACK, 21, DISABLE, ENABLE); DEFINE_IO_PACKET_REG_BIT_ENUM(PROTOCOL_HEADER_HS_MODE, 22, DISABLE, ENABLE); } void I2cBusAccessor::Initialize(dd::PhysicalAddress reg_paddr, size_t reg_size, os::InterruptName intr, bool pb, SpeedMode sm) { AMS_ASSERT(m_state == State::NotInitialized); m_is_power_bus = pb; m_speed_mode = sm; m_interrupt_name = intr; m_registers_phys_addr = reg_paddr; m_registers_size = reg_size; m_state = State::Initializing; } void I2cBusAccessor::RegisterDeviceCode(DeviceCode dc) { AMS_ASSERT(m_state == State::Initializing); m_device_code = dc; } void I2cBusAccessor::InitializeDriver() { AMS_ASSERT(m_state == State::Initializing); m_registers = reinterpret_cast<volatile I2cRegisters *>(dd::QueryIoMapping(m_registers_phys_addr, m_registers_size)); AMS_ABORT_UNLESS(m_registers != nullptr); m_state = State::Initialized; } void I2cBusAccessor::FinalizeDriver() { AMS_ASSERT(m_state == State::Initialized); m_state = State::Initializing; } Result I2cBusAccessor::InitializeDevice(I2cDeviceProperty *device) { /* Check that the device is valid. */ AMS_ASSERT(device != nullptr); AMS_ASSERT(m_state == State::Initialized); AMS_UNUSED(device); /* Acquire exclusive access. */ std::scoped_lock lk(m_user_count_mutex); /* Increment our user count -- if we're already open, we're done. */ AMS_ASSERT(m_user_count >= 0); ++m_user_count; R_SUCCEED_IF(m_user_count > 1); /* Initialize our interrupt event. */ os::InitializeInterruptEvent(std::addressof(m_interrupt_event), m_interrupt_name, os::EventClearMode_ManualClear); os::ClearInterruptEvent(std::addressof(m_interrupt_event)); /* If we're not power bus, perform power management init. */ if (!m_is_power_bus) { /* Initialize regulator library. */ regulator::Initialize(); /* Try to open regulator session. */ R_TRY(this->TryOpenRegulatorSession()); /* If we have a regulator session, set voltage to 2.9V. */ if (m_has_regulator_session) { /* NOTE: Nintendo does not check the result, here. */ regulator::SetVoltageValue(std::addressof(m_regulator_session), 2'900'000u); } /* Initialize clock/reset library. */ clkrst::Initialize(); } /* Execute initial config. */ this->ExecuteInitialConfig(); /* If we have a regulator session, enable voltage. */ if (!m_is_power_bus && m_has_regulator_session) { /* Check whether voltage was already enabled. */ const bool was_enabled = regulator::GetVoltageEnabled(std::addressof(m_regulator_session)); /* NOTE: Nintendo does not check the result of this call. */ regulator::SetVoltageEnabled(std::addressof(m_regulator_session), true); /* If we enabled voltage, delay to give our enable time to take. */ if (!was_enabled) { os::SleepThread(TimeSpan::FromMicroSeconds(560)); } } R_SUCCEED(); } void I2cBusAccessor::FinalizeDevice(I2cDeviceProperty *device) { /* Check that the device is valid. */ AMS_ASSERT(device != nullptr); AMS_ASSERT(m_state == State::Initialized); AMS_UNUSED(device); /* Acquire exclusive access. */ std::scoped_lock lk(m_user_count_mutex); /* Increment our user count -- if we're not the last user, we're done. */ AMS_ASSERT(m_user_count > 0); --m_user_count; if (m_user_count > 0) { return; } /* Finalize our interrupt event. */ os::FinalizeInterruptEvent(std::addressof(m_interrupt_event)); /* If we have a regulator session, disable voltage. */ if (m_has_regulator_session) { /* NOTE: Nintendo does not check the result of this call. */ regulator::SetVoltageEnabled(std::addressof(m_regulator_session), false); } /* Finalize the clock/reset library. */ clkrst::Finalize(); /* If we have a regulator session, close it. */ if (m_has_regulator_session) { regulator::CloseSession(std::addressof(m_regulator_session)); m_has_regulator_session = false; } /* Finalize the regulator library. */ regulator::Finalize(); } Result I2cBusAccessor::Send(I2cDeviceProperty *device, const void *src, size_t src_size, TransactionOption option) { /* Check pre-conditions. */ AMS_ASSERT(device != nullptr); AMS_ASSERT(src != nullptr); AMS_ASSERT(src_size > 0); if (m_is_power_bus) { AMS_ASSERT(m_state == State::Initialized || m_state == State::Suspended); } else { AMS_ASSERT(m_state == State::Initialized); } /* Send the data. */ R_RETURN(this->Send(static_cast<const u8 *>(src), src_size, option, device->GetAddress(), device->GetAddressingMode())); } Result I2cBusAccessor::Receive(void *dst, size_t dst_size, I2cDeviceProperty *device, TransactionOption option) { /* Check pre-conditions. */ AMS_ASSERT(device != nullptr); AMS_ASSERT(dst != nullptr); AMS_ASSERT(dst_size > 0); if (m_is_power_bus) { AMS_ASSERT(m_state == State::Initialized || m_state == State::Suspended); } else { AMS_ASSERT(m_state == State::Initialized); } /* Send the data. */ R_RETURN(this->Receive(static_cast<u8 *>(dst), dst_size, option, device->GetAddress(), device->GetAddressingMode())); } void I2cBusAccessor::SuspendBus() { /* Check that state is valid. */ AMS_ASSERT(m_state == State::Initialized); /* Acquire exclusive access. */ std::scoped_lock lk(m_user_count_mutex); /* If we need to, disable clock/voltage appropriately. */ if (!m_is_power_bus && m_user_count > 0) { /* Disable clock. */ { /* Open a clkrst session. */ clkrst::ClkRstSession clkrst_session; R_ABORT_UNLESS(clkrst::OpenSession(std::addressof(clkrst_session), m_device_code)); ON_SCOPE_EXIT { clkrst::CloseSession(std::addressof(clkrst_session)); }; /* Set clock disabled for the session. */ clkrst::SetClockDisabled(std::addressof(clkrst_session)); } /* Disable voltage. */ if (m_has_regulator_session) { regulator::SetVoltageEnabled(std::addressof(m_regulator_session), false); } } /* Update state. */ m_state = State::Suspended; } void I2cBusAccessor::SuspendPowerBus() { /* Check that state is valid. */ AMS_ASSERT(m_state == State::Suspended); /* Acquire exclusive access. */ std::scoped_lock lk(m_user_count_mutex); /* If we need to, disable clock/voltage appropriately. */ if (m_is_power_bus && m_user_count > 0) { /* Nothing should actually be done here. */ } /* Update state. */ m_state = State::PowerBusSuspended; } void I2cBusAccessor::ResumeBus() { /* Check that state is valid. */ AMS_ASSERT(m_state == State::Suspended); /* Acquire exclusive access. */ std::scoped_lock lk(m_user_count_mutex); /* If we need to, enable clock/voltage appropriately. */ if (!m_is_power_bus && m_user_count > 0) { /* Enable voltage. */ if (m_has_regulator_session) { /* Check whether voltage was already enabled. */ const bool was_enabled = regulator::GetVoltageEnabled(std::addressof(m_regulator_session)); /* NOTE: Nintendo does not check the result of this call. */ regulator::SetVoltageEnabled(std::addressof(m_regulator_session), true); /* If we enabled voltage, delay to give our enable time to take. */ if (!was_enabled) { os::SleepThread(TimeSpan::FromMicroSeconds(560)); } } /* Execute initial config, which will enable clock as relevant. */ this->ExecuteInitialConfig(); } /* Update state. */ m_state = State::Initialized; } void I2cBusAccessor::ResumePowerBus() { /* Check that state is valid. */ AMS_ASSERT(m_state == State::PowerBusSuspended); /* Acquire exclusive access. */ std::scoped_lock lk(m_user_count_mutex); /* If we need to, enable clock/voltage appropriately. */ if (m_is_power_bus && m_user_count > 0) { /* Execute initial config, which will enable clock as relevant. */ this->ExecuteInitialConfig(); } /* Update state. */ m_state = State::Suspended; } Result I2cBusAccessor::TryOpenRegulatorSession() { /* Ensure we track the session. */ m_has_regulator_session = true; auto s_guard = SCOPE_GUARD { m_has_regulator_session = false; }; /* Try to open the session. */ R_TRY_CATCH(regulator::OpenSession(std::addressof(m_regulator_session), m_device_code)) { R_CATCH(ddsf::ResultDeviceCodeNotFound) { /* It's okay if the device isn't found, but we don't have a session if so. */ m_has_regulator_session = false; } } R_END_TRY_CATCH; /* We opened (or not). */ s_guard.Cancel(); R_SUCCEED(); } void I2cBusAccessor::ExecuteInitialConfig() { /* Lock exclusive access to registers. */ std::scoped_lock lk(m_register_mutex); /* Reset the controller. */ this->ResetController(); /* Set clock registers. */ this->SetClockRegisters(m_speed_mode); /* Set packet mode registers. */ this->SetPacketModeRegisters(); /* Flush fifos. */ this->FlushFifos(); } Result I2cBusAccessor::Send(const u8 *src, size_t src_size, TransactionOption option, u16 slave_address, AddressingMode addressing_mode) { /* Acquire exclusive access to the registers. */ std::scoped_lock lk(m_register_mutex); /* Configure interrupt mask, clear interrupt status. */ reg::Write(m_registers->interrupt_mask_register, I2C_REG_BITS_ENUM(INTERRUPT_MASK_REGISTER_TFIFO_DATA_REQ_INT_EN, ENABLE), I2C_REG_BITS_ENUM(INTERRUPT_MASK_REGISTER_ARB_LOST_INT_EN, ENABLE), I2C_REG_BITS_ENUM(INTERRUPT_MASK_REGISTER_NOACK_INT_EN, ENABLE), I2C_REG_BITS_ENUM(INTERRUPT_MASK_REGISTER_PACKET_XFER_COMPLETE_INT_EN, ENABLE)); reg::Write(m_registers->interrupt_status_register, I2C_REG_BITS_ENUM(INTERRUPT_STATUS_REGISTER_ARB_LOST, SET), I2C_REG_BITS_ENUM(INTERRUPT_STATUS_REGISTER_NOACK, SET), I2C_REG_BITS_ENUM(INTERRUPT_STATUS_REGISTER_RFIFO_UNF, SET), I2C_REG_BITS_ENUM(INTERRUPT_STATUS_REGISTER_TFIFO_OVF, SET), I2C_REG_BITS_ENUM(INTERRUPT_STATUS_REGISTER_PACKET_XFER_COMPLETE, SET), I2C_REG_BITS_ENUM(INTERRUPT_STATUS_REGISTER_ALL_PACKETS_XFER_COMPLETE, SET)); /* Write the header. */ this->WriteHeader(Xfer_Write, src_size, option, slave_address, addressing_mode); /* Setup tracking variables for the data. */ const u8 *cur = src; size_t remaining = src_size; while (true) { /* Get the number of empty bytes in the fifo status. */ const u32 empty = reg::GetValue(m_registers->fifo_status, I2C_REG_BITS_MASK(FIFO_STATUS_TX_FIFO_EMPTY_CNT)); /* Write up to (empty) bytes to the fifo. */ for (u32 i = 0; remaining > 0 && i < empty; ++i) { /* Build the data word to send. */ const size_t cur_bytes = std::min(remaining, sizeof(u32)); u32 word = 0; for (size_t j = 0; j < cur_bytes; ++j) { word |= cur[j] << (BITSIZEOF(u8) * j); } /* Write the data word. */ reg::Write(m_registers->tx_packet_fifo, word); /* Advance. */ cur += cur_bytes; remaining -= cur_bytes; } /* If we're done, break. */ if (remaining == 0) { break; } /* Wait for our current data to send. */ os::ClearInterruptEvent(std::addressof(m_interrupt_event)); if (!os::TimedWaitInterruptEvent(std::addressof(m_interrupt_event), Timeout)) { /* We timed out. */ this->HandleTransactionError(i2c::ResultBusBusy()); this->DisableInterruptMask(); os::ClearInterruptEvent(std::addressof(m_interrupt_event)); R_THROW(i2c::ResultTimeout()); } /* Check and handle any errors. */ R_TRY(this->CheckAndHandleError()); } /* Configure interrupt mask to not care about tfifo data req. */ reg::Write(m_registers->interrupt_mask_register, I2C_REG_BITS_ENUM(INTERRUPT_MASK_REGISTER_ARB_LOST_INT_EN, ENABLE), I2C_REG_BITS_ENUM(INTERRUPT_MASK_REGISTER_NOACK_INT_EN, ENABLE), I2C_REG_BITS_ENUM(INTERRUPT_MASK_REGISTER_PACKET_XFER_COMPLETE_INT_EN, ENABLE)); /* Wait for the packet transfer to complete. */ while (true) { /* Check and handle any errors. */ R_TRY(this->CheckAndHandleError()); /* Check if packet transfer is done. */ if (reg::HasValue(m_registers->interrupt_status_register, I2C_REG_BITS_ENUM(INTERRUPT_STATUS_REGISTER_PACKET_XFER_COMPLETE, SET))) { break; } /* Wait for our the packet to transfer. */ os::ClearInterruptEvent(std::addressof(m_interrupt_event)); if (!os::TimedWaitInterruptEvent(std::addressof(m_interrupt_event), Timeout)) { /* We timed out. */ this->HandleTransactionError(i2c::ResultBusBusy()); this->DisableInterruptMask(); os::ClearInterruptEvent(std::addressof(m_interrupt_event)); R_THROW(i2c::ResultTimeout()); } } /* Check and handle any errors. */ R_TRY(this->CheckAndHandleError()); /* We're done. */ this->DisableInterruptMask(); R_SUCCEED(); } Result I2cBusAccessor::Receive(u8 *dst, size_t dst_size, TransactionOption option, u16 slave_address, AddressingMode addressing_mode) { /* Acquire exclusive access to the registers. */ std::scoped_lock lk(m_register_mutex); /* Configure interrupt mask, clear interrupt status. */ reg::Write(m_registers->interrupt_mask_register, I2C_REG_BITS_ENUM(INTERRUPT_MASK_REGISTER_RFIFO_DATA_REQ_INT_EN, ENABLE), I2C_REG_BITS_ENUM(INTERRUPT_MASK_REGISTER_ARB_LOST_INT_EN, ENABLE), I2C_REG_BITS_ENUM(INTERRUPT_MASK_REGISTER_NOACK_INT_EN, ENABLE), I2C_REG_BITS_ENUM(INTERRUPT_MASK_REGISTER_PACKET_XFER_COMPLETE_INT_EN, ENABLE)); reg::Write(m_registers->interrupt_status_register, I2C_REG_BITS_ENUM(INTERRUPT_STATUS_REGISTER_ARB_LOST, SET), I2C_REG_BITS_ENUM(INTERRUPT_STATUS_REGISTER_NOACK, SET), I2C_REG_BITS_ENUM(INTERRUPT_STATUS_REGISTER_RFIFO_UNF, SET), I2C_REG_BITS_ENUM(INTERRUPT_STATUS_REGISTER_TFIFO_OVF, SET), I2C_REG_BITS_ENUM(INTERRUPT_STATUS_REGISTER_PACKET_XFER_COMPLETE, SET), I2C_REG_BITS_ENUM(INTERRUPT_STATUS_REGISTER_ALL_PACKETS_XFER_COMPLETE, SET)); /* Write the header. */ this->WriteHeader(Xfer_Read, dst_size, option, slave_address, addressing_mode); /* Setup tracking variables for the data. */ u8 *cur = dst; size_t remaining = dst_size; while (remaining > 0) { /* Wait for data to come in. */ os::ClearInterruptEvent(std::addressof(m_interrupt_event)); if (!os::TimedWaitInterruptEvent(std::addressof(m_interrupt_event), Timeout)) { /* We timed out. */ this->HandleTransactionError(i2c::ResultBusBusy()); this->DisableInterruptMask(); os::ClearInterruptEvent(std::addressof(m_interrupt_event)); R_THROW(i2c::ResultTimeout()); } /* Check and handle any errors. */ R_TRY(this->CheckAndHandleError()); /* Get the number of full bytes in the fifo status. */ const u32 full = reg::GetValue(m_registers->fifo_status, I2C_REG_BITS_MASK(FIFO_STATUS_RX_FIFO_FULL_CNT)); /* Determine how many words we can read. */ const size_t cur_words = std::min(util::DivideUp(remaining, sizeof(u32)), static_cast<size_t>(full)); /* Read the correct number of words from the fifo. */ for (size_t i = 0; i < cur_words; ++i) { /* Read the word from the fifo. */ const u32 word = reg::Read(m_registers->rx_fifo); /* Copy bytes from the word. */ const size_t cur_bytes = std::min(remaining, sizeof(u32)); for (size_t j = 0; j < cur_bytes; ++j) { cur[j] = (word >> (BITSIZEOF(u8) * j)) & 0xFF; } /* Advance. */ cur += cur_bytes; remaining -= cur_bytes; } } /* We're done. */ R_SUCCEED(); } void I2cBusAccessor::WriteHeader(Xfer xfer, size_t size, TransactionOption option, u16 slave_address, AddressingMode addressing_mode) { /* Parse interesting values from our arguments. */ const bool is_read = xfer == Xfer_Read; const bool is_7_bit = addressing_mode == AddressingMode_SevenBit; const bool is_stop = (option & TransactionOption_StopCondition) != 0; const bool is_hs = m_speed_mode == SpeedMode_HighSpeed; const u32 slave_addr = ((static_cast<u32>(slave_address) & 0x7F) << 1) | (is_read ? 1 : 0); /* Flush fifos. */ this->FlushFifos(); /* Enqueue the first header word. */ reg::Write(m_registers->tx_packet_fifo, IO_PACKET_BITS_ENUM (HEADER_WORD0_PROT_HDR_SZ, 1_WORD), IO_PACKET_BITS_VALUE(HEADER_WORD0_PKT_ID, 0), IO_PACKET_BITS_VALUE(HEADER_WORD0_CONTROLLER_ID, 0), IO_PACKET_BITS_ENUM (HEADER_WORD0_PROTOCOL, I2C), IO_PACKET_BITS_ENUM (HEADER_WORD0_PKT_TYPE, REQUEST)); /* Enqueue the second header word. */ reg::Write(m_registers->tx_packet_fifo, IO_PACKET_BITS_VALUE(HEADER_WORD1_PAYLOAD_SIZE, static_cast<u32>(size - 1))); /* Enqueue the protocol header word. */ reg::Write(m_registers->tx_packet_fifo, IO_PACKET_BITS_ENUM_SEL(PROTOCOL_HEADER_HS_MODE, is_hs, ENABLE, DISABLE), IO_PACKET_BITS_ENUM (PROTOCOL_HEADER_CONTINUE_ON_NACK, DISABLE), IO_PACKET_BITS_ENUM (PROTOCOL_HEADER_SEND_START_BYTE, DISABLE), IO_PACKET_BITS_ENUM_SEL(PROTOCOL_HEADER_READ_WRITE, is_read, READ, WRITE), IO_PACKET_BITS_ENUM_SEL(PROTOCOL_HEADER_ADDRESS_MODE, is_7_bit, SEVEN_BIT, TEN_BIT), IO_PACKET_BITS_ENUM (PROTOCOL_HEADER_IE, ENABLE), IO_PACKET_BITS_ENUM_SEL(PROTOCOL_HEADER_REPEAT_START_STOP, is_stop, STOP_CONDITION, REPEAT_START_CONDITION), IO_PACKET_BITS_ENUM (PROTOCOL_HEADER_CONTINUE_XFER, USE_REPEAT_START_TOP), IO_PACKET_BITS_VALUE (PROTOCOL_HEADER_HS_MASTER_ADDR, 0), IO_PACKET_BITS_VALUE (PROTOCOL_HEADER_SLAVE_ADDR, slave_addr)); } void I2cBusAccessor::ResetController() const { /* Reset the controller. */ if (!m_is_power_bus) { /* Open a clkrst session. */ clkrst::ClkRstSession clkrst_session; R_ABORT_UNLESS(clkrst::OpenSession(std::addressof(clkrst_session), m_device_code)); ON_SCOPE_EXIT { clkrst::CloseSession(std::addressof(clkrst_session)); }; /* Reset the controller, setting clock rate to 408 MHz / 5 (to account for clock divisor). */ /* NOTE: Nintendo does not check result for any of these calls. */ clkrst::SetResetAsserted(std::addressof(clkrst_session)); clkrst::SetClockRate(std::addressof(clkrst_session), 408'000'000 / (4 + 1)); clkrst::SetResetDeasserted(std::addressof(clkrst_session)); } } void I2cBusAccessor::ClearBus() const { /* Try to clear the bus up to three times. */ constexpr int MaxRetryCount = 3; constexpr int BusyLoopMicroSeconds = 1000; int try_count = 0; bool need_retry; do { /* Update trackers. */ ++try_count; need_retry = false; /* Reset the controller. */ this->ResetController(); /* Configure the sclk threshold for bus clear config. */ reg::Write(m_registers->bus_clear_config, I2C_REG_BITS_VALUE(BUS_CLEAR_CONFIG_BC_SCLK_THRESHOLD, 9)); /* Set stop cond and terminate in bus clear config. */ reg::ReadWrite(m_registers->bus_clear_config, I2C_REG_BITS_ENUM(BUS_CLEAR_CONFIG_BC_STOP_COND, STOP)); reg::ReadWrite(m_registers->bus_clear_config, I2C_REG_BITS_ENUM(BUS_CLEAR_CONFIG_BC_TERMINATE, IMMEDIATE)); /* Set master config load, busy loop up to 1ms for it to take. */ reg::ReadWrite(m_registers->config_load, I2C_REG_BITS_ENUM(CONFIG_LOAD_MSTR_CONFIG_LOAD, ENABLE)); const os::Tick start_tick_a = os::GetSystemTick(); while (reg::HasValue(m_registers->config_load, I2C_REG_BITS_ENUM(CONFIG_LOAD_MSTR_CONFIG_LOAD, ENABLE))) { if ((os::GetSystemTick() - start_tick_a).ToTimeSpan().GetMicroSeconds() > BusyLoopMicroSeconds) { need_retry = true; break; } } if (need_retry) { continue; } /* Set bus clear enable, wait up to 1ms for it to take. */ reg::ReadWrite(m_registers->bus_clear_config, I2C_REG_BITS_ENUM(BUS_CLEAR_CONFIG_BC_ENABLE, ENABLE)); const os::Tick start_tick_b = os::GetSystemTick(); while (reg::HasValue(m_registers->bus_clear_config, I2C_REG_BITS_ENUM(BUS_CLEAR_CONFIG_BC_ENABLE, ENABLE))) { if ((os::GetSystemTick() - start_tick_b).ToTimeSpan().GetMicroSeconds() > BusyLoopMicroSeconds) { need_retry = true; break; } } if (need_retry) { continue; } /* Wait up to 1ms for the bus clear to complete. */ const os::Tick start_tick_c = os::GetSystemTick(); while (reg::HasValue(m_registers->bus_clear_status, I2C_REG_BITS_ENUM(BUS_CLEAR_STATUS_BC_STATUS, NOT_CLEARED))) { if ((os::GetSystemTick() - start_tick_c).ToTimeSpan().GetMicroSeconds() > BusyLoopMicroSeconds) { need_retry = true; break; } } if (need_retry) { continue; } } while (try_count < MaxRetryCount && need_retry); } void I2cBusAccessor::SetClockRegisters(SpeedMode speed_mode) { /* Determine parameters for the speed mode. */ u32 t_high, t_low, clk_div, debounce, src_div; bool high_speed = false; if (m_is_power_bus) { t_high = 0x02; t_low = 0x04; clk_div = 0x05; debounce = 0x02; src_div = 0; /* unused */ } else { switch (speed_mode) { case SpeedMode_Standard: t_high = 0x02; t_low = 0x04; clk_div = 0x19; debounce = 0x02; src_div = 0x13; break; case SpeedMode_Fast: t_high = 0x02; t_low = 0x04; clk_div = 0x19; debounce = 0x02; src_div = 0x04; break; case SpeedMode_FastPlus: t_high = 0x02; t_low = 0x04; clk_div = 0x10; debounce = 0x00; src_div = 0x02; break; case SpeedMode_HighSpeed: t_high = 0x03; t_low = 0x08; clk_div = 0x02; debounce = 0x00; src_div = 0x02; high_speed = true; break; AMS_UNREACHABLE_DEFAULT_CASE(); } } /* Write the clock divisors. */ if (high_speed) { reg::Write(m_registers->hs_interface_timing_0, I2C_REG_BITS_VALUE(HS_INTERFACE_TIMING_0_HS_THIGH, t_high), I2C_REG_BITS_VALUE(HS_INTERFACE_TIMING_0_HS_TLOW, t_low)); reg::Write(m_registers->clk_divisor_register, I2C_REG_BITS_VALUE(CLK_DIVISOR_REGISTER_HSMODE, clk_div)); } else { reg::Write(m_registers->interface_timing_0, I2C_REG_BITS_VALUE(INTERFACE_TIMING_0_THIGH, t_high), I2C_REG_BITS_VALUE(INTERFACE_TIMING_0_TLOW, t_low)); reg::Write(m_registers->clk_divisor_register, I2C_REG_BITS_VALUE(CLK_DIVISOR_REGISTER_STD_FAST_MODE, clk_div)); } /* Configure debounce. */ reg::Write(m_registers->cnfg, I2C_REG_BITS_VALUE(I2C_CNFG_DEBOUNCE_CNT, debounce)); reg::Read(m_registers->cnfg); /* Set the clock rate, if we should. */ if (!m_is_power_bus) { /* Open a clkrst session. */ clkrst::ClkRstSession clkrst_session; R_ABORT_UNLESS(clkrst::OpenSession(std::addressof(clkrst_session), m_device_code)); ON_SCOPE_EXIT { clkrst::CloseSession(std::addressof(clkrst_session)); }; /* Reset the controller, setting clock rate to 408 MHz / (src_div + 1). */ /* NOTE: Nintendo does not check result for any of these calls. */ clkrst::SetResetAsserted(std::addressof(clkrst_session)); clkrst::SetClockRate(std::addressof(clkrst_session), 408'000'000 / (src_div + 1)); clkrst::SetResetDeasserted(std::addressof(clkrst_session)); } } void I2cBusAccessor::SetPacketModeRegisters() { /* Set packet mode enable. */ reg::ReadWrite(m_registers->cnfg, I2C_REG_BITS_ENUM(I2C_CNFG_PACKET_MODE_EN, GO)); /* Set master config load. */ reg::ReadWrite(m_registers->config_load, I2C_REG_BITS_ENUM(CONFIG_LOAD_MSTR_CONFIG_LOAD, ENABLE)); /* Set tx/fifo triggers to default (maximum values). */ reg::Write(m_registers->fifo_control, I2C_REG_BITS_VALUE(FIFO_CONTROL_RX_FIFO_TRIG, 7), I2C_REG_BITS_VALUE(FIFO_CONTROL_TX_FIFO_TRIG, 7)); } Result I2cBusAccessor::FlushFifos() { /* Flush the fifo. */ reg::Write(m_registers->fifo_control, I2C_REG_BITS_VALUE(FIFO_CONTROL_RX_FIFO_TRIG, 7), I2C_REG_BITS_VALUE(FIFO_CONTROL_TX_FIFO_TRIG, 7), I2C_REG_BITS_ENUM (FIFO_CONTROL_RX_FIFO_FLUSH, SET), I2C_REG_BITS_ENUM (FIFO_CONTROL_TX_FIFO_FLUSH, SET)); /* Wait up to 5 ms for the flush to complete. */ int count = 0; while (!reg::HasValue(m_registers->fifo_control, I2C_REG_BITS_ENUM(FIFO_CONTROL_FIFO_FLUSH, RX_UNSET_TX_UNSET))) { R_UNLESS((++count < 5), i2c::ResultBusBusy()); os::SleepThread(TimeSpan::FromMilliSeconds(1)); } R_SUCCEED(); } Result I2cBusAccessor::GetTransactionResult() const { /* Get packet status/interrupt status. */ volatile u32 packet_status = reg::Read(m_registers->packet_transfer_status); volatile u32 interrupt_status = reg::Read(m_registers->interrupt_status_register); /* Check for ack. */ R_UNLESS(reg::HasValue(packet_status, I2C_REG_BITS_ENUM(PACKET_TRANSFER_STATUS_NOACK_FOR_DATA, UNSET)), i2c::ResultNoAck()); R_UNLESS(reg::HasValue(packet_status, I2C_REG_BITS_ENUM(PACKET_TRANSFER_STATUS_NOACK_FOR_ADDR, UNSET)), i2c::ResultNoAck()); R_UNLESS(reg::HasValue(interrupt_status, I2C_REG_BITS_ENUM(INTERRUPT_STATUS_REGISTER_NOACK, UNSET)), i2c::ResultNoAck()); /* If we lost arbitration, we'll need to clear the bus. */ auto clear_guard = SCOPE_GUARD { this->ClearBus(); }; /* Check for arb lost. */ R_UNLESS(reg::HasValue(packet_status, I2C_REG_BITS_ENUM(PACKET_TRANSFER_STATUS_ARB_LOST, UNSET)), i2c::ResultBusBusy()); R_UNLESS(reg::HasValue(interrupt_status, I2C_REG_BITS_ENUM(INTERRUPT_STATUS_REGISTER_ARB_LOST, UNSET)), i2c::ResultBusBusy()); clear_guard.Cancel(); R_SUCCEED(); } void I2cBusAccessor::HandleTransactionError(Result result) { R_TRY_CATCH(result) { R_CATCH(i2c::ResultNoAck, i2c::ResultBusBusy) { /* Reset the controller. */ this->ResetController(); /* Set clock registers. */ this->SetClockRegisters(m_speed_mode); /* Set packet mode registers. */ this->SetPacketModeRegisters(); /* Flush fifos. */ this->FlushFifos(); } } R_END_TRY_CATCH_WITH_ABORT_UNLESS; } }
36,459
C++
.cpp
621
44.764895
356
0.552402
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,629
i2c_server_api.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/i2c/server/i2c_server_api.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "i2c_server_manager_impl.hpp" namespace ams::i2c::server { namespace { ams::sf::UnmanagedServiceObject<i2c::sf::IManager, i2c::server::ManagerImpl> g_manager_impl; ams::sf::UnmanagedServiceObject<i2c::sf::IManager, i2c::server::ManagerImpl> g_pcv_manager_impl; } ams::sf::SharedPointer<i2c::sf::IManager> GetServiceObject() { return g_manager_impl.GetShared(); } ams::sf::SharedPointer<i2c::sf::IManager> GetServiceObjectPowerBus() { return g_pcv_manager_impl.GetShared(); } }
1,212
C++
.cpp
29
38.137931
104
0.728741
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,630
i2c_server_manager_impl.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/i2c/server/i2c_server_manager_impl.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "i2c_server_manager_impl.hpp" namespace ams::i2c::server { ManagerImpl::ManagerImpl() { m_heap_handle = lmem::CreateExpHeap(m_heap_buffer, sizeof(m_heap_buffer), lmem::CreateOption_None); m_allocator.Attach(m_heap_handle); } ManagerImpl::~ManagerImpl() { lmem::DestroyExpHeap(m_heap_handle); } Result ManagerImpl::OpenSessionForDev(ams::sf::Out<ams::sf::SharedPointer<i2c::sf::ISession>> out, s32 bus_idx, u16 slave_address, i2c::AddressingMode addressing_mode, i2c::SpeedMode speed_mode) { /* TODO */ AMS_UNUSED(out, bus_idx, slave_address, addressing_mode, speed_mode); AMS_ABORT(); } Result ManagerImpl::OpenSession(ams::sf::Out<ams::sf::SharedPointer<i2c::sf::ISession>> out, i2c::I2cDevice device) { R_RETURN(this->OpenSession2(out, ConvertToDeviceCode(device))); } Result ManagerImpl::HasDevice(ams::sf::Out<bool> out, i2c::I2cDevice device) { /* TODO */ AMS_UNUSED(out, device); AMS_ABORT(); } Result ManagerImpl::HasDeviceForDev(ams::sf::Out<bool> out, i2c::I2cDevice device) { /* TODO */ AMS_UNUSED(out, device); AMS_ABORT(); } Result ManagerImpl::OpenSession2(ams::sf::Out<ams::sf::SharedPointer<i2c::sf::ISession>> out, DeviceCode device_code) { /* Allocate a session. */ auto session = Factory::CreateSharedEmplaced<i2c::sf::ISession, SessionImpl>(std::addressof(m_allocator), this); /* Open the session. */ R_TRY(session.GetImpl().OpenSession(device_code)); /* We succeeded. */ *out = std::move(session); R_SUCCEED(); } }
2,334
C++
.cpp
53
38.490566
200
0.679295
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,631
cal_fs_utils.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/cal/cal_fs_utils.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "cal_crc_utils.hpp" #include "cal_fs_utils.hpp" namespace ams::cal::impl { Result ReadCalibrationBlock(s64 offset, void *dst, size_t block_size) { /* Open the calibration binary partition. */ std::unique_ptr<fs::IStorage> storage; R_TRY(fs::OpenBisPartition(std::addressof(storage), fs::BisPartitionId::CalibrationBinary)); /* Read data from the partition. */ R_TRY(storage->Read(offset, dst, block_size)); /* Validate the crc. */ R_TRY(ValidateCalibrationCrc(dst, block_size)); R_SUCCEED(); } }
1,246
C++
.cpp
30
37.466667
100
0.710744
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,632
cal_battery_api.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/cal/cal_battery_api.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "cal_fs_utils.hpp" namespace ams::cal { namespace { constexpr inline s64 BatteryLotOffset = 0x2CE0; constexpr inline size_t BatteryLotSize = 0x20; constexpr inline s64 BatteryVersionOffset = 0x4310; constexpr inline size_t BatteryVersionSize = 0x10; constexpr inline size_t BatteryVendorSizeMax = 0x18; } Result GetBatteryVersion(u8 *out) { /* Read the battery version. */ u8 battery_version[BatteryVersionSize]; R_TRY(cal::impl::ReadCalibrationBlock(BatteryVersionOffset, battery_version, sizeof(battery_version))); /* Write the output. */ *out = battery_version[0]; R_SUCCEED(); } Result GetBatteryVendor(size_t *out_vendor_size, void *dst, size_t dst_size) { /* Read the battery lot. */ char battery_lot[BatteryLotSize]; R_TRY(cal::impl::ReadCalibrationBlock(BatteryLotOffset, battery_lot, sizeof(battery_lot))); /* Copy output. */ *out_vendor_size = static_cast<size_t>(util::Strlcpy(static_cast<char *>(dst), battery_lot, std::min(dst_size, BatteryVendorSizeMax))); R_SUCCEED(); } }
1,833
C++
.cpp
42
38.238095
143
0.699438
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,633
cal_crc_utils.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/cal/cal_crc_utils.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "cal_crc_utils.hpp" namespace ams::cal::impl { namespace { constexpr inline const u16 CrcTable[0x10] = { 0x0000, 0xCC01, 0xD801, 0x1400, 0xF001, 0x3C00, 0x2800, 0xE401, 0xA001, 0x6C00, 0x7800, 0xB401, 0x5000, 0x9C01, 0x8801, 0x4400 }; } u16 CalculateCrc16(const void *data, size_t size) { AMS_ASSERT(data != nullptr); u16 crc = 0x55AA; const u8 *data_u8 = static_cast<const u8 *>(data); for (size_t i = 0; i < size; ++i) { crc = (crc >> 4) ^ (CrcTable[crc & 0xF]) ^ (CrcTable[(data_u8[i] >> 0) & 0xF]); crc = (crc >> 4) ^ (CrcTable[crc & 0xF]) ^ (CrcTable[(data_u8[i] >> 4) & 0xF]); } return crc; } Result ValidateCalibrationCrc(const void *data, size_t size) { AMS_ASSERT(data != nullptr); AMS_ASSERT(size >= sizeof(u16)); const u16 crc = *reinterpret_cast<const u16 *>(reinterpret_cast<uintptr_t>(data) + size - sizeof(u16)); R_UNLESS(CalculateCrc16(data, size - sizeof(u16)) == crc, cal::ResultCalibrationDataCrcError()); R_SUCCEED(); } }
1,801
C++
.cpp
42
37.095238
111
0.645309
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,634
ddsf_device_code_entry_manager.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/ddsf/ddsf_device_code_entry_manager.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> namespace ams::ddsf { Result DeviceCodeEntryManager::Add(DeviceCode device_code, IDevice *device) { /* Check pre-conditions. */ AMS_ASSERT(device != nullptr); AMS_ASSERT(device->IsDriverAttached()); /* Acquire exclusive access to the manager. */ std::scoped_lock lk(m_entry_list_lock); /* Check that we don't already have an entry with the code. */ for (const auto &holder : m_entry_list) { AMS_ASSERT(holder.IsConstructed()); AMS_ASSERT(holder.Get().GetDeviceCode() != device_code); AMS_UNUSED(holder); } /* Allocate memory for a new device code entry holder. */ void *holder_storage = m_memory_resource->Allocate(sizeof(DeviceCodeEntryHolder)); R_UNLESS(holder_storage != nullptr, ddsf::ResultOutOfResource()); /* Initialize the new holder. */ auto *holder = std::construct_at(static_cast<DeviceCodeEntryHolder *>(holder_storage)); holder->Construct(device_code, device); /* Link the new holder. */ holder->AddTo(m_entry_list); R_SUCCEED(); } bool DeviceCodeEntryManager::Remove(DeviceCode device_code) { /* Acquire exclusive access to the manager. */ std::scoped_lock lk(m_entry_list_lock); /* Find and erase the entry. */ bool erased = false; for (auto it = m_entry_list.begin(); it != m_entry_list.end(); /* ... */) { /* Get the current entry, and advance the iterator. */ DeviceCodeEntryHolder *cur = std::addressof(*(it++)); /* If the entry matches the device code, remove it. */ AMS_ASSERT(cur->IsConstructed()); if (cur->Get().GetDeviceCode() == device_code) { /* Destroy and deallocate the holder. */ cur->Destroy(); std::destroy_at(cur); m_memory_resource->Deallocate(cur, sizeof(*cur)); erased = true; } } return erased; } Result DeviceCodeEntryManager::FindDeviceCodeEntry(DeviceCodeEntry **out, DeviceCode device_code) { /* Check arguments. */ AMS_ASSERT(out != nullptr); R_UNLESS(out != nullptr, ddsf::ResultInvalidArgument()); /* Find the device. */ bool found = false; this->ForEachEntry([&](DeviceCodeEntry &entry) -> bool { if (entry.GetDeviceCode() == device_code) { found = true; *out = std::addressof(entry); return false; } return true; }); /* Check that we found the device. */ R_UNLESS(found, ddsf::ResultDeviceCodeNotFound()); R_SUCCEED(); } Result DeviceCodeEntryManager::FindDeviceCodeEntry(const DeviceCodeEntry **out, DeviceCode device_code) const { /* Check arguments. */ AMS_ASSERT(out != nullptr); R_UNLESS(out != nullptr, ddsf::ResultInvalidArgument()); /* Find the device. */ bool found = false; this->ForEachEntry([&](const DeviceCodeEntry &entry) -> bool { if (entry.GetDeviceCode() == device_code) { found = true; *out = std::addressof(entry); return false; } return true; }); /* Check that we found the device. */ R_UNLESS(found, ddsf::ResultDeviceCodeNotFound()); R_SUCCEED(); } Result DeviceCodeEntryManager::FindDevice(IDevice **out, DeviceCode device_code) { /* Check pre-conditions. */ AMS_ASSERT(out != nullptr); /* Find the entry. */ DeviceCodeEntry *entry; R_TRY(this->FindDeviceCodeEntry(std::addressof(entry), device_code)); /* Set the output. */ if (out != nullptr) { *out = std::addressof(entry->GetDevice()); } R_SUCCEED(); } Result DeviceCodeEntryManager::FindDevice(const IDevice **out, DeviceCode device_code) const { /* Check pre-conditions. */ AMS_ASSERT(out != nullptr); /* Find the entry. */ const DeviceCodeEntry *entry; R_TRY(this->FindDeviceCodeEntry(std::addressof(entry), device_code)); /* Set the output. */ if (out != nullptr) { *out = std::addressof(entry->GetDevice()); } R_SUCCEED(); } }
5,074
C++
.cpp
120
33.216667
115
0.599716
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,635
ddsf_session_api.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/ddsf/ddsf_session_api.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> namespace ams::ddsf { Result OpenSession(IDevice *device, ISession *session, AccessMode access_mode) { /* Check pre-conditions. */ AMS_ASSERT(device != nullptr); AMS_ASSERT(session != nullptr); AMS_ASSERT(!session->IsOpen()); /* Attack the session to the device. */ session->AttachDevice(device, access_mode); auto session_guard = SCOPE_GUARD { session->DetachDevice(); }; /* Attach the device to the session. */ R_TRY(device->AttachSession(session)); /* We succeeded. */ session_guard.Cancel(); R_SUCCEED(); } void CloseSession(ISession *session) { /* Check pre-conditions. */ AMS_ASSERT(session != nullptr); /* Detach the device from the session. */ session->GetDevice().DetachSession(session); /* Detach the session from the device. */ session->DetachDevice(); } }
1,600
C++
.cpp
40
34.425
84
0.672469
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,636
ddsf_event_handler.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/ddsf/ddsf_event_handler.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> namespace ams::ddsf { namespace { enum class LoopControlCommand { None = 0, Register = 1, Unregister = 2, Terminate = 3, }; } struct EventHandlerManager::LoopControlCommandParameters { LoopControlCommand command; IEventHandler *target; LoopControlCommandParameters() : command(LoopControlCommand::None), target(nullptr) { /* ... */ } LoopControlCommandParameters(LoopControlCommand c, IEventHandler *t) : command(c), target(t) { /* ... */ } }; void EventHandlerManager::Initialize() { /* Check that we're not already initialized. */ if (m_is_initialized) { return; } /* Initialize multi wait/holder. */ os::InitializeMultiWait(std::addressof(m_multi_wait)); os::InitializeMultiWaitHolder(std::addressof(m_loop_control_event_holder), m_loop_control_event.GetBase()); os::LinkMultiWaitHolder(std::addressof(m_multi_wait), std::addressof(m_loop_control_event_holder)); m_is_initialized = true; } void EventHandlerManager::Finalize() { /* Check that we're initialized and not looping. */ AMS_ASSERT(!m_is_looping); AMS_ASSERT(m_is_initialized); if (!m_is_initialized) { return; } /* Finalize multi wait/holder. */ os::UnlinkMultiWaitHolder(std::addressof(m_loop_control_event_holder)); os::FinalizeMultiWaitHolder(std::addressof(m_loop_control_event_holder)); os::FinalizeMultiWait(std::addressof(m_multi_wait)); m_is_initialized = false; } void EventHandlerManager::ProcessControlCommand(LoopControlCommandParameters *params) { /* Check pre-conditions. */ AMS_ASSERT(m_is_initialized); AMS_ASSERT(params != nullptr); /* Acquire exclusive access. */ std::scoped_lock lk(m_loop_control_lock); /* If we're processing for the loop thread, we can directly handle. */ if (!m_is_looping || this->IsRunningOnLoopThread()) { this->ProcessControlCommandImpl(params); } else { /* Otherwise, signal to the loop thread. */ m_loop_control_command_params = params; m_loop_control_event.Signal(); m_loop_control_command_done_event.Wait(); } } void EventHandlerManager::ProcessControlCommandImpl(LoopControlCommandParameters *params) { /* Check pre-conditions. */ AMS_ASSERT(m_loop_control_lock.IsLockedByCurrentThread() || !m_loop_control_lock.TryLock()); AMS_ASSERT(params != nullptr); AMS_ASSERT(params->target != nullptr); /* Process the command. */ switch (params->command) { case LoopControlCommand::Register: params->target->Link(std::addressof(m_multi_wait)); break; case LoopControlCommand::Unregister: params->target->Unlink(); break; AMS_UNREACHABLE_DEFAULT_CASE(); } } void EventHandlerManager::RegisterHandler(IEventHandler *handler) { /* Check that the handler is valid. */ AMS_ASSERT(handler != nullptr); AMS_ASSERT(handler->IsInitialized()); /* Send registration command. */ LoopControlCommandParameters params(LoopControlCommand::Register, handler); return this->ProcessControlCommand(std::addressof(params)); } void EventHandlerManager::UnregisterHandler(IEventHandler *handler) { /* Check that the handler is valid. */ AMS_ASSERT(handler != nullptr); AMS_ASSERT(handler->IsInitialized()); /* Send registration command. */ LoopControlCommandParameters params(LoopControlCommand::Unregister, handler); return this->ProcessControlCommand(std::addressof(params)); } void EventHandlerManager::WaitLoopEnter() { /* Acquire exclusive access. */ std::scoped_lock lk(m_loop_control_lock); /* Wait until we're looping. */ while (!m_is_looping) { m_is_looping_cv.Wait(m_loop_control_lock); } } void EventHandlerManager::WaitLoopExit() { /* Acquire exclusive access. */ std::scoped_lock lk(m_loop_control_lock); /* Wait until we're not looping. */ while (m_is_looping) { m_is_looping_cv.Wait(m_loop_control_lock); } } void EventHandlerManager::RequestStop() { /* Check that we're looping and not the loop thread. */ AMS_ASSERT(m_is_looping); AMS_ASSERT(!this->IsRunningOnLoopThread()); if (m_is_looping) { /* Acquire exclusive access. */ std::scoped_lock lk(m_loop_control_lock); /* Signal to the loop thread. */ LoopControlCommandParameters params(LoopControlCommand::Terminate, nullptr); m_loop_control_command_params = std::addressof(params); m_loop_control_event.Signal(); m_loop_control_command_done_event.Wait(); } } void EventHandlerManager::LoopAuto() { /* Check that we're not already looping. */ AMS_ASSERT(!m_is_looping); /* Begin looping with the current thread. */ m_loop_thread = os::GetCurrentThread(); m_is_looping = true; m_is_looping_cv.Broadcast(); /* Whenever we're done looping, clean up. */ ON_SCOPE_EXIT { m_loop_thread = nullptr; m_is_looping = false; m_is_looping_cv.Broadcast(); }; /* Loop until we're asked to stop. */ bool should_terminate = false; while (!should_terminate) { /* Wait for a holder to be signaled. */ os::MultiWaitHolderType *event_holder = os::WaitAny(std::addressof(m_multi_wait)); AMS_ASSERT(event_holder != nullptr); /* Check if we have a request to handle. */ if (event_holder == std::addressof(m_loop_control_event_holder)) { /* Check that the request hasn't already been handled. */ if (m_loop_control_event.TryWait()) { /* Handle the request. */ AMS_ASSERT(m_loop_control_command_params != nullptr); switch (m_loop_control_command_params->command) { case LoopControlCommand::Register: case LoopControlCommand::Unregister: this->ProcessControlCommandImpl(m_loop_control_command_params); break; case LoopControlCommand::Terminate: should_terminate = true; break; AMS_UNREACHABLE_DEFAULT_CASE(); } /* Clear the request, and signal that it's done. */ m_loop_control_command_params = nullptr; m_loop_control_command_done_event.Signal(); } } else { /* Handle the event. */ IEventHandler::ToEventHandler(event_holder).HandleEvent(); } } } }
7,914
C++
.cpp
179
33.865922
115
0.603896
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,637
ddsf_memory_api.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/ddsf/ddsf_memory_api.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> namespace ams::ddsf { namespace { constinit ams::MemoryResource *g_memory_resource = nullptr; constinit ams::MemoryResource *g_device_code_entry_holder_memory_resource = nullptr; } void SetMemoryResource(ams::MemoryResource *mr) { AMS_ASSERT(g_memory_resource == nullptr); g_memory_resource = mr; AMS_ASSERT(g_memory_resource != nullptr); } ams::MemoryResource *GetMemoryResource() { AMS_ASSERT(g_memory_resource != nullptr); return g_memory_resource; } void SetDeviceCodeEntryHolderMemoryResource(ams::MemoryResource *mr) { AMS_ASSERT(g_device_code_entry_holder_memory_resource == nullptr); g_device_code_entry_holder_memory_resource = mr; AMS_ASSERT(g_device_code_entry_holder_memory_resource != nullptr); } ams::MemoryResource *GetDeviceCodeEntryHolderMemoryResource() { AMS_ASSERT(g_device_code_entry_holder_memory_resource != nullptr); return g_device_code_entry_holder_memory_resource; } }
1,729
C++
.cpp
40
38.25
92
0.708333
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,638
fs_context.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/fs_context.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> namespace ams::fs { namespace { constinit bool g_auto_abort_enabled = true; /* NOTE: This generates a global constructor. */ os::SdkThreadLocalStorage g_context_tls; } void SetEnabledAutoAbort(bool enabled) { g_auto_abort_enabled = enabled; } AbortSpecifier DefaultResultHandler(Result result) { AMS_UNUSED(result); if (g_auto_abort_enabled) { return AbortSpecifier::Default; } else { return AbortSpecifier::Return; } } AbortSpecifier AlwaysReturnResultHandler(Result result) { AMS_UNUSED(result); return AbortSpecifier::Return; } constinit FsContext g_default_context(DefaultResultHandler); constinit FsContext g_always_return_context(AlwaysReturnResultHandler); void SetDefaultFsContextResultHandler(const ResultHandler handler) { if (handler == nullptr) { g_default_context.SetHandler(DefaultResultHandler); } else { g_default_context.SetHandler(handler); } } const FsContext *GetCurrentThreadFsContext() { const FsContext *context = reinterpret_cast<const FsContext *>(g_context_tls.GetValue()); if (context == nullptr) { context = std::addressof(g_default_context); } return context; } void SetCurrentThreadFsContext(const FsContext *context) { g_context_tls.SetValue(reinterpret_cast<uintptr_t>(context)); } ScopedAutoAbortDisabler::ScopedAutoAbortDisabler() : m_prev_context(GetCurrentThreadFsContext()) { SetCurrentThreadFsContext(std::addressof(g_always_return_context)); } }
2,348
C++
.cpp
60
32.9
102
0.698944
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,639
fs_mmc.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/fs_mmc.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "fsa/fs_mount_utils.hpp" #include "impl/fs_file_system_proxy_service_object.hpp" #include "impl/fs_file_system_service_object_adapter.hpp" namespace ams::fs { Result GetMmcCid(void *dst, size_t size) { /* Check pre-conditions. */ AMS_FS_R_UNLESS(dst != nullptr, fs::ResultNullptrArgument()); auto fsp = impl::GetFileSystemProxyServiceObject(); /* Open a device operator. */ sf::SharedPointer<fssrv::sf::IDeviceOperator> device_operator; AMS_FS_R_TRY(fsp->OpenDeviceOperator(std::addressof(device_operator))); /* Get the cid. */ AMS_FS_R_TRY(device_operator->GetMmcCid(sf::OutBuffer(dst, size), static_cast<s64>(size))); R_SUCCEED(); } Result GetMmcSpeedMode(MmcSpeedMode *out) { /* Check pre-conditions. */ AMS_FS_R_UNLESS(out != nullptr, fs::ResultNullptrArgument()); auto fsp = impl::GetFileSystemProxyServiceObject(); /* Open a device operator. */ sf::SharedPointer<fssrv::sf::IDeviceOperator> device_operator; AMS_FS_R_TRY(fsp->OpenDeviceOperator(std::addressof(device_operator))); /* Get the speed mode. */ s64 speed_mode = 0; AMS_FS_R_TRY(device_operator->GetMmcSpeedMode(std::addressof(speed_mode))); *out = static_cast<MmcSpeedMode>(speed_mode); R_SUCCEED(); } Result GetMmcPatrolCount(u32 *out) { /* Check pre-conditions. */ AMS_FS_R_UNLESS(out != nullptr, fs::ResultNullptrArgument()); auto fsp = impl::GetFileSystemProxyServiceObject(); /* Open a device operator. */ sf::SharedPointer<fssrv::sf::IDeviceOperator> device_operator; AMS_FS_R_TRY(fsp->OpenDeviceOperator(std::addressof(device_operator))); /* Get the patrol count. */ AMS_FS_R_TRY(device_operator->GetMmcPatrolCount(out)); R_SUCCEED(); } Result GetAndClearMmcErrorInfo(StorageErrorInfo *out_sei, size_t *out_log_size, char *out_log_buffer, size_t log_buffer_size) { /* Check pre-conditions. */ AMS_FS_R_UNLESS(out_sei != nullptr, fs::ResultNullptrArgument()); AMS_FS_R_UNLESS(out_log_size != nullptr, fs::ResultNullptrArgument()); AMS_FS_R_UNLESS(out_log_buffer != nullptr, fs::ResultNullptrArgument()); auto fsp = impl::GetFileSystemProxyServiceObject(); /* Open a device operator. */ sf::SharedPointer<fssrv::sf::IDeviceOperator> device_operator; AMS_FS_R_TRY(fsp->OpenDeviceOperator(std::addressof(device_operator))); /* Get the error info. */ s64 log_size = 0; AMS_FS_R_TRY(device_operator->GetAndClearMmcErrorInfo(out_sei, std::addressof(log_size), sf::OutBuffer(out_log_buffer, log_buffer_size), static_cast<s64>(log_buffer_size))); *out_log_size = static_cast<size_t>(log_size); R_SUCCEED(); } Result GetMmcExtendedCsd(void *dst, size_t size) { /* Check pre-conditions. */ AMS_FS_R_UNLESS(dst != nullptr, fs::ResultNullptrArgument()); auto fsp = impl::GetFileSystemProxyServiceObject(); /* Open a device operator. */ sf::SharedPointer<fssrv::sf::IDeviceOperator> device_operator; AMS_FS_R_TRY(fsp->OpenDeviceOperator(std::addressof(device_operator))); /* Get the csd. */ AMS_FS_R_TRY(device_operator->GetMmcExtendedCsd(sf::OutBuffer(dst, size), static_cast<s64>(size))); R_SUCCEED(); } }
4,124
C++
.cpp
82
43.329268
181
0.670237
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,640
fs_data.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/fs_data.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "fsa/fs_mount_utils.hpp" #include "impl/fs_file_system_proxy_service_object.hpp" namespace ams::fs::impl { namespace { Result OpenDataStorageByDataIdImpl(sf::SharedPointer<fssrv::sf::IStorage> *out, ncm::DataId data_id, ncm::StorageId storage_id) { auto fsp = impl::GetFileSystemProxyServiceObject(); R_TRY_CATCH(fsp->OpenDataStorageByDataId(out, data_id, static_cast<u8>(storage_id))) { R_CONVERT(ncm::ResultContentMetaNotFound, fs::ResultTargetNotFound()); } R_END_TRY_CATCH; R_SUCCEED(); } Result OpenDataStorageByDataId(std::unique_ptr<ams::fs::IStorage> *out, ncm::DataId data_id, ncm::StorageId storage_id) { /* Open storage. */ sf::SharedPointer<fssrv::sf::IStorage> s; AMS_FS_R_TRY(OpenDataStorageByDataIdImpl(std::addressof(s), data_id, storage_id)); auto storage = std::make_unique<impl::StorageServiceObjectAdapter<fssrv::sf::IStorage>>(std::move(s)); R_UNLESS(storage != nullptr, fs::ResultAllocationMemoryFailedInDataA()); *out = std::move(storage); R_SUCCEED(); } Result MountDataImpl(const char *name, ncm::DataId data_id, ncm::StorageId storage_id, void *cache_buffer, size_t cache_size, bool use_cache, bool use_data_cache, bool use_path_cache) { std::unique_ptr<fs::IStorage> storage; R_TRY(OpenDataStorageByDataId(std::addressof(storage), data_id, storage_id)); auto fs = std::make_unique<RomFsFileSystem>(); R_UNLESS(fs != nullptr, fs::ResultAllocationMemoryFailedInDataB()); R_TRY(fs->Initialize(std::move(storage), cache_buffer, cache_size, use_cache)); R_RETURN(fsa::Register(name, std::move(fs), nullptr, use_data_cache, use_path_cache, false)); } } Result QueryMountDataCacheSize(size_t *out, ncm::DataId data_id, ncm::StorageId storage_id) { AMS_FS_R_UNLESS(out != nullptr, fs::ResultNullptrArgument()); std::unique_ptr<fs::IStorage> storage; AMS_FS_R_TRY(OpenDataStorageByDataId(std::addressof(storage), data_id, storage_id)); size_t size = 0; AMS_FS_R_TRY(RomFsFileSystem::GetRequiredWorkingMemorySize(std::addressof(size), storage.get())); constexpr size_t MinimumCacheSize = 32; *out = std::max(size, MinimumCacheSize); R_SUCCEED(); } Result MountData(const char *name, ncm::DataId data_id, ncm::StorageId storage_id) { /* Validate the mount name. */ AMS_FS_R_TRY(impl::CheckMountName(name)); R_RETURN(MountDataImpl(name, data_id, storage_id, nullptr, 0, false, false, false)); } Result MountData(const char *name, ncm::DataId data_id, ncm::StorageId storage_id, void *cache_buffer, size_t cache_size) { /* Validate the mount name. */ AMS_FS_R_TRY(impl::CheckMountName(name)); AMS_FS_R_UNLESS(cache_buffer != nullptr, fs::ResultNullptrArgument()); R_RETURN(MountDataImpl(name, data_id, storage_id, cache_buffer, cache_size, true, false, false)); } Result MountData(const char *name, ncm::DataId data_id, ncm::StorageId storage_id, void *cache_buffer, size_t cache_size, bool use_data_cache, bool use_path_cache) { /* Validate the mount name. */ AMS_FS_R_TRY(impl::CheckMountName(name)); AMS_FS_R_UNLESS(cache_buffer != nullptr, fs::ResultNullptrArgument()); R_RETURN(MountDataImpl(name, data_id, storage_id, cache_buffer, cache_size, true, use_data_cache, use_path_cache)); } }
4,263
C++
.cpp
73
50.589041
193
0.674346
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,641
fs_content.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/fs_content.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "fsa/fs_mount_utils.hpp" #include "impl/fs_file_system_proxy_service_object.hpp" #include "impl/fs_file_system_service_object_adapter.hpp" namespace ams::fs { namespace { impl::FileSystemProxyType ConvertToFileSystemProxyType(ContentType content_type) { switch (content_type) { case ContentType_Control: return impl::FileSystemProxyType_Control; case ContentType_Manual: return impl::FileSystemProxyType_Manual; case ContentType_Meta: return impl::FileSystemProxyType_Meta; case ContentType_Data: return impl::FileSystemProxyType_Data; AMS_UNREACHABLE_DEFAULT_CASE(); } } Result MountContentImpl(const char *name, const char *path, fs::ContentAttributes attr, u64 id, ContentType type) { /* Validate the mount name. */ R_TRY(impl::CheckMountNameAllowingReserved(name)); /* Validate the path. */ R_UNLESS(path != nullptr, fs::ResultInvalidPath()); /* Convert the path for fsp. */ fssrv::sf::FspPath sf_path; R_TRY(fs::ConvertToFspPath(std::addressof(sf_path), path)); /* Open the filesystem. */ auto fsp = impl::GetFileSystemProxyServiceObject(); sf::SharedPointer<fssrv::sf::IFileSystem> fs; R_TRY(fsp->OpenFileSystemWithId(std::addressof(fs), sf_path, attr, id, ConvertToFileSystemProxyType(type))); /* Allocate a new filesystem wrapper. */ auto fsa = std::make_unique<impl::FileSystemServiceObjectAdapter>(std::move(fs)); R_UNLESS(fsa != nullptr, fs::ResultAllocationMemoryFailedInContentA()); /* Register. */ R_RETURN(fsa::Register(name, std::move(fsa))); } } Result MountContent(const char *name, const char *path, fs::ContentAttributes attr, ContentType content_type) { auto mount_impl = [=]() -> Result { /* This API only supports mounting Meta content. */ R_UNLESS(content_type == ContentType_Meta, fs::ResultInvalidArgument()); R_RETURN(MountContentImpl(name, path, attr, ncm::InvalidProgramId.value, content_type)); }; /* Perform the mount. */ AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_SYSTEM_MOUNT(mount_impl(), name, AMS_FS_IMPL_ACCESS_LOG_FORMAT_MOUNT_CONTENT_PATH(name, path, content_type))); /* Enable access logging. */ AMS_FS_IMPL_ACCESS_LOG_SYSTEM_FS_ACCESSOR_ENABLE(name); R_SUCCEED(); } Result MountContent(const char *name, const char *path, fs::ContentAttributes attr, ncm::ProgramId id, ContentType content_type) { auto mount_impl = [=]() -> Result { R_RETURN(MountContentImpl(name, path, attr, id.value, content_type)); }; /* Perform the mount. */ AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_SYSTEM_MOUNT(mount_impl(), name, AMS_FS_IMPL_ACCESS_LOG_FORMAT_MOUNT_CONTENT_PATH_AND_PROGRAM_ID(name, path, id, content_type))); /* Enable access logging. */ AMS_FS_IMPL_ACCESS_LOG_SYSTEM_FS_ACCESSOR_ENABLE(name); R_SUCCEED(); } Result MountContent(const char *name, const char *path, fs::ContentAttributes attr, ncm::DataId id, ContentType content_type) { auto mount_impl = [=]() -> Result { R_RETURN(MountContentImpl(name, path, attr, id.value, content_type)); }; /* Perform the mount. */ AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_SYSTEM_MOUNT(mount_impl(), name, AMS_FS_IMPL_ACCESS_LOG_FORMAT_MOUNT_CONTENT_PATH_AND_DATA_ID(name, path, id, content_type))); /* Enable access logging. */ AMS_FS_IMPL_ACCESS_LOG_SYSTEM_FS_ACCESSOR_ENABLE(name); R_SUCCEED(); } }
4,449
C++
.cpp
82
45.621951
173
0.656459
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,642
fs_error_info.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/fs_error_info.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "fsa/fs_mount_utils.hpp" #include "impl/fs_file_system_proxy_service_object.hpp" #include "impl/fs_file_system_service_object_adapter.hpp" namespace ams::fs { Result GetAndClearFileSystemProxyErrorInfo(FileSystemProxyErrorInfo *out) { /* Check pre-conditions. */ AMS_FS_R_UNLESS(out != nullptr, fs::ResultNullptrArgument()); auto fsp = impl::GetFileSystemProxyServiceObject(); /* Get the error info. */ AMS_FS_R_TRY(fsp->GetAndClearErrorInfo(out)); R_SUCCEED(); } }
1,200
C++
.cpp
29
37.758621
79
0.730472
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,643
fs_image_directory.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/fs_image_directory.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "fsa/fs_mount_utils.hpp" #include "impl/fs_file_system_proxy_service_object.hpp" #include "impl/fs_file_system_service_object_adapter.hpp" namespace ams::fs { Result MountImageDirectory(const char *name, ImageDirectoryId id) { auto mount_impl = [=]() -> Result { /* Validate the mount name. */ R_TRY(impl::CheckMountName(name)); /* Open the image directory. */ auto fsp = impl::GetFileSystemProxyServiceObject(); sf::SharedPointer<fssrv::sf::IFileSystem> fs; R_TRY(fsp->OpenImageDirectoryFileSystem(std::addressof(fs), static_cast<u32>(id))); /* Allocate a new filesystem wrapper. */ auto fsa = std::make_unique<impl::FileSystemServiceObjectAdapter>(std::move(fs)); R_UNLESS(fsa != nullptr, fs::ResultAllocationMemoryFailedInImageDirectoryA()); /* Register. */ R_RETURN(fsa::Register(name, std::move(fsa))); }; /* Perform the mount. */ AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_SYSTEM_MOUNT(mount_impl(), name, AMS_FS_IMPL_ACCESS_LOG_FORMAT_MOUNT_IMAGE_DIRECTORY(name, id))); /* Enable access logging. */ AMS_FS_IMPL_ACCESS_LOG_SYSTEM_FS_ACCESSOR_ENABLE(name); R_SUCCEED(); } }
1,949
C++
.cpp
41
41.195122
141
0.676672
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,644
fs_filesystem_utils.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/fs_filesystem_utils.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "fsa/fs_mount_utils.hpp" #include "fsa/fs_filesystem_accessor.hpp" namespace ams::fs { Result EnsureDirectory(const char *path) { /* Get the filesystem accessor and sub path. */ impl::FileSystemAccessor *accessor; const char *sub_path; R_TRY(impl::FindFileSystem(std::addressof(accessor), std::addressof(sub_path), path)); /* Set up the true sub path. */ fs::Path sub_fs_path; R_TRY(accessor->SetUpPath(std::addressof(sub_fs_path), sub_path)); /* Use the system implementation. */ R_RETURN(fssystem::EnsureDirectory(accessor->GetRawFileSystemUnsafe(), sub_fs_path)); } Result EnsureParentDirectory(const char *path) { /* Get the filesystem accessor and sub path. */ impl::FileSystemAccessor *accessor; const char *sub_path; R_TRY(impl::FindFileSystem(std::addressof(accessor), std::addressof(sub_path), path)); /* Set up the true sub path. */ fs::Path sub_fs_path; R_TRY(accessor->SetUpPath(std::addressof(sub_fs_path), sub_path)); /* Convert the path to the parent directory path. */ R_TRY(sub_fs_path.RemoveChild()); /* Use the system implementation. */ R_RETURN(fssystem::EnsureDirectory(accessor->GetRawFileSystemUnsafe(), sub_fs_path)); } Result HasFile(bool *out, const char *path) { /* Get the filesystem accessor and sub path. */ impl::FileSystemAccessor *accessor; const char *sub_path; R_TRY(impl::FindFileSystem(std::addressof(accessor), std::addressof(sub_path), path)); /* Set up the true sub path. */ fs::Path sub_fs_path; R_TRY(accessor->SetUpPath(std::addressof(sub_fs_path), sub_path)); R_RETURN(fssystem::HasFile(out, accessor->GetRawFileSystemUnsafe(), sub_fs_path)); } Result HasDirectory(bool *out, const char *path) { /* Get the filesystem accessor and sub path. */ impl::FileSystemAccessor *accessor; const char *sub_path; R_TRY(impl::FindFileSystem(std::addressof(accessor), std::addressof(sub_path), path)); /* Set up the true sub path. */ fs::Path sub_fs_path; R_TRY(accessor->SetUpPath(std::addressof(sub_fs_path), sub_path)); R_RETURN(fssystem::HasDirectory(out, accessor->GetRawFileSystemUnsafe(), sub_fs_path)); } }
3,053
C++
.cpp
64
41.25
95
0.674176
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,645
fs_rights_id.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/fs_rights_id.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include <stratosphere/fs/fs_rights_id.hpp> #include "impl/fs_file_system_proxy_service_object.hpp" namespace ams::fs { Result GetRightsId(RightsId *out, const char *path, fs::ContentAttributes attr) { /* If possible, prefer the non-removed functionality. */ if (hos::GetVersion() >= hos::Version_3_0_0) { u8 dummy_key_generation; R_RETURN(GetRightsId(out, std::addressof(dummy_key_generation), path, attr)); } AMS_FS_R_UNLESS(out != nullptr, fs::ResultNullptrArgument()); AMS_FS_R_UNLESS(path != nullptr, fs::ResultNullptrArgument()); /* Convert the path for fsp. */ fssrv::sf::FspPath sf_path; R_TRY(fs::ConvertToFspPath(std::addressof(sf_path), path)); auto fsp = impl::GetFileSystemProxyServiceObject(); AMS_FS_R_TRY(fsp->GetRightsIdByPath(out, sf_path)); R_SUCCEED(); } Result GetRightsId(RightsId *out, u8 *out_key_generation, const char *path, fs::ContentAttributes attr) { AMS_FS_R_UNLESS(out != nullptr, fs::ResultNullptrArgument()); AMS_FS_R_UNLESS(out_key_generation != nullptr, fs::ResultNullptrArgument()); AMS_FS_R_UNLESS(path != nullptr, fs::ResultNullptrArgument()); /* Convert the path for fsp. */ fssrv::sf::FspPath sf_path; R_TRY(fs::ConvertToFspPath(std::addressof(sf_path), path)); auto fsp = impl::GetFileSystemProxyServiceObject(); AMS_FS_R_TRY(fsp->GetRightsIdAndKeyGenerationByPath(out, out_key_generation, sf_path, attr)); R_SUCCEED(); } }
2,269
C++
.cpp
46
43.456522
109
0.676909
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,646
fs_application.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/fs_application.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "fsa/fs_mount_utils.hpp" #include "impl/fs_file_system_service_object_adapter.hpp" #include "impl/fs_file_system_proxy_service_object.hpp" namespace ams::fs { Result MountApplicationPackage(const char *name, const char *common_path) { auto mount_impl = [=]() -> Result { /* Validate the mount name. */ R_TRY(impl::CheckMountName(name)); /* Validate the path. */ R_UNLESS(common_path != nullptr, fs::ResultInvalidPath()); /* Convert the path for ipc. */ fssrv::sf::FspPath sf_path; R_TRY(fs::ConvertToFspPath(std::addressof(sf_path), common_path)); /* Open the filesystem. */ auto fsp = impl::GetFileSystemProxyServiceObject(); sf::SharedPointer<fssrv::sf::IFileSystem> fs; R_TRY(fsp->OpenFileSystemWithId(std::addressof(fs), sf_path, fs::ContentAttributes_None, ncm::InvalidProgramId.value, impl::FileSystemProxyType_Package)); /* Allocate a new filesystem wrapper. */ auto fsa = std::make_unique<impl::FileSystemServiceObjectAdapter>(std::move(fs)); R_UNLESS(fsa != nullptr, fs::ResultAllocationMemoryFailedInApplicationA()); /* Register. */ R_RETURN(fsa::Register(name, std::move(fsa))); }; /* Perform the mount. */ AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_SYSTEM_MOUNT(mount_impl(), name, AMS_FS_IMPL_ACCESS_LOG_FORMAT_MOUNT_APPLICATION_PACKAGE(name, common_path))); /* Enable access logging. */ AMS_FS_IMPL_ACCESS_LOG_SYSTEM_FS_ACCESSOR_ENABLE(name); R_SUCCEED(); } }
2,306
C++
.cpp
46
43.021739
166
0.668297
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,647
fs_sd_card.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/fs_sd_card.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "fsa/fs_mount_utils.hpp" #include "impl/fs_file_system_proxy_service_object.hpp" #include "impl/fs_file_system_service_object_adapter.hpp" #include "impl/fs_event_notifier_service_object_adapter.hpp" namespace ams::fs { namespace { constexpr inline const char AtmosphereErrorReportDirectory[] = "/atmosphere/erpt_reports"; /* NOTE: Nintendo does not attach a generator to a mounted SD card filesystem. */ /* However, it is desirable for homebrew to be able to access SD via common path. */ class SdCardCommonMountNameGenerator : public fsa::ICommonMountNameGenerator, public impl::Newable { public: explicit SdCardCommonMountNameGenerator() { /* ... */ } virtual Result GenerateCommonMountName(char *dst, size_t dst_size) override { /* Determine how much space we need. */ const size_t needed_size = util::Strnlen(impl::SdCardFileSystemMountName, MountNameLengthMax) + 2; AMS_ABORT_UNLESS(dst_size >= needed_size); /* Generate the name. */ const auto size = util::SNPrintf(dst, dst_size, "%s:", impl::SdCardFileSystemMountName); AMS_ASSERT(static_cast<size_t>(size) == needed_size - 1); AMS_UNUSED(size); R_SUCCEED(); } }; } Result MountSdCard(const char *name) { /* Validate the mount name. */ AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_MOUNT_UNLESS_R_SUCCEEDED(impl::CheckMountNameAllowingReserved(name), name, AMS_FS_IMPL_ACCESS_LOG_FORMAT_MOUNT, name)); /* Open the SD card filesystem. */ auto fsp = impl::GetFileSystemProxyServiceObject(); sf::SharedPointer<fssrv::sf::IFileSystem> fs; R_TRY(fsp->OpenSdCardFileSystem(std::addressof(fs))); /* Allocate a new filesystem wrapper. */ auto fsa = std::make_unique<impl::FileSystemServiceObjectAdapter>(std::move(fs)); R_UNLESS(fsa != nullptr, fs::ResultAllocationMemoryFailedInSdCardA()); /* Allocate a new mountname generator. */ /* NOTE: Nintendo does not attach a generator. */ auto generator = std::make_unique<SdCardCommonMountNameGenerator>(); R_UNLESS(generator != nullptr, fs::ResultAllocationMemoryFailedInSdCardA()); /* Register. */ R_RETURN(fsa::Register(name, std::move(fsa), std::move(generator))); } Result MountSdCardErrorReportDirectoryForAtmosphere(const char *name) { /* Validate the mount name. */ R_TRY(impl::CheckMountName(name)); /* Open the SD card filesystem. */ auto fsp = impl::GetFileSystemProxyServiceObject(); sf::SharedPointer<fssrv::sf::IFileSystem> fs; R_TRY(fsp->OpenSdCardFileSystem(std::addressof(fs))); /* Allocate a new filesystem wrapper. */ auto fsa = fs::AllocateShared<impl::FileSystemServiceObjectAdapter>(std::move(fs)); R_UNLESS(fsa != nullptr, fs::ResultAllocationMemoryFailedInSdCardA()); /* Ensure that the error report directory exists. */ constexpr fs::Path fs_path = fs::MakeConstantPath(AtmosphereErrorReportDirectory); R_TRY(fssystem::EnsureDirectory(fsa.get(), fs_path)); /* Create a subdirectory filesystem. */ auto subdir_fs = std::make_unique<fssystem::SubDirectoryFileSystem>(std::move(fsa)); R_UNLESS(subdir_fs != nullptr, fs::ResultAllocationMemoryFailedInSdCardA()); R_TRY(subdir_fs->Initialize(fs_path)); /* Register. */ R_RETURN(fsa::Register(name, std::move(subdir_fs))); } Result OpenSdCardDetectionEventNotifier(std::unique_ptr<IEventNotifier> *out) { auto fsp = impl::GetFileSystemProxyServiceObject(); /* Try to open an event notifier. */ sf::SharedPointer<fssrv::sf::IEventNotifier> notifier; AMS_FS_R_TRY(fsp->OpenSdCardDetectionEventNotifier(std::addressof(notifier))); /* Create an event notifier adapter. */ auto adapter = std::make_unique<impl::EventNotifierObjectAdapter>(std::move(notifier)); AMS_FS_R_UNLESS(adapter != nullptr, fs::ResultAllocationMemoryFailedInSdCardB()); *out = std::move(adapter); R_SUCCEED(); } bool IsSdCardInserted() { auto fsp = impl::GetFileSystemProxyServiceObject(); /* Open a device operator. */ sf::SharedPointer<fssrv::sf::IDeviceOperator> device_operator; AMS_FS_R_ABORT_UNLESS(fsp->OpenDeviceOperator(std::addressof(device_operator))); /* Get insertion status. */ bool inserted; AMS_FS_R_ABORT_UNLESS(device_operator->IsSdCardInserted(std::addressof(inserted))); return inserted; } Result GetSdCardSpeedMode(SdCardSpeedMode *out) { /* Check pre-conditions. */ AMS_FS_R_UNLESS(out != nullptr, fs::ResultNullptrArgument()); auto fsp = impl::GetFileSystemProxyServiceObject(); /* Open a device operator. */ sf::SharedPointer<fssrv::sf::IDeviceOperator> device_operator; AMS_FS_R_TRY(fsp->OpenDeviceOperator(std::addressof(device_operator))); /* Get the speed mode. */ s64 speed_mode = 0; AMS_FS_R_TRY(device_operator->GetSdCardSpeedMode(std::addressof(speed_mode))); *out = static_cast<SdCardSpeedMode>(speed_mode); R_SUCCEED(); } Result GetSdCardCid(void *dst, size_t size) { /* Check pre-conditions. */ AMS_FS_R_UNLESS(dst != nullptr, fs::ResultNullptrArgument()); auto fsp = impl::GetFileSystemProxyServiceObject(); /* Open a device operator. */ sf::SharedPointer<fssrv::sf::IDeviceOperator> device_operator; AMS_FS_R_TRY(fsp->OpenDeviceOperator(std::addressof(device_operator))); /* Get the cid. */ AMS_FS_R_TRY(device_operator->GetSdCardCid(sf::OutBuffer(dst, size), static_cast<s64>(size))); R_SUCCEED(); } Result GetSdCardUserAreaSize(s64 *out) { /* Check pre-conditions. */ AMS_FS_R_UNLESS(out != nullptr, fs::ResultNullptrArgument()); auto fsp = impl::GetFileSystemProxyServiceObject(); /* Open a device operator. */ sf::SharedPointer<fssrv::sf::IDeviceOperator> device_operator; AMS_FS_R_TRY(fsp->OpenDeviceOperator(std::addressof(device_operator))); /* Get the size. */ AMS_FS_R_TRY(device_operator->GetSdCardUserAreaSize(out)); R_SUCCEED(); } Result GetSdCardProtectedAreaSize(s64 *out) { /* Check pre-conditions. */ AMS_FS_R_UNLESS(out != nullptr, fs::ResultNullptrArgument()); auto fsp = impl::GetFileSystemProxyServiceObject(); /* Open a device operator. */ sf::SharedPointer<fssrv::sf::IDeviceOperator> device_operator; AMS_FS_R_TRY(fsp->OpenDeviceOperator(std::addressof(device_operator))); /* Get the size. */ AMS_FS_R_TRY(device_operator->GetSdCardProtectedAreaSize(out)); R_SUCCEED(); } Result GetAndClearSdCardErrorInfo(StorageErrorInfo *out_sei, size_t *out_log_size, char *out_log_buffer, size_t log_buffer_size) { /* Check pre-conditions. */ AMS_FS_R_UNLESS(out_sei != nullptr, fs::ResultNullptrArgument()); AMS_FS_R_UNLESS(out_log_size != nullptr, fs::ResultNullptrArgument()); AMS_FS_R_UNLESS(out_log_buffer != nullptr, fs::ResultNullptrArgument()); auto fsp = impl::GetFileSystemProxyServiceObject(); /* Open a device operator. */ sf::SharedPointer<fssrv::sf::IDeviceOperator> device_operator; AMS_FS_R_TRY(fsp->OpenDeviceOperator(std::addressof(device_operator))); /* Get the error info. */ s64 log_size = 0; AMS_FS_R_TRY(device_operator->GetAndClearSdCardErrorInfo(out_sei, std::addressof(log_size), sf::OutBuffer(out_log_buffer, log_buffer_size), static_cast<s64>(log_buffer_size))); *out_log_size = static_cast<size_t>(log_size); R_SUCCEED(); } }
8,708
C++
.cpp
160
45.83125
184
0.662861
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,648
fs_system_save_data.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/fs_system_save_data.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "fsa/fs_mount_utils.hpp" #include "impl/fs_file_system_proxy_service_object.hpp" #include "impl/fs_file_system_service_object_adapter.hpp" namespace ams::fs { Result MountSystemSaveData(const char *name, SystemSaveDataId id) { R_RETURN(MountSystemSaveData(name, id, InvalidUserId)); } Result MountSystemSaveData(const char *name, SaveDataSpaceId space_id, SystemSaveDataId id) { R_RETURN(MountSystemSaveData(name, space_id, id, InvalidUserId)); } Result MountSystemSaveData(const char *name, SystemSaveDataId id, UserId user_id) { R_RETURN(MountSystemSaveData(name, SaveDataSpaceId::System, id, user_id)); } Result MountSystemSaveData(const char *name, SaveDataSpaceId space_id, SystemSaveDataId id, UserId user_id) { auto mount_impl = [=]() -> Result { /* Validate the mount name. */ R_TRY(impl::CheckMountName(name)); /* Create the attribute. */ const auto attribute = SaveDataAttribute::Make(ncm::InvalidProgramId, SaveDataType::System, user_id, id); /* Open the filesystem. */ auto fsp = impl::GetFileSystemProxyServiceObject(); sf::SharedPointer<fssrv::sf::IFileSystem> fs; R_TRY(fsp->OpenSaveDataFileSystemBySystemSaveDataId(std::addressof(fs), static_cast<u8>(space_id), attribute)); /* Allocate a new filesystem wrapper. */ auto fsa = std::make_unique<impl::FileSystemServiceObjectAdapter>(std::move(fs)); R_UNLESS(fsa != nullptr, fs::ResultAllocationMemoryFailedInSystemSaveDataA()); /* Register. */ R_RETURN(fsa::Register(name, std::move(fsa))); }; AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_SYSTEM_MOUNT(mount_impl(), name, AMS_FS_IMPL_ACCESS_LOG_FORMAT_MOUNT_SYSTEM_SAVE_DATA(name, space_id, id, user_id))); AMS_FS_IMPL_ACCESS_LOG_SYSTEM_FS_ACCESSOR_ENABLE(name); R_SUCCEED(); } }
2,621
C++
.cpp
50
45.88
161
0.694922
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,649
fs_code.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/fs_code.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "fsa/fs_mount_utils.hpp" #include "impl/fs_file_system_service_object_adapter.hpp" #include "impl/fs_file_system_proxy_service_object.hpp" namespace ams::fs { namespace { constinit os::SdkMutex g_mount_stratosphere_romfs_lock; constinit bool g_mounted_stratosphere_romfs = false; constinit util::TypedStorage<FileHandleStorage> g_stratosphere_romfs_storage = {}; constinit util::TypedStorage<RomFsFileSystem> g_stratosphere_romfs_fs = {}; Result EnsureStratosphereRomfsMounted() { std::scoped_lock lk(g_mount_stratosphere_romfs_lock); if (AMS_UNLIKELY(!g_mounted_stratosphere_romfs)) { /* Mount the SD card. */ R_TRY(fs::MountSdCard("#strat-romfs-sd")); auto sd_guard = SCOPE_GUARD { fs::Unmount("#strat-romfs-sd"); }; /* Open sd:/atmosphere/stratosphere.romfs. */ fs::FileHandle stratosphere_romfs_file; R_TRY(fs::OpenFile(std::addressof(stratosphere_romfs_file), "#strat-romfs-sd:/atmosphere/stratosphere.romfs", fs::OpenMode_Read)); /* Setup the storage. */ /* NOTE: This owns the file, and so on failure it will be closed appropriately. */ auto storage_guard = util::ConstructAtGuarded(g_stratosphere_romfs_storage, stratosphere_romfs_file, true); /* Create the filesystem. */ auto fs_guard = util::ConstructAtGuarded(g_stratosphere_romfs_fs); /* Initialize the filesystem. */ R_TRY(GetReference(g_stratosphere_romfs_fs).Initialize(GetPointer(g_stratosphere_romfs_storage), nullptr, 0, false)); /* We succeeded, and so stratosphere.romfs is mounted. */ fs_guard.Cancel(); storage_guard.Cancel(); sd_guard.Cancel(); g_mounted_stratosphere_romfs = true; } R_SUCCEED(); } fsa::IFileSystem &GetStratosphereRomFsFileSystem() { /* Ensure that stratosphere.romfs is mounted. */ /* NOTE: Abort is used here to ensure that atmosphere's filesystem is structurally valid. */ R_ABORT_UNLESS(EnsureStratosphereRomfsMounted()); return GetReference(g_stratosphere_romfs_fs); } Result OpenCodeFileSystemImpl(CodeVerificationData *out_verification_data, std::unique_ptr<fsa::IFileSystem> *out, const char *path, fs::ContentAttributes attr, ncm::ProgramId program_id) { /* Print a path suitable for the remote service. */ fssrv::sf::Path sf_path; R_TRY(FormatToFspPath(std::addressof(sf_path), "%s", path)); /* Open the filesystem. */ auto fsp = impl::GetFileSystemProxyForLoaderServiceObject(); R_TRY(fsp->SetCurrentProcess({})); sf::SharedPointer<fssrv::sf::IFileSystem> fs; R_TRY(fsp->OpenCodeFileSystem(std::addressof(fs), ams::sf::OutBuffer(out_verification_data, sizeof(*out_verification_data)), sf_path, attr, program_id)); /* Allocate a new filesystem wrapper. */ auto fsa = std::make_unique<impl::FileSystemServiceObjectAdapter>(std::move(fs)); R_UNLESS(fsa != nullptr, fs::ResultAllocationMemoryFailedInCodeA()); *out = std::move(fsa); R_SUCCEED(); } Result OpenPackageFileSystemImpl(std::unique_ptr<fsa::IFileSystem> *out, const fssrv::sf::FspPath &path) { /* Open the filesystem. */ auto fsp = impl::GetFileSystemProxyServiceObject(); sf::SharedPointer<fssrv::sf::IFileSystem> fs; R_TRY(fsp->OpenFileSystemWithId(std::addressof(fs), path, fs::ContentAttributes_None, ncm::InvalidProgramId.value, impl::FileSystemProxyType_Package)); /* Allocate a new filesystem wrapper. */ auto fsa = std::make_unique<impl::FileSystemServiceObjectAdapter>(std::move(fs)); R_UNLESS(fsa != nullptr, fs::ResultAllocationMemoryFailedInCodeA()); *out = std::move(fsa); R_SUCCEED(); } Result OpenSdCardCodeFileSystemImpl(std::unique_ptr<fsa::IFileSystem> *out, ncm::ProgramId program_id) { /* Ensure we don't access the SD card too early. */ R_UNLESS(cfg::IsSdCardInitialized(), fs::ResultSdCardNotPresent()); /* Print a path to the program's package. */ fssrv::sf::Path sf_path; R_TRY(FormatToFspPath(std::addressof(sf_path), "%s:/atmosphere/contents/%016" PRIx64 "/exefs.nsp", impl::SdCardFileSystemMountName, program_id.value)); R_RETURN(OpenPackageFileSystemImpl(out, sf_path)); } Result OpenStratosphereCodeFileSystemImpl(std::unique_ptr<fsa::IFileSystem> *out, ncm::ProgramId program_id) { /* Ensure we don't access the SD card too early. */ R_UNLESS(cfg::IsSdCardInitialized(), fs::ResultSdCardNotPresent()); /* Open the program's package. */ std::unique_ptr<fsa::IFile> package_file; { /* Get the stratosphere.romfs filesystem. */ auto &romfs_fs = GetStratosphereRomFsFileSystem(); /* Print a path to the program's package. */ fs::Path path; R_TRY(path.InitializeWithFormat("/atmosphere/contents/%016" PRIx64 "/exefs.nsp", program_id.value)); R_TRY(path.Normalize(fs::PathFlags{})); /* Open the package within stratosphere.romfs. */ R_TRY(romfs_fs.OpenFile(std::addressof(package_file), path, fs::OpenMode_Read)); } /* Create a file storage for the program's package. */ auto package_storage = fs::AllocateShared<FileStorage>(std::move(package_file)); R_UNLESS(package_storage != nullptr, fs::ResultAllocationMemoryFailedInCodeA()); /* Create a partition filesystem. */ auto package_fs = std::make_unique<fssystem::PartitionFileSystem>(); R_UNLESS(package_fs != nullptr, fs::ResultAllocationMemoryFailedInCodeA()); /* Initialize the partition filesystem. */ R_TRY(package_fs->Initialize(package_storage)); *out = std::move(package_fs); R_SUCCEED(); } Result OpenSdCardCodeOrStratosphereCodeOrCodeFileSystemImpl(CodeVerificationData *out_verification_data, std::unique_ptr<fsa::IFileSystem> *out, const char *path, fs::ContentAttributes attr, ncm::ProgramId program_id) { /* If we can open an sd card code fs, use it. */ R_SUCCEED_IF(R_SUCCEEDED(OpenSdCardCodeFileSystemImpl(out, program_id))); /* If we can open a stratosphere code fs, use it. */ R_SUCCEED_IF(R_SUCCEEDED(OpenStratosphereCodeFileSystemImpl(out, program_id))); /* Otherwise, fall back to a normal code fs. */ R_RETURN(OpenCodeFileSystemImpl(out_verification_data, out, path, attr, program_id)); } Result OpenHblCodeFileSystemImpl(std::unique_ptr<fsa::IFileSystem> *out) { /* Get the HBL path. */ const char *hbl_path = cfg::GetHblPath(); /* Print a path to the hbl package. */ fssrv::sf::Path sf_path; R_TRY(FormatToFspPath(std::addressof(sf_path), "%s:/%s", impl::SdCardFileSystemMountName, hbl_path[0] == '/' ? hbl_path + 1 : hbl_path)); R_RETURN(OpenPackageFileSystemImpl(out, sf_path)); } Result OpenSdCardFileSystemImpl(std::shared_ptr<fsa::IFileSystem> *out) { /* Open the SD card filesystem. */ auto fsp = impl::GetFileSystemProxyServiceObject(); sf::SharedPointer<fssrv::sf::IFileSystem> fs; R_TRY(fsp->OpenSdCardFileSystem(std::addressof(fs))); /* Allocate a new filesystem wrapper. */ auto fsa = fs::AllocateShared<impl::FileSystemServiceObjectAdapter>(std::move(fs)); R_UNLESS(fsa != nullptr, fs::ResultAllocationMemoryFailedInCodeA()); *out = std::move(fsa); R_SUCCEED(); } class OpenFileOnlyFileSystem : public fsa::IFileSystem, public impl::Newable { private: virtual Result DoCommit() override final { R_SUCCEED(); } virtual Result DoOpenDirectory(std::unique_ptr<fsa::IDirectory> *out_dir, const fs::Path &path, OpenDirectoryMode mode) override final { AMS_UNUSED(out_dir, path, mode); R_THROW(fs::ResultUnsupportedOperation()); } virtual Result DoGetEntryType(DirectoryEntryType *out, const fs::Path &path) override final { AMS_UNUSED(out, path); R_THROW(fs::ResultUnsupportedOperation()); } virtual Result DoCreateFile(const fs::Path &path, s64 size, int flags) override final { AMS_UNUSED(path, size, flags); R_THROW(fs::ResultUnsupportedOperation()); } virtual Result DoDeleteFile(const fs::Path &path) override final { AMS_UNUSED(path); R_THROW(fs::ResultUnsupportedOperation()); } virtual Result DoCreateDirectory(const fs::Path &path) override final { AMS_UNUSED(path); R_THROW(fs::ResultUnsupportedOperation()); } virtual Result DoDeleteDirectory(const fs::Path &path) override final { AMS_UNUSED(path); R_THROW(fs::ResultUnsupportedOperation()); } virtual Result DoDeleteDirectoryRecursively(const fs::Path &path) override final { AMS_UNUSED(path); R_THROW(fs::ResultUnsupportedOperation()); } virtual Result DoRenameFile(const fs::Path &old_path, const fs::Path &new_path) override final { AMS_UNUSED(old_path, new_path); R_THROW(fs::ResultUnsupportedOperation()); } virtual Result DoRenameDirectory(const fs::Path &old_path, const fs::Path &new_path) override final { AMS_UNUSED(old_path, new_path); R_THROW(fs::ResultUnsupportedOperation()); } virtual Result DoCleanDirectoryRecursively(const fs::Path &path) override final { AMS_UNUSED(path); R_THROW(fs::ResultUnsupportedOperation()); } virtual Result DoGetFreeSpaceSize(s64 *out, const fs::Path &path) override final { AMS_UNUSED(out, path); R_THROW(fs::ResultUnsupportedOperation()); } virtual Result DoGetTotalSpaceSize(s64 *out, const fs::Path &path) override final { AMS_UNUSED(out, path); R_THROW(fs::ResultUnsupportedOperation()); } virtual Result DoCommitProvisionally(s64 counter) override final { AMS_UNUSED(counter); R_THROW(fs::ResultUnsupportedOperation()); } }; class SdCardRedirectionCodeFileSystem : public OpenFileOnlyFileSystem { private: util::optional<ReadOnlyFileSystem> m_sd_content_fs; ReadOnlyFileSystem m_code_fs; bool m_is_redirect; public: SdCardRedirectionCodeFileSystem(std::unique_ptr<fsa::IFileSystem> &&code, ncm::ProgramId program_id, bool redirect) : m_code_fs(std::move(code)), m_is_redirect(redirect) { if (!cfg::IsSdCardInitialized()) { return; } /* Open an SD card filesystem. */ std::shared_ptr<fsa::IFileSystem> sd_fs; if (R_FAILED(OpenSdCardFileSystemImpl(std::addressof(sd_fs)))) { return; } /* Create a redirection filesystem to the relevant content folder. */ auto subdir_fs = std::make_unique<fssystem::SubDirectoryFileSystem>(std::move(sd_fs)); if (subdir_fs == nullptr) { return; } fs::Path path; R_ABORT_UNLESS(path.InitializeWithFormat("/atmosphere/contents/%016" PRIx64 "/exefs", program_id.value)); R_ABORT_UNLESS(path.Normalize(fs::PathFlags{})); R_ABORT_UNLESS(subdir_fs->Initialize(path)); m_sd_content_fs.emplace(std::move(subdir_fs)); } private: bool IsFileStubbed(const fs::Path &path) { /* If we don't have an sd content fs, nothing is stubbed. */ if (!m_sd_content_fs) { return false; } /* Create a path representing the stub. */ fs::Path stub_path; if (R_FAILED(stub_path.InitializeWithFormat("%s.stub", path.GetString()))) { return false; } if (R_FAILED(stub_path.Normalize(fs::PathFlags{}))) { return false; } /* Query whether we have the file. */ bool has_file; if (R_FAILED(fssystem::HasFile(std::addressof(has_file), std::addressof(*m_sd_content_fs), stub_path))) { return false; } return has_file; } virtual Result DoOpenFile(std::unique_ptr<fsa::IFile> *out_file, const fs::Path &path, OpenMode mode) override final { /* Only allow opening files with mode = read. */ R_UNLESS((mode & fs::OpenMode_All) == fs::OpenMode_Read, fs::ResultInvalidOpenMode()); /* If we support redirection, we'd like to prefer a file from the sd card. */ if (m_is_redirect) { R_SUCCEED_IF(R_SUCCEEDED(m_sd_content_fs->OpenFile(out_file, path, mode))); } /* Otherwise, check if the file is stubbed. */ R_UNLESS(!this->IsFileStubbed(path), fs::ResultPathNotFound()); /* Open a file from the base code fs. */ R_RETURN(m_code_fs.OpenFile(out_file, path, mode)); } }; class AtmosphereCodeFileSystem : public OpenFileOnlyFileSystem { private: util::optional<SdCardRedirectionCodeFileSystem> m_code_fs; util::optional<ReadOnlyFileSystem> m_hbl_fs; ncm::ProgramId m_program_id; bool m_initialized; public: AtmosphereCodeFileSystem() : m_initialized(false) { /* ... */ } Result Initialize(CodeVerificationData *out_verification_data, const char *path, fs::ContentAttributes attr, ncm::ProgramId program_id, bool is_hbl, bool is_specific) { AMS_ABORT_UNLESS(!m_initialized); /* If we're hbl, we need to open a hbl fs. */ if (is_hbl) { std::unique_ptr<fsa::IFileSystem> fsa; R_TRY(OpenHblCodeFileSystemImpl(std::addressof(fsa))); m_hbl_fs.emplace(std::move(fsa)); } /* Open the code filesystem. */ std::unique_ptr<fsa::IFileSystem> fsa; R_TRY(OpenSdCardCodeOrStratosphereCodeOrCodeFileSystemImpl(out_verification_data, std::addressof(fsa), path, attr, program_id)); m_code_fs.emplace(std::move(fsa), program_id, is_specific); m_program_id = program_id; m_initialized = true; R_SUCCEED(); } private: virtual Result DoOpenFile(std::unique_ptr<fsa::IFile> *out_file, const fs::Path &path, OpenMode mode) override final { /* Ensure that we're initialized. */ R_UNLESS(m_initialized, fs::ResultNotInitialized()); /* Only allow opening files with mode = read. */ R_UNLESS((mode & fs::OpenMode_All) == fs::OpenMode_Read, fs::ResultInvalidOpenMode()); /* First, check if there's an external code. */ { fsa::IFileSystem *ecs = fssystem::GetExternalCodeFileSystem(m_program_id); if (ecs != nullptr) { R_RETURN(ecs->OpenFile(out_file, path, mode)); } } /* If we're hbl, open from the hbl fs. */ if (m_hbl_fs) { R_RETURN(m_hbl_fs->OpenFile(out_file, path, mode)); } /* If we're not hbl, fall back to our code filesystem. */ R_RETURN(m_code_fs->OpenFile(out_file, path, mode)); } }; } Result MountCode(CodeVerificationData *out, const char *name, const char *path, fs::ContentAttributes attr, ncm::ProgramId program_id) { auto mount_impl = [=]() -> Result { /* Clear the output. */ std::memset(out, 0, sizeof(*out)); /* Validate the mount name. */ R_TRY(impl::CheckMountName(name)); /* Validate the path isn't null. */ R_UNLESS(path != nullptr, fs::ResultInvalidPath()); /* Open the code file system. */ std::unique_ptr<fsa::IFileSystem> fsa; R_TRY(OpenCodeFileSystemImpl(out, std::addressof(fsa), path, attr, program_id)); /* Register. */ R_RETURN(fsa::Register(name, std::move(fsa))); }; /* Perform the mount. */ AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_SYSTEM_MOUNT(mount_impl(), name, AMS_FS_IMPL_ACCESS_LOG_FORMAT_MOUNT_CODE(name, path, program_id))); /* Enable access logging. */ AMS_FS_IMPL_ACCESS_LOG_SYSTEM_FS_ACCESSOR_ENABLE(name); R_SUCCEED(); } Result MountCodeForAtmosphereWithRedirection(CodeVerificationData *out, const char *name, const char *path, fs::ContentAttributes attr, ncm::ProgramId program_id, bool is_hbl, bool is_specific) { auto mount_impl = [=]() -> Result { /* Clear the output. */ std::memset(out, 0, sizeof(*out)); /* Validate the mount name. */ R_TRY(impl::CheckMountName(name)); /* Validate the path isn't null. */ R_UNLESS(path != nullptr, fs::ResultInvalidPath()); /* Create an AtmosphereCodeFileSystem. */ auto ams_code_fs = std::make_unique<AtmosphereCodeFileSystem>(); R_UNLESS(ams_code_fs != nullptr, fs::ResultAllocationMemoryFailedInCodeA()); /* Initialize the code file system. */ R_TRY(ams_code_fs->Initialize(out, path, attr, program_id, is_hbl, is_specific)); /* Register. */ R_RETURN(fsa::Register(name, std::move(ams_code_fs))); }; /* Perform the mount. */ AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_SYSTEM_MOUNT(mount_impl(), name, AMS_FS_IMPL_ACCESS_LOG_FORMAT_MOUNT_CODE(name, path, program_id))); /* Enable access logging. */ AMS_FS_IMPL_ACCESS_LOG_SYSTEM_FS_ACCESSOR_ENABLE(name); R_SUCCEED(); } Result MountCodeForAtmosphere(CodeVerificationData *out, const char *name, const char *path, fs::ContentAttributes attr, ncm::ProgramId program_id) { auto mount_impl = [=]() -> Result { /* Clear the output. */ std::memset(out, 0, sizeof(*out)); /* Validate the mount name. */ R_TRY(impl::CheckMountName(name)); /* Validate the path isn't null. */ R_UNLESS(path != nullptr, fs::ResultInvalidPath()); /* Open the code file system. */ std::unique_ptr<fsa::IFileSystem> fsa; R_TRY(OpenSdCardCodeOrStratosphereCodeOrCodeFileSystemImpl(out, std::addressof(fsa), path, attr, program_id)); /* Create a wrapper fs. */ auto wrap_fsa = std::make_unique<SdCardRedirectionCodeFileSystem>(std::move(fsa), program_id, false); R_UNLESS(wrap_fsa != nullptr, fs::ResultAllocationMemoryFailedInCodeA()); /* Register. */ R_RETURN(fsa::Register(name, std::move(wrap_fsa))); }; /* Perform the mount. */ AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_SYSTEM_MOUNT(mount_impl(), name, AMS_FS_IMPL_ACCESS_LOG_FORMAT_MOUNT_CODE(name, path, program_id))); /* Enable access logging. */ AMS_FS_IMPL_ACCESS_LOG_SYSTEM_FS_ACCESSOR_ENABLE(name); R_SUCCEED(); } }
21,828
C++
.cpp
372
43.532258
227
0.575136
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,650
fs_memory_report_info.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/fs_memory_report_info.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "fsa/fs_mount_utils.hpp" #include "impl/fs_file_system_proxy_service_object.hpp" #include "impl/fs_file_system_service_object_adapter.hpp" namespace ams::fs { Result GetAndClearMemoryReportInfo(MemoryReportInfo *out) { /* Check pre-conditions. */ AMS_FS_R_UNLESS(out != nullptr, fs::ResultNullptrArgument()); auto fsp = impl::GetFileSystemProxyServiceObject(); /* Get the memory report info. */ AMS_FS_R_TRY(fsp->GetAndClearMemoryReportInfo(out)); R_SUCCEED(); } }
1,199
C++
.cpp
29
37.724138
76
0.729381
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,651
fs_memory_management.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/fs_memory_management.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> namespace ams::fs { namespace { constinit bool g_used_default_allocator = false; void *DefaultAllocate(size_t size) { g_used_default_allocator = true; return ams::Malloc(size); } void DefaultDeallocate(void *ptr, size_t size) { AMS_UNUSED(size); ams::Free(ptr); } constinit os::SdkMutex g_mutex; constinit AllocateFunction g_allocate_func = DefaultAllocate; constinit DeallocateFunction g_deallocate_func = DefaultDeallocate; constexpr size_t RequiredAlignment = alignof(u64); Result SetAllocatorImpl(AllocateFunction allocator, DeallocateFunction deallocator) { /* Ensure SetAllocator is used correctly. */ R_UNLESS(g_allocate_func == DefaultAllocate, fs::ResultAllocatorAlreadyRegistered()); R_UNLESS(g_deallocate_func == DefaultDeallocate, fs::ResultAllocatorAlreadyRegistered()); R_UNLESS(allocator != nullptr, fs::ResultNullptrArgument()); R_UNLESS(deallocator != nullptr, fs::ResultNullptrArgument()); R_UNLESS(!g_used_default_allocator, fs::ResultDefaultAllocatorUsed()); /* Set allocators. */ g_allocate_func = allocator; g_deallocate_func = deallocator; R_SUCCEED(); } } void SetAllocator(AllocateFunction allocator, DeallocateFunction deallocator) { R_ABORT_UNLESS(SetAllocatorImpl(allocator, deallocator)); } namespace impl { void LockAllocatorMutex() { g_mutex.Lock(); } void UnlockAllocatorMutex() { g_mutex.Unlock(); } void *AllocateUnsafe(size_t size) { /* Check pre-conditions. */ AMS_ASSERT(g_mutex.IsLockedByCurrentThread()); /* Allocate. */ void * const ptr = g_allocate_func(size); /* Check alignment. */ if (AMS_UNLIKELY(!util::IsAligned(reinterpret_cast<uintptr_t>(ptr), RequiredAlignment))) { R_ABORT_UNLESS(fs::ResultAllocatorAlignmentViolation()); } /* Return allocated pointer. */ return ptr; } void DeallocateUnsafe(void *ptr, size_t size) { /* Check pre-conditions. */ AMS_ASSERT(g_mutex.IsLockedByCurrentThread()); /* Deallocate the pointer. */ g_deallocate_func(ptr, size); } void *Allocate(size_t size) { /* Check pre-conditions. */ AMS_ASSERT(g_allocate_func != nullptr); /* Lock the allocator. */ std::scoped_lock lk(g_mutex); return AllocateUnsafe(size); } void Deallocate(void *ptr, size_t size) { /* Check pre-conditions. */ AMS_ASSERT(g_deallocate_func != nullptr); /* If the pointer is non-null, deallocate it. */ if (ptr != nullptr) { /* Lock the allocator. */ std::scoped_lock lk(g_mutex); DeallocateUnsafe(ptr, size); } } } }
3,862
C++
.cpp
91
32.769231
102
0.603632
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,652
fs_romfs_filesystem.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/fs_romfs_filesystem.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> namespace ams::fs { namespace { Result ConvertNcaCorruptedResult(Result res) { AMS_ASSERT(fs::ResultNcaCorrupted::Includes(res)); R_TRY_CATCH(res) { R_CONVERT(fs::ResultInvalidNcaFileSystemType, fs::ResultInvalidRomNcaFileSystemType()) R_CONVERT(fs::ResultInvalidAcidFileSize, fs::ResultInvalidRomAcidFileSize()) R_CONVERT(fs::ResultInvalidAcidSize, fs::ResultInvalidRomAcidSize()) R_CONVERT(fs::ResultInvalidAcid, fs::ResultInvalidRomAcid()) R_CONVERT(fs::ResultAcidVerificationFailed, fs::ResultRomAcidVerificationFailed()) R_CONVERT(fs::ResultInvalidNcaSignature, fs::ResultInvalidRomNcaSignature()) R_CONVERT(fs::ResultNcaHeaderSignature1VerificationFailed, fs::ResultRomNcaHeaderSignature1VerificationFailed()) R_CONVERT(fs::ResultNcaHeaderSignature2VerificationFailed, fs::ResultRomNcaHeaderSignature2VerificationFailed()) R_CONVERT(fs::ResultNcaFsHeaderHashVerificationFailed, fs::ResultRomNcaFsHeaderHashVerificationFailed()) R_CONVERT(fs::ResultInvalidNcaKeyIndex, fs::ResultInvalidRomNcaKeyIndex()) R_CONVERT(fs::ResultInvalidNcaFsHeaderHashType, fs::ResultInvalidRomNcaFsHeaderHashType()) R_CONVERT(fs::ResultInvalidNcaFsHeaderEncryptionType, fs::ResultInvalidRomNcaFsHeaderEncryptionType()) R_CONVERT(fs::ResultInvalidHierarchicalSha256BlockSize, fs::ResultInvalidRomHierarchicalSha256BlockSize()) R_CONVERT(fs::ResultInvalidHierarchicalSha256LayerCount, fs::ResultInvalidRomHierarchicalSha256LayerCount()) R_CONVERT(fs::ResultHierarchicalSha256BaseStorageTooLarge, fs::ResultRomHierarchicalSha256BaseStorageTooLarge()) R_CONVERT(fs::ResultHierarchicalSha256HashVerificationFailed, fs::ResultRomHierarchicalSha256HashVerificationFailed()) R_CATCH_ALL() { /* ... */ } } R_END_TRY_CATCH; AMS_ASSERT(false); R_THROW(fs::ResultNcaCorrupted()); } Result ConvertIntegrityVerificationStorageCorruptedResult(Result res) { AMS_ASSERT(fs::ResultIntegrityVerificationStorageCorrupted::Includes(res)); R_TRY_CATCH(res) { R_CONVERT(fs::ResultIncorrectIntegrityVerificationMagic, fs::ResultIncorrectRomIntegrityVerificationMagic()) R_CONVERT(fs::ResultInvalidZeroHash, fs::ResultInvalidRomZeroHash()) R_CONVERT(fs::ResultNonRealDataVerificationFailed, fs::ResultRomNonRealDataVerificationFailed()) R_CONVERT(fs::ResultInvalidHierarchicalIntegrityVerificationLayerCount, fs::ResultInvalidRomHierarchicalIntegrityVerificationLayerCount()) R_CONVERT(fs::ResultClearedRealDataVerificationFailed, fs::ResultClearedRomRealDataVerificationFailed()) R_CONVERT(fs::ResultUnclearedRealDataVerificationFailed, fs::ResultUnclearedRomRealDataVerificationFailed()) R_CATCH_ALL() { /* ... */ } } R_END_TRY_CATCH; AMS_ASSERT(false); R_THROW(fs::ResultIntegrityVerificationStorageCorrupted()); } Result ConvertBuiltInStorageCorruptedResult(Result res) { AMS_ASSERT(fs::ResultBuiltInStorageCorrupted::Includes(res)); R_TRY_CATCH(res) { R_CONVERT(fs::ResultGptHeaderVerificationFailed, fs::ResultRomGptHeaderVerificationFailed()) R_CATCH_ALL() { /* ... */ } } R_END_TRY_CATCH; AMS_ASSERT(false); R_THROW(fs::ResultBuiltInStorageCorrupted()); } Result ConvertPartitionFileSystemCorruptedResult(Result res) { AMS_ASSERT(fs::ResultPartitionFileSystemCorrupted::Includes(res)); R_TRY_CATCH(res) { R_CONVERT(fs::ResultInvalidSha256PartitionHashTarget, fs::ResultInvalidRomSha256PartitionHashTarget()) R_CONVERT(fs::ResultSha256PartitionHashVerificationFailed, fs::ResultRomSha256PartitionHashVerificationFailed()) R_CONVERT(fs::ResultPartitionSignatureVerificationFailed, fs::ResultRomPartitionSignatureVerificationFailed()) R_CONVERT(fs::ResultSha256PartitionSignatureVerificationFailed, fs::ResultRomSha256PartitionSignatureVerificationFailed()) R_CONVERT(fs::ResultInvalidPartitionEntryOffset, fs::ResultInvalidRomPartitionEntryOffset()) R_CONVERT(fs::ResultInvalidSha256PartitionMetaDataSize, fs::ResultInvalidRomSha256PartitionMetaDataSize()) R_CATCH_ALL() { /* ... */ } } R_END_TRY_CATCH; AMS_ASSERT(false); R_THROW(fs::ResultPartitionFileSystemCorrupted()); } Result ConvertFatFileSystemCorruptedResult(Result res) { AMS_ASSERT(fs::ResultFatFileSystemCorrupted::Includes(res)); R_RETURN(res); } Result ConvertHostFileSystemCorruptedResult(Result res) { AMS_ASSERT(fs::ResultHostFileSystemCorrupted::Includes(res)); R_TRY_CATCH(res) { R_CONVERT(fs::ResultHostEntryCorrupted, fs::ResultRomHostEntryCorrupted()) R_CONVERT(fs::ResultHostFileDataCorrupted, fs::ResultRomHostFileDataCorrupted()) R_CONVERT(fs::ResultHostFileCorrupted, fs::ResultRomHostFileCorrupted()) R_CONVERT(fs::ResultInvalidHostHandle, fs::ResultInvalidRomHostHandle()) R_CATCH_ALL() { /* ... */ } } R_END_TRY_CATCH; AMS_ASSERT(false); R_THROW(fs::ResultHostFileSystemCorrupted()); } Result ConvertDatabaseCorruptedResult(Result res) { AMS_ASSERT(fs::ResultDatabaseCorrupted::Includes(res)); R_TRY_CATCH(res) { R_CONVERT(fs::ResultInvalidAllocationTableBlock, fs::ResultInvalidRomAllocationTableBlock()) R_CONVERT(fs::ResultInvalidKeyValueListElementIndex, fs::ResultInvalidRomKeyValueListElementIndex()) R_CATCH_ALL() { /* ... */ } } R_END_TRY_CATCH; AMS_ASSERT(false); R_THROW(fs::ResultDatabaseCorrupted()); } Result ConvertRomFsResult(Result res) { R_TRY_CATCH(res) { R_CONVERT(fs::ResultUnsupportedVersion, fs::ResultUnsupportedRomVersion()) R_CONVERT(fs::ResultNcaCorrupted, ConvertNcaCorruptedResult(res)) R_CONVERT(fs::ResultIntegrityVerificationStorageCorrupted, ConvertIntegrityVerificationStorageCorruptedResult(res)) R_CONVERT(fs::ResultBuiltInStorageCorrupted, ConvertBuiltInStorageCorruptedResult(res)) R_CONVERT(fs::ResultPartitionFileSystemCorrupted, ConvertPartitionFileSystemCorruptedResult(res)) R_CONVERT(fs::ResultFatFileSystemCorrupted, ConvertFatFileSystemCorruptedResult(res)) R_CONVERT(fs::ResultHostFileSystemCorrupted, ConvertHostFileSystemCorruptedResult(res)) R_CONVERT(fs::ResultDatabaseCorrupted, ConvertDatabaseCorruptedResult(res)) R_CONVERT(fs::ResultNotFound, fs::ResultPathNotFound()) R_CONVERT(fs::ResultPermissionDenied, fs::ResultTargetLocked()) R_CONVERT(fs::ResultIncompatiblePath, fs::ResultPathNotFound()) } R_END_TRY_CATCH; R_SUCCEED(); } Result ReadFile(IStorage *storage, s64 offset, void *buffer, size_t size) { AMS_ASSERT(storage != nullptr); AMS_ASSERT(offset >= 0); AMS_ASSERT(buffer != nullptr || size == 0); R_RETURN(ConvertRomFsResult(storage->Read(offset, buffer, size))); } Result ReadFileHeader(IStorage *storage, RomFileSystemInformation *out) { AMS_ASSERT(storage != nullptr); AMS_ASSERT(out != nullptr); R_RETURN(ReadFile(storage, 0, out, sizeof(*out))); } constexpr size_t CalculateRequiredWorkingMemorySize(const RomFileSystemInformation &header) { const size_t needed_size = header.directory_bucket_size + header.directory_entry_size + header.file_bucket_size + header.file_entry_size; return util::AlignUp(needed_size, 8); } class RomFsFile : public fsa::IFile, public impl::Newable { private: RomFsFileSystem *m_parent; s64 m_start; s64 m_end; public: RomFsFile(RomFsFileSystem *p, s64 s, s64 e) : m_parent(p), m_start(s), m_end(e) { /* ... */ } virtual ~RomFsFile() { /* ... */ } Result VerifyArguments(size_t *out, s64 offset, void *buf, size_t size, const fs::ReadOption &option) { R_TRY(DryRead(out, offset, size, option, fs::OpenMode_Read)); AMS_ASSERT(this->GetStorage() != nullptr); AMS_ASSERT(offset >= 0); AMS_ASSERT(buf != nullptr || size == 0); AMS_UNUSED(buf); R_SUCCEED(); } Result ConvertResult(Result res) const { R_RETURN(ConvertRomFsResult(res)); } s64 GetOffset() const { return m_start; } s64 GetSize() const { return m_end - m_start; } IStorage *GetStorage() { return m_parent->GetBaseStorage(); } public: virtual Result DoRead(size_t *out, s64 offset, void *buffer, size_t size, const fs::ReadOption &option) override { size_t read_size = 0; R_TRY(this->VerifyArguments(std::addressof(read_size), offset, buffer, size, option)); R_TRY(this->ConvertResult(this->GetStorage()->Read(offset + m_start, buffer, size))); *out = read_size; R_SUCCEED(); } virtual Result DoGetSize(s64 *out) override { *out = this->GetSize(); R_SUCCEED(); } virtual Result DoFlush() override { R_SUCCEED(); } virtual Result DoWrite(s64 offset, const void *buffer, size_t size, const fs::WriteOption &option) override { AMS_UNUSED(offset, buffer, size, option); R_THROW(fs::ResultUnsupportedWriteForRomFsFile()); } virtual Result DoSetSize(s64 size) override { AMS_UNUSED(size); R_THROW(fs::ResultUnsupportedWriteForRomFsFile()); } virtual Result DoOperateRange(void *dst, size_t dst_size, fs::OperationId op_id, s64 offset, s64 size, const void *src, size_t src_size) override { switch (op_id) { case OperationId::Invalidate: R_RETURN(this->GetStorage()->OperateRange(fs::OperationId::Invalidate, 0, std::numeric_limits<s64>::max())); case OperationId::QueryRange: { R_UNLESS(offset >= 0, fs::ResultInvalidOffset()); R_UNLESS(this->GetSize() >= offset, fs::ResultOutOfRange()); auto operate_size = size; if (offset + operate_size > this->GetSize() || offset + operate_size < offset) { operate_size = this->GetSize() - offset; } R_RETURN(this->GetStorage()->OperateRange(dst, dst_size, op_id, m_start + offset, operate_size, src, src_size)); } default: R_THROW(fs::ResultUnsupportedOperateRangeForRomFsFile()); } } public: virtual sf::cmif::DomainObjectId GetDomainObjectId() const override { AMS_ABORT(); } }; class RomFsDirectory : public fsa::IDirectory, public impl::Newable { private: using FindPosition = RomFsFileSystem::RomFileTable::FindPosition; private: RomFsFileSystem *m_parent; FindPosition m_current_find; FindPosition m_first_find; fs::OpenDirectoryMode m_mode; public: RomFsDirectory(RomFsFileSystem *p, const FindPosition &f, fs::OpenDirectoryMode m) : m_parent(p), m_current_find(f), m_first_find(f), m_mode(m) { /* ... */ } virtual ~RomFsDirectory() override { /* ... */ } public: virtual Result DoRead(s64 *out_count, DirectoryEntry *out_entries, s64 max_entries) override { R_RETURN(this->ReadInternal(out_count, std::addressof(m_current_find), out_entries, max_entries)); } virtual Result DoGetEntryCount(s64 *out) override { FindPosition find = m_first_find; R_RETURN(this->ReadInternal(out, std::addressof(find), nullptr, 0)); } private: Result ReadInternal(s64 *out_count, FindPosition *find, DirectoryEntry *out_entries, s64 max_entries) { AMS_ASSERT(out_count != nullptr); AMS_ASSERT(find != nullptr); constexpr size_t NameBufferSize = fs::EntryNameLengthMax + 1; char *name_buf = static_cast<char *>(::ams::fs::impl::Allocate(NameBufferSize)); R_UNLESS(name_buf != nullptr, fs::ResultAllocationMemoryFailedInRomFsFileSystemE()); ON_SCOPE_EXIT { ::ams::fs::impl::Deallocate(name_buf, NameBufferSize); }; s32 i = 0; if (m_mode & fs::OpenDirectoryMode_Directory) { while (i < max_entries || out_entries == nullptr) { R_TRY_CATCH(m_parent->GetRomFileTable()->FindNextDirectory(name_buf, find, NameBufferSize)) { R_CATCH(fs::ResultDbmFindFinished) { break; } } R_END_TRY_CATCH; if (out_entries) { const size_t name_len = util::Strnlen(name_buf, NameBufferSize); R_UNLESS(name_len < NameBufferSize, fs::ResultTooLongPath()); std::memcpy(out_entries[i].name, name_buf, name_len); out_entries[i].name[name_len] = '\x00'; out_entries[i].type = fs::DirectoryEntryType_Directory; out_entries[i].file_size = 0; } i++; } } if (m_mode & fs::OpenDirectoryMode_File) { while (i < max_entries || out_entries == nullptr) { auto file_pos = find->next_file; R_TRY_CATCH(m_parent->GetRomFileTable()->FindNextFile(name_buf, find, NameBufferSize)) { R_CATCH(fs::ResultDbmFindFinished) { break; } } R_END_TRY_CATCH; if (out_entries) { const size_t name_len = util::Strnlen(name_buf, NameBufferSize); R_UNLESS(name_len < NameBufferSize, fs::ResultTooLongPath()); std::memcpy(out_entries[i].name, name_buf, name_len); out_entries[i].name[name_len] = '\x00'; out_entries[i].type = fs::DirectoryEntryType_File; RomFsFileSystem::RomFileTable::FileInfo file_info; R_TRY(m_parent->GetRomFileTable()->OpenFile(std::addressof(file_info), m_parent->GetRomFileTable()->PositionToFileId(file_pos))); out_entries[i].file_size = file_info.size.Get(); } i++; } } *out_count = i; R_SUCCEED(); } public: virtual sf::cmif::DomainObjectId GetDomainObjectId() const override { AMS_ABORT(); } }; } RomFsFileSystem::RomFsFileSystem() : m_base_storage() { /* ... */ } RomFsFileSystem::~RomFsFileSystem() { /* ... */ } Result RomFsFileSystem::GetRequiredWorkingMemorySize(size_t *out, IStorage *storage) { RomFileSystemInformation header; R_TRY(ReadFileHeader(storage, std::addressof(header))); *out = CalculateRequiredWorkingMemorySize(header); R_SUCCEED(); } Result RomFsFileSystem::Initialize(IStorage *base, void *work, size_t work_size, bool use_cache) { AMS_ABORT_UNLESS(!use_cache || work != nullptr); AMS_ABORT_UNLESS(base != nullptr); /* Read the header. */ RomFileSystemInformation header; R_TRY(ReadFileHeader(base, std::addressof(header))); /* Set up our storages. */ if (use_cache) { const size_t needed_size = CalculateRequiredWorkingMemorySize(header); R_UNLESS(work_size >= needed_size, fs::ResultPreconditionViolation()); u8 *buf = static_cast<u8 *>(work); auto dir_bucket_buf = buf; buf += header.directory_bucket_size; auto dir_entry_buf = buf; buf += header.directory_entry_size; auto file_bucket_buf = buf; buf += header.file_bucket_size; auto file_entry_buf = buf; buf += header.file_entry_size; R_TRY(ReadFile(base, header.directory_bucket_offset, dir_bucket_buf, header.directory_bucket_size)); R_TRY(ReadFile(base, header.directory_entry_offset, dir_entry_buf, header.directory_entry_size)); R_TRY(ReadFile(base, header.file_bucket_offset, file_bucket_buf, header.file_bucket_size)); R_TRY(ReadFile(base, header.file_entry_offset, file_entry_buf, header.file_entry_size)); m_dir_bucket_storage.reset(new MemoryStorage(dir_bucket_buf, header.directory_bucket_size)); m_dir_entry_storage.reset(new MemoryStorage(dir_entry_buf, header.directory_entry_size)); m_file_bucket_storage.reset(new MemoryStorage(file_bucket_buf, header.file_bucket_size)); m_file_entry_storage.reset(new MemoryStorage(file_entry_buf, header.file_entry_size)); } else { m_dir_bucket_storage.reset(new SubStorage(base, header.directory_bucket_offset, header.directory_bucket_size)); m_dir_entry_storage.reset(new SubStorage(base, header.directory_entry_offset, header.directory_entry_size)); m_file_bucket_storage.reset(new SubStorage(base, header.file_bucket_offset, header.file_bucket_size)); m_file_entry_storage.reset(new SubStorage(base, header.file_entry_offset, header.file_entry_size)); } /* Ensure we allocated storages successfully. */ R_UNLESS(m_dir_bucket_storage != nullptr, fs::ResultAllocationMemoryFailedInRomFsFileSystemA()); R_UNLESS(m_dir_entry_storage != nullptr, fs::ResultAllocationMemoryFailedInRomFsFileSystemA()); R_UNLESS(m_file_bucket_storage != nullptr, fs::ResultAllocationMemoryFailedInRomFsFileSystemA()); R_UNLESS(m_file_entry_storage != nullptr, fs::ResultAllocationMemoryFailedInRomFsFileSystemA()); /* Initialize the rom table. */ { SubStorage db(m_dir_bucket_storage.get(), 0, header.directory_bucket_size); SubStorage de(m_dir_entry_storage.get(), 0, header.directory_entry_size); SubStorage fb(m_file_bucket_storage.get(), 0, header.file_bucket_size); SubStorage fe(m_file_entry_storage.get(), 0, header.file_entry_size); R_TRY(m_rom_file_table.Initialize(db, de, fb, fe)); } /* Set members. */ m_entry_size = header.body_offset; m_base_storage = base; R_SUCCEED(); } Result RomFsFileSystem::Initialize(std::unique_ptr<IStorage>&& base, void *work, size_t work_size, bool use_cache) { m_unique_storage = std::move(base); R_RETURN(this->Initialize(m_unique_storage.get(), work, work_size, use_cache)); } Result RomFsFileSystem::GetFileInfo(RomFileTable::FileInfo *out, const char *path) { R_TRY_CATCH(m_rom_file_table.OpenFile(out, path)) { R_CONVERT(fs::ResultDbmNotFound, fs::ResultPathNotFound()); R_CONVERT(fs::ResultDbmInvalidOperation, fs::ResultPathNotFound()); } R_END_TRY_CATCH; R_SUCCEED(); } IStorage *RomFsFileSystem::GetBaseStorage() { return m_base_storage; } RomFsFileSystem::RomFileTable *RomFsFileSystem::GetRomFileTable() { return std::addressof(m_rom_file_table); } Result RomFsFileSystem::GetFileBaseOffset(s64 *out, const char *path) { AMS_ABORT_UNLESS(out != nullptr); AMS_ABORT_UNLESS(path != nullptr); RomFileTable::FileInfo info; R_TRY(this->GetFileInfo(std::addressof(info), path)); *out = m_entry_size + info.offset.Get(); R_SUCCEED(); } Result RomFsFileSystem::DoCreateFile(const fs::Path &path, s64 size, int flags) { AMS_UNUSED(path, size, flags); R_THROW(fs::ResultUnsupportedWriteForRomFsFileSystem()); } Result RomFsFileSystem::DoDeleteFile(const fs::Path &path) { AMS_UNUSED(path); R_THROW(fs::ResultUnsupportedWriteForRomFsFileSystem()); } Result RomFsFileSystem::DoCreateDirectory(const fs::Path &path) { AMS_UNUSED(path); R_THROW(fs::ResultUnsupportedWriteForRomFsFileSystem()); } Result RomFsFileSystem::DoDeleteDirectory(const fs::Path &path) { AMS_UNUSED(path); R_THROW(fs::ResultUnsupportedWriteForRomFsFileSystem()); } Result RomFsFileSystem::DoDeleteDirectoryRecursively(const fs::Path &path) { AMS_UNUSED(path); R_THROW(fs::ResultUnsupportedWriteForRomFsFileSystem()); } Result RomFsFileSystem::DoRenameFile(const fs::Path &old_path, const fs::Path &new_path) { AMS_UNUSED(old_path, new_path); R_THROW(fs::ResultUnsupportedWriteForRomFsFileSystem()); } Result RomFsFileSystem::DoRenameDirectory(const fs::Path &old_path, const fs::Path &new_path) { AMS_UNUSED(old_path, new_path); R_THROW(fs::ResultUnsupportedWriteForRomFsFileSystem()); } Result RomFsFileSystem::DoGetEntryType(fs::DirectoryEntryType *out, const fs::Path &path) { HierarchicalRomFileTable::FindPosition find_pos; R_TRY_CATCH(m_rom_file_table.FindOpen(std::addressof(find_pos), path.GetString())) { R_CONVERT(fs::ResultDbmNotFound, fs::ResultPathNotFound()) R_CATCH(fs::ResultDbmInvalidOperation) { *out = fs::DirectoryEntryType_File; R_SUCCEED(); } } R_END_TRY_CATCH; *out = fs::DirectoryEntryType_Directory; R_SUCCEED(); } Result RomFsFileSystem::DoOpenFile(std::unique_ptr<fs::fsa::IFile> *out_file, const fs::Path &path, fs::OpenMode mode) { AMS_ASSERT(out_file != nullptr); R_UNLESS((mode & fs::OpenMode_All) == fs::OpenMode_Read, fs::ResultInvalidOpenMode()); RomFileTable::FileInfo file_info{}; R_TRY(this->GetFileInfo(std::addressof(file_info), path.GetString())); auto file = std::make_unique<RomFsFile>(this, m_entry_size + file_info.offset.Get(), m_entry_size + file_info.offset.Get() + file_info.size.Get()); R_UNLESS(file != nullptr, fs::ResultAllocationMemoryFailedInRomFsFileSystemB()); *out_file = std::move(file); R_SUCCEED(); } Result RomFsFileSystem::DoOpenDirectory(std::unique_ptr<fs::fsa::IDirectory> *out_dir, const fs::Path &path, fs::OpenDirectoryMode mode) { AMS_ASSERT(out_dir != nullptr); RomFileTable::FindPosition find; R_TRY_CATCH(m_rom_file_table.FindOpen(std::addressof(find), path.GetString())) { R_CONVERT(fs::ResultDbmNotFound, fs::ResultPathNotFound()) R_CONVERT(fs::ResultDbmInvalidOperation, fs::ResultPathNotFound()) } R_END_TRY_CATCH; auto dir = std::make_unique<RomFsDirectory>(this, find, mode); R_UNLESS(dir != nullptr, fs::ResultAllocationMemoryFailedInRomFsFileSystemC()); *out_dir = std::move(dir); R_SUCCEED(); } Result RomFsFileSystem::DoCommit() { R_SUCCEED(); } Result RomFsFileSystem::DoGetFreeSpaceSize(s64 *out, const fs::Path &path) { AMS_UNUSED(path); *out = 0; R_SUCCEED(); } Result RomFsFileSystem::DoGetTotalSpaceSize(s64 *out, const fs::Path &path) { AMS_UNUSED(out, path); R_THROW(fs::ResultUnsupportedGetTotalSpaceSizeForRomFsFileSystem()); } Result RomFsFileSystem::DoCleanDirectoryRecursively(const fs::Path &path) { AMS_UNUSED(path); R_THROW(fs::ResultUnsupportedWriteForRomFsFileSystem()); } Result RomFsFileSystem::DoCommitProvisionally(s64 counter) { AMS_UNUSED(counter); R_THROW(fs::ResultUnsupportedCommitProvisionallyForRomFsFileSystem()); } Result RomFsFileSystem::DoRollback() { R_SUCCEED(); } }
27,069
C++
.cpp
452
45.65708
173
0.595564
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,653
fs_result_utils.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/fs_result_utils.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> namespace ams::fs { namespace { constinit bool g_handled_by_application = false; } void SetResultHandledByApplication(bool application) { g_handled_by_application = application; } namespace impl { bool IsAbortNeeded(Result result) { /* If the result succeeded, we never need to abort. */ if (R_SUCCEEDED(result)) { return false; } /* Get the abort specifier from current context. */ switch (GetCurrentThreadFsContext()->HandleResult(result)) { case AbortSpecifier::Default: if (g_handled_by_application) { return !fs::ResultHandledByAllProcess::Includes(result); } else { return !(fs::ResultHandledByAllProcess::Includes(result) || fs::ResultHandledBySystemProcess::Includes(result)); } case AbortSpecifier::Abort: return true; case AbortSpecifier::Return: return false; AMS_UNREACHABLE_DEFAULT_CASE(); } } void LogResultErrorMessage(Result result) { /* TODO: log specific results */ AMS_UNUSED(result); } void LogErrorMessage(Result result, const char *function) { /* If the result succeeded, there's nothing to log. */ if (R_SUCCEEDED(result)) { return; } /* TODO: Actually log stuff. */ AMS_UNUSED(function); } } }
2,282
C++
.cpp
58
29.465517
136
0.602895
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,654
fs_remote_file_system_proxy.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/fs_remote_file_system_proxy.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "fs_remote_file_system_proxy.hpp" #include "fs_remote_file_system_proxy_for_loader.hpp" #if defined(ATMOSPHERE_BOARD_NINTENDO_NX) extern "C" { extern u32 __nx_fs_num_sessions; } #endif namespace ams::fs { #if defined(ATMOSPHERE_BOARD_NINTENDO_NX) RemoteFileSystemProxy::RemoteFileSystemProxy(int session_count) { /* Ensure we can connect to sm. */ R_ABORT_UNLESS(sm::Initialize()); ON_SCOPE_EXIT { R_ABORT_UNLESS(sm::Finalize()); }; /* Initialize libnx. */ __nx_fs_num_sessions = static_cast<u32>(session_count); R_ABORT_UNLESS(::fsInitialize()); } RemoteFileSystemProxy::~RemoteFileSystemProxy() { ::fsExit(); } RemoteFileSystemProxyForLoader::RemoteFileSystemProxyForLoader() { /* Ensure we can connect to sm. */ R_ABORT_UNLESS(sm::Initialize()); ON_SCOPE_EXIT { R_ABORT_UNLESS(sm::Finalize()); }; R_ABORT_UNLESS(::fsldrInitialize()); } RemoteFileSystemProxyForLoader::~RemoteFileSystemProxyForLoader() { ::fsldrExit(); } #endif }
1,756
C++
.cpp
47
32.851064
76
0.699058
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,655
fs_host.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/fs_host.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "fsa/fs_mount_utils.hpp" #include "impl/fs_file_system_proxy_service_object.hpp" #include "impl/fs_file_system_service_object_adapter.hpp" namespace ams::fs { namespace { class HostRootCommonMountNameGenerator : public fsa::ICommonMountNameGenerator, public impl::Newable { public: explicit HostRootCommonMountNameGenerator() { /* ... */ } virtual Result GenerateCommonMountName(char *dst, size_t dst_size) override { /* Determine how much space we need. */ constexpr size_t RequiredNameBufferSizeSize = AMS_FS_IMPL_HOST_ROOT_FILE_SYSTEM_MOUNT_NAME_LEN + 1 + 1; AMS_ASSERT(dst_size >= RequiredNameBufferSizeSize); AMS_UNUSED(RequiredNameBufferSizeSize); /* Generate the name. */ const auto size = util::SNPrintf(dst, dst_size, AMS_FS_IMPL_HOST_ROOT_FILE_SYSTEM_MOUNT_NAME ":"); AMS_ASSERT(static_cast<size_t>(size) == RequiredNameBufferSizeSize - 1); AMS_UNUSED(size); R_SUCCEED(); } }; class HostCommonMountNameGenerator : public fsa::ICommonMountNameGenerator, public impl::Newable { private: char m_path[fs::EntryNameLengthMax + 1]; public: HostCommonMountNameGenerator(const char *path) { util::Strlcpy<char>(m_path, path, sizeof(m_path)); } virtual Result GenerateCommonMountName(char *dst, size_t dst_size) override { /* Determine how much space we need. */ const size_t required_size = AMS_FS_IMPL_HOST_ROOT_FILE_SYSTEM_MOUNT_NAME_LEN + 1 + util::Strnlen<char>(m_path, sizeof(m_path)) + 1; /* @Host:%s */ R_UNLESS(dst_size >= required_size, fs::ResultTooLongPath()); /* Generate the name. */ const auto size = util::SNPrintf(dst, dst_size, AMS_FS_IMPL_HOST_ROOT_FILE_SYSTEM_MOUNT_NAME ":%s", m_path); AMS_ASSERT(static_cast<size_t>(size) == required_size - 1); AMS_UNUSED(size); R_SUCCEED(); } }; Result OpenHostFileSystemImpl(std::unique_ptr<fs::fsa::IFileSystem> *out, const fssrv::sf::FspPath &path, const MountHostOption &option) { /* Open the filesystem. */ auto fsp = impl::GetFileSystemProxyServiceObject(); sf::SharedPointer<fssrv::sf::IFileSystem> fs; if (option != MountHostOption::None) { R_TRY(fsp->OpenHostFileSystemWithOption(std::addressof(fs), path, option._value)); } else { R_TRY(fsp->OpenHostFileSystem(std::addressof(fs), path)); } /* Allocate a new filesystem wrapper. */ auto fsa = std::make_unique<impl::FileSystemServiceObjectAdapter>(std::move(fs)); R_UNLESS(fsa != nullptr, fs::ResultAllocationMemoryFailedInHostA()); /* Set the output. */ *out = std::move(fsa); R_SUCCEED(); } Result PreMountHost(std::unique_ptr<fs::HostCommonMountNameGenerator> *out, const char *name, const char *path) { /* Check pre-conditions. */ AMS_ASSERT(out != nullptr); /* Check the mount name. */ R_TRY(impl::CheckMountName(name)); /* Check that path is valid. */ R_UNLESS(path != nullptr, fs::ResultNullptrArgument()); /* Create a new HostCommonMountNameGenerator. */ *out = std::make_unique<HostCommonMountNameGenerator>(path); R_UNLESS(out->get() != nullptr, fs::ResultAllocationMemoryFailedInHostB()); R_SUCCEED(); } } namespace impl { Result OpenHostFileSystem(std::unique_ptr<fs::fsa::IFileSystem> *out, const char *name, const char *path, const fs::MountHostOption &option) { /* Validate arguments. */ R_UNLESS(out != nullptr, fs::ResultNullptrArgument()); R_UNLESS(name != nullptr, fs::ResultNullptrArgument()); R_UNLESS(path != nullptr, fs::ResultNullptrArgument()); /* Check mount name isn't windows path or reserved. */ R_UNLESS(!fs::IsWindowsDrive(name), fs::ResultInvalidMountName()); R_UNLESS(!fs::impl::IsReservedMountName(name), fs::ResultInvalidMountName()); /* Convert the path for fsp. */ fssrv::sf::FspPath sf_path; R_TRY(fs::ConvertToFspPath(std::addressof(sf_path), path)); /* Ensure that the path doesn't correspond to the root. */ if (sf_path.str[0] == 0) { sf_path.str[0] = '.'; sf_path.str[1] = 0; } /* Open the host file system. */ R_RETURN(OpenHostFileSystemImpl(out, sf_path, option)); } } Result MountHost(const char *name, const char *root_path) { /* Pre-mount host. */ std::unique_ptr<fs::HostCommonMountNameGenerator> generator; AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_MOUNT_UNLESS_R_SUCCEEDED(PreMountHost(std::addressof(generator), name, root_path), name, AMS_FS_IMPL_ACCESS_LOG_FORMAT_MOUNT_HOST(name, root_path))); /* Open the filesystem. */ std::unique_ptr<fs::fsa::IFileSystem> fsa; R_TRY(AMS_FS_IMPL_ACCESS_LOG_MOUNT_UNLESS_R_SUCCEEDED(impl::OpenHostFileSystem(std::addressof(fsa), name, root_path, MountHostOption::None), name, AMS_FS_IMPL_ACCESS_LOG_FORMAT_MOUNT_HOST(name, root_path))); /* Declare registration helper. */ auto register_impl = [&]() -> Result { /* Register. */ R_RETURN(fsa::Register(name, std::move(fsa), std::move(generator))); }; /* Mount the filesystem. */ AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_MOUNT(register_impl(), name, AMS_FS_IMPL_ACCESS_LOG_FORMAT_MOUNT_HOST(name, root_path))); /* Enable access logging. */ AMS_FS_IMPL_ACCESS_LOG_FS_ACCESSOR_ENABLE(name); R_SUCCEED(); } Result MountHost(const char *name, const char *root_path, const MountHostOption &option) { /* Pre-mount host. */ std::unique_ptr<fs::HostCommonMountNameGenerator> generator; AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_MOUNT_UNLESS_R_SUCCEEDED(PreMountHost(std::addressof(generator), name, root_path), name, AMS_FS_IMPL_ACCESS_LOG_FORMAT_MOUNT_HOST_WITH_OPTION(name, root_path, option))); /* Open the filesystem. */ std::unique_ptr<fs::fsa::IFileSystem> fsa; R_TRY(AMS_FS_IMPL_ACCESS_LOG_MOUNT_UNLESS_R_SUCCEEDED(impl::OpenHostFileSystem(std::addressof(fsa), name, root_path, option), name, AMS_FS_IMPL_ACCESS_LOG_FORMAT_MOUNT_HOST_WITH_OPTION(name, root_path, option))); /* Declare registration helper. */ auto register_impl = [&]() -> Result { /* Register. */ R_RETURN(fsa::Register(name, std::move(fsa), std::move(generator))); }; /* Mount the filesystem. */ AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_MOUNT(register_impl(), name, AMS_FS_IMPL_ACCESS_LOG_FORMAT_MOUNT_HOST_WITH_OPTION(name, root_path, option))); /* Enable access logging. */ AMS_FS_IMPL_ACCESS_LOG_FS_ACCESSOR_ENABLE(name); R_SUCCEED(); } Result MountHostRoot() { /* Create host root path. */ fssrv::sf::FspPath sf_path; sf_path.str[0] = 0; /* Open the filesystem. */ std::unique_ptr<fs::fsa::IFileSystem> fsa; R_TRY(AMS_FS_IMPL_ACCESS_LOG_MOUNT_UNLESS_R_SUCCEEDED(OpenHostFileSystemImpl(std::addressof(fsa), sf_path, MountHostOption::None), impl::HostRootFileSystemMountName, AMS_FS_IMPL_ACCESS_LOG_FORMAT_MOUNT_HOST_ROOT())); /* Declare registration helper. */ auto register_impl = [&]() -> Result { /* Allocate a new mountname generator. */ auto generator = std::make_unique<HostRootCommonMountNameGenerator>(); R_UNLESS(generator != nullptr, fs::ResultAllocationMemoryFailedInHostC()); /* Register. */ R_RETURN(fsa::Register(impl::HostRootFileSystemMountName, std::move(fsa), std::move(generator))); }; /* Mount the filesystem. */ AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_MOUNT(register_impl(), impl::HostRootFileSystemMountName, AMS_FS_IMPL_ACCESS_LOG_FORMAT_MOUNT_HOST_ROOT())); /* Enable access logging. */ AMS_FS_IMPL_ACCESS_LOG_FS_ACCESSOR_ENABLE(impl::HostRootFileSystemMountName); R_SUCCEED(); } Result MountHostRoot(const MountHostOption &option) { /* Create host root path. */ fssrv::sf::FspPath sf_path; sf_path.str[0] = 0; /* Open the filesystem. */ std::unique_ptr<fs::fsa::IFileSystem> fsa; R_TRY(AMS_FS_IMPL_ACCESS_LOG_MOUNT_UNLESS_R_SUCCEEDED(OpenHostFileSystemImpl(std::addressof(fsa), sf_path, option), impl::HostRootFileSystemMountName, AMS_FS_IMPL_ACCESS_LOG_FORMAT_MOUNT_HOST_ROOT_WITH_OPTION(option))); /* Declare registration helper. */ auto register_impl = [&]() -> Result { /* Allocate a new mountname generator. */ auto generator = std::make_unique<HostRootCommonMountNameGenerator>(); R_UNLESS(generator != nullptr, fs::ResultAllocationMemoryFailedInHostC()); /* Register. */ R_RETURN(fsa::Register(impl::HostRootFileSystemMountName, std::move(fsa), std::move(generator))); }; /* Mount the filesystem. */ AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_MOUNT(register_impl(), impl::HostRootFileSystemMountName, AMS_FS_IMPL_ACCESS_LOG_FORMAT_MOUNT_HOST_ROOT_WITH_OPTION(option))); /* Enable access logging. */ AMS_FS_IMPL_ACCESS_LOG_FS_ACCESSOR_ENABLE(impl::HostRootFileSystemMountName); R_SUCCEED(); } void UnmountHostRoot() { return Unmount(impl::HostRootFileSystemMountName); } }
10,726
C++
.cpp
186
46.66129
227
0.621936
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,656
fs_api.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/fs_api.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "fs_remote_file_system_proxy.hpp" #include "fs_remote_file_system_proxy_for_loader.hpp" #include "impl/fs_library.hpp" namespace ams::fs { #if defined(ATMOSPHERE_OS_HORIZON) namespace { alignas(0x10) constinit std::byte g_fsp_service_object_buffer[0x80] = {}; alignas(0x10) constinit std::byte g_fsp_ldr_service_object_buffer[0x80] = {}; constinit bool g_use_static_fsp_service_object_buffer = false; constinit bool g_use_static_fsp_ldr_service_object_buffer = false; class HipcClientAllocator { public: using Policy = sf::StatelessAllocationPolicy<HipcClientAllocator>; public: constexpr HipcClientAllocator() = default; void *Allocate(size_t size) { if (g_use_static_fsp_service_object_buffer) { return std::addressof(g_fsp_service_object_buffer); } else if (g_use_static_fsp_ldr_service_object_buffer) { return std::addressof(g_fsp_ldr_service_object_buffer); } else { return ::ams::fs::impl::Allocate(size); } } void Deallocate(void *ptr, size_t size) { if (ptr == std::addressof(g_fsp_service_object_buffer)) { return; } else if (ptr == std::addressof(g_fsp_ldr_service_object_buffer)) { return; } else { return ::ams::fs::impl::Deallocate(ptr, size); } } }; enum class FileSystemProxySessionSetting { SystemNormal = 0, Application = 1, SystemMulti = 2, }; constexpr ALWAYS_INLINE int GetSessionCount(FileSystemProxySessionSetting setting) { switch (setting) { case FileSystemProxySessionSetting::Application: return 3; case FileSystemProxySessionSetting::SystemNormal: return 1; case FileSystemProxySessionSetting::SystemMulti: return 2; AMS_UNREACHABLE_DEFAULT_CASE(); } } constinit bool g_is_fsp_object_initialized = false; constinit FileSystemProxySessionSetting g_fsp_session_setting = FileSystemProxySessionSetting::SystemNormal; /* TODO: SessionResourceManager */ } #endif namespace { constinit sf::SharedPointer<fssrv::sf::IFileSystemProxy> g_fsp_service_object; sf::SharedPointer<fssrv::sf::IFileSystemProxy> GetFileSystemProxyServiceObjectImpl() { /* Ensure the library is initialized. */ ::ams::fs::impl::InitializeFileSystemLibrary(); sf::SharedPointer<fssrv::sf::IFileSystemProxy> fsp_object; #if defined(ATMOSPHERE_BOARD_NINTENDO_NX) && defined(ATMOSPHERE_OS_HORIZON) /* Try to use the custom object. */ fsp_object = g_fsp_service_object; /* If we don't have one, create a remote object. */ if (fsp_object == nullptr) { /* Make our next allocation use our static reserved buffer for the service object. */ g_use_static_fsp_service_object_buffer = true; ON_SCOPE_EXIT { g_use_static_fsp_service_object_buffer = false; }; using ObjectFactory = sf::ObjectFactory<HipcClientAllocator::Policy>; /* Create the object. */ fsp_object = ObjectFactory::CreateSharedEmplaced<fssrv::sf::IFileSystemProxy, RemoteFileSystemProxy>(GetSessionCount(g_fsp_session_setting)); AMS_ABORT_UNLESS(fsp_object != nullptr); /* Set the current process. */ fsp_object->SetCurrentProcess({}); } #else /* On non-horizon, use the system object. */ fsp_object = fssrv::impl::GetFileSystemProxyServiceObject(); AMS_ABORT_UNLESS(fsp_object != nullptr); /* Set the current process. */ fsp_object->SetCurrentProcess({}); #endif /* Return the object. */ return fsp_object; } sf::SharedPointer<fssrv::sf::IFileSystemProxyForLoader> GetFileSystemProxyForLoaderServiceObjectImpl() { /* Ensure the library is initialized. */ ::ams::fs::impl::InitializeFileSystemLibrary(); sf::SharedPointer<fssrv::sf::IFileSystemProxyForLoader> fsp_ldr_object; #if defined(ATMOSPHERE_BOARD_NINTENDO_NX) && defined(ATMOSPHERE_OS_HORIZON) /* Make our next allocation use our static reserved buffer for the service object. */ g_use_static_fsp_ldr_service_object_buffer = true; ON_SCOPE_EXIT { g_use_static_fsp_ldr_service_object_buffer = false; }; using ObjectFactory = sf::ObjectFactory<HipcClientAllocator::Policy>; /* Create the object. */ fsp_ldr_object = ObjectFactory::CreateSharedEmplaced<fssrv::sf::IFileSystemProxyForLoader, RemoteFileSystemProxyForLoader>(); AMS_ABORT_UNLESS(fsp_ldr_object != nullptr); #else /* On non-horizon, use the system object. */ fsp_ldr_object = fssrv::impl::GetFileSystemProxyForLoaderServiceObject(); AMS_ABORT_UNLESS(fsp_ldr_object != nullptr); #endif /* Return the object. */ return fsp_ldr_object; } } namespace impl { sf::SharedPointer<fssrv::sf::IFileSystemProxy> GetFileSystemProxyServiceObject() { AMS_FUNCTION_LOCAL_STATIC(sf::SharedPointer<fssrv::sf::IFileSystemProxy>, s_fsp_service_object, GetFileSystemProxyServiceObjectImpl()); return s_fsp_service_object; } sf::SharedPointer<fssrv::sf::IFileSystemProxyForLoader> GetFileSystemProxyForLoaderServiceObject() { AMS_FUNCTION_LOCAL_STATIC(sf::SharedPointer<fssrv::sf::IFileSystemProxyForLoader>, s_fsp_ldr_service_object, GetFileSystemProxyForLoaderServiceObjectImpl()); return s_fsp_ldr_service_object; } } void InitializeForHostTool() { #if !defined(ATMOSPHERE_OS_HORIZON) AMS_ABORT_UNLESS(impl::GetFileSystemProxyServiceObject() != nullptr); R_ABORT_UNLESS(::ams::fs::MountHostRoot()); #endif } void InitializeForSystem() { #if defined(ATMOSPHERE_OS_HORIZON) AMS_ABORT_UNLESS(!g_is_fsp_object_initialized); AMS_ABORT_UNLESS(g_fsp_session_setting == FileSystemProxySessionSetting::SystemNormal); g_fsp_session_setting = FileSystemProxySessionSetting::SystemNormal; /* Nintendo doesn't do this, but we have to for timing reasons. */ AMS_ABORT_UNLESS(impl::GetFileSystemProxyServiceObject() != nullptr); #endif } void InitializeWithMultiSessionForSystem() { #if defined(ATMOSPHERE_OS_HORIZON) AMS_ABORT_UNLESS(!g_is_fsp_object_initialized); AMS_ABORT_UNLESS(g_fsp_session_setting == FileSystemProxySessionSetting::SystemNormal); g_fsp_session_setting = FileSystemProxySessionSetting::SystemMulti; /* Nintendo doesn't do this, but we have to for timing reasons. */ AMS_ABORT_UNLESS(impl::GetFileSystemProxyServiceObject() != nullptr); #endif } }
8,066
C++
.cpp
155
40.703226
169
0.633846
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,657
fs_access_log.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/fs_access_log.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "impl/fs_file_system_proxy_service_object.hpp" #include "fsa/fs_user_mount_table.hpp" #include "fsa/fs_directory_accessor.hpp" #include "fsa/fs_file_accessor.hpp" #include "fsa/fs_filesystem_accessor.hpp" #define AMS_FS_IMPL_ACCESS_LOG_AMS_API_VERSION "ams_version: " STRINGIZE(ATMOSPHERE_RELEASE_VERSION_MAJOR) "." STRINGIZE(ATMOSPHERE_RELEASE_VERSION_MINOR) "." STRINGIZE(ATMOSPHERE_RELEASE_VERSION_MICRO) /* TODO: Other specs? */ #define AMS_FS_IMPL_ACCESS_LOG_SPEC "spec: NX" namespace ams::fs { /* Forward declare priority getter. */ fs::PriorityRaw GetPriorityRawOnCurrentThreadInternal(); namespace { constinit u32 g_global_access_log_mode = fs::AccessLogMode_None; constinit u32 g_local_access_log_target = fs::impl::AccessLogTarget_None; constinit std::atomic_bool g_access_log_initialized = false; constinit os::SdkMutex g_access_log_initialization_mutex; void SetLocalAccessLogImpl(bool enabled) { if (enabled) { g_local_access_log_target |= fs::impl::AccessLogTarget_Application; } else { g_local_access_log_target &= ~fs::impl::AccessLogTarget_Application; } } } Result GetGlobalAccessLogMode(u32 *out) { const auto fsp = impl::GetFileSystemProxyServiceObject(); AMS_FS_R_TRY(fsp->GetGlobalAccessLogMode(out)); R_SUCCEED(); } Result SetGlobalAccessLogMode(u32 mode) { const auto fsp = impl::GetFileSystemProxyServiceObject(); AMS_FS_R_TRY(fsp->SetGlobalAccessLogMode(mode)); R_SUCCEED(); } void SetLocalAccessLog(bool enabled) { SetLocalAccessLogImpl(enabled); } void SetLocalApplicationAccessLog(bool enabled) { SetLocalAccessLogImpl(enabled); } void SetLocalSystemAccessLogForDebug(bool enabled) { #if defined(AMS_BUILD_FOR_DEBUGGING) if (enabled) { g_local_access_log_target |= (fs::impl::AccessLogTarget_Application | fs::impl::AccessLogTarget_System); } else { g_local_access_log_target &= ~(fs::impl::AccessLogTarget_Application | fs::impl::AccessLogTarget_System); } #else AMS_UNUSED(enabled); #endif } } namespace ams::fs::impl { #define ADD_ENUM_CASE(v) case v: return #v const char *IdString::ToValueString(int id) { const int len = util::SNPrintf(m_buffer, sizeof(m_buffer), "%d", id); AMS_ASSERT(static_cast<size_t>(len) < sizeof(m_buffer)); AMS_UNUSED(len); return m_buffer; } template<> const char *IdString::ToString<fs::Priority>(fs::Priority id) { switch (id) { case fs::Priority_Realtime: return "Realtime"; case fs::Priority_Normal: return "Normal"; case fs::Priority_Low: return "Low"; default: return ToValueString(static_cast<int>(id)); } } template<> const char *IdString::ToString<fs::PriorityRaw>(fs::PriorityRaw id) { switch (id) { case fs::PriorityRaw_Realtime: return "Realtime"; case fs::PriorityRaw_Normal: return "Normal"; case fs::PriorityRaw_Low: return "Low"; case fs::PriorityRaw_Background: return "Realtime"; default: return ToValueString(static_cast<int>(id)); } } template<> const char *IdString::ToString<fs::ContentStorageId>(fs::ContentStorageId id) { switch (id) { using enum fs::ContentStorageId; ADD_ENUM_CASE(User); ADD_ENUM_CASE(System); ADD_ENUM_CASE(SdCard); ADD_ENUM_CASE(System0); default: return ToValueString(static_cast<int>(id)); } } template<> const char *IdString::ToString<fs::SaveDataSpaceId>(fs::SaveDataSpaceId id) { switch (id) { using enum fs::SaveDataSpaceId; ADD_ENUM_CASE(System); ADD_ENUM_CASE(User); ADD_ENUM_CASE(SdSystem); ADD_ENUM_CASE(ProperSystem); default: return ToValueString(static_cast<int>(id)); } } template<> const char *IdString::ToString<fs::ContentType>(fs::ContentType id) { switch (id) { case fs::ContentType_Meta: return "Meta"; case fs::ContentType_Control: return "Control"; case fs::ContentType_Manual: return "Manual"; case fs::ContentType_Logo: return "Logo"; case fs::ContentType_Data: return "Data"; default: return ToValueString(static_cast<int>(id)); } } template<> const char *IdString::ToString<fs::MountHostOption>(fs::MountHostOption id) { if (id == MountHostOption::PseudoCaseSensitive) { return "MountHostOptionFlag_PseudoCaseSensitive"; } else { return ToValueString(static_cast<int>(id._value)); } } template<> const char *IdString::ToString<fs::BisPartitionId>(fs::BisPartitionId id) { switch (id) { using enum fs::BisPartitionId; ADD_ENUM_CASE(BootPartition1Root); ADD_ENUM_CASE(BootPartition2Root); ADD_ENUM_CASE(UserDataRoot); ADD_ENUM_CASE(BootConfigAndPackage2Part1); ADD_ENUM_CASE(BootConfigAndPackage2Part2); ADD_ENUM_CASE(BootConfigAndPackage2Part3); ADD_ENUM_CASE(BootConfigAndPackage2Part4); ADD_ENUM_CASE(BootConfigAndPackage2Part5); ADD_ENUM_CASE(BootConfigAndPackage2Part6); ADD_ENUM_CASE(CalibrationBinary); ADD_ENUM_CASE(CalibrationFile); ADD_ENUM_CASE(SafeMode); ADD_ENUM_CASE(User); ADD_ENUM_CASE(System); ADD_ENUM_CASE(SystemProperEncryption); ADD_ENUM_CASE(SystemProperPartition); ADD_ENUM_CASE(DeviceTreeBlob); ADD_ENUM_CASE(System0); default: return ToValueString(static_cast<int>(id)); } } template<> const char *IdString::ToString<fs::DirectoryEntryType>(fs::DirectoryEntryType type) { switch (type) { case fs::DirectoryEntryType_Directory: return "Directory"; case fs::DirectoryEntryType_File: return "File"; default: return ToValueString(static_cast<int>(type)); } } template<> const char *IdString::ToString<fs::GameCardPartition>(fs::GameCardPartition id) { switch (id) { using enum fs::GameCardPartition; ADD_ENUM_CASE(Update); ADD_ENUM_CASE(Normal); ADD_ENUM_CASE(Secure); default: return ToValueString(static_cast<int>(id)); } } template<> const char *IdString::ToString<fssystem::NcaHeader::ContentType>(fssystem::NcaHeader::ContentType id) { switch (id) { using enum fssystem::NcaHeader::ContentType; ADD_ENUM_CASE(Program); ADD_ENUM_CASE(Meta); ADD_ENUM_CASE(Control); ADD_ENUM_CASE(Manual); ADD_ENUM_CASE(Data); ADD_ENUM_CASE(PublicData); default: return ToValueString(static_cast<int>(id)); } } template<> const char *IdString::ToString<fssystem::NcaHeader::DistributionType>(fssystem::NcaHeader::DistributionType id) { switch (id) { using enum fssystem::NcaHeader::DistributionType; ADD_ENUM_CASE(Download); ADD_ENUM_CASE(GameCard); default: return ToValueString(static_cast<int>(id)); } } template<> const char *IdString::ToString<fssystem::NcaHeader::EncryptionType>(fssystem::NcaHeader::EncryptionType id) { switch (id) { using enum fssystem::NcaHeader::EncryptionType; ADD_ENUM_CASE(Auto); ADD_ENUM_CASE(None); default: return ToValueString(static_cast<int>(id)); } } template<> const char *IdString::ToString<fssystem::NcaHeader::DecryptionKey>(fssystem::NcaHeader::DecryptionKey id) { switch (id) { using enum fssystem::NcaHeader::DecryptionKey; case DecryptionKey_AesXts1: return "AesXts1"; case DecryptionKey_AesXts2: return "AesXts2"; case DecryptionKey_AesCtr: return "AesCtr"; case DecryptionKey_AesCtrEx: return "AesCtrEx"; case DecryptionKey_AesCtrHw: return "AesCtrHw"; default: return ToValueString(static_cast<int>(id)); } } template<> const char *IdString::ToString<fssystem::NcaFsHeader::FsType>(fssystem::NcaFsHeader::FsType id) { switch (id) { using enum fssystem::NcaFsHeader::FsType; ADD_ENUM_CASE(RomFs); ADD_ENUM_CASE(PartitionFs); default: return ToValueString(static_cast<int>(id)); } } template<> const char *IdString::ToString<fssystem::NcaFsHeader::EncryptionType>(fssystem::NcaFsHeader::EncryptionType id) { switch (id) { using enum fssystem::NcaFsHeader::EncryptionType; ADD_ENUM_CASE(Auto); ADD_ENUM_CASE(None); ADD_ENUM_CASE(AesXts); ADD_ENUM_CASE(AesCtr); ADD_ENUM_CASE(AesCtrEx); ADD_ENUM_CASE(AesCtrSkipLayerHash); ADD_ENUM_CASE(AesCtrExSkipLayerHash); default: return ToValueString(static_cast<int>(id)); } } template<> const char *IdString::ToString<fssystem::NcaFsHeader::HashType>(fssystem::NcaFsHeader::HashType id) { switch (id) { using enum fssystem::NcaFsHeader::HashType; ADD_ENUM_CASE(Auto); ADD_ENUM_CASE(None); ADD_ENUM_CASE(HierarchicalSha256Hash); ADD_ENUM_CASE(HierarchicalIntegrityHash); ADD_ENUM_CASE(AutoSha3); ADD_ENUM_CASE(HierarchicalSha3256Hash); ADD_ENUM_CASE(HierarchicalIntegritySha3Hash); default: return ToValueString(static_cast<int>(id)); } } template<> const char *IdString::ToString<fssystem::NcaFsHeader::MetaDataHashType>(fssystem::NcaFsHeader::MetaDataHashType id) { switch (id) { using enum fssystem::NcaFsHeader::MetaDataHashType; ADD_ENUM_CASE(None); ADD_ENUM_CASE(HierarchicalIntegrity); default: return ToValueString(static_cast<int>(id)); } } template<> const char *IdString::ToString<gc::impl::MemoryCapacity>(gc::impl::MemoryCapacity id) { switch (id) { using enum gc::impl::MemoryCapacity; case MemoryCapacity_1GB: return "1GB"; case MemoryCapacity_2GB: return "2GB"; case MemoryCapacity_4GB: return "4GB"; case MemoryCapacity_8GB: return "8GB"; case MemoryCapacity_16GB: return "16GB"; case MemoryCapacity_32GB: return "32GB"; default: return ToValueString(static_cast<int>(id)); } } template<> const char *IdString::ToString<gc::impl::SelSec>(gc::impl::SelSec id) { switch (id) { using enum gc::impl::SelSec; case SelSec_T1: return "T1"; case SelSec_T2: return "T2"; default: return ToValueString(static_cast<int>(id)); } } template<> const char *IdString::ToString<gc::impl::KekIndex>(gc::impl::KekIndex id) { switch (id) { using enum gc::impl::KekIndex; case KekIndex_Version0: return "Version0"; case KekIndex_VersionForDev: return "VersionForDev"; default: return ToValueString(static_cast<int>(id)); } } template<> const char *IdString::ToString<gc::impl::AccessControl1ClockRate>(gc::impl::AccessControl1ClockRate id) { switch (id) { using enum gc::impl::AccessControl1ClockRate; case AccessControl1ClockRate_25MHz: return "25 MHz"; case AccessControl1ClockRate_50MHz: return "50 MHz"; default: return ToValueString(static_cast<int>(id)); } } template<> const char *IdString::ToString<gc::impl::FwVersion>(gc::impl::FwVersion id) { switch (id) { using enum gc::impl::FwVersion; case FwVersion_ForDev: return "ForDev"; case FwVersion_1_0_0: return "1.0.0"; case FwVersion_4_0_0: return "4.0.0"; case FwVersion_9_0_0: return "9.0.0"; case FwVersion_11_0_0: return "11.0.0"; case FwVersion_12_0_0: return "12.0.0"; default: return ToValueString(static_cast<int>(id)); } } template<> const char *IdString::ToString<fs::GameCardCompatibilityType>(fs::GameCardCompatibilityType id) { switch (id) { using enum fs::GameCardCompatibilityType; ADD_ENUM_CASE(Normal); ADD_ENUM_CASE(Terra); default: return ToValueString(static_cast<int>(id)); } } template<> const char *IdString::ToString<fssrv::impl::AccessControlBits::Bits>(fssrv::impl::AccessControlBits::Bits id) { switch (id) { using enum fssrv::impl::AccessControlBits::Bits; ADD_ENUM_CASE(ApplicationInfo); ADD_ENUM_CASE(BootModeControl); ADD_ENUM_CASE(Calibration); ADD_ENUM_CASE(SystemSaveData); ADD_ENUM_CASE(GameCard); ADD_ENUM_CASE(SaveDataBackUp); ADD_ENUM_CASE(SaveDataManagement); ADD_ENUM_CASE(BisAllRaw); ADD_ENUM_CASE(GameCardRaw); ADD_ENUM_CASE(GameCardPrivate); ADD_ENUM_CASE(SetTime); ADD_ENUM_CASE(ContentManager); ADD_ENUM_CASE(ImageManager); ADD_ENUM_CASE(CreateSaveData); ADD_ENUM_CASE(SystemSaveDataManagement); ADD_ENUM_CASE(BisFileSystem); ADD_ENUM_CASE(SystemUpdate); ADD_ENUM_CASE(SaveDataMeta); ADD_ENUM_CASE(DeviceSaveData); ADD_ENUM_CASE(SettingsControl); ADD_ENUM_CASE(SystemData); ADD_ENUM_CASE(SdCard); ADD_ENUM_CASE(Host); ADD_ENUM_CASE(FillBis); ADD_ENUM_CASE(CorruptSaveData); ADD_ENUM_CASE(SaveDataForDebug); ADD_ENUM_CASE(FormatSdCard); ADD_ENUM_CASE(GetRightsId); ADD_ENUM_CASE(RegisterExternalKey); ADD_ENUM_CASE(RegisterUpdatePartition); ADD_ENUM_CASE(SaveDataTransfer); ADD_ENUM_CASE(DeviceDetection); ADD_ENUM_CASE(AccessFailureResolution); ADD_ENUM_CASE(SaveDataTransferVersion2); ADD_ENUM_CASE(RegisterProgramIndexMapInfo); ADD_ENUM_CASE(CreateOwnSaveData); ADD_ENUM_CASE(MoveCacheStorage); ADD_ENUM_CASE(Debug); ADD_ENUM_CASE(FullPermission); default: return ToValueString(util::CountTrailingZeros(util::ToUnderlying(id))); } } template<> const char *IdString::ToString<fssrv::impl::AccessControl::AccessibilityType>(fssrv::impl::AccessControl::AccessibilityType id) { switch (id) { using enum fssrv::impl::AccessControl::AccessibilityType; ADD_ENUM_CASE(MountLogo); ADD_ENUM_CASE(MountContentMeta); ADD_ENUM_CASE(MountContentControl); ADD_ENUM_CASE(MountContentManual); ADD_ENUM_CASE(MountContentData); ADD_ENUM_CASE(MountApplicationPackage); ADD_ENUM_CASE(MountSaveDataStorage); ADD_ENUM_CASE(MountContentStorage); ADD_ENUM_CASE(MountImageAndVideoStorage); ADD_ENUM_CASE(MountCloudBackupWorkStorage); ADD_ENUM_CASE(MountCustomStorage); ADD_ENUM_CASE(MountBisCalibrationFile); ADD_ENUM_CASE(MountBisSafeMode); ADD_ENUM_CASE(MountBisUser); ADD_ENUM_CASE(MountBisSystem); ADD_ENUM_CASE(MountBisSystemProperEncryption); ADD_ENUM_CASE(MountBisSystemProperPartition); ADD_ENUM_CASE(MountSdCard); ADD_ENUM_CASE(MountGameCard); ADD_ENUM_CASE(MountDeviceSaveData); ADD_ENUM_CASE(MountSystemSaveData); ADD_ENUM_CASE(MountOthersSaveData); ADD_ENUM_CASE(MountOthersSystemSaveData); ADD_ENUM_CASE(OpenBisPartitionBootPartition1Root); ADD_ENUM_CASE(OpenBisPartitionBootPartition2Root); ADD_ENUM_CASE(OpenBisPartitionUserDataRoot); ADD_ENUM_CASE(OpenBisPartitionBootConfigAndPackage2Part1); ADD_ENUM_CASE(OpenBisPartitionBootConfigAndPackage2Part2); ADD_ENUM_CASE(OpenBisPartitionBootConfigAndPackage2Part3); ADD_ENUM_CASE(OpenBisPartitionBootConfigAndPackage2Part4); ADD_ENUM_CASE(OpenBisPartitionBootConfigAndPackage2Part5); ADD_ENUM_CASE(OpenBisPartitionBootConfigAndPackage2Part6); ADD_ENUM_CASE(OpenBisPartitionCalibrationBinary); ADD_ENUM_CASE(OpenBisPartitionCalibrationFile); ADD_ENUM_CASE(OpenBisPartitionSafeMode); ADD_ENUM_CASE(OpenBisPartitionUser); ADD_ENUM_CASE(OpenBisPartitionSystem); ADD_ENUM_CASE(OpenBisPartitionSystemProperEncryption); ADD_ENUM_CASE(OpenBisPartitionSystemProperPartition); ADD_ENUM_CASE(OpenSdCardStorage); ADD_ENUM_CASE(OpenGameCardStorage); ADD_ENUM_CASE(MountSystemDataPrivate); ADD_ENUM_CASE(MountHost); ADD_ENUM_CASE(MountRegisteredUpdatePartition); ADD_ENUM_CASE(MountSaveDataInternalStorage); ADD_ENUM_CASE(MountTemporaryDirectory); ADD_ENUM_CASE(MountAllBaseFileSystem); ADD_ENUM_CASE(NotMount); default: return ToValueString(static_cast<int>(id)); } } template<> const char *IdString::ToString<fssrv::impl::AccessControl::OperationType>(fssrv::impl::AccessControl::OperationType id) { switch (id) { using enum fssrv::impl::AccessControl::OperationType; ADD_ENUM_CASE(InvalidateBisCache); ADD_ENUM_CASE(EraseMmc); ADD_ENUM_CASE(GetGameCardDeviceCertificate); ADD_ENUM_CASE(GetGameCardIdSet); ADD_ENUM_CASE(FinalizeGameCardDriver); ADD_ENUM_CASE(GetGameCardAsicInfo); ADD_ENUM_CASE(CreateSaveData); ADD_ENUM_CASE(DeleteSaveData); ADD_ENUM_CASE(CreateSystemSaveData); ADD_ENUM_CASE(CreateOthersSystemSaveData); ADD_ENUM_CASE(DeleteSystemSaveData); ADD_ENUM_CASE(OpenSaveDataInfoReader); ADD_ENUM_CASE(OpenSaveDataInfoReaderForSystem); ADD_ENUM_CASE(OpenSaveDataInfoReaderForInternal); ADD_ENUM_CASE(OpenSaveDataMetaFile); ADD_ENUM_CASE(SetCurrentPosixTime); ADD_ENUM_CASE(ReadSaveDataFileSystemExtraData); ADD_ENUM_CASE(SetGlobalAccessLogMode); ADD_ENUM_CASE(SetSpeedEmulationMode); ADD_ENUM_CASE(Debug); ADD_ENUM_CASE(FillBis); ADD_ENUM_CASE(CorruptSaveData); ADD_ENUM_CASE(CorruptSystemSaveData); ADD_ENUM_CASE(VerifySaveData); ADD_ENUM_CASE(DebugSaveData); ADD_ENUM_CASE(FormatSdCard); ADD_ENUM_CASE(GetRightsId); ADD_ENUM_CASE(RegisterExternalKey); ADD_ENUM_CASE(SetEncryptionSeed); ADD_ENUM_CASE(WriteSaveDataFileSystemExtraDataTimeStamp); ADD_ENUM_CASE(WriteSaveDataFileSystemExtraDataFlags); ADD_ENUM_CASE(WriteSaveDataFileSystemExtraDataCommitId); ADD_ENUM_CASE(WriteSaveDataFileSystemExtraDataAll); ADD_ENUM_CASE(ExtendSaveData); ADD_ENUM_CASE(ExtendSystemSaveData); ADD_ENUM_CASE(ExtendOthersSystemSaveData); ADD_ENUM_CASE(RegisterUpdatePartition); ADD_ENUM_CASE(OpenSaveDataTransferManager); ADD_ENUM_CASE(OpenSaveDataTransferManagerVersion2); ADD_ENUM_CASE(OpenSaveDataTransferManagerForSaveDataRepair); ADD_ENUM_CASE(OpenSaveDataTransferManagerForSaveDataRepairTool); ADD_ENUM_CASE(OpenSaveDataTransferProhibiter); ADD_ENUM_CASE(OpenSaveDataMover); ADD_ENUM_CASE(OpenBisWiper); ADD_ENUM_CASE(ListAccessibleSaveDataOwnerId); ADD_ENUM_CASE(ControlMmcPatrol); ADD_ENUM_CASE(OverrideSaveDataTransferTokenSignVerificationKey); ADD_ENUM_CASE(OpenSdCardDetectionEventNotifier); ADD_ENUM_CASE(OpenGameCardDetectionEventNotifier); ADD_ENUM_CASE(OpenSystemDataUpdateEventNotifier); ADD_ENUM_CASE(NotifySystemDataUpdateEvent); ADD_ENUM_CASE(OpenAccessFailureDetectionEventNotifier); ADD_ENUM_CASE(GetAccessFailureDetectionEvent); ADD_ENUM_CASE(IsAccessFailureDetected); ADD_ENUM_CASE(ResolveAccessFailure); ADD_ENUM_CASE(AbandonAccessFailure); ADD_ENUM_CASE(QuerySaveDataInternalStorageTotalSize); ADD_ENUM_CASE(GetSaveDataCommitId); ADD_ENUM_CASE(SetSdCardAccessibility); ADD_ENUM_CASE(SimulateDevice); ADD_ENUM_CASE(CreateSaveDataWithHashSalt); ADD_ENUM_CASE(RegisterProgramIndexMapInfo); ADD_ENUM_CASE(ChallengeCardExistence); ADD_ENUM_CASE(CreateOwnSaveData); ADD_ENUM_CASE(DeleteOwnSaveData); ADD_ENUM_CASE(ReadOwnSaveDataFileSystemExtraData); ADD_ENUM_CASE(ExtendOwnSaveData); ADD_ENUM_CASE(OpenOwnSaveDataTransferProhibiter); ADD_ENUM_CASE(FindOwnSaveDataWithFilter); ADD_ENUM_CASE(OpenSaveDataTransferManagerForRepair); ADD_ENUM_CASE(SetDebugConfiguration); ADD_ENUM_CASE(OpenDataStorageByPath); default: return ToValueString(static_cast<int>(id)); } } namespace { class AccessLogPrinterCallbackManager { private: AccessLogPrinterCallback m_callback; public: constexpr AccessLogPrinterCallbackManager() : m_callback(nullptr) { /* ... */ } constexpr bool IsRegisteredCallback() const { return m_callback != nullptr; } constexpr void RegisterCallback(AccessLogPrinterCallback c) { AMS_ASSERT(m_callback == nullptr); m_callback = c; } constexpr int InvokeCallback(char *buf, size_t size) const { AMS_ASSERT(m_callback != nullptr); return m_callback(buf, size); } }; constinit AccessLogPrinterCallbackManager g_access_log_manager_printer_callback_manager; ALWAYS_INLINE AccessLogPrinterCallbackManager &GetStartAccessLogPrinterCallbackManager() { return g_access_log_manager_printer_callback_manager; } const char *GetPriorityRawName(fs::impl::IdString &id_string) { return id_string.ToString(fs::GetPriorityRawOnCurrentThreadInternal()); } Result OutputAccessLogToSdCardImpl(const char *log, size_t size) { const auto fsp = impl::GetFileSystemProxyServiceObject(); AMS_FS_R_TRY(fsp->OutputAccessLogToSdCard(sf::InBuffer(log, size))); R_SUCCEED(); } void OutputAccessLogToSdCard(const char *format, std::va_list vl) { if ((g_global_access_log_mode & AccessLogMode_SdCard) != 0) { /* Create a buffer to hold the log's input string. */ int log_buffer_size = 1_KB; auto log_buffer = fs::impl::MakeUnique<char[]>(log_buffer_size); while (true) { if (log_buffer == nullptr) { return; } const auto size = util::VSNPrintf(log_buffer.get(), log_buffer_size, format, vl); if (size < log_buffer_size) { break; } log_buffer_size = size + 1; log_buffer = fs::impl::MakeUnique<char[]>(log_buffer_size); } /* Output. */ OutputAccessLogToSdCardImpl(log_buffer.get(), log_buffer_size - 1); } } void OutputAccessLogImpl(const char *log, size_t size) { if ((g_global_access_log_mode & AccessLogMode_Log) != 0) { /* TODO: Support logging. */ } else if ((g_global_access_log_mode & AccessLogMode_SdCard) != 0) { OutputAccessLogToSdCardImpl(log, size - 1); } } void OutputAccessLog(Result result, const char *priority, os::Tick start, os::Tick end, const char *name, const void *handle, const char *format, std::va_list vl) { /* Create a buffer to hold the log's input string. */ int str_buffer_size = 1_KB; auto str_buffer = fs::impl::MakeUnique<char[]>(str_buffer_size); while (true) { if (str_buffer == nullptr) { return; } const auto size = util::VSNPrintf(str_buffer.get(), str_buffer_size, format, vl); if (size < str_buffer_size) { break; } str_buffer_size = size + 1; str_buffer = fs::impl::MakeUnique<char[]>(str_buffer_size); } /* Create a buffer to hold the log. */ int log_buffer_size = 0; decltype(str_buffer) log_buffer; { /* Declare format string. */ constexpr const char FormatString[] = "FS_ACCESS { " "start: %9" PRId64 ", " "end: %9" PRId64 ", " "result: 0x%08" PRIX32 ", " "handle: 0x%p, " "priority: %s, " "function: \"%s\"" "%s" " }\n"; /* Convert the timing to ms. */ const s64 start_ms = start.ToTimeSpan().GetMilliSeconds(); const s64 end_ms = end.ToTimeSpan().GetMilliSeconds(); /* Print the log. */ int try_size = std::max<int>(str_buffer_size + sizeof(FormatString) + 0x100, 1_KB); while (true) { log_buffer = fs::impl::MakeUnique<char[]>(try_size); if (log_buffer == nullptr) { return; } log_buffer_size = 1 + util::SNPrintf(log_buffer.get(), try_size, FormatString, start_ms, end_ms, result.GetValue(), handle, priority, name, str_buffer.get()); if (log_buffer_size <= try_size) { break; } try_size = log_buffer_size; } } OutputAccessLogImpl(log_buffer.get(), log_buffer_size); } void GetProgramIndexForAccessLog(u32 *out_index, u32 *out_count) { if (hos::GetVersion() >= hos::Version_7_0_0) { /* Use libnx bindings if available. */ const auto fsp = impl::GetFileSystemProxyServiceObject(); R_ABORT_UNLESS(fsp->GetProgramIndexForAccessLog(out_index, out_count)); } else { /* Use hardcoded defaults. */ *out_index = 0; *out_count = 0; } } void OutputAccessLogStart() { /* Get the program index. */ u32 program_index = 0, program_count = 0; GetProgramIndexForAccessLog(std::addressof(program_index), std::addressof(program_count)); /* Print the log buffer. */ if (program_count < 2) { constexpr const char StartLog[] = "FS_ACCESS: { " AMS_FS_IMPL_ACCESS_LOG_AMS_API_VERSION ", " AMS_FS_IMPL_ACCESS_LOG_SPEC " }\n"; OutputAccessLogImpl(StartLog, sizeof(StartLog)); } else { constexpr const char StartLog[] = "FS_ACCESS: { " AMS_FS_IMPL_ACCESS_LOG_AMS_API_VERSION ", " AMS_FS_IMPL_ACCESS_LOG_SPEC ", " "program_index: %d" " }\n"; char log_buffer[0x80]; const int len = 1 + util::SNPrintf(log_buffer, sizeof(log_buffer), StartLog, static_cast<int>(program_index)); if (static_cast<size_t>(len) <= sizeof(log_buffer)) { OutputAccessLogImpl(log_buffer, len); } } } [[maybe_unused]] void OutputAccessLogStartForSystem() { constexpr const char StartLog[] = "FS_ACCESS: { " AMS_FS_IMPL_ACCESS_LOG_AMS_API_VERSION ", " AMS_FS_IMPL_ACCESS_LOG_SPEC ", " "for_system: true" " }\n"; OutputAccessLogImpl(StartLog, sizeof(StartLog)); } void OutputAccessLogStartGeneratedByCallback() { /* Get the manager. */ const auto &manager = GetStartAccessLogPrinterCallbackManager(); if (manager.IsRegisteredCallback()) { /* Invoke the callback. */ char log_buffer[0x80]; const int len = 1 + manager.InvokeCallback(log_buffer, sizeof(log_buffer)); /* Print, if we fit. */ if (static_cast<size_t>(len) <= sizeof(log_buffer)) { OutputAccessLogImpl(log_buffer, len); } } } } bool IsEnabledAccessLog(u32 target) { /* If we don't need to log to the target, return false. */ if ((g_local_access_log_target & target) == 0) { return false; } /* Ensure we've initialized. */ if (!g_access_log_initialized) { std::scoped_lock lk(g_access_log_initialization_mutex); if (!g_access_log_initialized) { #if defined (AMS_BUILD_FOR_DEBUGGING) if ((g_local_access_log_target & fs::impl::AccessLogTarget_System) != 0) { g_global_access_log_mode = AccessLogMode_Log; OutputAccessLogStartForSystem(); OutputAccessLogStartGeneratedByCallback(); } else #endif { AMS_FS_R_ABORT_UNLESS(GetGlobalAccessLogMode(std::addressof(g_global_access_log_mode))); if (g_global_access_log_mode != AccessLogMode_None) { OutputAccessLogStart(); OutputAccessLogStartGeneratedByCallback(); } } g_access_log_initialized = true; } } return g_global_access_log_mode != AccessLogMode_None; } bool IsEnabledAccessLog() { return IsEnabledAccessLog(fs::impl::AccessLogTarget_Application | fs::impl::AccessLogTarget_System); } void RegisterStartAccessLogPrinterCallback(AccessLogPrinterCallback callback) { GetStartAccessLogPrinterCallbackManager().RegisterCallback(callback); } void OutputAccessLog(Result result, fs::Priority priority, os::Tick start, os::Tick end, const char *name, const void *handle, const char *fmt, ...) { std::va_list vl; va_start(vl, fmt); OutputAccessLog(result, fs::impl::IdString().ToString(priority), start, end, name, handle, fmt, vl); va_end(vl); } void OutputAccessLog(Result result, fs::PriorityRaw priority_raw, os::Tick start, os::Tick end, const char *name, const void *handle, const char *fmt, ...){ std::va_list vl; va_start(vl, fmt); OutputAccessLog(result, fs::impl::IdString().ToString(priority_raw), start, end, name, handle, fmt, vl); va_end(vl); } void OutputAccessLog(Result result, os::Tick start, os::Tick end, const char *name, fs::FileHandle handle, const char *fmt, ...) { std::va_list vl; va_start(vl, fmt); fs::impl::IdString id_string; OutputAccessLog(result, GetPriorityRawName(id_string), start, end, name, handle.handle, fmt, vl); va_end(vl); } void OutputAccessLog(Result result, os::Tick start, os::Tick end, const char *name, fs::DirectoryHandle handle, const char *fmt, ...) { std::va_list vl; va_start(vl, fmt); fs::impl::IdString id_string; OutputAccessLog(result, GetPriorityRawName(id_string), start, end, name, handle.handle, fmt, vl); va_end(vl); } void OutputAccessLog(Result result, os::Tick start, os::Tick end, const char *name, fs::impl::IdentifyAccessLogHandle handle, const char *fmt, ...) { std::va_list vl; va_start(vl, fmt); fs::impl::IdString id_string; OutputAccessLog(result, GetPriorityRawName(id_string), start, end, name, handle.handle, fmt, vl); va_end(vl); } void OutputAccessLog(Result result, os::Tick start, os::Tick end, const char *name, const void *handle, const char *fmt, ...) { std::va_list vl; va_start(vl, fmt); fs::impl::IdString id_string; OutputAccessLog(result, GetPriorityRawName(id_string), start, end, name, handle, fmt, vl); va_end(vl); } void OutputAccessLogToOnlySdCard(const char *fmt, ...) { std::va_list vl; va_start(vl, fmt); OutputAccessLogToSdCard(fmt, vl); va_end(vl); } void OutputAccessLogUnlessResultSuccess(Result result, os::Tick start, os::Tick end, const char *name, fs::FileHandle handle, const char *fmt, ...) { if (R_FAILED(result)) { std::va_list vl; va_start(vl, fmt); fs::impl::IdString id_string; OutputAccessLog(result, GetPriorityRawName(id_string), start, end, name, handle.handle, fmt, vl); va_end(vl); } } void OutputAccessLogUnlessResultSuccess(Result result, os::Tick start, os::Tick end, const char *name, fs::DirectoryHandle handle, const char *fmt, ...) { if (R_FAILED(result)) { std::va_list vl; va_start(vl, fmt); fs::impl::IdString id_string; OutputAccessLog(result, GetPriorityRawName(id_string), start, end, name, handle.handle, fmt, vl); va_end(vl); } } void OutputAccessLogUnlessResultSuccess(Result result, os::Tick start, os::Tick end, const char *name, const void *handle, const char *fmt, ...) { if (R_FAILED(result)) { std::va_list vl; va_start(vl, fmt); fs::impl::IdString id_string; OutputAccessLog(result, GetPriorityRawName(id_string), start, end, name, handle, fmt, vl); va_end(vl); } } bool IsEnabledHandleAccessLog(fs::FileHandle handle) { /* Get the file accessor. */ impl::FileAccessor *accessor = reinterpret_cast<impl::FileAccessor *>(handle.handle); if (accessor == nullptr) { return true; } /* Check the parent. */ if (auto *parent = accessor->GetParent(); parent != nullptr) { return parent->IsEnabledAccessLog(); } else { return false; } } bool IsEnabledHandleAccessLog(fs::DirectoryHandle handle) { /* Get the file accessor. */ impl::DirectoryAccessor *accessor = reinterpret_cast<impl::DirectoryAccessor *>(handle.handle); if (accessor == nullptr) { return true; } /* Check the parent. */ if (auto *parent = accessor->GetParent(); parent != nullptr) { return parent->IsEnabledAccessLog(); } else { return false; } } bool IsEnabledHandleAccessLog(fs::impl::IdentifyAccessLogHandle handle) { AMS_UNUSED(handle); return true; } bool IsEnabledHandleAccessLog(const void *handle) { if (handle == nullptr) { return true; } /* We should never receive non-null here. */ AMS_ASSERT(handle == nullptr); return false; } bool IsEnabledFileSystemAccessorAccessLog(const char *mount_name) { /* Get the accessor. */ impl::FileSystemAccessor *accessor = nullptr; if (R_FAILED(impl::Find(std::addressof(accessor), mount_name))) { return true; } return accessor->IsEnabledAccessLog(); } void EnableFileSystemAccessorAccessLog(const char *mount_name) { /* Get the accessor. */ impl::FileSystemAccessor *accessor = nullptr; AMS_FS_R_ABORT_UNLESS(impl::Find(std::addressof(accessor), mount_name)); accessor->SetAccessLogEnabled(true); } }
38,358
C++
.cpp
806
35.215881
202
0.59381
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,658
fs_system_data.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/fs_system_data.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "fsa/fs_mount_utils.hpp" namespace ams::fs { Result QueryMountSystemDataCacheSize(size_t *out, ncm::SystemDataId data_id) { AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_SYSTEM(impl::QueryMountDataCacheSize(out, data_id, ncm::StorageId::BuiltInSystem), nullptr, AMS_FS_IMPL_ACCESS_LOG_FORMAT_QUERY_MOUNT_SYSTEM_DATA_CACHE_SIZE(data_id, out))); R_SUCCEED(); } Result MountSystemData(const char *name, ncm::SystemDataId data_id) { AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_SYSTEM_MOUNT(impl::MountData(name, data_id, ncm::StorageId::BuiltInSystem), name, AMS_FS_IMPL_ACCESS_LOG_FORMAT_MOUNT_SYSTEM_DATA(name, data_id))); AMS_FS_IMPL_ACCESS_LOG_SYSTEM_FS_ACCESSOR_ENABLE(name); R_SUCCEED(); } Result MountSystemData(const char *name, ncm::SystemDataId data_id, void *cache_buffer, size_t cache_size) { AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_SYSTEM_MOUNT(impl::MountData(name, data_id, ncm::StorageId::BuiltInSystem, cache_buffer, cache_size), name, AMS_FS_IMPL_ACCESS_LOG_FORMAT_MOUNT_SYSTEM_DATA(name, data_id))); AMS_FS_IMPL_ACCESS_LOG_SYSTEM_FS_ACCESSOR_ENABLE(name); R_SUCCEED(); } }
1,831
C++
.cpp
33
51.242424
217
0.728388
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,659
fs_content_storage.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/fs_content_storage.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "fsa/fs_mount_utils.hpp" #include "impl/fs_file_system_service_object_adapter.hpp" #include "impl/fs_file_system_proxy_service_object.hpp" namespace ams::fs { namespace { class ContentStorageCommonMountNameGenerator : public fsa::ICommonMountNameGenerator, public impl::Newable { private: const ContentStorageId id; public: explicit ContentStorageCommonMountNameGenerator(ContentStorageId i) : id(i) { /* ... */ } virtual Result GenerateCommonMountName(char *dst, size_t dst_size) override { /* Determine how much space we need. */ const size_t needed_size = util::Strnlen(GetContentStorageMountName(id), MountNameLengthMax) + 2; AMS_ABORT_UNLESS(dst_size >= needed_size); /* Generate the name. */ const auto size = util::SNPrintf(dst, dst_size, "%s:", GetContentStorageMountName(id)); AMS_ASSERT(static_cast<size_t>(size) == needed_size - 1); AMS_UNUSED(size); R_SUCCEED(); } }; } const char *GetContentStorageMountName(ContentStorageId id) { switch (id) { case ContentStorageId::System: return impl::ContentStorageSystemMountName; case ContentStorageId::User: return impl::ContentStorageUserMountName; case ContentStorageId::SdCard: return impl::ContentStorageSdCardMountName; AMS_UNREACHABLE_DEFAULT_CASE(); } } Result MountContentStorage(ContentStorageId id) { R_RETURN(MountContentStorage(GetContentStorageMountName(id), id)); } Result MountContentStorage(const char *name, ContentStorageId id) { auto mount_impl = [=]() -> Result { /* Validate the mount name. */ R_TRY(impl::CheckMountNameAllowingReserved(name)); /* It can take some time for the system partition to be ready (if it's on the SD card). */ /* Thus, we will retry up to 10 times, waiting one second each time. */ constexpr size_t MaxRetries = 10; constexpr auto RetryInterval = TimeSpan::FromSeconds(1); /* Mount the content storage */ auto fsp = impl::GetFileSystemProxyServiceObject(); sf::SharedPointer<fssrv::sf::IFileSystem> fs; for (size_t i = 0; i < MaxRetries; i++) { /* Try to open the filesystem. */ R_TRY_CATCH(fsp->OpenContentStorageFileSystem(std::addressof(fs), static_cast<u32>(id))) { R_CATCH(fs::ResultSystemPartitionNotReady) { if (i < MaxRetries - 1) { os::SleepThread(RetryInterval); continue; } else { R_THROW(fs::ResultSystemPartitionNotReady()); } } } R_END_TRY_CATCH; /* The filesystem was opened successfully. */ break; } /* Allocate a new filesystem wrapper. */ auto fsa = std::make_unique<impl::FileSystemServiceObjectAdapter>(std::move(fs)); R_UNLESS(fsa != nullptr, fs::ResultAllocationMemoryFailedInContentStorageA()); /* Allocate a new mountname generator. */ auto generator = std::make_unique<ContentStorageCommonMountNameGenerator>(id); R_UNLESS(generator != nullptr, fs::ResultAllocationMemoryFailedInContentStorageB()); /* Register. */ R_RETURN(fsa::Register(name, std::move(fsa), std::move(generator))); }; /* Perform the mount. */ AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_SYSTEM_MOUNT(mount_impl(), name, AMS_FS_IMPL_ACCESS_LOG_FORMAT_MOUNT_CONTENT_STORAGE(name, id))); /* Enable access logging. */ AMS_FS_IMPL_ACCESS_LOG_SYSTEM_FS_ACCESSOR_ENABLE(name); R_SUCCEED(); } }
4,698
C++
.cpp
91
40.043956
141
0.613607
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,660
fs_save_data_management.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/fs_save_data_management.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "fsa/fs_mount_utils.hpp" #include "impl/fs_file_system_proxy_service_object.hpp" namespace ams::fs { namespace impl { Result ReadSaveDataFileSystemExtraData(SaveDataExtraData *out, SaveDataId id) { auto fsp = impl::GetFileSystemProxyServiceObject(); AMS_FS_R_TRY(fsp->ReadSaveDataFileSystemExtraData(sf::OutBuffer(out, sizeof(*out)), id)); R_SUCCEED(); } Result ReadSaveDataFileSystemExtraData(SaveDataExtraData *out, SaveDataSpaceId space_id, SaveDataId id) { auto fsp = impl::GetFileSystemProxyServiceObject(); AMS_FS_R_TRY(fsp->ReadSaveDataFileSystemExtraDataBySaveDataSpaceId(sf::OutBuffer(out, sizeof(*out)), static_cast<u8>(space_id), id)); R_SUCCEED(); } Result WriteSaveDataFileSystemExtraData(SaveDataSpaceId space_id, SaveDataId id, const SaveDataExtraData &extra_data) { auto fsp = impl::GetFileSystemProxyServiceObject(); AMS_FS_R_TRY(fsp->WriteSaveDataFileSystemExtraData(id, static_cast<u8>(space_id), sf::InBuffer(std::addressof(extra_data), sizeof(extra_data)))); R_SUCCEED(); } } void DisableAutoSaveDataCreation() { auto fsp = impl::GetFileSystemProxyServiceObject(); AMS_FS_R_ABORT_UNLESS(fsp->DisableAutoSaveDataCreation()); } Result CreateSystemSaveData(SaveDataSpaceId space_id, SystemSaveDataId save_id, UserId user_id, u64 owner_id, s64 size, s64 journal_size, u32 flags) { auto create_impl = [=]() -> Result { const auto attribute = SaveDataAttribute::Make(ncm::InvalidProgramId, SaveDataType::System, user_id, save_id); const SaveDataCreationInfo info = { .size = size, .journal_size = journal_size, .block_size = DefaultSaveDataBlockSize, .owner_id = owner_id, .flags = flags, .space_id = space_id, .pseudo = false, }; auto fsp = impl::GetFileSystemProxyServiceObject(); R_RETURN(fsp->CreateSaveDataFileSystemBySystemSaveDataId(attribute, info)); }; AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_SYSTEM(create_impl(), nullptr, AMS_FS_IMPL_ACCESS_LOG_FORMAT_CREATE_SYSTEM_SAVE_DATA(space_id, save_id, user_id, owner_id, size, journal_size, flags))); R_SUCCEED(); } Result CreateSystemSaveData(SystemSaveDataId save_id, s64 size, s64 journal_size, u32 flags) { R_RETURN(CreateSystemSaveData(SaveDataSpaceId::System, save_id, InvalidUserId, 0, size, journal_size, flags)); } Result CreateSystemSaveData(SystemSaveDataId save_id, u64 owner_id, s64 size, s64 journal_size, u32 flags) { R_RETURN(CreateSystemSaveData(SaveDataSpaceId::System, save_id, InvalidUserId, owner_id, size, journal_size, flags)); } Result CreateSystemSaveData(SaveDataSpaceId space_id, SystemSaveDataId save_id, u64 owner_id, s64 size, s64 journal_size, u32 flags) { R_RETURN(CreateSystemSaveData(space_id, save_id, InvalidUserId, owner_id, size, journal_size, flags)); } Result CreateSystemSaveData(SystemSaveDataId save_id, UserId user_id, s64 size, s64 journal_size, u32 flags) { R_RETURN(CreateSystemSaveData(SaveDataSpaceId::System, save_id, user_id, 0, size, journal_size, flags)); } Result CreateSystemSaveData(SystemSaveDataId save_id, UserId user_id, u64 owner_id, s64 size, s64 journal_size, u32 flags) { R_RETURN(CreateSystemSaveData(SaveDataSpaceId::System, save_id, user_id, owner_id, size, journal_size, flags)); } Result DeleteSaveData(SaveDataId id) { auto delete_impl = [=]() -> Result { auto fsp = impl::GetFileSystemProxyServiceObject(); R_RETURN(fsp->DeleteSaveDataFileSystem(id)); }; AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_SYSTEM(delete_impl(), nullptr, AMS_FS_IMPL_ACCESS_LOG_FORMAT_SAVE_DATA_ID, id)); R_SUCCEED(); } Result DeleteSaveData(SaveDataSpaceId space_id, SaveDataId id) { auto delete_impl = [=]() -> Result { auto fsp = impl::GetFileSystemProxyServiceObject(); R_RETURN(fsp->DeleteSaveDataFileSystemBySaveDataSpaceId(static_cast<u8>(space_id), id)); }; AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_SYSTEM(delete_impl(), nullptr, AMS_FS_IMPL_ACCESS_LOG_FORMAT_DELETE_SAVE_DATA(space_id, id))); R_SUCCEED(); } Result DeleteSystemSaveData(SaveDataSpaceId space_id, SystemSaveDataId id, UserId user_id) { auto delete_impl = [=]() -> Result { const auto attribute = SaveDataAttribute::Make(ncm::InvalidProgramId, SaveDataType::System, user_id, id); auto fsp = impl::GetFileSystemProxyServiceObject(); R_RETURN(fsp->DeleteSaveDataFileSystemBySaveDataAttribute(static_cast<u8>(space_id), attribute)); }; AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_SYSTEM(delete_impl(), nullptr, AMS_FS_IMPL_ACCESS_LOG_FORMAT_DELETE_SYSTEM_SAVE_DATA(space_id, id, user_id))); R_SUCCEED(); } Result GetSaveDataFlags(u32 *out, SaveDataId id) { SaveDataExtraData extra_data; R_TRY(impl::ReadSaveDataFileSystemExtraData(std::addressof(extra_data), id)); *out = extra_data.flags; R_SUCCEED(); } Result GetSaveDataFlags(u32 *out, SaveDataSpaceId space_id, SaveDataId id) { SaveDataExtraData extra_data; R_TRY(impl::ReadSaveDataFileSystemExtraData(std::addressof(extra_data), space_id, id)); *out = extra_data.flags; R_SUCCEED(); } Result SetSaveDataFlags(SaveDataId id, SaveDataSpaceId space_id, u32 flags) { SaveDataExtraData extra_data; R_TRY(impl::ReadSaveDataFileSystemExtraData(std::addressof(extra_data), space_id, id)); extra_data.flags = flags; R_RETURN(impl::WriteSaveDataFileSystemExtraData(space_id, id, extra_data)); } Result GetSaveDataAvailableSize(s64 *out, SaveDataId id) { SaveDataExtraData extra_data; R_TRY(impl::ReadSaveDataFileSystemExtraData(std::addressof(extra_data), id)); *out = extra_data.available_size; R_SUCCEED(); } Result GetSaveDataJournalSize(s64 *out, SaveDataId id) { SaveDataExtraData extra_data; R_TRY(impl::ReadSaveDataFileSystemExtraData(std::addressof(extra_data), id)); *out = extra_data.journal_size; R_SUCCEED(); } Result ExtendSaveData(SaveDataSpaceId space_id, SaveDataId id, s64 available_size, s64 journal_size) { auto extend_impl = [=]() -> Result { auto fsp = impl::GetFileSystemProxyServiceObject(); R_RETURN(fsp->ExtendSaveDataFileSystem(static_cast<u8>(space_id), id, available_size, journal_size)); }; AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_SYSTEM(extend_impl(), nullptr, AMS_FS_IMPL_ACCESS_LOG_FORMAT_EXTEND_SAVE_DATA(space_id, id, available_size, journal_size))); R_SUCCEED(); } }
7,688
C++
.cpp
137
47.846715
196
0.681123
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,661
fs_signed_system_partition.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/fs_signed_system_partition.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "fsa/fs_filesystem_accessor.hpp" #include "fsa/fs_mount_utils.hpp" #include "impl/fs_file_system_proxy_service_object.hpp" namespace ams::fs { namespace { Result GetSignedSystemPartitionOnSdCardValid(char *out, impl::FileSystemAccessor *accessor) { R_TRY_CATCH(accessor->QueryEntry(out, sizeof(*out), nullptr, 0, fsa::QueryId::IsSignedSystemPartitionOnSdCardValid, "/")) { /* If querying isn't supported, then the partition isn't valid. */ R_CATCH(fs::ResultUnsupportedOperation) { *out = false; } } R_END_TRY_CATCH_WITH_ABORT_UNLESS; R_SUCCEED(); } } bool IsSignedSystemPartitionOnSdCardValid(const char *system_root_path) { /* Get the accessor for the system filesystem. */ impl::FileSystemAccessor *accessor; const char *sub_path; AMS_FS_R_ABORT_UNLESS(impl::FindFileSystem(std::addressof(accessor), std::addressof(sub_path), system_root_path)); char is_valid; AMS_FS_R_ABORT_UNLESS(GetSignedSystemPartitionOnSdCardValid(std::addressof(is_valid), accessor)); return is_valid; } bool IsSignedSystemPartitionOnSdCardValidDeprecated() { /* Ensure we only call with correct version. */ auto version = hos::GetVersion(); AMS_ABORT_UNLESS(hos::Version_4_0_0 <= version && version < hos::Version_8_0_0); /* Check that the partition is valid. */ auto fsp = impl::GetFileSystemProxyServiceObject(); bool is_valid; AMS_FS_R_ABORT_UNLESS(fsp->IsSignedSystemPartitionOnSdCardValid(std::addressof(is_valid))); return is_valid; } }
2,330
C++
.cpp
49
41.428571
135
0.696743
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,662
fs_game_card.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/fs_game_card.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "fsa/fs_mount_utils.hpp" #include "impl/fs_file_system_proxy_service_object.hpp" #include "impl/fs_file_system_service_object_adapter.hpp" namespace ams::fs { namespace { const char *GetGameCardMountNameSuffix(GameCardPartition which) { switch (which) { case GameCardPartition::Update: return impl::GameCardFileSystemMountNameUpdateSuffix; case GameCardPartition::Normal: return impl::GameCardFileSystemMountNameNormalSuffix; case GameCardPartition::Secure: return impl::GameCardFileSystemMountNameSecureSuffix; AMS_UNREACHABLE_DEFAULT_CASE(); } } class GameCardCommonMountNameGenerator : public fsa::ICommonMountNameGenerator, public impl::Newable { private: const GameCardHandle m_handle; const GameCardPartition m_partition; public: explicit GameCardCommonMountNameGenerator(GameCardHandle h, GameCardPartition p) : m_handle(h), m_partition(p) { /* ... */ } virtual Result GenerateCommonMountName(char *dst, size_t dst_size) override { /* Determine how much space we need. */ const size_t needed_size = util::Strnlen(impl::GameCardFileSystemMountName, MountNameLengthMax) + util::Strnlen(GetGameCardMountNameSuffix(m_partition), MountNameLengthMax) + sizeof(GameCardHandle) * 2 + 2; AMS_ABORT_UNLESS(dst_size >= needed_size); /* Generate the name. */ const auto size = util::SNPrintf(dst, dst_size, "%s%s%08x:", impl::GameCardFileSystemMountName, GetGameCardMountNameSuffix(m_partition), m_handle); AMS_ASSERT(static_cast<size_t>(size) == needed_size - 1); AMS_UNUSED(size); R_SUCCEED(); } }; } Result GetGameCardHandle(GameCardHandle *out) { auto fsp = impl::GetFileSystemProxyServiceObject(); /* Open a device operator. */ sf::SharedPointer<fssrv::sf::IDeviceOperator> device_operator; AMS_FS_R_TRY(fsp->OpenDeviceOperator(std::addressof(device_operator))); /* Get the handle. */ u32 handle; AMS_FS_R_TRY(device_operator->GetGameCardHandle(std::addressof(handle))); *out = handle; R_SUCCEED(); } Result MountGameCardPartition(const char *name, GameCardHandle handle, GameCardPartition partition) { auto mount_impl = [=]() -> Result { /* Validate the mount name. */ R_TRY(impl::CheckMountNameAllowingReserved(name)); /* Open the gamecard filesystem. */ auto fsp = impl::GetFileSystemProxyServiceObject(); sf::SharedPointer<fssrv::sf::IFileSystem> fs; R_TRY(fsp->OpenGameCardFileSystem(std::addressof(fs), static_cast<u32>(handle), static_cast<u32>(partition))); /* Allocate a new filesystem wrapper. */ auto fsa = std::make_unique<impl::FileSystemServiceObjectAdapter>(std::move(fs)); R_UNLESS(fsa != nullptr, fs::ResultAllocationMemoryFailedInGameCardC()); /* Allocate a new mountname generator. */ auto generator = std::make_unique<GameCardCommonMountNameGenerator>(handle, partition); R_UNLESS(generator != nullptr, fs::ResultAllocationMemoryFailedInGameCardD()); /* Register. */ R_RETURN(fsa::Register(name, std::move(fsa), std::move(generator))); }; /* Perform the mount. */ AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_SYSTEM_MOUNT(mount_impl(), name, AMS_FS_IMPL_ACCESS_LOG_FORMAT_MOUNT_GAME_CARD_PARTITION(name, handle, partition))); /* Enable access logging. */ AMS_FS_IMPL_ACCESS_LOG_SYSTEM_FS_ACCESSOR_ENABLE(name); R_SUCCEED(); } bool IsGameCardInserted() { auto fsp = impl::GetFileSystemProxyServiceObject(); /* Open a device operator. */ sf::SharedPointer<fssrv::sf::IDeviceOperator> device_operator; AMS_FS_R_ABORT_UNLESS(fsp->OpenDeviceOperator(std::addressof(device_operator))); /* Get insertion status. */ bool inserted; AMS_FS_R_ABORT_UNLESS(device_operator->IsGameCardInserted(std::addressof(inserted))); return inserted; } Result GetGameCardCid(void *dst, size_t size) { /* Check pre-conditions. */ AMS_FS_R_UNLESS(size >= sizeof(gc::GameCardIdSet), fs::ResultInvalidSize()); auto fsp = impl::GetFileSystemProxyServiceObject(); /* Open a device operator. */ sf::SharedPointer<fssrv::sf::IDeviceOperator> device_operator; AMS_FS_R_TRY(fsp->OpenDeviceOperator(std::addressof(device_operator))); /* Get the id set. */ gc::GameCardIdSet gc_id_set; AMS_FS_R_TRY(device_operator->GetGameCardIdSet(sf::OutBuffer(std::addressof(gc_id_set), sizeof(gc_id_set)), static_cast<s64>(sizeof(gc_id_set)))); /* Copy the id set to output. */ std::memcpy(dst, std::addressof(gc_id_set), sizeof(gc_id_set)); R_SUCCEED(); } Result GetGameCardDeviceId(void *dst, size_t size) { auto fsp = impl::GetFileSystemProxyServiceObject(); /* Open a device operator. */ sf::SharedPointer<fssrv::sf::IDeviceOperator> device_operator; AMS_FS_R_TRY(fsp->OpenDeviceOperator(std::addressof(device_operator))); /* Get the cid. */ AMS_FS_R_TRY(device_operator->GetGameCardDeviceId(sf::OutBuffer(dst, size), static_cast<s64>(size))); R_SUCCEED(); } Result GetGameCardErrorReportInfo(GameCardErrorReportInfo *out) { auto fsp = impl::GetFileSystemProxyServiceObject(); /* Open a device operator. */ sf::SharedPointer<fssrv::sf::IDeviceOperator> device_operator; AMS_FS_R_TRY(fsp->OpenDeviceOperator(std::addressof(device_operator))); /* Get the error report info. */ AMS_FS_R_TRY(device_operator->GetGameCardErrorReportInfo(out)); R_SUCCEED(); } }
6,742
C++
.cpp
124
44.806452
226
0.657191
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,663
fs_device_save_data.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/fs_device_save_data.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "fsa/fs_mount_utils.hpp" #include "impl/fs_file_system_proxy_service_object.hpp" #include "impl/fs_file_system_service_object_adapter.hpp" namespace ams::fs { namespace { constexpr inline SaveDataSpaceId DeviceSaveDataSpaceId = SaveDataSpaceId::User; Result MountDeviceSaveDataImpl(const char *name, const SaveDataAttribute &attribute) { /* Validate the mount name. */ R_TRY(impl::CheckMountName(name)); /* Open the filesystem. */ auto fsp = impl::GetFileSystemProxyServiceObject(); sf::SharedPointer<fssrv::sf::IFileSystem> fs; R_TRY(fsp->OpenSaveDataFileSystem(std::addressof(fs), static_cast<u8>(DeviceSaveDataSpaceId), attribute)); /* Allocate a new filesystem wrapper. */ auto fsa = std::make_unique<impl::FileSystemServiceObjectAdapter>(std::move(fs)); R_UNLESS(fsa != nullptr, fs::ResultAllocationMemoryFailedInDeviceSaveDataA()); /* Register. */ R_RETURN(fsa::Register(name, std::move(fsa))); } } Result MountDeviceSaveData(const char *name) { const auto attr = SaveDataAttribute::Make(ncm::InvalidProgramId, SaveDataType::Device, InvalidUserId, InvalidSystemSaveDataId); /* Perform the mount. */ AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_MOUNT(MountDeviceSaveDataImpl(name, attr), name, AMS_FS_IMPL_ACCESS_LOG_FORMAT_MOUNT, name)); /* Enable access logging. */ AMS_FS_IMPL_ACCESS_LOG_FS_ACCESSOR_ENABLE(name); R_SUCCEED(); } Result MountDeviceSaveData(const char *name, const ncm::ApplicationId application_id) { const auto attr = SaveDataAttribute::Make(application_id, SaveDataType::Device, InvalidUserId, InvalidSystemSaveDataId); /* Perform the mount. */ AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_MOUNT(MountDeviceSaveDataImpl(name, attr), name, AMS_FS_IMPL_ACCESS_LOG_FORMAT_MOUNT_DEVICE_SAVE_DATA_APPLICATION_ID(name, application_id))); /* Enable access logging. */ AMS_FS_IMPL_ACCESS_LOG_FS_ACCESSOR_ENABLE(name); R_SUCCEED(); } }
2,800
C++
.cpp
53
46.037736
185
0.7
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,664
fs_priority.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/fs_priority.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> namespace ams::fs { namespace { constexpr bool IsValidPriority(fs::Priority priority) { return priority == Priority_Low || priority == Priority_Normal || priority == Priority_Realtime; } constexpr bool IsValidPriorityRaw(fs::PriorityRaw priority_raw) { return priority_raw == PriorityRaw_Background || priority_raw == PriorityRaw_Low || priority_raw == PriorityRaw_Normal || priority_raw == PriorityRaw_Realtime; } fs::PriorityRaw ConvertPriorityToPriorityRaw(fs::Priority priority) { AMS_ASSERT(IsValidPriority(priority)); switch (priority) { case Priority_Low: return PriorityRaw_Low; case Priority_Normal: return PriorityRaw_Normal; case Priority_Realtime: return PriorityRaw_Realtime; AMS_UNREACHABLE_DEFAULT_CASE(); } } fs::Priority ConvertPriorityRawToPriority(fs::PriorityRaw priority_raw) { AMS_ASSERT(IsValidPriorityRaw(priority_raw)); switch (priority_raw) { case PriorityRaw_Background: return Priority_Low; case PriorityRaw_Low: return Priority_Low; case PriorityRaw_Normal: return Priority_Normal; case PriorityRaw_Realtime: return Priority_Realtime; AMS_UNREACHABLE_DEFAULT_CASE(); } } void UpdateTlsIoPriority(os::ThreadType *thread, u8 tls_io) { sf::SetFsInlineContext(thread, (tls_io & impl::TlsIoPriorityMask) | (sf::GetFsInlineContext(thread) & ~impl::TlsIoPriorityMask)); } Result GetPriorityRawImpl(fs::PriorityRaw *out, os::ThreadType *thread) { /* Validate arguments. */ R_UNLESS(thread != nullptr, fs::ResultNullptrArgument()); /* Get the raw priority. */ PriorityRaw priority_raw; R_TRY(impl::ConvertTlsIoPriorityToFsPriority(std::addressof(priority_raw), impl::GetTlsIoPriority(thread))); /* Set output. */ *out = priority_raw; R_SUCCEED(); } Result GetPriorityImpl(fs::Priority *out, os::ThreadType *thread) { /* Validate arguments. */ R_UNLESS(thread != nullptr, fs::ResultNullptrArgument()); /* Get the raw priority. */ PriorityRaw priority_raw; R_TRY(impl::ConvertTlsIoPriorityToFsPriority(std::addressof(priority_raw), impl::GetTlsIoPriority(thread))); /* Set output. */ *out = ConvertPriorityRawToPriority(priority_raw); R_SUCCEED(); } Result SetPriorityRawImpl(os::ThreadType *thread, fs::PriorityRaw priority_raw) { /* Validate arguments. */ R_UNLESS(thread != nullptr, fs::ResultNullptrArgument()); R_UNLESS(IsValidPriorityRaw(priority_raw), fs::ResultInvalidArgument()); /* Convert to tls io. */ u8 tls_io; R_TRY(impl::ConvertFsPriorityToTlsIoPriority(std::addressof(tls_io), priority_raw)); /* Update the priority. */ UpdateTlsIoPriority(thread, tls_io); R_SUCCEED(); } Result SetPriorityImpl(os::ThreadType *thread, fs::Priority priority) { /* Validate arguments. */ R_UNLESS(thread != nullptr, fs::ResultNullptrArgument()); R_UNLESS(IsValidPriority(priority), fs::ResultInvalidArgument()); /* Convert to tls io. */ u8 tls_io; R_TRY(impl::ConvertFsPriorityToTlsIoPriority(std::addressof(tls_io), ConvertPriorityToPriorityRaw(priority))); /* Update the priority. */ UpdateTlsIoPriority(thread, tls_io); R_SUCCEED(); } } Priority GetPriorityOnCurrentThread() { fs::Priority priority; AMS_FS_R_ABORT_UNLESS(AMS_FS_IMPL_ACCESS_LOG(GetPriorityImpl(std::addressof(priority), os::GetCurrentThread()), nullptr, AMS_FS_IMPL_ACCESS_LOG_FORMAT_NONE)); return priority; } Priority GetPriority(os::ThreadType *thread) { fs::Priority priority; AMS_FS_R_ABORT_UNLESS(AMS_FS_IMPL_ACCESS_LOG(GetPriorityImpl(std::addressof(priority), thread), nullptr, AMS_FS_IMPL_ACCESS_LOG_FORMAT_THREAD_ID, reinterpret_cast<u64>(thread != nullptr ? os::GetThreadId(thread) : os::ThreadId{}))); return priority; } PriorityRaw GetPriorityRawOnCurrentThread() { fs::PriorityRaw priority_raw; AMS_FS_R_ABORT_UNLESS(AMS_FS_IMPL_ACCESS_LOG(GetPriorityRawImpl(std::addressof(priority_raw), os::GetCurrentThread()), nullptr, AMS_FS_IMPL_ACCESS_LOG_FORMAT_NONE)); return priority_raw; } PriorityRaw GetPriorityRawOnCurrentThreadInternal() { fs::PriorityRaw priority_raw; R_ABORT_UNLESS(GetPriorityRawImpl(std::addressof(priority_raw), os::GetCurrentThread())); return priority_raw; } PriorityRaw GetPriorityRaw(os::ThreadType *thread) { fs::PriorityRaw priority_raw; AMS_FS_R_ABORT_UNLESS(AMS_FS_IMPL_ACCESS_LOG(GetPriorityRawImpl(std::addressof(priority_raw), thread), nullptr, AMS_FS_IMPL_ACCESS_LOG_FORMAT_THREAD_ID, reinterpret_cast<u64>(thread != nullptr ? os::GetThreadId(thread) : os::ThreadId{}))); return priority_raw; } void SetPriorityOnCurrentThread(Priority priority) { AMS_FS_R_ABORT_UNLESS(AMS_FS_IMPL_ACCESS_LOG(SetPriorityImpl(os::GetCurrentThread(), priority), nullptr, AMS_FS_IMPL_ACCESS_LOG_FORMAT_NONE)); } void SetPriority(os::ThreadType *thread, Priority priority) { AMS_FS_R_ABORT_UNLESS(AMS_FS_IMPL_ACCESS_LOG(SetPriorityImpl(os::GetCurrentThread(), priority), nullptr, AMS_FS_IMPL_ACCESS_LOG_FORMAT_THREAD_ID, reinterpret_cast<u64>(thread != nullptr ? os::GetThreadId(thread) : os::ThreadId{}))); } void SetPriorityRawOnCurrentThread(PriorityRaw priority_raw) { AMS_FS_R_ABORT_UNLESS(AMS_FS_IMPL_ACCESS_LOG(SetPriorityRawImpl(os::GetCurrentThread(), priority_raw), nullptr, AMS_FS_IMPL_ACCESS_LOG_FORMAT_NONE)); } void SetPriorityRaw(os::ThreadType *thread, PriorityRaw priority_raw) { AMS_FS_R_ABORT_UNLESS(AMS_FS_IMPL_ACCESS_LOG(SetPriorityRawImpl(os::GetCurrentThread(), priority_raw), nullptr, AMS_FS_IMPL_ACCESS_LOG_FORMAT_THREAD_ID, reinterpret_cast<u64>(thread != nullptr ? os::GetThreadId(thread) : os::ThreadId{}))); } }
7,136
C++
.cpp
127
46.661417
247
0.661411
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,665
fs_program_id.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/fs_program_id.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include <stratosphere/fs/fs_rights_id.hpp> #include "impl/fs_file_system_proxy_service_object.hpp" namespace ams::fs { Result GetProgramId(ncm::ProgramId *out, const char *path, fs::ContentAttributes attr) { AMS_FS_R_UNLESS(out != nullptr, fs::ResultNullptrArgument()); AMS_FS_R_UNLESS(path != nullptr, fs::ResultNullptrArgument()); /* Convert the path for fsp. */ fssrv::sf::FspPath sf_path; R_TRY(fs::ConvertToFspPath(std::addressof(sf_path), path)); auto fsp = impl::GetFileSystemProxyServiceObject(); AMS_FS_R_TRY(fsp->GetProgramId(out, sf_path, attr)); R_SUCCEED(); } }
1,317
C++
.cpp
30
39.866667
92
0.712949
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,666
fs_bis.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/fs_bis.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "fsa/fs_mount_utils.hpp" #include "impl/fs_file_system_service_object_adapter.hpp" #include "impl/fs_file_system_proxy_service_object.hpp" namespace ams::fs { namespace { class BisCommonMountNameGenerator : public fsa::ICommonMountNameGenerator, public impl::Newable { private: const BisPartitionId m_id; public: explicit BisCommonMountNameGenerator(BisPartitionId i) : m_id(i) { /* ... */ } virtual Result GenerateCommonMountName(char *dst, size_t dst_size) override { /* Determine how much space we need. */ const char *bis_mount_name = GetBisMountName(m_id); const size_t needed_size = util::Strnlen(bis_mount_name, MountNameLengthMax) + 2; AMS_ABORT_UNLESS(dst_size >= needed_size); /* Generate the name. */ const auto size = util::SNPrintf(dst, dst_size, "%s:", bis_mount_name); AMS_ASSERT(static_cast<size_t>(size) == needed_size - 1); AMS_UNUSED(size); R_SUCCEED(); } }; } namespace impl { Result MountBisImpl(const char *name, BisPartitionId id, const char *root_path) { auto mount_impl = [=]() -> Result { /* Validate the mount name. */ R_TRY(impl::CheckMountNameAllowingReserved(name)); /* Convert the path for ipc. */ /* NOTE: Nintendo ignores the root_path here. */ fssrv::sf::FspPath sf_path; sf_path.str[0] = '\x00'; AMS_UNUSED(root_path); /* Open the filesystem. */ auto fsp = impl::GetFileSystemProxyServiceObject(); sf::SharedPointer<fssrv::sf::IFileSystem> fs; R_TRY(fsp->OpenBisFileSystem(std::addressof(fs), sf_path, static_cast<u32>(id))); /* Allocate a new mountname generator. */ auto generator = std::make_unique<BisCommonMountNameGenerator>(id); R_UNLESS(generator != nullptr, fs::ResultAllocationMemoryFailedInBisA()); /* Allocate a new filesystem wrapper. */ auto fsa = std::make_unique<impl::FileSystemServiceObjectAdapter>(std::move(fs)); R_UNLESS(fsa != nullptr, fs::ResultAllocationMemoryFailedInBisB()); /* Register. */ R_RETURN(fsa::Register(name, std::move(fsa), std::move(generator))); }; /* Perform the mount. */ AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_SYSTEM_MOUNT(mount_impl(), name, AMS_FS_IMPL_ACCESS_LOG_FORMAT_MOUNT_BIS(name, id, root_path))); /* Enable access logging. */ AMS_FS_IMPL_ACCESS_LOG_SYSTEM_FS_ACCESSOR_ENABLE(name); R_SUCCEED(); } Result SetBisRootForHostImpl(BisPartitionId id, const char *root_path) { AMS_UNUSED(id, root_path); AMS_ABORT("TODO"); } } const char *GetBisMountName(BisPartitionId id) { switch (id) { case BisPartitionId::CalibrationFile: return impl::BisCalibrationFilePartitionMountName; case BisPartitionId::SafeMode: return impl::BisSafeModePartitionMountName; case BisPartitionId::User: return impl::BisUserPartitionMountName; case BisPartitionId::System: return impl::BisSystemPartitionMountName; AMS_UNREACHABLE_DEFAULT_CASE(); } } Result MountBis(BisPartitionId id, const char *root_path) { R_RETURN(impl::MountBisImpl(GetBisMountName(id), id, root_path)); } Result MountBis(const char *name, BisPartitionId id) { R_RETURN(impl::MountBisImpl(name, id, nullptr)); } void SetBisRootForHost(BisPartitionId id, const char *root_path) { R_ABORT_UNLESS(impl::SetBisRootForHostImpl(id, root_path)); } Result OpenBisPartition(std::unique_ptr<fs::IStorage> *out, BisPartitionId id) { /* Open the partition. */ auto fsp = impl::GetFileSystemProxyServiceObject(); sf::SharedPointer<fssrv::sf::IStorage> s; AMS_FS_R_TRY(fsp->OpenBisStorage(std::addressof(s), static_cast<u32>(id))); /* Allocate a new storage wrapper. */ auto storage = std::make_unique<impl::StorageServiceObjectAdapter<fssrv::sf::IStorage>>(std::move(s)); AMS_FS_R_UNLESS(storage != nullptr, fs::ResultAllocationMemoryFailedInBisC()); *out = std::move(storage); R_SUCCEED(); } Result InvalidateBisCache() { auto fsp = impl::GetFileSystemProxyServiceObject(); AMS_FS_R_ABORT_UNLESS(fsp->InvalidateBisCache()); R_SUCCEED(); } }
5,447
C++
.cpp
108
40.12963
144
0.62154
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,667
fs_library.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/impl/fs_library.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include <stratosphere/fssrv/fssrv_interface_adapters.hpp> #include "fs_library.hpp" #include "fs_file_system_service_object_adapter.hpp" #include "../../fssrv/impl/fssrv_allocator_for_service_framework.hpp" namespace ams::fs::impl { #if !defined(ATMOSPHERE_OS_HORIZON) namespace { constexpr size_t SystemHeapSize = 8_MB; alignas(os::MemoryPageSize) constinit u8 g_system_heap[SystemHeapSize]; ALWAYS_INLINE auto &GetSystemHeapAllocator() { AMS_FUNCTION_LOCAL_STATIC(mem::StandardAllocator, s_system_heap_allocator, g_system_heap, sizeof(g_system_heap)); return s_system_heap_allocator; } constinit util::optional<fssrv::MemoryResourceFromStandardAllocator> g_system_heap_memory_resource; void *AllocateForSystem(size_t size) { return g_system_heap_memory_resource->Allocate(size); } void DeallocateForSystem(void *p, size_t size) { return g_system_heap_memory_resource->Deallocate(p, size); } [[maybe_unused]] constexpr size_t BufferPoolSize = 6_MB; [[maybe_unused]] constexpr size_t DeviceBufferSize = 8_MB; [[maybe_unused]] constexpr size_t DeviceWorkBufferSize = os::MemoryPageSize; [[maybe_unused]] constexpr size_t BufferManagerHeapSize = 14_MB; constexpr size_t DeviceWorkBufferRequiredSize = 0x140; static_assert(util::IsAligned(BufferManagerHeapSize, os::MemoryBlockUnitSize)); //alignas(os::MemoryPageSize) u8 g_buffer_pool[BufferPoolSize]; alignas(os::MemoryPageSize) u8 g_device_buffer[DeviceBufferSize]; alignas(os::MemoryPageSize) u8 g_device_work_buffer[DeviceWorkBufferSize]; //alignas(os::MemoryPageSize) u8 g_buffer_manager_heap[BufferManagerHeapSize]; // //alignas(os::MemoryPageSize) u8 g_buffer_manager_work_buffer[64_KB]; /* TODO: Other work buffers. */ /* TODO: Implement pooled threads. */ // constexpr int PooledThreadCount = 12; // constexpr size_t PooledThreadStackSize = 32_KB; // fssystem::PooledThread g_pooled_threads[PooledThreadCount]; /* FileSystem creators. */ constinit util::optional<fssrv::fscreator::LocalFileSystemCreator> g_local_fs_creator; constinit util::optional<fssrv::fscreator::SubDirectoryFileSystemCreator> g_subdir_fs_creator; constinit fssrv::fscreator::FileSystemCreatorInterfaces g_fs_creator_interfaces = {}; Result InitializeFileSystemLibraryImpl() { /* Set system allocator. */ fssystem::InitializeAllocator(::ams::fs::impl::Allocate, ::ams::fs::impl::Deallocate); fssystem::InitializeAllocatorForSystem(::ams::fs::impl::AllocateForSystem, ::ams::fs::impl::DeallocateForSystem); /* TODO: Many things. */ g_system_heap_memory_resource.emplace(std::addressof(GetSystemHeapAllocator())); fssystem::InitializeBufferPool(reinterpret_cast<char *>(g_device_buffer), DeviceBufferSize, reinterpret_cast<char *>(g_device_work_buffer), DeviceWorkBufferRequiredSize); /* Setup fscreators/interfaces. */ g_local_fs_creator.emplace(true); g_subdir_fs_creator.emplace(); g_fs_creator_interfaces.local_fs_creator = std::addressof(*g_local_fs_creator); g_fs_creator_interfaces.subdir_fs_creator = std::addressof(*g_subdir_fs_creator); /* Initialize fssrv. */ const fssrv::FileSystemProxyConfiguration config = { .m_fs_creator_interfaces = std::addressof(g_fs_creator_interfaces), .m_base_storage_service_impl = nullptr /* TODO */, .m_base_file_system_service_impl = nullptr /* TODO */, .m_nca_file_system_service_impl = nullptr /* TODO */, .m_save_data_file_system_service_impl = nullptr /* TODO */, .m_access_failure_management_service_impl = nullptr /* TODO */, .m_time_service_impl = nullptr /* TODO */, .m_status_report_service_impl = nullptr /* TODO */, .m_program_registry_service_impl = nullptr /* TODO */, .m_access_log_service_impl = nullptr /* TODO */, .m_debug_configuration_service_impl = nullptr /* TODO */, }; fssrv::InitializeForFileSystemProxy(config); R_SUCCEED(); } class FileSystemLibraryInitializer { public: FileSystemLibraryInitializer() { R_ABORT_UNLESS(InitializeFileSystemLibraryImpl()); } }; } #endif void InitializeFileSystemLibrary() { #if !defined(ATMOSPHERE_OS_HORIZON) AMS_FUNCTION_LOCAL_STATIC(FileSystemLibraryInitializer, s_library_initializer); AMS_UNUSED(s_library_initializer); #endif } }
5,542
C++
.cpp
97
47.824742
182
0.668142
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,668
fs_hash_generator_factory_selector.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/impl/fs_hash_generator_factory_selector.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> namespace ams::fs::impl { namespace { constinit fssystem::ShaHashGeneratorFactorySelector g_sha_hash_generator_factory_selector; } fssystem::IHash256GeneratorFactorySelector *GetNcaHashGeneratorFactorySelector() { return std::addressof(g_sha_hash_generator_factory_selector); } fssystem::IHash256GeneratorFactorySelector *GetSaveDataHashGeneratorFactorySelector() { return std::addressof(g_sha_hash_generator_factory_selector); } }
1,150
C++
.cpp
27
39.037037
98
0.762545
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,669
fs_id_string_impl.os.generic.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/impl/fs_id_string_impl.os.generic.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include <exosphere/pkg1.hpp> namespace ams::fs::impl { #define ADD_ENUM_CASE(v) case v: return #v template<> const char *IdString::ToString<pkg1::KeyGeneration>(pkg1::KeyGeneration id) { static_assert(pkg1::KeyGeneration_Current == pkg1::KeyGeneration_19_0_0); switch (id) { using enum pkg1::KeyGeneration; case KeyGeneration_1_0_0: return "1.0.0-2.3.0"; case KeyGeneration_3_0_0: return "3.0.0"; case KeyGeneration_3_0_1: return "3.0.1-3.0.2"; case KeyGeneration_4_0_0: return "4.0.0-4.1.0"; case KeyGeneration_5_0_0: return "5.0.0-5.1.0"; case KeyGeneration_6_0_0: return "6.0.0-6.1.0"; case KeyGeneration_6_2_0: return "6.2.0"; case KeyGeneration_7_0_0: return "7.0.0-8.0.1"; case KeyGeneration_8_1_0: return "8.1.0-8.1.1"; case KeyGeneration_9_0_0: return "9.0.0-9.0.1"; case KeyGeneration_9_1_0: return "9.1.0-12.0.3"; case KeyGeneration_12_1_0: return "12.1.0"; case KeyGeneration_13_0_0: return "13.0.0-13.2.1"; case KeyGeneration_14_0_0: return "14.0.0-14.1.2"; case KeyGeneration_15_0_0: return "15.0.0-15.0.1"; case KeyGeneration_16_0_0: return "16.0.0-16.0.3"; case KeyGeneration_17_0_0: return "17.0.0-17.0.1"; case KeyGeneration_18_0_0: return "18.0.0-18.1.0"; case KeyGeneration_19_0_0: return "19.0.0-"; default: return "Unknown"; } } }
2,219
C++
.cpp
46
40.586957
92
0.627478
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,670
fs_path_normalizer_tests.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/tests/fs_path_normalizer_tests.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> namespace ams::fs { namespace { constexpr size_t DefaultPathBufferSize = fs::EntryNameLengthMax + 1; //#define ENABLE_PRINT_FORMAT_TEST_DEBUGGING #if defined(ENABLE_PRINT_FORMAT_TEST_DEBUGGING) template<u32 Expected, u32 Actual> struct Print { constexpr Print() { if (std::is_constant_evaluated()) { __builtin_unreachable(); } } }; template<u32 E = 0, u32 A = 0, size_t N = 0> consteval void PrintResultMismatchImpl(u32 e, u32 a) { if constexpr (N == 32) { Print<E, A>{}; } else { const bool is_e = (e & (1 << N)) != 0; const bool is_a = (a & (1 << N)) != 0; if (is_e) { if (is_a) { PrintResultMismatchImpl<E | (1 << N), A | (1 << N), N + 1>(e, a); } else { PrintResultMismatchImpl<E | (1 << N), A | (0 << N), N + 1>(e, a); } } else { if (is_a) { PrintResultMismatchImpl<E | (0 << N), A | (1 << N), N + 1>(e, a); } else { PrintResultMismatchImpl<E | (0 << N), A | (0 << N), N + 1>(e, a); } } } } consteval void PrintResultMismatch(const Result &lhs, const Result &rhs) { PrintResultMismatchImpl(lhs.GetDescription(), rhs.GetDescription()); } template<size_t Index, char Expected, char Actual> struct PrintMismatchChar { constexpr PrintMismatchChar() { if (std::is_constant_evaluated()) { __builtin_unreachable(); } } }; template<size_t Ix, char Expected, size_t C = 0> consteval void PrintCharacterMismatch(char c) { if (c == static_cast<char>(C)) { PrintMismatchChar<Ix, Expected, static_cast<char>(C)>{}; return; } if constexpr (C < std::numeric_limits<unsigned char>::max()) { PrintCharacterMismatch<Ix, Expected, C + 1>(c); } } template<size_t Ix, char C = 0> consteval void PrintCharacterMismatch(char c, char c2) { if (c == static_cast<char>(C)) { PrintCharacterMismatch<Ix, static_cast<char>(C)>(c2); return; } if constexpr (C < std::numeric_limits<unsigned char>::max()) { PrintCharacterMismatch<Ix, C + 1>(c, c2); } } template<size_t Ix = 0> consteval void PrintCharacterMismatch(size_t ix, char c, char c2) { if (Ix == ix) { PrintCharacterMismatch<Ix>(c, c2); return; } if constexpr (Ix <= DefaultPathBufferSize) { PrintCharacterMismatch<Ix + 1>(ix, c, c2); } } #endif consteval bool TestNormalizeImpl(const char *path, size_t buffer_size, const char *normalized, bool windows_path, bool drive_relative, bool all_chars, size_t expected_length, Result expected_result) { /* Allocate a buffer to normalize into. */ char *buffer = new char[buffer_size]; ON_SCOPE_EXIT { delete[] buffer; }; buffer[buffer_size - 1] = '\xcc'; /* Perform normalization. */ size_t actual_length; const Result actual_result = PathNormalizer::Normalize(buffer, std::addressof(actual_length), path, buffer_size, windows_path, drive_relative, all_chars); /* Check that the expected result matches the actual. */ if (actual_result.GetValue() != expected_result.GetValue()) { #if defined(ENABLE_PRINT_FORMAT_TEST_DEBUGGING) PrintResultMismatch(expected_result.GetValue(), actual_result.GetValue()); #endif return false; } /* Check that the expected string matches the actual. */ for (size_t i = 0; i < buffer_size; ++i) { if (normalized[i] != StringTraits::NullTerminator || R_SUCCEEDED(expected_result)) { if (buffer[i] != normalized[i]) { #if defined(ENABLE_PRINT_FORMAT_TEST_DEBUGGING) PrintCharacterMismatch(i, normalized[i], buffer[i]); #endif return false; } } if (normalized[i] == StringTraits::NullTerminator || buffer[i] == StringTraits::NullTerminator) { break; } } /* Check that the expected length matches the actual. */ if (R_SUCCEEDED(expected_result) || fs::ResultTooLongPath::Includes(expected_result)) { if (expected_length != actual_length) { #if defined(ENABLE_PRINT_FORMAT_TEST_DEBUGGING) PrintResultMismatchImpl(static_cast<u32>(expected_length), static_cast<u32>(actual_length)); #endif return false; } } return true; } struct NormalizeTestData { const char *path; bool windows; bool rel; bool allow_all; const char *normalized; size_t len; Result result; }; template<size_t N, size_t Ix = 0> consteval bool DoNormalizeTests(const NormalizeTestData (&tests)[N]) { if constexpr (Ix >= N) { return true; } const auto &test = tests[Ix]; if (!TestNormalizeImpl(test.path, DefaultPathBufferSize, test.normalized, test.windows, test.rel, test.allow_all, test.len, test.result)) { return false; } if constexpr (Ix < N) { return DoNormalizeTests<N, Ix + 1>(tests); } else { AMS_ASSUME(false); } } consteval bool TestNormalized() { constexpr NormalizeTestData Tests[] = { { "/aa/bb/c/", false, true, false, "/aa/bb/c", 8, ResultSuccess() }, { "aa/bb/c/", false, false, false, "", 0, fs::ResultInvalidPathFormat() }, { "aa/bb/c/", false, true, false, "/aa/bb/c", 8, ResultSuccess() }, { "mount:a/b", false, true, false, "/", 0, fs::ResultInvalidCharacter() }, { "mo|unt:a/b", false, true, true, "/mo|unt:a/b", 11, ResultSuccess() }, { "/aa/bb/../..", true, false, false, "/", 1, ResultSuccess() }, { "/aa/bb/../../..", true, false, false, "/", 1, ResultSuccess() }, { "/aa/bb/../../..", false, false, false, "/aa/bb/", 0, fs::ResultDirectoryUnobtainable() }, { "aa/bb/../../..", true, true, false, "/", 1, ResultSuccess() }, { "aa/bb/../../..", false, true, false, "/aa/bb/", 0, fs::ResultDirectoryUnobtainable() }, { "mount:a/b", false, true, true, "/mount:a/b", 10, ResultSuccess() }, { "/a|/bb/cc", false, false, true, "/a|/bb/cc", 9, ResultSuccess() }, { "/>a/bb/cc", false, false, true, "/>a/bb/cc", 9, ResultSuccess() }, { "/aa/.</cc", false, false, true, "/aa/.</cc", 9, ResultSuccess() }, { "/aa/..</cc", false, false, true, "/aa/..</cc", 10, ResultSuccess() }, { "", false, false, false, "", 0, fs::ResultInvalidPathFormat() }, { "/", false, false, false, "/", 1, ResultSuccess() }, { "/.", false, false, false, "/", 1, ResultSuccess() }, { "/./", false, false, false, "/", 1, ResultSuccess() }, { "/..", false, false, false, "/", 0, fs::ResultDirectoryUnobtainable() }, { "//.", false, false, false, "/", 1, ResultSuccess() }, { "/ ..", false, false, false, "/ ..", 4, ResultSuccess() }, { "/.. /", false, false, false, "/.. ", 4, ResultSuccess() }, { "/. /.", false, false, false, "/. ", 3, ResultSuccess() }, { "/aa/bb/cc/dd/./.././../..", false, false, false, "/aa", 3, ResultSuccess() }, { "/aa/bb/cc/dd/./.././../../..", false, false, false, "/", 1, ResultSuccess() }, { "/./aa/./bb/./cc/./dd/.", false, false, false, "/aa/bb/cc/dd", 12, ResultSuccess() }, { "/aa\\bb/cc", false, false, false, "/aa\\bb/cc", 9, ResultSuccess() }, { "/aa\\bb/cc", false, false, false, "/aa\\bb/cc", 9, ResultSuccess() }, { "/a|/bb/cc", false, false, false, "/", 0, fs::ResultInvalidCharacter() }, { "/>a/bb/cc", false, false, false, "/", 0, fs::ResultInvalidCharacter() }, { "/aa/.</cc", false, false, false, "/aa/", 0, fs::ResultInvalidCharacter() }, { "/aa/..</cc", false, false, false, "/aa/", 0, fs::ResultInvalidCharacter() }, { "\\\\aa/bb/cc", false, false, false, "", 0, fs::ResultInvalidPathFormat() }, { "\\\\aa\\bb\\cc", false, false, false, "", 0, fs::ResultInvalidPathFormat() }, { "/aa/bb/..\\cc", false, false, false, "/aa/cc", 6, ResultSuccess() }, { "/aa/bb\\..\\cc", false, false, false, "/aa/cc", 6, ResultSuccess() }, { "/aa/bb\\..", false, false, false, "/aa", 3, ResultSuccess() }, { "/aa\\bb/../cc", false, false, false, "/cc", 3, ResultSuccess() } }; return DoNormalizeTests(Tests); } static_assert(TestNormalized()); struct NormalizeTestDataSmallBuffer { const char *path; size_t buffer_size; const char *normalized; size_t len; Result result; }; template<size_t N, size_t Ix = 0> consteval bool DoNormalizeTests(const NormalizeTestDataSmallBuffer (&tests)[N]) { if constexpr (Ix >= N) { return true; } const auto &test = tests[Ix]; if (!TestNormalizeImpl(test.path, test.buffer_size, test.normalized, false, false, false, test.len, test.result)) { return false; } if constexpr (Ix < N) { return DoNormalizeTests<N, Ix + 1>(tests); } else { AMS_ASSUME(false); } } consteval bool TestNormalizedSmallBuffer() { constexpr NormalizeTestDataSmallBuffer Tests[] = { { "/aa/bb/cc/", 7, "/aa/bb", 6, fs::ResultTooLongPath() }, { "/aa/bb/cc/", 8, "/aa/bb/", 7, fs::ResultTooLongPath() }, { "/aa/bb/cc/", 9, "/aa/bb/c", 8, fs::ResultTooLongPath() }, { "/aa/bb/cc/", 10, "/aa/bb/cc", 9, ResultSuccess() }, { "/aa/bb/cc", 9, "/aa/bb/c", 8, fs::ResultTooLongPath() }, { "/aa/bb/cc", 10, "/aa/bb/cc", 9, ResultSuccess() }, { "/./aa/./bb/./cc", 9, "/aa/bb/c", 8, fs::ResultTooLongPath() }, { "/./aa/./bb/./cc", 10, "/aa/bb/cc", 9, ResultSuccess() }, { "/aa/bb/cc/../../..", 9, "/aa/bb/c", 8, fs::ResultTooLongPath() }, { "/aa/bb/cc/../../..", 10, "/aa/bb/cc", 9, fs::ResultTooLongPath() }, { "/aa/bb/.", 7, "/aa/bb", 6, fs::ResultTooLongPath() }, { "/aa/bb/./", 7, "/aa/bb", 6, fs::ResultTooLongPath() }, { "/aa/bb/..", 8, "/aa", 3, ResultSuccess() }, { "/aa/bb", 1, "", 0, fs::ResultTooLongPath() }, { "/aa/bb", 2, "/", 1, fs::ResultTooLongPath() }, { "/aa/bb", 3, "/a", 2, fs::ResultTooLongPath() }, { "aa/bb", 1, "", 0, fs::ResultInvalidPathFormat() } }; return DoNormalizeTests(Tests); } static_assert(TestNormalizedSmallBuffer()); consteval bool TestIsNormalizedImpl(const char *path, bool allow_all, bool expected_normalized, size_t expected_size, Result expected_result) { /* Perform normalization checking. */ bool actual_normalized; size_t actual_size = 0; const Result actual_result = PathNormalizer::IsNormalized(std::addressof(actual_normalized), std::addressof(actual_size), path, allow_all); /* Check that the expected result matches the actual. */ if (actual_result.GetValue() != expected_result.GetValue()) { #if defined(ENABLE_PRINT_FORMAT_TEST_DEBUGGING) PrintResultMismatch(expected_result.GetValue(), actual_result.GetValue()); #endif return false; } if (expected_size != actual_size) { #if defined(ENABLE_PRINT_FORMAT_TEST_DEBUGGING) PrintResultMismatchImpl(static_cast<u32>(expected_size), static_cast<u32>(actual_size)); #endif return false; } /* Check that the expected output matches the actual. */ if (R_SUCCEEDED(expected_result)) { if (expected_normalized != actual_normalized) { #if defined(ENABLE_PRINT_FORMAT_TEST_DEBUGGING) PrintResultMismatchImpl(static_cast<u32>(expected_normalized), static_cast<u32>(actual_normalized)); #endif return false; } } return true; } struct IsNormalizedTestData { const char *path; bool allow_all; bool normalized; size_t len; Result result; }; template<size_t N, size_t Ix = 0> consteval bool DoIsNormalizedTests(const IsNormalizedTestData (&tests)[N]) { if constexpr (Ix >= N) { return true; } const auto &test = tests[Ix]; if (!TestIsNormalizedImpl(test.path, test.allow_all, test.normalized, test.len, test.result)) { return false; } if constexpr (Ix < N) { return DoIsNormalizedTests<N, Ix + 1>(tests); } else { AMS_ASSUME(false); } } consteval bool TestIsNormalized() { constexpr IsNormalizedTestData Tests[] = { { "/aa/bb/c/", false, false, 9, ResultSuccess() }, { "aa/bb/c/", false, false, 0, fs::ResultInvalidPathFormat() }, { "aa/bb/c/", false, false, 0, fs::ResultInvalidPathFormat() }, { "mount:a/b", false, false, 0, fs::ResultInvalidPathFormat() }, { "mo|unt:a/b", true, false, 0, fs::ResultInvalidPathFormat() }, { "/aa/bb/../..", false, false, 0, ResultSuccess() }, { "/aa/bb/../../..", false, false, 0, ResultSuccess() }, { "/aa/bb/../../..", false, false, 0, ResultSuccess() }, { "aa/bb/../../..", false, false, 0, fs::ResultInvalidPathFormat() }, { "aa/bb/../../..", false, false, 0, fs::ResultInvalidPathFormat() }, { "mount:a/b", true, false, 0, fs::ResultInvalidPathFormat() }, { "/a|/bb/cc", true, true, 9, ResultSuccess() }, { "/>a/bb/cc", true, true, 9, ResultSuccess() }, { "/aa/.</cc", true, true, 9, ResultSuccess() }, { "/aa/..</cc", true, true, 10, ResultSuccess() }, { "", false, false, 0, fs::ResultInvalidPathFormat() }, { "/", false, true, 1, ResultSuccess() }, { "/.", false, false, 2, ResultSuccess() }, { "/./", false, false, 0, ResultSuccess() }, { "/..", false, false, 3, ResultSuccess() }, { "//.", false, false, 0, ResultSuccess() }, { "/ ..", false, true, 4, ResultSuccess() }, { "/.. /", false, false, 5, ResultSuccess() }, { "/. /.", false, false, 5, ResultSuccess() }, { "/aa/bb/cc/dd/./.././../..", false, false, 0, ResultSuccess() }, { "/aa/bb/cc/dd/./.././../../..", false, false, 0, ResultSuccess() }, { "/./aa/./bb/./cc/./dd/.", false, false, 0, ResultSuccess() }, { "/aa\\bb/cc", false, true, 9, ResultSuccess() }, { "/aa\\bb/cc", false, true, 9, ResultSuccess() }, { "/a|/bb/cc", false, false, 0, fs::ResultInvalidCharacter() }, { "/>a/bb/cc", false, false, 0, fs::ResultInvalidCharacter() }, { "/aa/.</cc", false, false, 0, fs::ResultInvalidCharacter() }, { "/aa/..</cc", false, false, 0, fs::ResultInvalidCharacter() }, { "\\\\aa/bb/cc", false, false, 0, fs::ResultInvalidPathFormat() }, { "\\\\aa\\bb\\cc", false, false, 0, fs::ResultInvalidPathFormat() }, { "/aa/bb/..\\cc", false, true, 12, ResultSuccess() }, { "/aa/bb\\..\\cc", false, true, 12, ResultSuccess() }, { "/aa/bb\\..", false, true, 9, ResultSuccess() }, { "/aa\\bb/../cc", false, false, 0, ResultSuccess() } }; return DoIsNormalizedTests(Tests); } static_assert(TestIsNormalized()); } }
18,212
C++
.cpp
345
38.469565
208
0.493602
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,671
fs_path_formatter_tests.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/tests/fs_path_formatter_tests.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> namespace ams::fs { namespace { constexpr size_t DefaultPathBufferSize = fs::EntryNameLengthMax + 1; consteval PathFlags DecodeFlags(const char *desc) { PathFlags flags{}; while (*desc) { switch (*(desc++)) { case 'B': flags.AllowBackslash(); break; case 'E': flags.AllowEmptyPath(); break; case 'M': flags.AllowMountName(); break; case 'R': flags.AllowRelativePath(); break; case 'W': flags.AllowWindowsPath(); break; case 'C': flags.AllowAllCharacters(); break; AMS_UNREACHABLE_DEFAULT_CASE(); } } return flags; } consteval size_t Strlen(const char *p) { size_t len = 0; while (p[len] != StringTraits::NullTerminator) { ++len; } return len; } //#define ENABLE_PRINT_FORMAT_TEST_DEBUGGING #if defined(ENABLE_PRINT_FORMAT_TEST_DEBUGGING) template<u32 Expected, u32 Actual> struct Print { constexpr Print() { if (std::is_constant_evaluated()) { __builtin_unreachable(); } } }; template<u32 E = 0, u32 A = 0, size_t N = 0> consteval void PrintResultMismatchImpl(u32 e, u32 a) { if constexpr (N == 32) { Print<E, A>{}; } else { const bool is_e = (e & (1 << N)) != 0; const bool is_a = (a & (1 << N)) != 0; if (is_e) { if (is_a) { PrintResultMismatchImpl<E | (1 << N), A | (1 << N), N + 1>(e, a); } else { PrintResultMismatchImpl<E | (1 << N), A | (0 << N), N + 1>(e, a); } } else { if (is_a) { PrintResultMismatchImpl<E | (0 << N), A | (1 << N), N + 1>(e, a); } else { PrintResultMismatchImpl<E | (0 << N), A | (0 << N), N + 1>(e, a); } } } } consteval void PrintResultMismatch(const Result &lhs, const Result &rhs) { PrintResultMismatchImpl(lhs.GetDescription(), rhs.GetDescription()); } template<size_t Index, char Expected, char Actual> struct PrintMismatchChar { constexpr PrintMismatchChar() { if (std::is_constant_evaluated()) { __builtin_unreachable(); } } }; template<size_t Ix, char Expected, size_t C = 0> consteval void PrintCharacterMismatch(char c) { if (c == static_cast<char>(C)) { PrintMismatchChar<Ix, Expected, static_cast<char>(C)>{}; return; } if constexpr (C < std::numeric_limits<unsigned char>::max()) { PrintCharacterMismatch<Ix, Expected, C + 1>(c); } } template<size_t Ix, char C = 0> consteval void PrintCharacterMismatch(char c, char c2) { if (c == static_cast<char>(C)) { PrintCharacterMismatch<Ix, static_cast<char>(C)>(c2); return; } if constexpr (C < std::numeric_limits<unsigned char>::max()) { PrintCharacterMismatch<Ix, C + 1>(c, c2); } } template<size_t Ix = 0> consteval void PrintCharacterMismatch(size_t ix, char c, char c2) { if (Ix == ix) { PrintCharacterMismatch<Ix>(c, c2); return; } if constexpr (Ix <= DefaultPathBufferSize) { PrintCharacterMismatch<Ix + 1>(ix, c, c2); } } #endif consteval bool TestNormalizedImpl(const char *path, const PathFlags &flags, size_t buffer_size, const char *normalized, Result expected_result) { /* Allocate a buffer to normalize into. */ char *buffer = new char[buffer_size]; ON_SCOPE_EXIT { delete[] buffer; }; buffer[buffer_size - 1] = '\xcc'; /* Perform normalization. */ const Result actual_result = PathFormatter::Normalize(buffer, buffer_size, path, Strlen(path) + 1, flags); /* Check that the expected result matches the actual. */ if (actual_result.GetValue() != expected_result.GetValue()) { #if defined(ENABLE_PRINT_FORMAT_TEST_DEBUGGING) PrintResultMismatch(expected_result.GetValue(), actual_result.GetValue()); #endif return false; } /* Check that the expected string matches the actual. */ for (size_t i = 0; i < buffer_size; ++i) { if (normalized[i] != StringTraits::NullTerminator || R_SUCCEEDED(expected_result)) { if (buffer[i] != normalized[i]) { #if defined(ENABLE_PRINT_FORMAT_TEST_DEBUGGING) PrintCharacterMismatch(i, normalized[i], buffer[i]); #endif return false; } } if (normalized[i] == StringTraits::NullTerminator || buffer[i] == StringTraits::NullTerminator) { break; } } return true; } struct NormalizeTestData { const char *path; const char *flag_desc; const char *normalized; Result result; size_t buffer_size = DefaultPathBufferSize; }; template<size_t N, size_t Ix = 0> consteval bool DoNormalizeTests(const NormalizeTestData (&tests)[N]) { if constexpr (Ix >= N) { return true; } const auto &test = tests[Ix]; if (!TestNormalizedImpl(test.path, DecodeFlags(test.flag_desc), test.buffer_size, test.normalized, test.result)) { return false; } if constexpr (Ix < N) { return DoNormalizeTests<N, Ix + 1>(tests); } else { AMS_ASSUME(false); } } consteval bool TestNormalizeEmptyPath() { constexpr NormalizeTestData Tests[] = { { "", "", "", fs::ResultInvalidPathFormat() }, { "", "E", "", ResultSuccess() }, { "/aa/bb/../cc", "E", "/aa/cc", ResultSuccess() }, }; return DoNormalizeTests(Tests); } static_assert(TestNormalizeEmptyPath()); consteval bool TestNormalizeMountName() { constexpr NormalizeTestData Tests[] = { { "mount:/aa/bb", "", "", fs::ResultInvalidPathFormat() }, { "mount:/aa/bb", "W", "", fs::ResultInvalidPathFormat() }, { "mount:/aa/bb", "M", "mount:/aa/bb", ResultSuccess() }, { "mount:/aa/./bb", "M", "mount:/aa/bb", ResultSuccess() }, { "mount:\\aa\\bb", "M", "mount:", fs::ResultInvalidPathFormat() }, { "m:/aa/bb", "M", "", fs::ResultInvalidPathFormat() }, { "mo>unt:/aa/bb", "M", "", fs::ResultInvalidCharacter() }, { "moun?t:/aa/bb", "M", "", fs::ResultInvalidCharacter() }, { "mo&unt:/aa/bb", "M", "mo&unt:/aa/bb", ResultSuccess() }, { "/aa/./bb", "M", "/aa/bb", ResultSuccess() }, { "mount/aa/./bb", "M", "", fs::ResultInvalidPathFormat() } }; return DoNormalizeTests(Tests); } static_assert(TestNormalizeMountName()); consteval bool TestNormalizeWindowsPath() { constexpr NormalizeTestData Tests[] = { { "c:/aa/bb", "", "", fs::ResultInvalidPathFormat() }, { "c:\\aa\\bb", "", "", fs::ResultInvalidCharacter() }, { "\\\\host\\share", "", "", fs::ResultInvalidCharacter() }, { "\\\\.\\c:\\", "", "", fs::ResultInvalidCharacter() }, { "\\\\.\\c:/aa/bb/.", "", "", fs::ResultInvalidCharacter() }, { "\\\\?\\c:\\", "", "", fs::ResultInvalidCharacter() }, { "mount:\\\\host\\share\\aa\\bb", "M", "mount:", fs::ResultInvalidCharacter() }, { "mount:\\\\host/share\\aa\\bb", "M", "mount:", fs::ResultInvalidCharacter() }, { "c:\\aa\\..\\..\\..\\bb", "W", "c:/bb", ResultSuccess() }, { "mount:/\\\\aa\\..\\bb", "MW", "mount:", fs::ResultInvalidPathFormat() }, { "mount:/c:\\aa\\..\\bb", "MW", "mount:c:/bb", ResultSuccess() }, { "mount:/aa/bb", "MW", "mount:/aa/bb", ResultSuccess() }, { "/mount:/aa/bb", "MW", "/", fs::ResultInvalidCharacter() }, { "/mount:/aa/bb", "W", "/", fs::ResultInvalidCharacter() }, { "a:aa/../bb", "MW", "a:aa/bb", ResultSuccess() }, { "a:aa\\..\\bb", "MW", "a:aa/bb", ResultSuccess() }, { "/a:aa\\..\\bb", "W", "/", fs::ResultInvalidCharacter() }, { "\\\\?\\c:\\.\\aa", "W", "\\\\?\\c:/aa", ResultSuccess() }, { "\\\\.\\c:\\.\\aa", "W", "\\\\.\\c:/aa", ResultSuccess() }, { "\\\\.\\mount:\\.\\aa", "W", "\\\\./", fs::ResultInvalidCharacter() }, { "\\\\./.\\aa", "W", "\\\\./aa", ResultSuccess() }, { "\\\\/aa", "W", "", fs::ResultInvalidPathFormat() }, { "\\\\\\aa", "W", "", fs::ResultInvalidPathFormat() }, { "\\\\", "W", "/", ResultSuccess() }, { "\\\\host\\share", "W", "\\\\host\\share/", ResultSuccess() }, { "\\\\host\\share\\path", "W", "\\\\host\\share/path", ResultSuccess() }, { "\\\\host\\share\\path\\aa\\bb\\..\\cc\\.", "W", "\\\\host\\share/path/aa/cc", ResultSuccess() }, { "\\\\host\\", "W", "", fs::ResultInvalidPathFormat() }, { "\\\\ho$st\\share\\path", "W", "", fs::ResultInvalidCharacter() }, { "\\\\host:\\share\\path", "W", "", fs::ResultInvalidCharacter() }, { "\\\\..\\share\\path", "W", "", fs::ResultInvalidPathFormat() }, { "\\\\host\\s:hare\\path", "W", "", fs::ResultInvalidCharacter() }, { "\\\\host\\.\\path", "W", "", fs::ResultInvalidPathFormat() }, { "\\\\host\\..\\path", "W", "", fs::ResultInvalidPathFormat() }, { "\\\\host\\sha:re", "W", "", fs::ResultInvalidCharacter() }, { ".\\\\host\\share", "RW", "..\\\\host\\share/", ResultSuccess() } }; return DoNormalizeTests(Tests); } static_assert(TestNormalizeWindowsPath()); consteval bool TestNormalizeRelativePath() { constexpr NormalizeTestData Tests[] = { { "./aa/bb", "", "", fs::ResultInvalidPathFormat() }, { "./aa/bb/../cc", "R", "./aa/cc", ResultSuccess() }, { ".\\aa/bb/../cc", "R", "..", fs::ResultInvalidCharacter() }, { ".", "R", ".", ResultSuccess() }, { "../aa/bb", "R", "", fs::ResultDirectoryUnobtainable() }, { "/aa/./bb", "R", "/aa/bb", ResultSuccess() }, { "mount:./aa/bb", "MR", "mount:./aa/bb", ResultSuccess() }, { "mount:./aa/./bb", "MR", "mount:./aa/bb", ResultSuccess() }, { "mount:./aa/bb", "M", "mount:", fs::ResultInvalidPathFormat() } }; return DoNormalizeTests(Tests); } static_assert(TestNormalizeRelativePath()); consteval bool TestNormalizeBackslash() { constexpr NormalizeTestData Tests[] = { { "\\aa\\bb\\..\\cc", "", "", fs::ResultInvalidPathFormat() }, { "\\aa\\bb\\..\\cc", "B", "", fs::ResultInvalidPathFormat() }, { "/aa\\bb\\..\\cc", "", "", fs::ResultInvalidCharacter() }, { "/aa\\bb\\..\\cc", "B", "/cc", ResultSuccess() }, { "/aa\\bb\\cc", "", "", fs::ResultInvalidCharacter() }, { "/aa\\bb\\cc", "B", "/aa\\bb\\cc", ResultSuccess() }, { "\\\\host\\share\\path\\aa\\bb\\cc", "W", "\\\\host\\share/path/aa/bb/cc", ResultSuccess() }, { "\\\\host\\share\\path\\aa\\bb\\cc", "WB", "\\\\host\\share/path/aa/bb/cc", ResultSuccess() }, { "/aa/bb\\../cc/..\\dd\\..\\ee/..", "", "", fs::ResultInvalidCharacter() }, { "/aa/bb\\../cc/..\\dd\\..\\ee/..", "B", "/aa", ResultSuccess() } }; return DoNormalizeTests(Tests); } static_assert(TestNormalizeBackslash()); consteval bool TestNormalizeAllowAllChars() { constexpr NormalizeTestData Tests[] = { { "/aa/b:b/cc", "", "/aa/", fs::ResultInvalidCharacter() }, { "/aa/b*b/cc", "", "/aa/", fs::ResultInvalidCharacter() }, { "/aa/b?b/cc", "", "/aa/", fs::ResultInvalidCharacter() }, { "/aa/b<b/cc", "", "/aa/", fs::ResultInvalidCharacter() }, { "/aa/b>b/cc", "", "/aa/", fs::ResultInvalidCharacter() }, { "/aa/b|b/cc", "", "/aa/", fs::ResultInvalidCharacter() }, { "/aa/b:b/cc", "C", "/aa/b:b/cc", ResultSuccess() }, { "/aa/b*b/cc", "C", "/aa/b*b/cc", ResultSuccess() }, { "/aa/b?b/cc", "C", "/aa/b?b/cc", ResultSuccess() }, { "/aa/b<b/cc", "C", "/aa/b<b/cc", ResultSuccess() }, { "/aa/b>b/cc", "C", "/aa/b>b/cc", ResultSuccess() }, { "/aa/b|b/cc", "C", "/aa/b|b/cc", ResultSuccess() }, { "/aa/b'b/cc", "", "/aa/b'b/cc", ResultSuccess() }, { "/aa/b\"b/cc", "", "/aa/b\"b/cc", ResultSuccess() }, { "/aa/b(b/cc", "", "/aa/b(b/cc", ResultSuccess() }, { "/aa/b)b/cc", "", "/aa/b)b/cc", ResultSuccess() }, { "/aa/b'b/cc", "C", "/aa/b'b/cc", ResultSuccess() }, { "/aa/b\"b/cc", "C", "/aa/b\"b/cc", ResultSuccess() }, { "/aa/b(b/cc", "C", "/aa/b(b/cc", ResultSuccess() }, { "/aa/b)b/cc", "C", "/aa/b)b/cc", ResultSuccess() }, { "mount:/aa/b<b/cc", "MC", "mount:/aa/b<b/cc", ResultSuccess() }, { "mo>unt:/aa/bb/cc", "MC", "", fs::ResultInvalidCharacter() } }; return DoNormalizeTests(Tests); } static_assert(TestNormalizeAllowAllChars()); consteval bool TestNormalizeAll() { constexpr NormalizeTestData Tests[] = { { "mount:./aa/bb", "WRM", "mount:./aa/bb", ResultSuccess() }, { "mount:./aa/bb\\cc/dd", "WRM", "mount:./aa/bb/cc/dd", ResultSuccess() }, { "mount:./aa/bb\\cc/dd", "WRMB", "mount:./aa/bb/cc/dd", ResultSuccess() }, { "mount:./.c:/aa/bb", "RM", "mount:./", fs::ResultInvalidCharacter() }, { "mount:.c:/aa/bb", "WRM", "mount:./", fs::ResultInvalidCharacter() }, { "mount:./cc:/aa/bb", "WRM", "mount:./", fs::ResultInvalidCharacter() }, { "mount:./\\\\host\\share/aa/bb", "MW", "mount:", fs::ResultInvalidPathFormat() }, { "mount:./\\\\host\\share/aa/bb", "WRM", "mount:.\\\\host\\share/aa/bb", ResultSuccess() }, { "mount:.\\\\host\\share/aa/bb", "WRM", "mount:..\\\\host\\share/aa/bb", ResultSuccess() }, { "mount:..\\\\host\\share/aa/bb", "WRM", "mount:.", fs::ResultDirectoryUnobtainable() }, { ".\\\\host\\share/aa/bb", "WRM", "..\\\\host\\share/aa/bb", ResultSuccess() }, { "..\\\\host\\share/aa/bb", "WRM", ".", fs::ResultDirectoryUnobtainable() }, { "mount:\\\\host\\share/aa/bb", "MW", "mount:\\\\host\\share/aa/bb", ResultSuccess() }, { "mount:\\aa\\bb", "BM", "mount:", fs::ResultInvalidPathFormat() }, { "mount:/aa\\bb", "BM", "mount:/aa\\bb", ResultSuccess() }, { ".//aa/bb", "RW", "./aa/bb", ResultSuccess() }, { "./aa/bb", "R", "./aa/bb", ResultSuccess() }, { "./c:/aa/bb", "RW", "./", fs::ResultInvalidCharacter() }, { "mount:./aa/b:b\\cc/dd", "WRMBC", "mount:./aa/b:b/cc/dd", ResultSuccess() } }; return DoNormalizeTests(Tests); } static_assert(TestNormalizeAll()); consteval bool TestNormalizeSmallBuffer() { constexpr NormalizeTestData Tests[] = { { "/aa/bb", "M", "", fs::ResultTooLongPath(), 1}, { "mount:/aa/bb", "MR", "", fs::ResultTooLongPath(), 6 }, { "mount:/aa/bb", "MR", "mount:", fs::ResultTooLongPath(), 7 }, { "aa/bb", "MR", "./", fs::ResultTooLongPath(), 3 }, { "\\\\host\\share", "W", "\\\\host\\share", fs::ResultTooLongPath(), 13 } }; return DoNormalizeTests(Tests); } static_assert(TestNormalizeSmallBuffer()); consteval bool TestIsNormalizedImpl(const char *path, const PathFlags &flags, bool expected_normalized, size_t expected_size, Result expected_result) { /* Perform normalization checking. */ bool actual_normalized; size_t actual_size; const Result actual_result = PathFormatter::IsNormalized(std::addressof(actual_normalized), std::addressof(actual_size), path, flags); /* Check that the expected result matches the actual. */ if (actual_result.GetValue() != expected_result.GetValue()) { #if defined(ENABLE_PRINT_FORMAT_TEST_DEBUGGING) PrintResultMismatch(expected_result.GetValue(), actual_result.GetValue()); #endif return false; } /* Check that the expected output matches the actual. */ if (R_SUCCEEDED(expected_result)) { if (expected_normalized != actual_normalized) { #if defined(ENABLE_PRINT_FORMAT_TEST_DEBUGGING) PrintResultMismatchImpl(static_cast<u32>(expected_normalized), static_cast<u32>(actual_normalized)); #endif return false; } if (expected_normalized) { if (expected_size != actual_size) { #if defined(ENABLE_PRINT_FORMAT_TEST_DEBUGGING) PrintResultMismatchImpl(static_cast<u32>(expected_size), static_cast<u32>(actual_size)); #endif return false; } } } return true; } struct IsNormalizedTestData { const char *path; const char *flag_desc; bool normalized; size_t len; Result result; }; template<size_t N, size_t Ix = 0> consteval bool DoIsNormalizedTests(const IsNormalizedTestData (&tests)[N]) { if constexpr (Ix >= N) { return true; } const auto &test = tests[Ix]; if (!TestIsNormalizedImpl(test.path, DecodeFlags(test.flag_desc), test.normalized, test.len, test.result)) { return false; } if constexpr (Ix < N) { return DoIsNormalizedTests<N, Ix + 1>(tests); } else { AMS_ASSUME(false); } } consteval bool TestIsNormalizedEmptyPath() { constexpr IsNormalizedTestData Tests[] = { { "", "", false, 0, fs::ResultInvalidPathFormat() }, { "", "E", true, 0, ResultSuccess() }, { "/aa/bb/../cc", "E", false, 0, ResultSuccess() } }; return DoIsNormalizedTests(Tests); } static_assert(TestIsNormalizedEmptyPath()); consteval bool TestIsNormalizedMountName() { constexpr IsNormalizedTestData Tests[] = { { "mount:/aa/bb", "", false, 0, fs::ResultInvalidPathFormat() }, { "mount:/aa/bb", "W", false, 0, fs::ResultInvalidPathFormat() }, { "mount:/aa/bb", "M", true, 12, ResultSuccess() }, { "mount:/aa/./bb", "M", false, 6, ResultSuccess() }, { "mount:\\aa\\bb", "M", false, 0, fs::ResultInvalidPathFormat() }, { "m:/aa/bb", "M", false, 0, fs::ResultInvalidPathFormat() }, { "mo>unt:/aa/bb", "M", false, 0, fs::ResultInvalidCharacter() }, { "moun?t:/aa/bb", "M", false, 0, fs::ResultInvalidCharacter() }, { "mo&unt:/aa/bb", "M", true, 13, ResultSuccess() }, { "/aa/./bb", "M", false, 0, ResultSuccess() }, { "mount/aa/./bb", "M", false, 0, fs::ResultInvalidPathFormat() } }; return DoIsNormalizedTests(Tests); } static_assert(TestIsNormalizedMountName()); consteval bool TestIsNormalizedWindowsPath() { constexpr IsNormalizedTestData Tests[] = { { "c:/aa/bb", "", false, 0, fs::ResultInvalidPathFormat() }, { "c:\\aa\\bb", "", false, 0, fs::ResultInvalidPathFormat() }, { "\\\\host\\share", "", false, 0, fs::ResultInvalidPathFormat() }, { "\\\\.\\c:\\", "", false, 0, fs::ResultInvalidPathFormat() }, { "\\\\.\\c:/aa/bb/.", "", false, 0, fs::ResultInvalidPathFormat() }, { "\\\\?\\c:\\", "", false, 0, fs::ResultInvalidPathFormat() }, { "mount:\\\\host\\share\\aa\\bb", "M", false, 0, fs::ResultInvalidPathFormat() }, { "mount:\\\\host/share\\aa\\bb", "M", false, 0, fs::ResultInvalidPathFormat() }, { "c:\\aa\\..\\..\\..\\bb", "W", false, 0, ResultSuccess() }, { "mount:/\\\\aa\\..\\bb", "MW", false, 0, ResultSuccess() }, { "mount:/c:\\aa\\..\\bb", "MW", false, 0, ResultSuccess() }, { "mount:/aa/bb", "MW", true, 12, ResultSuccess() }, { "/mount:/aa/bb", "MW", false, 0, fs::ResultInvalidCharacter() }, { "/mount:/aa/bb", "W", false, 0, fs::ResultInvalidCharacter() }, { "a:aa/../bb", "MW", false, 8, ResultSuccess() }, { "a:aa\\..\\bb", "MW", false, 0, ResultSuccess() }, { "/a:aa\\..\\bb", "W", false, 0, ResultSuccess() }, { "\\\\?\\c:\\.\\aa", "W", false, 0, ResultSuccess() }, { "\\\\.\\c:\\.\\aa", "W", false, 0, ResultSuccess() }, { "\\\\.\\mount:\\.\\aa", "W", false, 0, ResultSuccess() }, { "\\\\./.\\aa", "W", false, 0, ResultSuccess() }, { "\\\\/aa", "W", false, 0, fs::ResultInvalidPathFormat() }, { "\\\\\\aa", "W", false, 0, fs::ResultInvalidPathFormat() }, { "\\\\", "W", false, 0, ResultSuccess() }, { "\\\\host\\share", "W", false, 0, ResultSuccess() }, { "\\\\host\\share\\path", "W", false, 0, ResultSuccess() }, { "\\\\host\\share\\path\\aa\\bb\\..\\cc\\.", "W", false, 0, ResultSuccess() }, { "\\\\host\\", "W", false, 0, fs::ResultInvalidPathFormat() }, { "\\\\ho$st\\share\\path", "W", false, 0, fs::ResultInvalidCharacter() }, { "\\\\host:\\share\\path", "W", false, 0, fs::ResultInvalidCharacter() }, { "\\\\..\\share\\path", "W", false, 0, fs::ResultInvalidPathFormat() }, { "\\\\host\\s:hare\\path", "W", false, 0, fs::ResultInvalidCharacter() }, { "\\\\host\\.\\path", "W", false, 0, fs::ResultInvalidPathFormat() }, { "\\\\host\\..\\path", "W", false, 0, fs::ResultInvalidPathFormat() }, { "\\\\host\\sha:re", "W", false, 0, fs::ResultInvalidCharacter() }, { ".\\\\host\\share", "RW", false, 0, ResultSuccess() } }; return DoIsNormalizedTests(Tests); } static_assert(TestIsNormalizedWindowsPath()); consteval bool TestIsNormalizedRelativePath() { constexpr IsNormalizedTestData Tests[] = { { "./aa/bb", "", false, 0, fs::ResultInvalidPathFormat() }, { "./aa/bb/../cc", "R", false, 1, ResultSuccess() }, { ".\\aa/bb/../cc", "R", false, 0, ResultSuccess() }, { ".", "R", true, 1, ResultSuccess() }, { "../aa/bb", "R", false, 0, fs::ResultDirectoryUnobtainable() }, { "/aa/./bb", "R", false, 0, ResultSuccess() }, { "mount:./aa/bb", "MR", true, 13, ResultSuccess() }, { "mount:./aa/./bb", "MR", false, 7, ResultSuccess() }, { "mount:./aa/bb", "M", false, 0, fs::ResultInvalidPathFormat() } }; return DoIsNormalizedTests(Tests); } static_assert(TestIsNormalizedRelativePath()); consteval bool TestIsNormalizedBackslash() { constexpr IsNormalizedTestData Tests[] = { { "\\aa\\bb\\..\\cc", "", false, 0, fs::ResultInvalidPathFormat() }, { "\\aa\\bb\\..\\cc", "B", false, 0, fs::ResultInvalidPathFormat() }, { "/aa\\bb\\..\\cc", "", false, 0, fs::ResultInvalidCharacter() }, { "/aa\\bb\\..\\cc", "B", false, 0, ResultSuccess() }, { "/aa\\bb\\cc", "", false, 0, fs::ResultInvalidCharacter() }, { "/aa\\bb\\cc", "B", true, 9, ResultSuccess() }, { "\\\\host\\share\\path\\aa\\bb\\cc", "W", false, 0, ResultSuccess() }, { "\\\\host\\share\\path\\aa\\bb\\cc", "WB", false, 0, ResultSuccess() }, { "/aa/bb\\../cc/..\\dd\\..\\ee/..", "", false, 0, fs::ResultInvalidCharacter() }, { "/aa/bb\\../cc/..\\dd\\..\\ee/..", "B", false, 0, ResultSuccess() } }; return DoIsNormalizedTests(Tests); } static_assert(TestIsNormalizedBackslash()); consteval bool TestIsNormalizedAllowAllCharacters() { constexpr IsNormalizedTestData Tests[] = { { "/aa/b:b/cc", "", false, 0, fs::ResultInvalidCharacter() }, { "/aa/b*b/cc", "", false, 0, fs::ResultInvalidCharacter() }, { "/aa/b?b/cc", "", false, 0, fs::ResultInvalidCharacter() }, { "/aa/b<b/cc", "", false, 0, fs::ResultInvalidCharacter() }, { "/aa/b>b/cc", "", false, 0, fs::ResultInvalidCharacter() }, { "/aa/b|b/cc", "", false, 0, fs::ResultInvalidCharacter() }, { "/aa/b:b/cc", "C", true, 10, ResultSuccess() }, { "/aa/b*b/cc", "C", true, 10, ResultSuccess() }, { "/aa/b?b/cc", "C", true, 10, ResultSuccess() }, { "/aa/b<b/cc", "C", true, 10, ResultSuccess() }, { "/aa/b>b/cc", "C", true, 10, ResultSuccess() }, { "/aa/b|b/cc", "C", true, 10, ResultSuccess() }, { "/aa/b'b/cc", "", true, 10, ResultSuccess() }, { "/aa/b\"b/cc", "", true, 10, ResultSuccess() }, { "/aa/b(b/cc", "", true, 10, ResultSuccess() }, { "/aa/b)b/cc", "", true, 10, ResultSuccess() }, { "/aa/b'b/cc", "C", true, 10, ResultSuccess() }, { "/aa/b\"b/cc", "C", true, 10, ResultSuccess() }, { "/aa/b(b/cc", "C", true, 10, ResultSuccess() }, { "/aa/b)b/cc", "C", true, 10, ResultSuccess() }, { "mount:/aa/b<b/cc", "MC", true, 16, ResultSuccess() }, { "mo>unt:/aa/bb/cc", "MC", false, 0, fs::ResultInvalidCharacter() } }; return DoIsNormalizedTests(Tests); } static_assert(TestIsNormalizedAllowAllCharacters()); consteval bool TestIsNormalizedAll() { constexpr IsNormalizedTestData Tests[] = { { "mount:./aa/bb", "WRM", true, 13, ResultSuccess() }, { "mount:./aa/bb\\cc/dd", "WRM", false, 0, ResultSuccess() }, { "mount:./aa/bb\\cc/dd", "WRMB", true, 19, ResultSuccess() }, { "mount:./.c:/aa/bb", "RM", false, 0, fs::ResultInvalidCharacter() }, { "mount:.c:/aa/bb", "WRM", false, 0, ResultSuccess() }, { "mount:./cc:/aa/bb", "WRM", false, 0, fs::ResultInvalidCharacter() }, { "mount:./\\\\host\\share/aa/bb", "MW", false, 0, fs::ResultInvalidPathFormat() }, { "mount:./\\\\host\\share/aa/bb", "WRM", false, 0, ResultSuccess() }, { "mount:.\\\\host\\share/aa/bb", "WRM", false, 0, ResultSuccess() }, { "mount:..\\\\host\\share/aa/bb", "WRM", false, 0, ResultSuccess() }, { ".\\\\host\\share/aa/bb", "WRM", false, 0, ResultSuccess() }, { "..\\\\host\\share/aa/bb", "WRM", false, 0, ResultSuccess() }, { "mount:\\\\host\\share/aa/bb", "MW", true, 24, ResultSuccess() }, { "mount:\\aa\\bb", "BM", false, 0, fs::ResultInvalidPathFormat() }, { "mount:/aa\\bb", "BM", true, 12, ResultSuccess() }, { ".//aa/bb", "RW", false, 1, ResultSuccess() }, { "./aa/bb", "R", true, 7, ResultSuccess() }, { "./c:/aa/bb", "RW", false, 0, fs::ResultInvalidCharacter() }, { "mount:./aa/b:b\\cc/dd", "WRMBC", true, 20, ResultSuccess() } }; return DoIsNormalizedTests(Tests); } static_assert(TestIsNormalizedAll()); } }
30,811
C++
.cpp
549
41.169399
159
0.47075
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,672
fs_path_utility_tests.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/tests/fs_path_utility_tests.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> namespace ams::fs { namespace { struct IsSubPathTestData { const char *lhs; const char *rhs; bool is_sub_path; }; template<size_t N, size_t Ix = 0> consteval bool DoIsSubPathTests(const IsSubPathTestData (&tests)[N]) { if constexpr (Ix >= N) { return true; } const auto &test = tests[Ix]; if (::ams::fs::IsSubPath(test.lhs, test.rhs) != test.is_sub_path) { return false; } if constexpr (Ix < N) { return DoIsSubPathTests<N, Ix + 1>(tests); } else { AMS_ASSUME(false); } } consteval bool TestIsSubPath() { constexpr IsSubPathTestData Tests[] = { { "//a/b", "/a", false }, { "/a", "//a/b", false }, { "//a/b", "\\\\a", false }, { "//a/b", "//a", true }, { "/", "/a", true }, { "/a", "/", true }, { "/", "/", false }, { "", "", false }, { "/", "", true }, { "/", "mount:/a", false }, { "mount:/", "mount:/", false }, { "mount:/a/b", "mount:/a/b", false }, { "mount:/a/b", "mount:/a/b/c", true }, { "/a/b", "/a/b/c", true }, { "/a/b/c", "/a/b", true }, { "/a/b", "/a/b", false }, { "/a/b", "/a/b\\c", false } }; return DoIsSubPathTests(Tests); } static_assert(TestIsSubPath()); } }
2,327
C++
.cpp
63
26.412698
79
0.478705
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,673
fs_dbm_rom_path_tool.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/common/fs_dbm_rom_path_tool.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> namespace ams::fs::RomPathTool { Result PathParser::Initialize(const RomPathChar *path) { AMS_ASSERT(path != nullptr); /* Require paths start with a separator, and skip repeated separators. */ R_UNLESS(RomPathTool::IsSeparator(path[0]), fs::ResultDbmInvalidPathFormat()); while (RomPathTool::IsSeparator(path[1])) { ++path; } m_prev_path_start = path; m_prev_path_end = path; m_next_path = path + 1; R_SUCCEED(); } void PathParser::Finalize() { m_prev_path_start = nullptr; m_prev_path_end = nullptr; m_next_path = nullptr; m_finished = false; } bool PathParser::IsParseFinished() const { return m_finished; } bool PathParser::IsDirectoryPath() const { AMS_ASSERT(m_next_path != nullptr); if (RomPathTool::IsNullTerminator(m_next_path[0]) && RomPathTool::IsSeparator(m_next_path[-1])) { return true; } if (RomPathTool::IsCurrentDirectory(m_next_path)) { return true; } return RomPathTool::IsParentDirectory(m_next_path); } Result PathParser::GetNextDirectoryName(RomEntryName *out) { AMS_ASSERT(m_prev_path_start != nullptr); AMS_ASSERT(m_prev_path_end != nullptr); AMS_ASSERT(m_next_path != nullptr); AMS_ASSERT(out != nullptr); /* Get as directory name. */ R_TRY(this->GetAsDirectoryName(out)); /* Parse the next path. */ const RomPathChar *cur = m_next_path; size_t name_len; for (name_len = 0; !RomPathTool::IsSeparator(cur[name_len]); ++name_len) { if (RomPathTool::IsNullTerminator(cur[name_len])) { m_finished = true; m_prev_path_start = m_next_path; m_next_path = cur + name_len; m_prev_path_end = cur + name_len; R_SUCCEED(); } } /* Advance past separators. */ m_prev_path_start = m_next_path; m_prev_path_end = cur + name_len; for (m_next_path = m_prev_path_end + 1; RomPathTool::IsSeparator(m_next_path[0]); ++m_next_path) { /* ... */ } /* Check if we're finished. */ if (RomPathTool::IsNullTerminator(m_next_path[0])) { m_finished = true; } R_SUCCEED(); } Result PathParser::GetAsDirectoryName(RomEntryName *out) const { AMS_ASSERT(out != nullptr); AMS_ASSERT(m_prev_path_start != nullptr); AMS_ASSERT(m_prev_path_end != nullptr); AMS_ASSERT(m_next_path != nullptr); AMS_ASSERT(m_prev_path_start <= m_prev_path_end); const size_t len = m_prev_path_end - m_prev_path_start; R_UNLESS(len <= MaxPathLength, fs::ResultDbmDirectoryNameTooLong()); out->Initialize(m_prev_path_start, len); R_SUCCEED(); } Result PathParser::GetAsFileName(RomEntryName *out) const { AMS_ASSERT(out != nullptr); AMS_ASSERT(m_prev_path_start != nullptr); AMS_ASSERT(m_prev_path_end != nullptr); AMS_ASSERT(m_next_path != nullptr); AMS_ASSERT(m_prev_path_start <= m_prev_path_end); const size_t len = m_prev_path_end - m_prev_path_start; R_UNLESS(len <= MaxPathLength, fs::ResultDbmFileNameTooLong()); out->Initialize(m_prev_path_start, len); R_SUCCEED(); } Result GetParentDirectoryName(RomEntryName *out, const RomEntryName &cur, const RomPathChar *p) { AMS_ASSERT(out != nullptr); AMS_ASSERT(p != nullptr); const RomPathChar *start = cur.begin(); const RomPathChar *end = cur.end() - 1; s32 depth = 1; if (cur.IsParentDirectory()) { ++depth; } if (start > p) { size_t len = 0; for (const RomPathChar *head = start - 1; head >= p; --head) { if (RomPathTool::IsSeparator(*head)) { if (IsCurrentDirectory(head + 1, len)) { ++depth; } if (IsParentDirectory(head + 1, len)) { depth += 2; } if (depth == 0) { start = head + 1; break; } do { --head; } while (head > p && RomPathTool::IsSeparator(*head)); end = head; len = 0; --depth; } ++len; } R_UNLESS(depth == 0, fs::ResultDirectoryUnobtainable()); } if (end <= p) { out->Initialize(p, 0); } else { out->Initialize(start, end - start + 1); } R_SUCCEED(); } }
5,628
C++
.cpp
143
29.125874
106
0.547641
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,674
fs_file_storage.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/common/fs_file_storage.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> namespace ams::fs { Result FileStorage::UpdateSize() { R_SUCCEED_IF(m_size != InvalidSize); R_RETURN(m_base_file->GetSize(std::addressof(m_size))); } Result FileStorage::Read(s64 offset, void *buffer, size_t size) { /* Immediately succeed if there's nothing to read. */ R_SUCCEED_IF(size == 0); /* Validate buffer. */ R_UNLESS(buffer != nullptr, fs::ResultNullptrArgument()); /* Ensure our size is valid. */ R_TRY(this->UpdateSize()); /* Ensure our access is valid. */ R_TRY(IStorage::CheckAccessRange(offset, size, m_size)); size_t read_size; R_RETURN(m_base_file->Read(std::addressof(read_size), offset, buffer, size)); } Result FileStorage::Write(s64 offset, const void *buffer, size_t size) { /* Immediately succeed if there's nothing to write. */ R_SUCCEED_IF(size == 0); /* Validate buffer. */ R_UNLESS(buffer != nullptr, fs::ResultNullptrArgument()); /* Ensure our size is valid. */ R_TRY(this->UpdateSize()); /* Ensure our access is valid. */ R_TRY(IStorage::CheckAccessRange(offset, size, m_size)); R_RETURN(m_base_file->Write(offset, buffer, size, fs::WriteOption())); } Result FileStorage::Flush() { R_RETURN(m_base_file->Flush()); } Result FileStorage::GetSize(s64 *out_size) { R_TRY(this->UpdateSize()); *out_size = m_size; R_SUCCEED(); } Result FileStorage::SetSize(s64 size) { m_size = InvalidSize; R_RETURN(m_base_file->SetSize(size)); } Result FileStorage::OperateRange(void *dst, size_t dst_size, OperationId op_id, s64 offset, s64 size, const void *src, size_t src_size) { switch (op_id) { case OperationId::Invalidate: R_RETURN(m_base_file->OperateRange(OperationId::Invalidate, offset, size)); case OperationId::QueryRange: if (size == 0) { R_UNLESS(dst != nullptr, fs::ResultNullptrArgument()); R_UNLESS(dst_size == sizeof(QueryRangeInfo), fs::ResultInvalidSize()); reinterpret_cast<QueryRangeInfo *>(dst)->Clear(); R_SUCCEED(); } R_TRY(this->UpdateSize()); R_TRY(IStorage::CheckOffsetAndSize(offset, size)); R_RETURN(m_base_file->OperateRange(dst, dst_size, op_id, offset, size, src, src_size)); default: R_THROW(fs::ResultUnsupportedOperateRangeForFileStorage()); } } Result FileStorageBasedFileSystem::Initialize(std::shared_ptr<fs::fsa::IFileSystem> base_file_system, const fs::Path &path, fs::OpenMode mode) { /* Open the file. */ std::unique_ptr<fs::fsa::IFile> base_file; R_TRY(base_file_system->OpenFile(std::addressof(base_file), path, mode)); /* Set the file. */ this->SetFile(std::move(base_file)); m_base_file_system = std::move(base_file_system); R_SUCCEED(); } Result FileHandleStorage::UpdateSize() { R_SUCCEED_IF(m_size != InvalidSize); R_RETURN(GetFileSize(std::addressof(m_size), m_handle)); } Result FileHandleStorage::Read(s64 offset, void *buffer, size_t size) { /* Lock the mutex. */ std::scoped_lock lk(m_mutex); /* Immediately succeed if there's nothing to read. */ R_SUCCEED_IF(size == 0); /* Validate buffer. */ R_UNLESS(buffer != nullptr, fs::ResultNullptrArgument()); /* Ensure our size is valid. */ R_TRY(this->UpdateSize()); /* Ensure our access is valid. */ R_TRY(IStorage::CheckAccessRange(offset, size, m_size)); R_RETURN(ReadFile(m_handle, offset, buffer, size, fs::ReadOption())); } Result FileHandleStorage::Write(s64 offset, const void *buffer, size_t size) { /* Lock the mutex. */ std::scoped_lock lk(m_mutex); /* Immediately succeed if there's nothing to write. */ R_SUCCEED_IF(size == 0); /* Validate buffer. */ R_UNLESS(buffer != nullptr, fs::ResultNullptrArgument()); /* Ensure our size is valid. */ R_TRY(this->UpdateSize()); /* Ensure our access is valid. */ R_TRY(IStorage::CheckAccessRange(offset, size, m_size)); R_RETURN(WriteFile(m_handle, offset, buffer, size, fs::WriteOption())); } Result FileHandleStorage::Flush() { R_RETURN(FlushFile(m_handle)); } Result FileHandleStorage::GetSize(s64 *out_size) { R_TRY(this->UpdateSize()); *out_size = m_size; R_SUCCEED(); } Result FileHandleStorage::SetSize(s64 size) { m_size = InvalidSize; R_RETURN(SetFileSize(m_handle, size)); } Result FileHandleStorage::OperateRange(void *dst, size_t dst_size, OperationId op_id, s64 offset, s64 size, const void *src, size_t src_size) { AMS_UNUSED(src, src_size); switch (op_id) { case OperationId::QueryRange: /* Validate buffer and size. */ R_UNLESS(dst != nullptr, fs::ResultNullptrArgument()); R_UNLESS(dst_size == sizeof(QueryRangeInfo), fs::ResultInvalidSize()); R_RETURN(QueryRange(static_cast<QueryRangeInfo *>(dst), m_handle, offset, size)); default: R_THROW(fs::ResultUnsupportedOperateRangeForFileHandleStorage()); } } }
6,234
C++
.cpp
138
36.5
148
0.6109
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,675
fs_dbm_hierarchical_rom_file_table.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/common/fs_dbm_hierarchical_rom_file_table.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> namespace ams::fs { s64 HierarchicalRomFileTable::QueryDirectoryEntryBucketStorageSize(StorageSizeType count) { return DirectoryEntryMapTable::QueryBucketStorageSize(count); } s64 HierarchicalRomFileTable::QueryDirectoryEntrySize(StorageSizeType aux_size) { return DirectoryEntryMapTable::QueryEntrySize(aux_size); } s64 HierarchicalRomFileTable::QueryFileEntryBucketStorageSize(StorageSizeType count) { return FileEntryMapTable::QueryBucketStorageSize(count); } s64 HierarchicalRomFileTable::QueryFileEntrySize(StorageSizeType aux_size) { return FileEntryMapTable::QueryEntrySize(aux_size); } Result HierarchicalRomFileTable::Format(SubStorage dir_bucket, SubStorage file_bucket) { s64 dir_bucket_size; R_TRY(dir_bucket.GetSize(std::addressof(dir_bucket_size))); R_TRY(DirectoryEntryMapTable::Format(dir_bucket, DirectoryEntryMapTable::QueryBucketCount(dir_bucket_size))); s64 file_bucket_size; R_TRY(file_bucket.GetSize(std::addressof(file_bucket_size))); R_TRY(FileEntryMapTable::Format(file_bucket, FileEntryMapTable::QueryBucketCount(file_bucket_size))); R_SUCCEED(); } HierarchicalRomFileTable::HierarchicalRomFileTable() { /* ... */ } Result HierarchicalRomFileTable::Initialize(SubStorage dir_bucket, SubStorage dir_entry, SubStorage file_bucket, SubStorage file_entry) { s64 dir_bucket_size; R_TRY(dir_bucket.GetSize(std::addressof(dir_bucket_size))); R_TRY(m_dir_table.Initialize(dir_bucket, DirectoryEntryMapTable::QueryBucketCount(dir_bucket_size), dir_entry)); s64 file_bucket_size; R_TRY(file_bucket.GetSize(std::addressof(file_bucket_size))); R_TRY(m_file_table.Initialize(file_bucket, FileEntryMapTable::QueryBucketCount(file_bucket_size), file_entry)); R_SUCCEED(); } void HierarchicalRomFileTable::Finalize() { m_dir_table.Finalize(); m_file_table.Finalize(); } Result HierarchicalRomFileTable::CreateRootDirectory() { Position root_pos = RootPosition; EntryKey root_key = {}; root_key.key.parent = root_pos; RomDirectoryEntry root_entry = { .next = InvalidPosition, .dir = InvalidPosition, .file = InvalidPosition, }; R_RETURN(m_dir_table.Add(std::addressof(root_pos), root_key, root_entry)); } Result HierarchicalRomFileTable::CreateDirectory(RomDirectoryId *out, const RomPathChar *path) { AMS_ASSERT(out != nullptr); AMS_ASSERT(path != nullptr); RomDirectoryEntry parent_entry = {}; EntryKey new_key = {}; R_TRY(this->FindDirectoryRecursive(std::addressof(new_key), std::addressof(parent_entry), path)); R_TRY(this->CheckSameEntryExists(new_key, fs::ResultDbmAlreadyExists())); RomDirectoryEntry new_entry = { .next = InvalidPosition, .dir = InvalidPosition, .file = InvalidPosition, }; Position new_pos = 0; R_TRY_CATCH(m_dir_table.Add(std::addressof(new_pos), new_key, new_entry)) { R_CONVERT(fs::ResultDbmKeyFull, fs::ResultDbmDirectoryEntryFull()) } R_END_TRY_CATCH; *out = PositionToDirectoryId(new_pos); if (parent_entry.dir == InvalidPosition) { parent_entry.dir = new_pos; R_TRY(m_dir_table.SetByPosition(new_key.key.parent, parent_entry)); } else { Position cur_pos = parent_entry.dir; while (true) { RomEntryKey cur_key = {}; RomDirectoryEntry cur_entry = {}; R_TRY(m_dir_table.GetByPosition(std::addressof(cur_key), std::addressof(cur_entry), cur_pos)); if (cur_entry.next == InvalidPosition) { cur_entry.next = new_pos; R_TRY(m_dir_table.SetByPosition(cur_pos, cur_entry)); break; } cur_pos = cur_entry.next; } } R_SUCCEED(); } Result HierarchicalRomFileTable::CreateFile(RomFileId *out, const RomPathChar *path, const FileInfo &info) { AMS_ASSERT(out != nullptr); AMS_ASSERT(path != nullptr); RomDirectoryEntry parent_entry = {}; EntryKey new_key = {}; R_TRY(this->FindFileRecursive(std::addressof(new_key), std::addressof(parent_entry), path)); R_TRY(this->CheckSameEntryExists(new_key, fs::ResultDbmAlreadyExists())); RomFileEntry new_entry = { .next = InvalidPosition, .info = info, }; Position new_pos = 0; R_TRY_CATCH(m_file_table.Add(std::addressof(new_pos), new_key, new_entry)) { R_CONVERT(fs::ResultDbmKeyFull, fs::ResultDbmFileEntryFull()) } R_END_TRY_CATCH; *out = PositionToFileId(new_pos); if (parent_entry.file == InvalidPosition) { parent_entry.file = new_pos; R_TRY(m_dir_table.SetByPosition(new_key.key.parent, parent_entry)); } else { Position cur_pos = parent_entry.file; while (true) { RomEntryKey cur_key = {}; RomFileEntry cur_entry = {}; R_TRY(m_file_table.GetByPosition(std::addressof(cur_key), std::addressof(cur_entry), cur_pos)); if (cur_entry.next == InvalidPosition) { cur_entry.next = new_pos; R_TRY(m_file_table.SetByPosition(cur_pos, cur_entry)); break; } cur_pos = cur_entry.next; } } R_SUCCEED(); } Result HierarchicalRomFileTable::ConvertPathToDirectoryId(RomDirectoryId *out, const RomPathChar *path) { AMS_ASSERT(out != nullptr); AMS_ASSERT(path != nullptr); RomDirectoryEntry parent_entry = {}; EntryKey key = {}; R_TRY(this->FindDirectoryRecursive(std::addressof(key), std::addressof(parent_entry), path)); Position pos = 0; RomDirectoryEntry entry = {}; R_TRY(this->GetDirectoryEntry(std::addressof(pos), std::addressof(entry), key)); *out = PositionToDirectoryId(pos); R_SUCCEED(); } Result HierarchicalRomFileTable::ConvertPathToFileId(RomFileId *out, const RomPathChar *path) { AMS_ASSERT(out != nullptr); AMS_ASSERT(path != nullptr); RomDirectoryEntry parent_entry = {}; EntryKey key = {}; R_TRY(this->FindDirectoryRecursive(std::addressof(key), std::addressof(parent_entry), path)); Position pos = 0; RomFileEntry entry = {}; R_TRY(this->GetFileEntry(std::addressof(pos), std::addressof(entry), key)); *out = PositionToFileId(pos); R_SUCCEED(); } Result HierarchicalRomFileTable::OpenFile(FileInfo *out, const RomPathChar *path) { AMS_ASSERT(out != nullptr); AMS_ASSERT(path != nullptr); RomDirectoryEntry parent_entry = {}; EntryKey key = {}; R_TRY(this->FindFileRecursive(std::addressof(key), std::addressof(parent_entry), path)); R_RETURN(this->OpenFile(out, key)); } Result HierarchicalRomFileTable::OpenFile(FileInfo *out, RomFileId id) { AMS_ASSERT(out != nullptr); RomFileEntry entry = {}; R_TRY(this->GetFileEntry(std::addressof(entry), id)); *out = entry.info; R_SUCCEED(); } Result HierarchicalRomFileTable::FindOpen(FindPosition *out, const RomPathChar *path) { AMS_ASSERT(out != nullptr); AMS_ASSERT(path != nullptr); RomDirectoryEntry parent_entry = {}; EntryKey key = {}; R_TRY(this->FindDirectoryRecursive(std::addressof(key), std::addressof(parent_entry), path)); R_RETURN(this->FindOpen(out, key)); } Result HierarchicalRomFileTable::FindOpen(FindPosition *out, RomDirectoryId id) { AMS_ASSERT(out != nullptr); out->next_dir = InvalidPosition; out->next_file = InvalidPosition; RomDirectoryEntry entry = {}; R_TRY(this->GetDirectoryEntry(std::addressof(entry), id)); out->next_dir = entry.dir; out->next_file = entry.file; R_SUCCEED(); } Result HierarchicalRomFileTable::FindNextDirectory(RomPathChar *out, FindPosition *find, size_t length) { AMS_ASSERT(out != nullptr); AMS_ASSERT(find != nullptr); AMS_ASSERT(length > RomPathTool::MaxPathLength); AMS_UNUSED(length); R_UNLESS(find->next_dir != InvalidPosition, fs::ResultDbmFindFinished()); RomEntryKey key = {}; RomDirectoryEntry entry = {}; size_t aux_size = 0; R_TRY(m_dir_table.GetByPosition(std::addressof(key), std::addressof(entry), out, std::addressof(aux_size), find->next_dir)); AMS_ASSERT(aux_size / sizeof(RomPathChar) <= RomPathTool::MaxPathLength); out[aux_size / sizeof(RomPathChar)] = RomStringTraits::NullTerminator; find->next_dir = entry.next; R_SUCCEED(); } Result HierarchicalRomFileTable::FindNextFile(RomPathChar *out, FindPosition *find, size_t length) { AMS_ASSERT(out != nullptr); AMS_ASSERT(find != nullptr); AMS_ASSERT(length > RomPathTool::MaxPathLength); AMS_UNUSED(length); R_UNLESS(find->next_file != InvalidPosition, fs::ResultDbmFindFinished()); RomEntryKey key = {}; RomFileEntry entry = {}; size_t aux_size = 0; R_TRY(m_file_table.GetByPosition(std::addressof(key), std::addressof(entry), out, std::addressof(aux_size), find->next_file)); AMS_ASSERT(aux_size / sizeof(RomPathChar) <= RomPathTool::MaxPathLength); out[aux_size / sizeof(RomPathChar)] = RomStringTraits::NullTerminator; find->next_file = entry.next; R_SUCCEED(); } Result HierarchicalRomFileTable::QueryRomFileSystemSize(s64 *out_dir_entry_size, s64 *out_file_entry_size) { AMS_ASSERT(out_dir_entry_size != nullptr); AMS_ASSERT(out_file_entry_size != nullptr); *out_dir_entry_size = m_dir_table.GetTotalEntrySize(); *out_file_entry_size = m_file_table.GetTotalEntrySize(); R_SUCCEED(); } Result HierarchicalRomFileTable::GetParent(Position *out_pos, EntryKey *out_dir_key, RomDirectoryEntry *out_dir_entry, Position pos, RomPathTool::RomEntryName name, const RomPathChar *path) { AMS_ASSERT(out_pos != nullptr); AMS_ASSERT(out_dir_key != nullptr); AMS_ASSERT(out_dir_entry != nullptr); AMS_ASSERT(path != nullptr); RomEntryKey p_key = {}; RomDirectoryEntry p_entry = {}; R_TRY(m_dir_table.GetByPosition(std::addressof(p_key), std::addressof(p_entry), pos)); out_dir_key->key = p_key; R_TRY(RomPathTool::GetParentDirectoryName(std::addressof(out_dir_key->name), name, path)); R_TRY(this->GetDirectoryEntry(out_pos, out_dir_entry, *out_dir_key)); R_SUCCEED(); } Result HierarchicalRomFileTable::FindParentDirectoryRecursive(Position *out_pos, EntryKey *out_dir_key, RomDirectoryEntry *out_dir_entry, RomPathTool::PathParser *parser, const RomPathChar *path) { AMS_ASSERT(out_pos != nullptr); AMS_ASSERT(out_dir_key != nullptr); AMS_ASSERT(out_dir_entry != nullptr); AMS_ASSERT(parser != nullptr); AMS_ASSERT(path != nullptr); Position dir_pos = RootPosition; EntryKey dir_key = {}; RomDirectoryEntry dir_entry = {}; dir_key.key.parent = RootPosition; R_TRY(parser->GetNextDirectoryName(std::addressof(dir_key.name))); R_TRY(this->GetDirectoryEntry(std::addressof(dir_pos), std::addressof(dir_entry), dir_key)); Position parent_pos = dir_pos; while (!parser->IsParseFinished()) { EntryKey old_key = dir_key; R_TRY(parser->GetNextDirectoryName(std::addressof(dir_key.name))); if (dir_key.name.IsCurrentDirectory()) { dir_key = old_key; continue; } else if (dir_key.name.IsParentDirectory()) { R_UNLESS(parent_pos != RootPosition, fs::ResultDirectoryUnobtainable()); R_TRY(this->GetParent(std::addressof(parent_pos), std::addressof(dir_key), std::addressof(dir_entry), dir_key.key.parent, dir_key.name, path)); } else { dir_key.key.parent = parent_pos; R_TRY_CATCH(this->GetDirectoryEntry(std::addressof(dir_pos), std::addressof(dir_entry), dir_key)) { R_CONVERT(fs::ResultDbmInvalidOperation, fs::ResultDbmNotFound()) } R_END_TRY_CATCH; parent_pos = dir_pos; } } *out_pos = parent_pos; *out_dir_key = dir_key; *out_dir_entry = dir_entry; R_SUCCEED(); } Result HierarchicalRomFileTable::FindPathRecursive(EntryKey *out_key, RomDirectoryEntry *out_dir_entry, bool is_dir, const RomPathChar *path) { AMS_ASSERT(out_key != nullptr); AMS_ASSERT(out_dir_entry != nullptr); AMS_ASSERT(path != nullptr); RomPathTool::PathParser parser; R_TRY(parser.Initialize(path)); EntryKey parent_key = {}; Position parent_pos = 0; R_TRY(this->FindParentDirectoryRecursive(std::addressof(parent_pos), std::addressof(parent_key), out_dir_entry, std::addressof(parser), path)); if (is_dir) { RomPathTool::RomEntryName name = {}; R_TRY(parser.GetAsDirectoryName(std::addressof(name))); if (name.IsCurrentDirectory()) { *out_key = parent_key; if (out_key->key.parent != RootPosition) { Position pos = 0; R_TRY(this->GetParent(std::addressof(pos), std::addressof(parent_key), out_dir_entry, out_key->key.parent, out_key->name, path)); } } else if (name.IsParentDirectory()) { R_UNLESS(parent_pos != RootPosition, fs::ResultDirectoryUnobtainable()); Position pos = 0; RomDirectoryEntry cur_entry = {}; R_TRY(this->GetParent(std::addressof(pos), out_key, std::addressof(cur_entry), parent_key.key.parent, parent_key.name, path)); if (out_key->key.parent != RootPosition) { R_TRY(this->GetParent(std::addressof(pos), std::addressof(parent_key), out_dir_entry, out_key->key.parent, out_key->name, path)); } } else { out_key->name = name; out_key->key.parent = out_key->name.IsRootDirectory() ? RootPosition : parent_pos; } } else { { RomPathTool::RomEntryName name = {}; R_TRY(parser.GetAsDirectoryName(std::addressof(name))); R_UNLESS(!name.IsParentDirectory() || parent_pos != RootPosition, fs::ResultDirectoryUnobtainable()); } R_UNLESS(!parser.IsDirectoryPath(), fs::ResultDbmInvalidOperation()); out_key->key.parent = parent_pos; R_TRY(parser.GetAsFileName(std::addressof(out_key->name))); } R_SUCCEED(); } Result HierarchicalRomFileTable::FindDirectoryRecursive(EntryKey *out_key, RomDirectoryEntry *out_dir_entry, const RomPathChar *path) { AMS_ASSERT(out_key != nullptr); AMS_ASSERT(out_dir_entry != nullptr); AMS_ASSERT(path != nullptr); R_RETURN(this->FindPathRecursive(out_key, out_dir_entry, true, path)); } Result HierarchicalRomFileTable::FindFileRecursive(EntryKey *out_key, RomDirectoryEntry *out_dir_entry, const RomPathChar *path) { AMS_ASSERT(out_key != nullptr); AMS_ASSERT(out_dir_entry != nullptr); AMS_ASSERT(path != nullptr); R_RETURN(this->FindPathRecursive(out_key, out_dir_entry, false, path)); } Result HierarchicalRomFileTable::CheckSameEntryExists(const EntryKey &key, Result if_exists) { /* Check dir */ { Position pos = InvalidPosition; RomDirectoryEntry entry = {}; const Result get_res = m_dir_table.Get(std::addressof(pos), std::addressof(entry), key); if (!fs::ResultDbmKeyNotFound::Includes(get_res)) { R_TRY(get_res); R_THROW(if_exists); } } /* Check file */ { Position pos = InvalidPosition; RomFileEntry entry = {}; const Result get_res = m_file_table.Get(std::addressof(pos), std::addressof(entry), key); if (!fs::ResultDbmKeyNotFound::Includes(get_res)) { R_TRY(get_res); R_THROW(if_exists); } } R_SUCCEED(); } Result HierarchicalRomFileTable::GetDirectoryEntry(Position *out_pos, RomDirectoryEntry *out_entry, const EntryKey &key) { AMS_ASSERT(out_pos != nullptr); AMS_ASSERT(out_entry != nullptr); const Result dir_res = m_dir_table.Get(out_pos, out_entry, key); R_UNLESS(R_FAILED(dir_res), dir_res); R_UNLESS(fs::ResultDbmKeyNotFound::Includes(dir_res), dir_res); Position pos = 0; RomFileEntry entry = {}; const Result file_res = m_file_table.Get(std::addressof(pos), std::addressof(entry), key); R_UNLESS(R_FAILED(file_res), fs::ResultDbmInvalidOperation()); R_UNLESS(!fs::ResultDbmKeyNotFound::Includes(file_res), fs::ResultDbmDirectoryNotFound()); R_RETURN(file_res); } Result HierarchicalRomFileTable::GetDirectoryEntry(RomDirectoryEntry *out_entry, RomDirectoryId id) { AMS_ASSERT(out_entry != nullptr); Position pos = DirectoryIdToPosition(id); RomEntryKey key = {}; const Result dir_res = m_dir_table.GetByPosition(std::addressof(key), out_entry, pos); R_UNLESS(R_FAILED(dir_res), dir_res); R_UNLESS(fs::ResultDbmKeyNotFound::Includes(dir_res), dir_res); RomFileEntry entry = {}; const Result file_res = m_file_table.GetByPosition(std::addressof(key), std::addressof(entry), pos); R_UNLESS(R_FAILED(file_res), fs::ResultDbmInvalidOperation()); R_UNLESS(!fs::ResultDbmKeyNotFound::Includes(file_res), fs::ResultDbmDirectoryNotFound()); R_RETURN(file_res); } Result HierarchicalRomFileTable::GetFileEntry(Position *out_pos, RomFileEntry *out_entry, const EntryKey &key) { AMS_ASSERT(out_pos != nullptr); AMS_ASSERT(out_entry != nullptr); const Result file_res = m_file_table.Get(out_pos, out_entry, key); R_UNLESS(R_FAILED(file_res), file_res); R_UNLESS(fs::ResultDbmKeyNotFound::Includes(file_res), file_res); Position pos = 0; RomDirectoryEntry entry = {}; const Result dir_res = m_dir_table.Get(std::addressof(pos), std::addressof(entry), key); R_UNLESS(R_FAILED(dir_res), fs::ResultDbmInvalidOperation()); R_UNLESS(!fs::ResultDbmKeyNotFound::Includes(dir_res), fs::ResultDbmFileNotFound()); R_RETURN(dir_res); } Result HierarchicalRomFileTable::GetFileEntry(RomFileEntry *out_entry, RomFileId id) { AMS_ASSERT(out_entry != nullptr); Position pos = FileIdToPosition(id); RomEntryKey key = {}; const Result file_res = m_file_table.GetByPosition(std::addressof(key), out_entry, pos); R_UNLESS(R_FAILED(file_res), file_res); R_UNLESS(fs::ResultDbmKeyNotFound::Includes(file_res), file_res); RomDirectoryEntry entry = {}; const Result dir_res = m_dir_table.GetByPosition(std::addressof(key), std::addressof(entry), pos); R_UNLESS(R_FAILED(dir_res), fs::ResultDbmInvalidOperation()); R_UNLESS(!fs::ResultDbmKeyNotFound::Includes(dir_res), fs::ResultDbmFileNotFound()); R_RETURN(dir_res); } Result HierarchicalRomFileTable::OpenFile(FileInfo *out, const EntryKey &key) { AMS_ASSERT(out != nullptr); Position pos = 0; RomFileEntry entry = {}; R_TRY(this->GetFileEntry(std::addressof(pos), std::addressof(entry), key)); *out = entry.info; R_SUCCEED(); } Result HierarchicalRomFileTable::FindOpen(FindPosition *out, const EntryKey &key) { AMS_ASSERT(out != nullptr); out->next_dir = InvalidPosition; out->next_file = InvalidPosition; Position pos = 0; RomDirectoryEntry entry = {}; R_TRY(this->GetDirectoryEntry(std::addressof(pos), std::addressof(entry), key)); out->next_dir = entry.dir; out->next_file = entry.file; R_SUCCEED(); } }
21,618
C++
.cpp
425
41.035294
201
0.626246
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,676
fs_mount_utils.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/fsa/fs_mount_utils.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "fs_filesystem_accessor.hpp" #include "fs_mount_utils.hpp" #include "fs_user_mount_table.hpp" namespace ams::fs::impl { namespace { const char *FindMountNameDriveSeparator(const char *path) { for (const char *cur = path; cur < path + MountNameLengthMax + 1 && *cur != StringTraits::NullTerminator; ++cur) { if (*cur == StringTraits::DriveSeparator) { return cur; } } return nullptr; } constexpr bool IsHostRootPath(const char *path) { #if defined(ATMOSPHERE_OS_HORIZON) || defined(ATMOSPHERE_OS_WINDOWS) return fs::IsWindowsDrive(path) || fs::IsUncPath(path); #elif defined(ATMOSPHERE_OS_LINUX) || defined(ATMOSPHERE_OS_MACOS) return fs::IsPathAbsolute(path); #else #error "Unknown OS for host path identification" #endif } Result GetMountNameAndSubPath(MountName *out_mount_name, const char **out_sub_path, const char *path) { /* Handle the Host-path case. */ if (IsHostRootPath(path)) { std::strncpy(out_mount_name->str, HostRootFileSystemMountName, MountNameLengthMax); out_mount_name->str[MountNameLengthMax] = '\x00'; *out_sub_path = path; R_SUCCEED(); } /* Locate the drive separator. */ const char *drive_separator = FindMountNameDriveSeparator(path); R_UNLESS(drive_separator != nullptr, fs::ResultInvalidMountName()); /* Ensure the mount name isn't too long. */ const size_t len = drive_separator - path; R_UNLESS(0 < len, fs::ResultInvalidMountName()); R_UNLESS(len <= MountNameLengthMax, fs::ResultInvalidMountName()); /* Ensure the result sub-path is valid. */ const char *sub_path = drive_separator + 1; const auto starts_with_dir = (sub_path[0] == StringTraits::DirectorySeparator) || (sub_path[0] == StringTraits::AlternateDirectorySeparator); R_UNLESS(starts_with_dir, fs::ResultInvalidPathFormat()); /* Set output. */ std::memcpy(out_mount_name->str, path, len); out_mount_name->str[len] = StringTraits::NullTerminator; *out_sub_path = sub_path; R_SUCCEED(); } } bool IsValidMountName(const char *name) { if (name[0] == StringTraits::NullTerminator) { return false; } if ((('a' <= name[0] && name[0] <= 'z') || ('A' <= name[0] && name[0] <= 'Z')) && name[1] == StringTraits::NullTerminator) { return false; } size_t len = 0; for (const char *cur = name; *cur != StringTraits::NullTerminator; ++cur) { if (*cur == StringTraits::DriveSeparator || *cur == StringTraits::DirectorySeparator) { return false; } if ((++len) > MountNameLengthMax) { return false; } } return util::VerifyUtf8String(name, len); } bool IsReservedMountName(const char *name) { return name[0] == ReservedMountNamePrefixCharacter; } Result CheckMountName(const char *name) { R_TRY(CheckMountNameAllowingReserved(name)); R_UNLESS(!impl::IsReservedMountName(name), fs::ResultInvalidMountName()); R_SUCCEED(); } Result CheckMountNameAllowingReserved(const char *name) { R_UNLESS(name != nullptr, fs::ResultInvalidMountName()); R_UNLESS(impl::IsValidMountName(name), fs::ResultInvalidMountName()); R_SUCCEED(); } Result FindFileSystem(FileSystemAccessor **out_accessor, const char **out_sub_path, const char *path) { R_UNLESS(out_accessor != nullptr, fs::ResultUnexpectedInFindFileSystemA()); R_UNLESS(out_sub_path != nullptr, fs::ResultUnexpectedInFindFileSystemA()); R_UNLESS(path != nullptr, fs::ResultNullptrArgument()); R_UNLESS(strncmp(path, HostRootFileSystemMountName, util::Strnlen(HostRootFileSystemMountName, sizeof(MountName))) != 0, fs::ResultNotMounted()); MountName mount_name; R_TRY(GetMountNameAndSubPath(std::addressof(mount_name), out_sub_path, path)); R_RETURN(impl::Find(out_accessor, mount_name.str)); } Result Unmount(const char *name) { impl::FileSystemAccessor *accessor; R_TRY(impl::Find(std::addressof(accessor), name)); if (accessor->IsFileDataCacheAttachable()) { /* TODO: Data cache purge */ } impl::Unregister(name); R_SUCCEED(); } } namespace ams::fs { Result ConvertToFsCommonPath(char *dst, size_t dst_size, const char *src) { /* Ensure neither argument is nullptr. */ AMS_FS_R_UNLESS(dst != nullptr, fs::ResultNullptrArgument()); AMS_FS_R_UNLESS(src != nullptr, fs::ResultNullptrArgument()); /* Get the mount name and sub path for the path. */ MountName mount_name; const char *sub_path; AMS_FS_R_TRY(impl::GetMountNameAndSubPath(std::addressof(mount_name), std::addressof(sub_path), src)); impl::FileSystemAccessor *accessor; AMS_FS_R_TRY(impl::Find(std::addressof(accessor), mount_name.str)); AMS_FS_R_TRY(accessor->GetCommonMountName(dst, dst_size)); const auto mount_name_len = util::Strnlen(dst, dst_size); const auto common_path_len = util::SNPrintf(dst + mount_name_len, dst_size - mount_name_len, "%s", sub_path); AMS_FS_R_UNLESS(static_cast<size_t>(common_path_len) < dst_size - mount_name_len, fs::ResultTooLongPath()); R_SUCCEED(); } void Unmount(const char *mount_name) { AMS_FS_R_ABORT_UNLESS(AMS_FS_IMPL_ACCESS_LOG_UNMOUNT(impl::Unmount(mount_name), mount_name, AMS_FS_IMPL_ACCESS_LOG_FORMAT_MOUNT, mount_name)); } }
6,622
C++
.cpp
135
39.940741
153
0.628062
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,677
fs_user_filesystem_for_debug.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/fsa/fs_user_filesystem_for_debug.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "fs_filesystem_accessor.hpp" #include "fs_file_accessor.hpp" #include "fs_directory_accessor.hpp" #include "fs_mount_utils.hpp" #include "fs_user_mount_table.hpp" namespace ams::fs { namespace impl { Result GetFileTimeStampRawForDebug(FileTimeStampRaw *out, const char *path) { impl::FileSystemAccessor *accessor; const char *sub_path; R_TRY(impl::FindFileSystem(std::addressof(accessor), std::addressof(sub_path), path)); R_TRY(accessor->GetFileTimeStampRaw(out, sub_path)); R_SUCCEED(); } } Result GetFileTimeStamp(FileTimeStamp *out, const char *path) { fs::FileTimeStampRaw raw; AMS_FS_R_TRY(impl::GetFileTimeStampRawForDebug(std::addressof(raw), path)); static_assert(sizeof(raw) == sizeof(*out)); std::memcpy(out, std::addressof(raw), sizeof(raw)); R_SUCCEED(); } }
1,585
C++
.cpp
39
35.666667
98
0.702017
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,678
fs_file_accessor.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/fsa/fs_file_accessor.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "../fs_scoped_setter.hpp" #include "../fs_file_path_hash.hpp" #include "fs_file_accessor.hpp" #include "fs_filesystem_accessor.hpp" namespace ams::fs::impl { FileAccessor::FileAccessor(std::unique_ptr<fsa::IFile>&& f, FileSystemAccessor *p, OpenMode mode) : m_impl(std::move(f)), m_parent(p), m_write_state(WriteState::None), m_write_result(ResultSuccess()), m_open_mode(mode) { /* ... */ } FileAccessor::~FileAccessor() { /* Ensure that all files are flushed. */ if (R_SUCCEEDED(m_write_result)) { AMS_FS_ABORT_UNLESS_WITH_RESULT(m_write_state != WriteState::NeedsFlush, fs::ResultNeedFlush()); } m_impl.reset(); if (m_parent != nullptr) { m_parent->NotifyCloseFile(this); } } Result FileAccessor::ReadWithCacheAccessLog(size_t *out, s64 offset, void *buf, size_t size, const ReadOption &option, bool use_path_cache, bool use_data_cache) { /* TODO */ AMS_UNUSED(out, offset, buf, size, option, use_path_cache, use_data_cache); AMS_ABORT(); } Result FileAccessor::ReadWithoutCacheAccessLog(size_t *out, s64 offset, void *buf, size_t size, const ReadOption &option) { R_RETURN(m_impl->Read(out, offset, buf, size, option)); } Result FileAccessor::Read(size_t *out, s64 offset, void *buf, size_t size, const ReadOption &option) { /* Get a handle to this file for use in logging. */ FileHandle handle = { this }; /* Fail after a write fails. */ R_UNLESS(R_SUCCEEDED(m_write_result), AMS_FS_IMPL_ACCESS_LOG_WITH_NAME(m_write_result, handle, "ReadFile", AMS_FS_IMPL_ACCESS_LOG_FORMAT_READ_FILE(out, offset, size))); /* TODO: Support cache. */ const bool use_path_cache = m_parent != nullptr && m_file_path_hash != nullptr; const bool use_data_cache = /* TODO */false && m_parent != nullptr && m_parent->IsFileDataCacheAttachable(); if (use_path_cache && use_data_cache && false) { /* TODO */ R_RETURN(this->ReadWithCacheAccessLog(out, offset, buf, size, option, use_path_cache, use_data_cache)); } else { R_RETURN(AMS_FS_IMPL_ACCESS_LOG_WITH_NAME(this->ReadWithoutCacheAccessLog(out, offset, buf, size, option), handle, "ReadFile", AMS_FS_IMPL_ACCESS_LOG_FORMAT_READ_FILE(out, offset, size))); } } Result FileAccessor::Write(s64 offset, const void *buf, size_t size, const WriteOption &option) { /* Fail after a write fails. */ R_TRY(m_write_result); auto setter = MakeScopedSetter(m_write_state, WriteState::Failed); if (m_file_path_hash != nullptr && /* TODO */ false) { /* TODO */ AMS_ABORT(); } else { R_TRY(this->UpdateLastResult(m_impl->Write(offset, buf, size, option))); } setter.Set(option.HasFlushFlag() ? WriteState::None : WriteState::NeedsFlush); R_SUCCEED(); } Result FileAccessor::Flush() { /* Fail after a write fails. */ R_TRY(m_write_result); auto setter = MakeScopedSetter(m_write_state, WriteState::Failed); R_TRY(this->UpdateLastResult(m_impl->Flush())); setter.Set(WriteState::None); R_SUCCEED(); } Result FileAccessor::SetSize(s64 size) { /* Fail after a write fails. */ R_TRY(m_write_result); const WriteState old_write_state = m_write_state; auto setter = MakeScopedSetter(m_write_state, WriteState::Failed); R_TRY(this->UpdateLastResult(m_impl->SetSize(size))); if (m_file_path_hash != nullptr) { /* TODO: invalidate path cache */ } setter.Set(old_write_state); R_SUCCEED(); } Result FileAccessor::GetSize(s64 *out) { /* Fail after a write fails. */ R_TRY(m_write_result); R_RETURN(m_impl->GetSize(out)); } Result FileAccessor::OperateRange(void *dst, size_t dst_size, OperationId operation, s64 offset, s64 size, const void *src, size_t src_size) { R_RETURN(m_impl->OperateRange(dst, dst_size, operation, offset, size, src, src_size)); } }
4,843
C++
.cpp
101
40.782178
200
0.642781
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,679
fs_mount_table.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/fsa/fs_mount_table.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "fs_mount_table.hpp" namespace ams::fs::impl { namespace { bool MatchesName(const FileSystemAccessor &accessor, const char *name) { return std::strncmp(accessor.GetName(), name, sizeof(MountName)) == 0; } } bool MountTable::CanAcceptMountName(const char *name) { for (const auto &fs : m_fs_list) { if (MatchesName(fs, name)) { return false; } } return true; } Result MountTable::Mount(std::unique_ptr<FileSystemAccessor> &&fs) { std::scoped_lock lk(m_mutex); R_UNLESS(this->CanAcceptMountName(fs->GetName()), fs::ResultMountNameAlreadyExists()); m_fs_list.push_back(*fs.release()); R_SUCCEED(); } Result MountTable::Find(FileSystemAccessor **out, const char *name) { std::scoped_lock lk(m_mutex); for (auto &fs : m_fs_list) { if (MatchesName(fs, name)) { *out = std::addressof(fs); R_SUCCEED(); } } R_THROW(fs::ResultNotMounted()); } void MountTable::Unmount(const char *name) { std::scoped_lock lk(m_mutex); for (auto it = m_fs_list.cbegin(); it != m_fs_list.cend(); it++) { if (MatchesName(*it, name)) { auto p = std::addressof(*it); m_fs_list.erase(it); delete p; return; } } R_ABORT_UNLESS(fs::ResultNotMounted()); } }
2,182
C++
.cpp
60
28.683333
94
0.6056
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,680
fs_user_filesystem.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/fsa/fs_user_filesystem.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "fs_filesystem_accessor.hpp" #include "fs_file_accessor.hpp" #include "fs_directory_accessor.hpp" #include "fs_mount_utils.hpp" #include "fs_user_mount_table.hpp" namespace ams::fs { Result CreateFile(const char *path, s64 size) { R_RETURN(CreateFile(path, size, 0)); } Result CreateFile(const char* path, s64 size, int option) { impl::FileSystemAccessor *accessor; const char *sub_path; AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_UNLESS_R_SUCCEEDED(impl::FindFileSystem(std::addressof(accessor), std::addressof(sub_path), path), AMS_FS_IMPL_ACCESS_LOG_FORMAT_PATH, path)); AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_FILESYSTEM(accessor->CreateFile(sub_path, size, option), nullptr, accessor, AMS_FS_IMPL_ACCESS_LOG_FORMAT_PATH_AND_SIZE, path, size)); R_SUCCEED(); } Result DeleteFile(const char *path) { impl::FileSystemAccessor *accessor; const char *sub_path; AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_UNLESS_R_SUCCEEDED(impl::FindFileSystem(std::addressof(accessor), std::addressof(sub_path), path), AMS_FS_IMPL_ACCESS_LOG_FORMAT_PATH, path)); AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_FILESYSTEM(accessor->DeleteFile(sub_path), nullptr, accessor, AMS_FS_IMPL_ACCESS_LOG_FORMAT_PATH, path)); R_SUCCEED(); } Result CreateDirectory(const char *path) { impl::FileSystemAccessor *accessor; const char *sub_path; AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_UNLESS_R_SUCCEEDED(impl::FindFileSystem(std::addressof(accessor), std::addressof(sub_path), path), AMS_FS_IMPL_ACCESS_LOG_FORMAT_PATH, path)); AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_FILESYSTEM(accessor->CreateDirectory(sub_path), nullptr, accessor, AMS_FS_IMPL_ACCESS_LOG_FORMAT_PATH, path)); R_SUCCEED(); } Result DeleteDirectory(const char *path) { impl::FileSystemAccessor *accessor; const char *sub_path; AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_UNLESS_R_SUCCEEDED(impl::FindFileSystem(std::addressof(accessor), std::addressof(sub_path), path), AMS_FS_IMPL_ACCESS_LOG_FORMAT_PATH, path)); AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_FILESYSTEM(accessor->DeleteDirectory(sub_path), nullptr, accessor, AMS_FS_IMPL_ACCESS_LOG_FORMAT_PATH, path)); R_SUCCEED(); } Result DeleteDirectoryRecursively(const char *path) { impl::FileSystemAccessor *accessor; const char *sub_path; AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_UNLESS_R_SUCCEEDED(impl::FindFileSystem(std::addressof(accessor), std::addressof(sub_path), path), AMS_FS_IMPL_ACCESS_LOG_FORMAT_PATH, path)); AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_FILESYSTEM(accessor->DeleteDirectoryRecursively(sub_path), nullptr, accessor, AMS_FS_IMPL_ACCESS_LOG_FORMAT_PATH, path)); R_SUCCEED(); } Result RenameFile(const char *old_path, const char *new_path) { impl::FileSystemAccessor *old_accessor; impl::FileSystemAccessor *new_accessor; const char *old_sub_path; const char *new_sub_path; AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_UNLESS_R_SUCCEEDED(impl::FindFileSystem(std::addressof(old_accessor), std::addressof(old_sub_path), old_path), AMS_FS_IMPL_ACCESS_LOG_FORMAT_RENAME, old_path, new_path)); AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_UNLESS_R_SUCCEEDED(impl::FindFileSystem(std::addressof(new_accessor), std::addressof(new_sub_path), new_path), AMS_FS_IMPL_ACCESS_LOG_FORMAT_RENAME, old_path, new_path)); auto rename_impl = [=]() -> Result { R_UNLESS(old_accessor == new_accessor, fs::ResultRenameToOtherFileSystem()); R_TRY(old_accessor->RenameFile(old_sub_path, new_sub_path)); R_SUCCEED(); }; AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_FILESYSTEM(rename_impl(), nullptr, old_accessor, AMS_FS_IMPL_ACCESS_LOG_FORMAT_RENAME, old_path, new_path)); R_SUCCEED(); } Result RenameDirectory(const char *old_path, const char *new_path) { impl::FileSystemAccessor *old_accessor; impl::FileSystemAccessor *new_accessor; const char *old_sub_path; const char *new_sub_path; AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_UNLESS_R_SUCCEEDED(impl::FindFileSystem(std::addressof(old_accessor), std::addressof(old_sub_path), old_path), AMS_FS_IMPL_ACCESS_LOG_FORMAT_RENAME, old_path, new_path)); AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_UNLESS_R_SUCCEEDED(impl::FindFileSystem(std::addressof(new_accessor), std::addressof(new_sub_path), new_path), AMS_FS_IMPL_ACCESS_LOG_FORMAT_RENAME, old_path, new_path)); auto rename_impl = [=]() -> Result { R_UNLESS(old_accessor == new_accessor, fs::ResultRenameToOtherFileSystem()); R_TRY(old_accessor->RenameDirectory(old_sub_path, new_sub_path)); R_SUCCEED(); }; AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_FILESYSTEM(rename_impl(), nullptr, old_accessor, AMS_FS_IMPL_ACCESS_LOG_FORMAT_RENAME, old_path, new_path)); R_SUCCEED(); } Result GetEntryType(DirectoryEntryType *out, const char *path) { impl::FileSystemAccessor *accessor; const char *sub_path; AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_UNLESS_R_SUCCEEDED(impl::FindFileSystem(std::addressof(accessor), std::addressof(sub_path), path), AMS_FS_IMPL_ACCESS_LOG_FORMAT_PATH, path)); AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_FILESYSTEM(accessor->GetEntryType(out, sub_path), nullptr, accessor, AMS_FS_IMPL_ACCESS_LOG_FORMAT_GET_ENTRY_TYPE(out, path))); R_SUCCEED(); } Result OpenFile(FileHandle *out_file, const char *path, int mode) { impl::FileSystemAccessor *accessor; const char *sub_path; AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_UNLESS_R_SUCCEEDED(impl::FindFileSystem(std::addressof(accessor), std::addressof(sub_path), path), AMS_FS_IMPL_ACCESS_LOG_FORMAT_PATH_AND_OPEN_MODE, path, static_cast<u32>(mode))); std::unique_ptr<impl::FileAccessor> file_accessor; auto open_impl = [&]() -> Result { R_UNLESS(out_file != nullptr, fs::ResultNullptrArgument()); R_TRY(accessor->OpenFile(std::addressof(file_accessor), sub_path, static_cast<OpenMode>(mode))); R_SUCCEED(); }; AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_FILESYSTEM(open_impl(), nullptr, accessor, AMS_FS_IMPL_ACCESS_LOG_FORMAT_PATH_AND_OPEN_MODE, path, static_cast<u32>(mode))); out_file->handle = file_accessor.release(); R_SUCCEED(); } Result OpenDirectory(DirectoryHandle *out_dir, const char *path, int mode) { impl::FileSystemAccessor *accessor; const char *sub_path; AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_UNLESS_R_SUCCEEDED(impl::FindFileSystem(std::addressof(accessor), std::addressof(sub_path), path), AMS_FS_IMPL_ACCESS_LOG_FORMAT_PATH_AND_OPEN_MODE, path, static_cast<u32>(mode))); std::unique_ptr<impl::DirectoryAccessor> dir_accessor; auto open_impl = [&]() -> Result { R_UNLESS(out_dir != nullptr, fs::ResultNullptrArgument()); R_TRY(accessor->OpenDirectory(std::addressof(dir_accessor), sub_path, static_cast<OpenDirectoryMode>(mode))); R_SUCCEED(); }; AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_FILESYSTEM(open_impl(), nullptr, accessor, AMS_FS_IMPL_ACCESS_LOG_FORMAT_PATH_AND_OPEN_MODE, path, static_cast<u32>(mode))); out_dir->handle = dir_accessor.release(); R_SUCCEED(); } Result CleanDirectoryRecursively(const char *path) { impl::FileSystemAccessor *accessor; const char *sub_path; AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_UNLESS_R_SUCCEEDED(impl::FindFileSystem(std::addressof(accessor), std::addressof(sub_path), path), AMS_FS_IMPL_ACCESS_LOG_FORMAT_PATH, path)); AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_FILESYSTEM(accessor->CleanDirectoryRecursively(sub_path), nullptr, accessor, AMS_FS_IMPL_ACCESS_LOG_FORMAT_PATH, path)); R_SUCCEED(); } Result GetFreeSpaceSize(s64 *out, const char *path) { /* Find the filesystem without access logging. */ impl::FileSystemAccessor *accessor; const char *sub_path; AMS_FS_R_TRY(impl::FindFileSystem(std::addressof(accessor), std::addressof(sub_path), path)); /* Get the total space size. */ AMS_FS_R_TRY(accessor->GetFreeSpaceSize(out, sub_path)); R_SUCCEED(); } Result GetTotalSpaceSize(s64 *out, const char *path) { /* Find the filesystem without access logging. */ impl::FileSystemAccessor *accessor; const char *sub_path; AMS_FS_R_TRY(impl::FindFileSystem(std::addressof(accessor), std::addressof(sub_path), path)); /* Get the total space size. */ AMS_FS_R_TRY(accessor->GetTotalSpaceSize(out, sub_path)); R_SUCCEED(); } Result SetConcatenationFileAttribute(const char *path) { impl::FileSystemAccessor *accessor; const char *sub_path; AMS_FS_R_TRY(impl::FindFileSystem(std::addressof(accessor), std::addressof(sub_path), path)); AMS_FS_R_TRY(accessor->QueryEntry(nullptr, 0, nullptr, 0, fsa::QueryId::SetConcatenationFileAttribute, sub_path)); R_SUCCEED(); } Result OpenFile(FileHandle *out, std::unique_ptr<fsa::IFile> &&file, int mode) { AMS_FS_R_UNLESS(out != nullptr, fs::ResultNullptrArgument()); auto file_accessor = std::make_unique<impl::FileAccessor>(std::move(file), nullptr, static_cast<OpenMode>(mode)); AMS_FS_R_UNLESS(file_accessor != nullptr, fs::ResultAllocationMemoryFailedNew()); out->handle = file_accessor.release(); R_SUCCEED(); } namespace { Result CommitImpl(const char *mount_name, const char *func_name) { impl::FileSystemAccessor *accessor{}; AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_UNLESS_R_SUCCEEDED(impl::Find(std::addressof(accessor), mount_name), AMS_FS_IMPL_ACCESS_LOG_FORMAT_MOUNT, mount_name)); AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG_FILESYSTEM_WITH_NAME(accessor->Commit(), nullptr, accessor, func_name, AMS_FS_IMPL_ACCESS_LOG_FORMAT_MOUNT, mount_name)); R_SUCCEED(); } } Result Commit(const char *mount_name) { R_RETURN(CommitImpl(mount_name, AMS_CURRENT_FUNCTION_NAME)); } Result CommitSaveData(const char *mount_name) { R_RETURN(CommitImpl(mount_name, AMS_CURRENT_FUNCTION_NAME)); } }
11,076
C++
.cpp
179
54.03352
224
0.682832
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,681
fs_filesystem_accessor.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/fsa/fs_filesystem_accessor.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "fs_file_accessor.hpp" #include "fs_directory_accessor.hpp" #include "fs_filesystem_accessor.hpp" namespace ams::fs::impl { namespace { template<typename List, typename Iter> void Remove(List &list, Iter *desired) { for (auto it = list.cbegin(); it != list.cend(); ++it) { if (it.operator->() == desired) { list.erase(it); return; } } /* This should never happen. */ AMS_ABORT(); } Result SetMountName(char *dst, const char *name) { R_UNLESS(name[0] != 0, fs::ResultInvalidMountName()); const size_t n_len = util::Strlcpy<char>(dst, name, MountNameLengthMax + 1); R_UNLESS(n_len <= MountNameLengthMax, fs::ResultInvalidMountName()); R_SUCCEED(); } template<typename List> Result ValidateNoOpenWriteModeFiles(List &list) { for (auto it = list.cbegin(); it != list.cend(); it++) { R_UNLESS((it->GetOpenMode() & OpenMode_Write) == 0, fs::ResultWriteModeFileNotClosed()); } R_SUCCEED(); } } FileSystemAccessor::FileSystemAccessor(const char *n, std::unique_ptr<fsa::IFileSystem> &&fs, std::unique_ptr<fsa::ICommonMountNameGenerator> &&generator) : m_impl(std::move(fs)), m_open_list_lock(), m_mount_name_generator(std::move(generator)), m_access_log_enabled(false), m_data_cache_attachable(false), m_path_cache_attachable(false), m_path_cache_attached(false), m_multi_commit_supported(false), m_path_flags() { R_ABORT_UNLESS(SetMountName(m_name.str, n)); if (std::strcmp(m_name.str, AMS_FS_IMPL_HOST_ROOT_FILE_SYSTEM_MOUNT_NAME) == 0) { m_path_flags.AllowWindowsPath(); } } FileSystemAccessor::~FileSystemAccessor() { std::scoped_lock lk(m_open_list_lock); /* TODO: Iterate over list entries. */ if (!m_open_file_list.empty()) { R_ABORT_UNLESS(fs::ResultFileNotClosed()); } if (!m_open_dir_list.empty()) { R_ABORT_UNLESS(fs::ResultDirectoryNotClosed()); } if (m_path_cache_attached) { /* TODO: Invalidate path cache */ } } Result FileSystemAccessor::GetCommonMountName(char *dst, size_t dst_size) const { R_UNLESS(m_mount_name_generator != nullptr, fs::ResultPreconditionViolation()); R_RETURN(m_mount_name_generator->GenerateCommonMountName(dst, dst_size)); } std::shared_ptr<fssrv::impl::FileSystemInterfaceAdapter> FileSystemAccessor::GetMultiCommitTarget() { if (m_multi_commit_supported) { AMS_ABORT("TODO: Support multi commit"); } return nullptr; } void FileSystemAccessor::NotifyCloseFile(FileAccessor *f) { std::scoped_lock lk(m_open_list_lock); Remove(m_open_file_list, f); } void FileSystemAccessor::NotifyCloseDirectory(DirectoryAccessor *d) { std::scoped_lock lk(m_open_list_lock); Remove(m_open_dir_list, d); } Result FileSystemAccessor::SetUpPath(fs::Path *out, const char *p) { /* Initialize the path appropriately. */ bool normalized; size_t len; if (R_SUCCEEDED(PathFormatter::IsNormalized(std::addressof(normalized), std::addressof(len), p, m_path_flags)) && normalized) { /* We can use the input buffer directly. */ out->SetShallowBuffer(p); } else { /* Initialize with appropriate slash replacement. */ if (m_path_flags.IsWindowsPathAllowed()) { R_TRY(out->InitializeWithReplaceForwardSlashes(p)); } else { R_TRY(out->InitializeWithReplaceBackslash(p)); } /* Ensure we're normalized. */ R_TRY(out->Normalize(m_path_flags)); } /* Check the path isn't too long. */ R_UNLESS(out->GetLength() <= fs::EntryNameLengthMax, fs::ResultTooLongPath()); R_SUCCEED(); } Result FileSystemAccessor::CreateFile(const char *path, s64 size, int option) { /* Create path. */ fs::Path normalized_path; R_TRY(this->SetUpPath(std::addressof(normalized_path), path)); if (m_path_cache_attached) { /* TODO: Path cache */ R_TRY(m_impl->CreateFile(normalized_path, size, option)); } else { R_TRY(m_impl->CreateFile(normalized_path, size, option)); } R_SUCCEED(); } Result FileSystemAccessor::DeleteFile(const char *path) { /* Create path. */ fs::Path normalized_path; R_TRY(this->SetUpPath(std::addressof(normalized_path), path)); R_RETURN(m_impl->DeleteFile(normalized_path)); } Result FileSystemAccessor::CreateDirectory(const char *path) { /* Create path. */ fs::Path normalized_path; R_TRY(this->SetUpPath(std::addressof(normalized_path), path)); R_RETURN(m_impl->CreateDirectory(normalized_path)); } Result FileSystemAccessor::DeleteDirectory(const char *path) { /* Create path. */ fs::Path normalized_path; R_TRY(this->SetUpPath(std::addressof(normalized_path), path)); R_RETURN(m_impl->DeleteDirectory(normalized_path)); } Result FileSystemAccessor::DeleteDirectoryRecursively(const char *path) { /* Create path. */ fs::Path normalized_path; R_TRY(this->SetUpPath(std::addressof(normalized_path), path)); R_RETURN(m_impl->DeleteDirectoryRecursively(normalized_path)); } Result FileSystemAccessor::RenameFile(const char *old_path, const char *new_path) { /* Create path. */ fs::Path normalized_old_path; fs::Path normalized_new_path; R_TRY(this->SetUpPath(std::addressof(normalized_old_path), old_path)); R_TRY(this->SetUpPath(std::addressof(normalized_new_path), new_path)); if (m_path_cache_attached) { /* TODO: Path cache */ R_TRY(m_impl->RenameFile(normalized_old_path, normalized_new_path)); } else { R_TRY(m_impl->RenameFile(normalized_old_path, normalized_new_path)); } R_SUCCEED(); } Result FileSystemAccessor::RenameDirectory(const char *old_path, const char *new_path) { /* Create path. */ fs::Path normalized_old_path; fs::Path normalized_new_path; R_TRY(this->SetUpPath(std::addressof(normalized_old_path), old_path)); R_TRY(this->SetUpPath(std::addressof(normalized_new_path), new_path)); if (m_path_cache_attached) { /* TODO: Path cache */ R_TRY(m_impl->RenameDirectory(normalized_old_path, normalized_new_path)); } else { R_TRY(m_impl->RenameDirectory(normalized_old_path, normalized_new_path)); } R_SUCCEED(); } Result FileSystemAccessor::GetEntryType(DirectoryEntryType *out, const char *path) { /* Create path. */ fs::Path normalized_path; R_TRY(this->SetUpPath(std::addressof(normalized_path), path)); R_RETURN(m_impl->GetEntryType(out, normalized_path)); } Result FileSystemAccessor::OpenFile(std::unique_ptr<FileAccessor> *out_file, const char *path, OpenMode mode) { /* Create path. */ fs::Path normalized_path; R_TRY(this->SetUpPath(std::addressof(normalized_path), path)); std::unique_ptr<fsa::IFile> file; R_TRY(m_impl->OpenFile(std::addressof(file), normalized_path, mode)); auto accessor = new FileAccessor(std::move(file), this, mode); R_UNLESS(accessor != nullptr, fs::ResultAllocationMemoryFailedInFileSystemAccessorA()); { std::scoped_lock lk(m_open_list_lock); m_open_file_list.push_back(*accessor); } if (m_path_cache_attached) { if (mode & OpenMode_AllowAppend) { /* TODO: Append Path cache */ } else { /* TODO: Non-append path cache */ } } out_file->reset(accessor); R_SUCCEED(); } Result FileSystemAccessor::OpenDirectory(std::unique_ptr<DirectoryAccessor> *out_dir, const char *path, OpenDirectoryMode mode) { /* Create path. */ fs::Path normalized_path; R_TRY(this->SetUpPath(std::addressof(normalized_path), path)); std::unique_ptr<fsa::IDirectory> dir; R_TRY(m_impl->OpenDirectory(std::addressof(dir), normalized_path, mode)); auto accessor = new DirectoryAccessor(std::move(dir), *this); R_UNLESS(accessor != nullptr, fs::ResultAllocationMemoryFailedInFileSystemAccessorB()); { std::scoped_lock lk(m_open_list_lock); m_open_dir_list.push_back(*accessor); } out_dir->reset(accessor); R_SUCCEED(); } Result FileSystemAccessor::Commit() { { std::scoped_lock lk(m_open_list_lock); R_ABORT_UNLESS(ValidateNoOpenWriteModeFiles(m_open_file_list)); } R_RETURN(m_impl->Commit()); } Result FileSystemAccessor::GetFreeSpaceSize(s64 *out, const char *path) { /* Create path. */ fs::Path normalized_path; R_TRY(this->SetUpPath(std::addressof(normalized_path), path)); R_RETURN(m_impl->GetFreeSpaceSize(out, normalized_path)); } Result FileSystemAccessor::GetTotalSpaceSize(s64 *out, const char *path) { /* Create path. */ fs::Path normalized_path; R_TRY(this->SetUpPath(std::addressof(normalized_path), path)); R_RETURN(m_impl->GetTotalSpaceSize(out, normalized_path)); } Result FileSystemAccessor::CleanDirectoryRecursively(const char *path) { /* Create path. */ fs::Path normalized_path; R_TRY(this->SetUpPath(std::addressof(normalized_path), path)); R_RETURN(m_impl->CleanDirectoryRecursively(normalized_path)); } Result FileSystemAccessor::GetFileTimeStampRaw(FileTimeStampRaw *out, const char *path) { /* Create path. */ fs::Path normalized_path; R_TRY(this->SetUpPath(std::addressof(normalized_path), path)); R_RETURN(m_impl->GetFileTimeStampRaw(out, normalized_path)); } Result FileSystemAccessor::QueryEntry(char *dst, size_t dst_size, const char *src, size_t src_size, fsa::QueryId query, const char *path) { /* Create path. */ fs::Path normalized_path; R_TRY(this->SetUpPath(std::addressof(normalized_path), path)); R_RETURN(m_impl->QueryEntry(dst, dst_size, src, src_size, query, normalized_path)); } }
11,348
C++
.cpp
249
36.738956
165
0.627968
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,682
fs_user_directory.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/fsa/fs_user_directory.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "fs_directory_accessor.hpp" #include "fs_filesystem_accessor.hpp" namespace ams::fs { namespace { ALWAYS_INLINE impl::DirectoryAccessor *Get(DirectoryHandle handle) { return reinterpret_cast<impl::DirectoryAccessor *>(handle.handle); } } Result ReadDirectory(s64 *out_count, DirectoryEntry *out_entries, DirectoryHandle handle, s64 max_entries) { AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG(Get(handle)->Read(out_count, out_entries, max_entries), handle, AMS_FS_IMPL_ACCESS_LOG_FORMAT_READ_DIRECTORY(out_count, max_entries))); R_SUCCEED(); } Result GetDirectoryEntryCount(s64 *out, DirectoryHandle handle) { AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG(Get(handle)->GetEntryCount(out), handle, AMS_FS_IMPL_ACCESS_LOG_FORMAT_GET_DIRECTORY_ENTRY_COUNT(out))); R_SUCCEED(); } void CloseDirectory(DirectoryHandle handle) { AMS_FS_IMPL_ACCESS_LOG((delete Get(handle), ResultSuccess()), handle, AMS_FS_IMPL_ACCESS_LOG_FORMAT_NONE); } }
1,693
C++
.cpp
36
42.638889
179
0.726501
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,683
fs_user_file.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/fsa/fs_user_file.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "fs_file_accessor.hpp" #include "fs_filesystem_accessor.hpp" namespace ams::fs { namespace { ALWAYS_INLINE impl::FileAccessor *Get(FileHandle handle) { return reinterpret_cast<impl::FileAccessor *>(handle.handle); } Result ReadFileImpl(size_t *out, FileHandle handle, s64 offset, void *buffer, size_t size, const fs::ReadOption &option) { R_TRY(Get(handle)->Read(out, offset, buffer, size, option)); R_SUCCEED(); } } Result ReadFile(FileHandle handle, s64 offset, void *buffer, size_t size, const fs::ReadOption &option) { size_t read_size; AMS_FS_R_TRY(ReadFileImpl(std::addressof(read_size), handle, offset, buffer, size, option)); AMS_FS_R_UNLESS(read_size == size, fs::ResultOutOfRange()); R_SUCCEED(); } Result ReadFile(FileHandle handle, s64 offset, void *buffer, size_t size) { size_t read_size; AMS_FS_R_TRY(ReadFileImpl(std::addressof(read_size), handle, offset, buffer, size, ReadOption())); AMS_FS_R_UNLESS(read_size == size, fs::ResultOutOfRange()); R_SUCCEED(); } Result ReadFile(size_t *out, FileHandle handle, s64 offset, void *buffer, size_t size, const fs::ReadOption &option) { AMS_FS_R_TRY(ReadFileImpl(out, handle, offset, buffer, size, option)); R_SUCCEED(); } Result ReadFile(size_t *out, FileHandle handle, s64 offset, void *buffer, size_t size) { AMS_FS_R_TRY(ReadFileImpl(out, handle, offset, buffer, size, ReadOption())); R_SUCCEED(); } Result GetFileSize(s64 *out, FileHandle handle) { AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG(Get(handle)->GetSize(out), handle, AMS_FS_IMPL_ACCESS_LOG_FORMAT_GET_FILE_SIZE(out))); R_SUCCEED(); } Result FlushFile(FileHandle handle) { AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG(Get(handle)->Flush(), handle, AMS_FS_IMPL_ACCESS_LOG_FORMAT_NONE)); R_SUCCEED(); } Result WriteFile(FileHandle handle, s64 offset, const void *buffer, size_t size, const fs::WriteOption &option) { AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG(Get(handle)->Write(offset, buffer, size, option), handle, AMS_FS_IMPL_ACCESS_LOG_FORMAT_WRITE_FILE(option), offset, size)); R_SUCCEED(); } Result SetFileSize(FileHandle handle, s64 size) { AMS_FS_R_TRY(AMS_FS_IMPL_ACCESS_LOG(Get(handle)->SetSize(size), handle, AMS_FS_IMPL_ACCESS_LOG_FORMAT_SIZE, size)); R_SUCCEED(); } int GetFileOpenMode(FileHandle handle) { const int mode = Get(handle)->GetOpenMode(); AMS_FS_IMPL_ACCESS_LOG(ResultSuccess(), handle, AMS_FS_IMPL_ACCESS_LOG_FORMAT_OPEN_MODE, static_cast<u32>(mode)); return mode; } void CloseFile(FileHandle handle) { AMS_FS_IMPL_ACCESS_LOG((delete Get(handle), ResultSuccess()), handle, AMS_FS_IMPL_ACCESS_LOG_FORMAT_NONE); } Result QueryRange(QueryRangeInfo *out, FileHandle handle, s64 offset, s64 size) { AMS_FS_R_TRY(Get(handle)->OperateRange(out, sizeof(*out), OperationId::QueryRange, offset, size, nullptr, 0)); R_SUCCEED(); } }
3,809
C++
.cpp
77
43.233766
167
0.677254
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,684
fs_registrar.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/fsa/fs_registrar.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "fs_filesystem_accessor.hpp" #include "fs_user_mount_table.hpp" namespace ams::fs::fsa { Result Register(const char *name, std::unique_ptr<IFileSystem> &&fs) { auto accessor = std::make_unique<impl::FileSystemAccessor>(name, std::move(fs)); R_UNLESS(accessor != nullptr, fs::ResultAllocationMemoryFailedInRegisterA()); R_RETURN(impl::Register(std::move(accessor))); } Result Register(const char *name, std::unique_ptr<IFileSystem> &&fs, std::unique_ptr<ICommonMountNameGenerator> &&generator) { auto accessor = std::make_unique<impl::FileSystemAccessor>(name, std::move(fs), std::move(generator)); R_UNLESS(accessor != nullptr, fs::ResultAllocationMemoryFailedInRegisterB()); R_RETURN(impl::Register(std::move(accessor))); } Result Register(const char *name, std::unique_ptr<IFileSystem> &&fs, std::unique_ptr<ICommonMountNameGenerator> &&generator, bool use_data_cache, bool use_path_cache, bool support_multi_commit) { auto accessor = std::make_unique<impl::FileSystemAccessor>(name, std::move(fs), std::move(generator)); R_UNLESS(accessor != nullptr, fs::ResultAllocationMemoryFailedInRegisterB()); accessor->SetFileDataCacheAttachable(use_data_cache); accessor->SetPathBasedFileDataCacheAttachable(use_path_cache); accessor->SetMultiCommitSupported(support_multi_commit); R_RETURN(impl::Register(std::move(accessor))); } void Unregister(const char *name) { impl::Unregister(name); } }
2,207
C++
.cpp
41
48.926829
199
0.725417
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,685
fs_user_mount_table.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/fsa/fs_user_mount_table.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "fs_user_mount_table.hpp" #include "fs_mount_table.hpp" #include "fs_filesystem_accessor.hpp" namespace ams::fs::impl { namespace { constinit MountTable g_mount_table; } Result Register(std::unique_ptr<FileSystemAccessor> &&fs) { R_RETURN(g_mount_table.Mount(std::move(fs))); } Result Find(FileSystemAccessor **out, const char *name) { R_RETURN(g_mount_table.Find(out, name)); } void Unregister(const char *name) { g_mount_table.Unmount(name); } }
1,192
C++
.cpp
33
32.515152
76
0.717637
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,686
fs_directory_accessor.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/fs/fsa/fs_directory_accessor.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "fs_directory_accessor.hpp" #include "fs_filesystem_accessor.hpp" namespace ams::fs::impl { DirectoryAccessor::DirectoryAccessor(std::unique_ptr<fsa::IDirectory>&& d, FileSystemAccessor &p) : m_impl(std::move(d)), m_parent(p) { /* ... */ } DirectoryAccessor::~DirectoryAccessor() { m_impl.reset(); m_parent.NotifyCloseDirectory(this); } Result DirectoryAccessor::Read(s64 *out_count, DirectoryEntry *out_entries, s64 max_entries) { R_RETURN(m_impl->Read(out_count, out_entries, max_entries)); } Result DirectoryAccessor::GetEntryCount(s64 *out) { R_RETURN(m_impl->GetEntryCount(out)); } }
1,339
C++
.cpp
33
36.787879
139
0.716923
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,687
cs_target_io_server.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/cs/cs_target_io_server.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> namespace ams::cs { void InitializeTargetIoServer() { /* Launch target io server. */ os::ProcessId process_id; scs::LaunchProgram(std::addressof(process_id), ncm::ProgramLocation::Make(ncm::SystemProgramId::DevServer, ncm::StorageId::None), nullptr, 0, 0); } }
959
C++
.cpp
23
38.565217
153
0.733119
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,688
cs_remote_video_server.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/cs/cs_remote_video_server.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> namespace ams::cs { void InitializeRemoteVideoServer() { /* TODO: Support remote video server. */ } }
784
C++
.cpp
21
34.761905
76
0.742105
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,689
cs_command_processor.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/cs/cs_command_processor.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "cs_command_impl.hpp" /* Include command implementations. */ #include "cs_command_impl.inc" namespace ams::cs { namespace { struct ResponseFirmwareVersion { ResponseHeader header; settings::system::FirmwareVersion firmware_version; }; struct ResponseTakeScreenShot { ResponseHeader header; s32 data_size; s32 width; s32 height; }; constinit u8 g_data[0x1000]; } bool CommandProcessor::ProcessCommand(const CommandHeader &header, const u8 *body, s32 socket) { switch (header.command) { case Command_GetFirmwareVersion: SendFirmwareVersion(socket, header); break; case Command_TakeScreenShot: this->TakeScreenShot(header, socket, vi::LayerStack_ApplicationForDebug); break; case Command_TakeForegroundScreenShot: this->TakeScreenShot(header, socket, vi::LayerStack_LastFrame); break; /* TODO: Command support. */ default: scs::CommandProcessor::ProcessCommand(header, body, socket); break; } return true; } void CommandProcessor::SendFirmwareVersion(s32 socket, const CommandHeader &header) { /* Build the response. */ ResponseFirmwareVersion response = { .header = { .id = header.id, .response = Response_FirmwareVersion, .body_size = sizeof(response) - sizeof(response.header), }, .firmware_version = {}, }; /* Get the firmware version. */ const Result result = DoGetFirmwareVersionCommand(std::addressof(response.firmware_version)); if (R_SUCCEEDED(result)) { /* Send the response. */ auto lk = MakeSendGuardBlock(); Send(socket, std::addressof(response), sizeof(response)); } else { SendErrorResult(socket, header, result); } } void CommandProcessor::TakeScreenShot(const CommandHeader &header, s32 socket, vi::LayerStack layer_stack) { /* Create the command data. */ const CommandDataTakeScreenShot params = { .layer_stack = layer_stack, .buffer = g_data, .buffer_size = sizeof(g_data), }; /* Take the screenshot. */ Result result; { /* Acquire the send lock. */ auto lk = MakeSendGuardBlock(); /* Perform the command. */ result = DoTakeScreenShotCommand(params, [&](s32 data_size, s32 width, s32 height) { /* Use global buffer for response. */ ResponseTakeScreenShot *response = reinterpret_cast<ResponseTakeScreenShot *>(g_data); /* Set response header. */ *response = { .header = { .id = header.id, .response = Response_ScreenShot, .body_size = static_cast<u32>(sizeof(data_size) + sizeof(width) + sizeof(height) + data_size), }, .data_size = data_size, .width = width, .height = height, }; /* Send data. */ Send(socket, response, sizeof(*response)); }, [&](u8 *data, size_t data_size) { /* Send data. */ Send(socket, data, data_size); }); } /* Handle the error case. */ if (R_FAILED(result)) { SendErrorResult(socket, header, result); } } }
4,430
C++
.cpp
111
29
118
0.568705
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,690
cs_audio_server.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/cs/cs_audio_server.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> namespace ams::cs { void InitializeAudioServer() { /* TODO: Support audio server. */ } }
771
C++
.cpp
21
34.142857
76
0.738956
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,691
cs_hid_server.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/cs/cs_hid_server.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> namespace ams::cs { void InitializeHidServer() { /* TODO: Support hid redirection server. */ } }
779
C++
.cpp
21
34.52381
76
0.740397
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,692
boot2_api.board.nintendo_nx.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/boot2/boot2_api.board.nintendo_nx.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> namespace ams::boot2 { namespace { /* Launch lists. */ /* psc, bus, pcv is the minimal set of required programs to get SD card. */ /* bus depends on pcie, and pcv depends on settings. */ constexpr const ncm::SystemProgramId PreSdCardLaunchPrograms[] = { ncm::SystemProgramId::Psc, /* psc */ ncm::SystemProgramId::Pcie, /* pcie */ ncm::SystemProgramId::Bus, /* bus */ ncm::SystemProgramId::Settings, /* settings */ ncm::SystemProgramId::Pcv, /* pcv */ ncm::SystemProgramId::Usb, /* usb */ }; constexpr size_t NumPreSdCardLaunchPrograms = util::size(PreSdCardLaunchPrograms); constexpr const ncm::SystemProgramId AdditionalLaunchPrograms[] = { ncm::SystemProgramId::Omm, /* omm */ ncm::SystemProgramId::Am, /* am */ ncm::SystemProgramId::NvServices, /* nvservices */ ncm::SystemProgramId::NvnFlinger, /* nvnflinger */ ncm::SystemProgramId::Vi, /* vi */ ncm::SystemProgramId::Pgl, /* pgl */ ncm::SystemProgramId::Ns, /* ns */ //ncm::SystemProgramId::LogManager, /* lm */ ncm::SystemProgramId::Ppc, /* ppc */ ncm::SystemProgramId::Ptm, /* ptm */ ncm::SystemProgramId::Hid, /* hid */ ncm::SystemProgramId::Audio, /* audio */ ncm::SystemProgramId::Lbl, /* lbl */ ncm::SystemProgramId::Wlan, /* wlan */ ncm::SystemProgramId::Bluetooth, /* bluetooth */ ncm::SystemProgramId::BsdSockets, /* bsdsockets */ ncm::SystemProgramId::Eth, /* eth */ ncm::SystemProgramId::Nifm, /* nifm */ ncm::SystemProgramId::Ldn, /* ldn */ ncm::SystemProgramId::Account, /* account */ ncm::SystemProgramId::Friends, /* friends */ ncm::SystemProgramId::Nfc, /* nfc */ ncm::SystemProgramId::JpegDec, /* jpegdec */ ncm::SystemProgramId::CapSrv, /* capsrv */ ncm::SystemProgramId::Ssl, /* ssl */ ncm::SystemProgramId::Nim, /* nim */ ncm::SystemProgramId::Bcat, /* bcat */ ncm::SystemProgramId::Erpt, /* erpt */ ncm::SystemProgramId::Es, /* es */ ncm::SystemProgramId::Pctl, /* pctl */ ncm::SystemProgramId::Btm, /* btm */ ncm::SystemProgramId::Eupld, /* eupld */ ncm::SystemProgramId::Glue, /* glue */ /* ncm::SystemProgramId::Eclct, */ /* eclct */ /* Skip launching error collection in Atmosphere to lessen telemetry. */ ncm::SystemProgramId::Npns, /* npns */ ncm::SystemProgramId::Fatal, /* fatal */ ncm::SystemProgramId::Ro, /* ro */ ncm::SystemProgramId::Profiler, /* profiler */ ncm::SystemProgramId::Sdb, /* sdb */ ncm::SystemProgramId::Olsc, /* olsc */ ncm::SystemProgramId::Ngc, /* ngc */ ncm::SystemProgramId::Ngct, /* ngct */ }; constexpr size_t NumAdditionalLaunchPrograms = util::size(AdditionalLaunchPrograms); constexpr const ncm::SystemProgramId AdditionalMaintenanceLaunchPrograms[] = { ncm::SystemProgramId::Omm, /* omm */ ncm::SystemProgramId::Am, /* am */ ncm::SystemProgramId::NvServices, /* nvservices */ ncm::SystemProgramId::NvnFlinger, /* nvnflinger */ ncm::SystemProgramId::Vi, /* vi */ ncm::SystemProgramId::Pgl, /* pgl */ ncm::SystemProgramId::Ns, /* ns */ //ncm::SystemProgramId::LogManager, /* lm */ ncm::SystemProgramId::Ppc, /* ppc */ ncm::SystemProgramId::Ptm, /* ptm */ ncm::SystemProgramId::Hid, /* hid */ ncm::SystemProgramId::Audio, /* audio */ ncm::SystemProgramId::Lbl, /* lbl */ ncm::SystemProgramId::Wlan, /* wlan */ ncm::SystemProgramId::Bluetooth, /* bluetooth */ ncm::SystemProgramId::BsdSockets, /* bsdsockets */ ncm::SystemProgramId::Eth, /* eth */ ncm::SystemProgramId::Nifm, /* nifm */ ncm::SystemProgramId::Ldn, /* ldn */ ncm::SystemProgramId::Account, /* account */ ncm::SystemProgramId::Nfc, /* nfc */ ncm::SystemProgramId::JpegDec, /* jpegdec */ ncm::SystemProgramId::CapSrv, /* capsrv */ ncm::SystemProgramId::Ssl, /* ssl */ ncm::SystemProgramId::Nim, /* nim */ ncm::SystemProgramId::Erpt, /* erpt */ ncm::SystemProgramId::Es, /* es */ ncm::SystemProgramId::Pctl, /* pctl */ ncm::SystemProgramId::Btm, /* btm */ ncm::SystemProgramId::Glue, /* glue */ /* ncm::SystemProgramId::Eclct, */ /* eclct */ /* Skip launching error collection in Atmosphere to lessen telemetry. */ ncm::SystemProgramId::Fatal, /* fatal */ ncm::SystemProgramId::Ro, /* ro */ ncm::SystemProgramId::Profiler, /* profiler */ ncm::SystemProgramId::Sdb, /* sdb */ ncm::SystemProgramId::Olsc, /* olsc */ ncm::SystemProgramId::Ngc, /* ngc */ ncm::SystemProgramId::Ngct, /* ngct */ }; constexpr size_t NumAdditionalMaintenanceLaunchPrograms = util::size(AdditionalMaintenanceLaunchPrograms); /* Helpers. */ inline bool IsHexadecimal(const char *str) { while (*str) { if (!std::isxdigit(static_cast<unsigned char>(*(str++)))) { return false; } } return true; } inline bool IsNewLine(char c) { return c == '\r' || c == '\n'; } inline bool IsAllowedLaunchProgram(const ncm::ProgramLocation &loc) { if (loc.program_id == ncm::SystemProgramId::Pgl) { return hos::GetVersion() >= hos::Version_10_0_0; } return true; } void LaunchProgram(os::ProcessId *out_process_id, const ncm::ProgramLocation &loc, u32 launch_flags) { os::ProcessId process_id = os::InvalidProcessId; /* Only launch the process if we're allowed to. */ if (IsAllowedLaunchProgram(loc)) { /* Launch, lightly validate result. */ { const auto launch_result = pm::shell::LaunchProgram(std::addressof(process_id), loc, launch_flags); AMS_ABORT_UNLESS(!(svc::ResultOutOfResource::Includes(launch_result))); AMS_ABORT_UNLESS(!(svc::ResultOutOfMemory::Includes(launch_result))); AMS_ABORT_UNLESS(!(svc::ResultLimitReached::Includes(launch_result))); } if (out_process_id) { *out_process_id = process_id; } } } void LaunchList(const ncm::SystemProgramId *launch_list, size_t num_entries) { for (size_t i = 0; i < num_entries; i++) { LaunchProgram(nullptr, ncm::ProgramLocation::Make(launch_list[i], ncm::StorageId::BuiltInSystem), 0); } } bool GetGpioPadLow(DeviceCode device_code) { gpio::GpioPadSession button{}; if (R_FAILED(gpio::OpenSession(std::addressof(button), device_code))) { return false; } /* Ensure we close even on early return. */ ON_SCOPE_EXIT { gpio::CloseSession(std::addressof(button)); }; /* Set direction input. */ gpio::SetDirection(std::addressof(button), gpio::Direction_Input); return gpio::GetValue(std::addressof(button)) == gpio::GpioValue_Low; } bool IsForceMaintenance() { u8 force_maintenance = 1; settings::fwdbg::GetSettingsItemValue(std::addressof(force_maintenance), sizeof(force_maintenance), "boot", "force_maintenance"); return force_maintenance != 0; } bool IsHtcEnabled() { u8 enable_htc = 0; settings::fwdbg::GetSettingsItemValue(std::addressof(enable_htc), sizeof(enable_htc), "atmosphere", "enable_htc"); return enable_htc != 0; } bool IsStandaloneGdbstubEnabled() { u8 enable_gdbstub = 0; settings::fwdbg::GetSettingsItemValue(std::addressof(enable_gdbstub), sizeof(enable_gdbstub), "atmosphere", "enable_standalone_gdbstub"); return enable_gdbstub != 0; } bool IsAtmosphereLogManagerEnabled() { /* If htc is enabled, ams log manager is enabled. */ if (IsHtcEnabled()) { return true; } u8 enable_ams_lm = 0; settings::fwdbg::GetSettingsItemValue(std::addressof(enable_ams_lm), sizeof(enable_ams_lm), "atmosphere", "enable_log_manager"); return enable_ams_lm != 0; } bool IsMaintenanceMode() { /* Contact set:sys, retrieve boot!force_maintenance. */ if (IsForceMaintenance()) { return true; } /* Contact GPIO, read plus/minus buttons. */ { return GetGpioPadLow(gpio::DeviceCode_ButtonVolUp) && GetGpioPadLow(gpio::DeviceCode_ButtonVolDn); } } template<typename F> void IterateOverFlaggedProgramsOnSdCard(F f) { /* Validate that the contents directory exists. */ fs::DirectoryHandle contents_dir; if (R_FAILED(fs::OpenDirectory(std::addressof(contents_dir), "sdmc:/atmosphere/contents", fs::OpenDirectoryMode_Directory))) { return; } ON_SCOPE_EXIT { fs::CloseDirectory(contents_dir); }; /* Iterate over entries in the contents directory */ fs::DirectoryEntry entry; s64 count; while (R_SUCCEEDED(fs::ReadDirectory(std::addressof(count), std::addressof(entry), contents_dir, 1)) && count == 1) { /* Check that the subdirectory can be converted to a program id. */ if (std::strlen(entry.name) == 2 * sizeof(ncm::ProgramId) && IsHexadecimal(entry.name)) { /* Check if we've already launched the program. */ ncm::ProgramId program_id{std::strtoul(entry.name, nullptr, 16)}; /* Check if the program is flagged. */ if (!cfg::HasContentSpecificFlag(program_id, "boot2")) { continue; } /* Call the iteration callback. */ f(program_id); } } } void DetectAndDeclareFutureMitms() { IterateOverFlaggedProgramsOnSdCard([](ncm::ProgramId program_id) { /* When we find a flagged program, check if it has a mitm list. */ char mitm_list[0x400]; size_t mitm_list_size = 0; /* Read the mitm list off the SD card. */ { char path[fs::EntryNameLengthMax]; util::SNPrintf(path, sizeof(path), "sdmc:/atmosphere/contents/%016" PRIx64 "/mitm.lst", static_cast<u64>(program_id)); fs::FileHandle f; if (R_FAILED(fs::OpenFile(std::addressof(f), path, fs::OpenMode_Read))) { return; } ON_SCOPE_EXIT { fs::CloseFile(f); }; R_ABORT_UNLESS(fs::ReadFile(std::addressof(mitm_list_size), f, 0, mitm_list, sizeof(mitm_list))); } /* Validate read size. */ if (mitm_list_size > sizeof(mitm_list) || mitm_list_size == 0) { return; } /* Iterate over the contents of the file. */ /* We expect one service name per non-empty line, 1-8 characters. */ size_t offset = 0; while (offset < mitm_list_size) { /* Continue to the start of the next name. */ while (IsNewLine(mitm_list[offset])) { offset++; } if (offset >= mitm_list_size) { break; } /* Get the length of the current name. */ size_t name_len; for (name_len = 0; name_len <= sizeof(sm::ServiceName) && offset + name_len < mitm_list_size; name_len++) { if (IsNewLine(mitm_list[offset + name_len])) { break; } } /* Allow empty lines. */ if (name_len == 0) { continue; } /* Don't allow invalid lines. */ AMS_ABORT_UNLESS(name_len <= sizeof(sm::ServiceName)); /* Declare the service. */ R_ABORT_UNLESS(sm::mitm::DeclareFutureMitm(sm::ServiceName::Encode(mitm_list + offset, name_len))); /* Advance to the next line. */ offset += name_len; } }); } void LaunchFlaggedProgramsOnSdCard() { IterateOverFlaggedProgramsOnSdCard([](ncm::ProgramId program_id) { /* Check if we've already launched the program. */ if (pm::info::HasLaunchedBootProgram(program_id)) { return; } /* Launch the program. */ LaunchProgram(nullptr, ncm::ProgramLocation::Make(program_id, ncm::StorageId::None), 0); }); } bool IsUsbRequiredToMountSdCard() { return hos::GetVersion() >= hos::Version_9_0_0; } } /* Boot2 API. */ void LaunchPreSdCardBootProgramsAndBoot2() { /* This code is normally run by PM. */ /* Wait until fs.mitm has installed itself. We want this to happen as early as possible. */ R_ABORT_UNLESS(sm::mitm::WaitMitm(sm::ServiceName::Encode("fsp-srv"))); /* Launch programs required to mount the SD card. */ /* psc, bus, pcv (and usb on newer firmwares) is the minimal set of required programs. */ /* bus depends on pcie, and pcv depends on settings. */ { /* Launch psc. */ LaunchProgram(nullptr, ncm::ProgramLocation::Make(ncm::SystemProgramId::Psc, ncm::StorageId::BuiltInSystem), 0); /* Launch pcie. */ LaunchProgram(nullptr, ncm::ProgramLocation::Make(ncm::SystemProgramId::Pcie, ncm::StorageId::BuiltInSystem), 0); /* Launch bus. */ LaunchProgram(nullptr, ncm::ProgramLocation::Make(ncm::SystemProgramId::Bus, ncm::StorageId::BuiltInSystem), 0); /* Launch settings. */ LaunchProgram(nullptr, ncm::ProgramLocation::Make(ncm::SystemProgramId::Settings, ncm::StorageId::BuiltInSystem), 0); /* NOTE: Here we work around a race condition in the boot process by ensuring that settings initializes its db. */ { /* Connect to set:sys. */ R_ABORT_UNLESS(::setsysInitialize()); ON_SCOPE_EXIT { ::setsysExit(); }; /* Retrieve setting from the database. */ u8 force_maintenance = 0; settings::fwdbg::GetSettingsItemValue(std::addressof(force_maintenance), sizeof(force_maintenance), "boot", "force_maintenance"); } /* Launch pcv. */ LaunchProgram(nullptr, ncm::ProgramLocation::Make(ncm::SystemProgramId::Pcv, ncm::StorageId::BuiltInSystem), 0); /* On 9.0.0+, FS depends on the USB sysmodule having been launched in order to mount the SD card. */ if (IsUsbRequiredToMountSdCard()) { LaunchProgram(nullptr, ncm::ProgramLocation::Make(ncm::SystemProgramId::Usb, ncm::StorageId::BuiltInSystem), 0); } } /* Wait for the SD card required services to be ready. */ cfg::WaitSdCardRequiredServicesReady(); /* Wait for other atmosphere mitm modules to initialize. */ R_ABORT_UNLESS(sm::mitm::WaitMitm(sm::ServiceName::Encode("set:sys"))); if (spl::GetSocType() == spl::SocType_Erista) { if (hos::GetVersion() >= hos::Version_2_0_0) { R_ABORT_UNLESS(sm::mitm::WaitMitm(sm::ServiceName::Encode("bpc"))); } else { R_ABORT_UNLESS(sm::mitm::WaitMitm(sm::ServiceName::Encode("bpc:c"))); } } /* Launch Atmosphere boot2, using NcmStorageId_None to force SD card boot. */ LaunchProgram(nullptr, ncm::ProgramLocation::Make(ncm::SystemProgramId::Boot2, ncm::StorageId::None), 0); } void LaunchPostSdCardBootPrograms() { /* This code is normally run by boot2. */ /* Launch the usb system module, if we haven't already. */ if (!IsUsbRequiredToMountSdCard()) { LaunchProgram(nullptr, ncm::ProgramLocation::Make(ncm::SystemProgramId::Usb, ncm::StorageId::BuiltInSystem), 0); } /* Activate the system fs content storage. */ R_ABORT_UNLESS(ncm::ActivateFsContentStorage(fs::ContentStorageId::System)); /* Find out whether we are maintenance mode. */ const bool maintenance = IsMaintenanceMode(); if (maintenance) { pm::bm::SetMaintenanceBoot(); } /* Check for and forward declare non-atmosphere mitm modules. */ DetectAndDeclareFutureMitms(); /* Decide whether to launch tma or htc. */ if (IsHtcEnabled()) { LaunchProgram(nullptr, ncm::ProgramLocation::Make(ncm::SystemProgramId::Htc, ncm::StorageId::None), 0); LaunchProgram(nullptr, ncm::ProgramLocation::Make(ncm::SystemProgramId::Cs, ncm::StorageId::None), 0); LaunchProgram(nullptr, ncm::ProgramLocation::Make(ncm::SystemProgramId::DmntGen2, ncm::StorageId::None), 0); } else if (IsStandaloneGdbstubEnabled()) { LaunchProgram(nullptr, ncm::ProgramLocation::Make(ncm::SystemProgramId::DmntGen2, ncm::StorageId::None), 0); LaunchProgram(nullptr, ncm::ProgramLocation::Make(ncm::SystemProgramId::Tma, ncm::StorageId::BuiltInSystem), 0); } else { LaunchProgram(nullptr, ncm::ProgramLocation::Make(ncm::SystemProgramId::Dmnt, ncm::StorageId::None), 0); LaunchProgram(nullptr, ncm::ProgramLocation::Make(ncm::SystemProgramId::Tma, ncm::StorageId::BuiltInSystem), 0); } /* Decide whether to launch atmosphere or nintendo's log manager. */ if (IsAtmosphereLogManagerEnabled()) { LaunchProgram(nullptr, ncm::ProgramLocation::Make(ncm::AtmosphereProgramId::AtmosphereLogManager, ncm::StorageId::None), 0); } else { LaunchProgram(nullptr, ncm::ProgramLocation::Make(ncm::SystemProgramId::LogManager, ncm::StorageId::BuiltInSystem), 0); } /* Launch additional programs. */ if (maintenance) { LaunchList(AdditionalMaintenanceLaunchPrograms, NumAdditionalMaintenanceLaunchPrograms); /* Starting in 7.0.0, npns is launched during maintenance boot. */ if (hos::GetVersion() >= hos::Version_7_0_0) { LaunchProgram(nullptr, ncm::ProgramLocation::Make(ncm::SystemProgramId::Npns, ncm::StorageId::BuiltInSystem), 0); } } else { LaunchList(AdditionalLaunchPrograms, NumAdditionalLaunchPrograms); } /* Prior to 12.0.0, boot2 was responsible for launching grc and migration. */ if (hos::GetVersion() < hos::Version_12_0_0) { LaunchProgram(nullptr, ncm::ProgramLocation::Make(ncm::SystemProgramId::Grc, ncm::StorageId::BuiltInSystem), 0); LaunchProgram(nullptr, ncm::ProgramLocation::Make(ncm::SystemProgramId::Migration, ncm::StorageId::BuiltInSystem), 0); } /* Launch user programs off of the SD. */ LaunchFlaggedProgramsOnSdCard(); } }
21,448
C++
.cpp
389
42.012853
149
0.555953
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,693
os_sdk_recursive_mutex.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/os_sdk_recursive_mutex.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #if !defined(AMS_OS_INTERNAL_CRITICAL_SECTION_IMPL_CAN_CHECK_LOCKED_BY_CURRENT_THREAD) #include "impl/os_thread_manager.hpp" #endif namespace ams::os { void InitializeSdkRecursiveMutex(SdkRecursiveMutexType *rmutex) { /* Initialize the critical section. */ GetReference(rmutex->_storage).Initialize(); /* Set recursive count. */ rmutex->recursive_count = 0; /* If the underlying critical section can't readily be checked, set owner thread. */ #if !defined(AMS_OS_INTERNAL_CRITICAL_SECTION_IMPL_CAN_CHECK_LOCKED_BY_CURRENT_THREAD) rmutex->owner_thread = nullptr; #endif } bool IsSdkRecursiveMutexLockedByCurrentThread(const SdkRecursiveMutexType *rmutex) { #if defined(AMS_OS_INTERNAL_CRITICAL_SECTION_IMPL_CAN_CHECK_LOCKED_BY_CURRENT_THREAD) /* Check whether the critical section is held. */ return GetReference(rmutex->_storage).IsLockedByCurrentThread(); #else /* Check if the current thread is owner. */ return rmutex->owner_thread == os::impl::GetCurrentThread(); #endif } void LockSdkRecursiveMutex(SdkRecursiveMutexType *rmutex) { /* If we don't hold the mutex, enter the critical section. */ if (!IsSdkRecursiveMutexLockedByCurrentThread(rmutex)) { GetReference(rmutex->_storage).Enter(); /* If necessary, set owner thread. */ #if !defined(AMS_OS_INTERNAL_CRITICAL_SECTION_IMPL_CAN_CHECK_LOCKED_BY_CURRENT_THREAD) rmutex->owner_thread = os::impl::GetCurrentThread(); #endif } /* Increment (and check) recursive count. */ ++rmutex->recursive_count; AMS_ABORT_UNLESS(rmutex->recursive_count != 0); } bool TryLockSdkRecursiveMutex(SdkRecursiveMutexType *rmutex) { /* If we don't hold the mutex, try to enter the critical section. */ if (!IsSdkRecursiveMutexLockedByCurrentThread(rmutex)) { if (!GetReference(rmutex->_storage).TryEnter()) { return false; } /* If necessary, set owner thread. */ #if !defined(AMS_OS_INTERNAL_CRITICAL_SECTION_IMPL_CAN_CHECK_LOCKED_BY_CURRENT_THREAD) rmutex->owner_thread = os::impl::GetCurrentThread(); #endif } /* Increment (and check) recursive count. */ ++rmutex->recursive_count; AMS_ABORT_UNLESS(rmutex->recursive_count != 0); return true; } void UnlockSdkRecursiveMutex(SdkRecursiveMutexType *rmutex) { /* Check pre-conditions. */ AMS_ABORT_UNLESS(IsSdkRecursiveMutexLockedByCurrentThread(rmutex)); /* Decrement recursive count, and leave critical section if we no longer hold the mutex. */ if ((--rmutex->recursive_count) == 0) { /* If necessary, clear owner thread. */ #if !defined(AMS_OS_INTERNAL_CRITICAL_SECTION_IMPL_CAN_CHECK_LOCKED_BY_CURRENT_THREAD) rmutex->owner_thread = nullptr; #endif GetReference(rmutex->_storage).Leave(); } } }
3,775
C++
.cpp
81
38.91358
99
0.669386
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,694
os_transfer_memory.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/os_transfer_memory.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "impl/os_thread_manager.hpp" #include "impl/os_transfer_memory_impl.hpp" namespace ams::os { namespace { inline void SetupTransferMemoryType(TransferMemoryType *tmem, size_t size, NativeHandle handle, bool managed) { /* Set members. */ tmem->handle = handle; tmem->size = size; tmem->address = nullptr; tmem->allocated = false; /* Set managed. */ tmem->handle_managed = managed; /* Create the critical section. */ util::ConstructAt(tmem->cs_transfer_memory); } } Result CreateTransferMemory(TransferMemoryType *tmem, void *address, size_t size, MemoryPermission perm) { /* Validate pre-conditions. */ AMS_ASSERT(size > 0); AMS_ASSERT(util::IsAligned(size, os::MemoryPageSize)); AMS_ASSERT(address != nullptr); AMS_ASSERT(util::IsAligned(reinterpret_cast<uintptr_t>(address), os::MemoryPageSize)); /* Create the memory. */ NativeHandle handle; R_TRY(impl::TransferMemoryImpl::Create(std::addressof(handle), address, size, perm)); /* Setup the object. */ SetupTransferMemoryType(tmem, size, handle, true); R_SUCCEED(); } void AttachTransferMemory(TransferMemoryType *tmem, size_t size, NativeHandle handle, bool managed) { AMS_ASSERT(size > 0); AMS_ASSERT(util::IsAligned(size, os::MemoryPageSize)); AMS_ASSERT(handle != os::InvalidNativeHandle); /* Setup the object. */ SetupTransferMemoryType(tmem, size, handle, managed); } NativeHandle DetachTransferMemory(TransferMemoryType *tmem) { AMS_ASSERT(tmem->state == TransferMemoryType::State_Created); /* Set state to detached. */ tmem->state = TransferMemoryType::State_Detached; /* Clear handle. */ const NativeHandle handle = tmem->handle; tmem->handle = os::InvalidNativeHandle; tmem->handle_managed = false; return handle; } void DestroyTransferMemory(TransferMemoryType *tmem) { /* Unmap the transfer memory, if required. */ if (tmem->state == TransferMemoryType::State_Mapped) { UnmapTransferMemory(tmem); } /* Check the state is valid. */ AMS_ASSERT(tmem->state == TransferMemoryType::State_Created || tmem->state == TransferMemoryType::State_Detached); /* Set state to not initialized. */ tmem->state = TransferMemoryType::State_NotInitialized; /* Close the handle, if it's managed. */ if (tmem->handle_managed) { impl::TransferMemoryImpl::Close(tmem->handle); } tmem->handle_managed = false; /* Clear members. */ tmem->address = nullptr; tmem->size = 0; tmem->handle = os::InvalidNativeHandle; /* Destroy the critical section. */ util::DestroyAt(tmem->cs_transfer_memory); } Result MapTransferMemory(void **out, TransferMemoryType *tmem, MemoryPermission owner_perm) { /* Lock the current thread, and then the transfer memory. */ std::scoped_lock thread_lk(GetReference(impl::GetCurrentThread()->cs_thread)); std::scoped_lock lk(GetReference(tmem->cs_transfer_memory)); /* Ensure we're in a mappable state. */ AMS_ASSERT(tmem->state == TransferMemoryType::State_Created); /* Map. */ void *mapped_address; R_TRY(impl::TransferMemoryImpl::Map(std::addressof(mapped_address), tmem->handle, tmem->size, owner_perm)); /* Set fields now that we've mapped. */ tmem->allocated = true; tmem->address = mapped_address; tmem->state = TransferMemoryType::State_Mapped; /* Set output address. */ *out = mapped_address; R_SUCCEED(); } void UnmapTransferMemory(TransferMemoryType *tmem) { /* Lock the memory. */ std::scoped_lock lk(GetReference(tmem->cs_transfer_memory)); /* If the memory isn't mapped, we can't unmap it. */ if (tmem->state != TransferMemoryType::State_Mapped) { return; } /* Unmap the memory. */ impl::TransferMemoryImpl::Unmap(tmem->handle, tmem->address, tmem->size); /* Unmapped memory is necessarily not allocated. */ if (tmem->allocated) { tmem->allocated = false; } /* Clear the address. */ tmem->address = nullptr; tmem->state = TransferMemoryType::State_Created; } }
5,253
C++
.cpp
118
36.491525
122
0.638627
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,695
os_condition_variable.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/os_condition_variable.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "impl/os_thread_manager.hpp" #include "impl/os_timeout_helper.hpp" #include "impl/os_mutex_impl.hpp" namespace ams::os { void InitializeConditionVariable(ConditionVariableType *cv) { /* Construct object. */ util::ConstructAt(cv->_storage); /* Mark initialized. */ cv->state = ConditionVariableType::State_Initialized; } void FinalizeConditionVariable(ConditionVariableType *cv) { AMS_ASSERT(cv->state == ConditionVariableType::State_Initialized); /* Mark not initialized. */ cv->state = ConditionVariableType::State_NotInitialized; /* Destroy objects. */ util::DestroyAt(cv->_storage); } void SignalConditionVariable(ConditionVariableType *cv) { AMS_ASSERT(cv->state == ConditionVariableType::State_Initialized); GetReference(cv->_storage).Signal(); } void BroadcastConditionVariable(ConditionVariableType *cv) { AMS_ASSERT(cv->state == ConditionVariableType::State_Initialized); GetReference(cv->_storage).Broadcast(); } void WaitConditionVariable(ConditionVariableType *cv, MutexType *m) { AMS_ASSERT(cv->state == ConditionVariableType::State_Initialized); AMS_ASSERT(m->state == MutexType::State_Initialized); AMS_ASSERT(m->owner_thread == impl::GetCurrentThread()); AMS_ASSERT(m->nest_count == 1); impl::PopAndCheckLockLevel(m); if ((--m->nest_count) == 0) { m->owner_thread = nullptr; } GetReference(cv->_storage).Wait(GetPointer(m->_storage)); impl::PushAndCheckLockLevel(m); ++m->nest_count; m->owner_thread = impl::GetCurrentThread(); } ConditionVariableStatus TimedWaitConditionVariable(ConditionVariableType *cv, MutexType *m, TimeSpan timeout) { AMS_ASSERT(cv->state == ConditionVariableType::State_Initialized); AMS_ASSERT(m->state == MutexType::State_Initialized); AMS_ASSERT(m->owner_thread == impl::GetCurrentThread()); AMS_ASSERT(m->nest_count == 1); AMS_ASSERT(timeout.GetNanoSeconds() >= 0); impl::PopAndCheckLockLevel(m); if ((--m->nest_count) == 0) { m->owner_thread = nullptr; } ConditionVariableStatus status; if (timeout == TimeSpan(0)) { GetReference(m->_storage).Leave(); GetReference(m->_storage).Enter(); status = ConditionVariableStatus::TimedOut; } else { impl::TimeoutHelper timeout_helper(timeout); status = GetReference(cv->_storage).TimedWait(GetPointer(m->_storage), timeout_helper); } impl::PushAndCheckLockLevel(m); ++m->nest_count; m->owner_thread = impl::GetCurrentThread(); return status; } }
3,501
C++
.cpp
80
36.6
115
0.663819
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,696
os_multiple_wait.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/os_multiple_wait.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "impl/os_multiple_wait_impl.hpp" #include "impl/os_multiple_wait_holder_base.hpp" #include "impl/os_multiple_wait_holder_impl.hpp" namespace ams::os { namespace { ALWAYS_INLINE impl::MultiWaitImpl &GetMultiWaitImpl(MultiWaitType *multi_wait) { return GetReference(multi_wait->impl_storage); } ALWAYS_INLINE MultiWaitHolderType *CastToMultiWaitHolder(impl::MultiWaitHolderBase *base) { return reinterpret_cast<MultiWaitHolderType *>(base); } } void InitializeMultiWait(MultiWaitType *multi_wait) { /* Initialize storage. */ util::ConstructAt(multi_wait->impl_storage); /* Mark initialized. */ multi_wait->state = MultiWaitType::State_Initialized; } void FinalizeMultiWait(MultiWaitType *multi_wait) { auto &impl = GetMultiWaitImpl(multi_wait); AMS_ASSERT(multi_wait->state == MultiWaitType::State_Initialized); AMS_ASSERT(impl.IsListEmpty()); AMS_UNUSED(impl); /* Mark not initialized. */ multi_wait->state = MultiWaitType::State_NotInitialized; /* Destroy. */ util::DestroyAt(multi_wait->impl_storage); } MultiWaitHolderType *WaitAny(MultiWaitType *multi_wait) { auto &impl = GetMultiWaitImpl(multi_wait); AMS_ASSERT(multi_wait->state == MultiWaitType::State_Initialized); AMS_ASSERT(impl.IsListNotEmpty()); auto *holder = CastToMultiWaitHolder(impl.WaitAny()); AMS_ASSERT(holder != nullptr); return holder; } MultiWaitHolderType *TryWaitAny(MultiWaitType *multi_wait) { auto &impl = GetMultiWaitImpl(multi_wait); AMS_ASSERT(multi_wait->state == MultiWaitType::State_Initialized); AMS_ASSERT(impl.IsListNotEmpty()); auto *holder = CastToMultiWaitHolder(impl.TryWaitAny()); return holder; } MultiWaitHolderType *TimedWaitAny(MultiWaitType *multi_wait, TimeSpan timeout) { auto &impl = GetMultiWaitImpl(multi_wait); AMS_ASSERT(multi_wait->state == MultiWaitType::State_Initialized); AMS_ASSERT(impl.IsListNotEmpty()); AMS_ASSERT(timeout.GetNanoSeconds() >= 0); auto *holder = CastToMultiWaitHolder(impl.TimedWaitAny(timeout)); return holder; } void FinalizeMultiWaitHolder(MultiWaitHolderType *holder) { auto *holder_base = reinterpret_cast<impl::MultiWaitHolderBase *>(GetPointer(holder->impl_storage)); AMS_ASSERT(holder_base->IsNotLinked()); /* Destroy. */ static_assert(std::is_trivially_destructible<impl::MultiWaitHolderBase>::value); /* std::destroy_at(holder_base); */ AMS_UNUSED(holder_base); } void LinkMultiWaitHolder(MultiWaitType *multi_wait, MultiWaitHolderType *holder) { auto &impl = GetMultiWaitImpl(multi_wait); auto *holder_base = reinterpret_cast<impl::MultiWaitHolderBase *>(GetPointer(holder->impl_storage)); AMS_ASSERT(multi_wait->state == MultiWaitType::State_Initialized); AMS_ASSERT(holder_base->IsNotLinked()); impl.PushBackToList(*holder_base); holder_base->SetMultiWait(std::addressof(impl)); } void UnlinkMultiWaitHolder(MultiWaitHolderType *holder) { auto *holder_base = reinterpret_cast<impl::MultiWaitHolderBase *>(GetPointer(holder->impl_storage)); /* Don't allow unlinking of an unlinked holder. */ AMS_ABORT_UNLESS(holder_base->IsLinked()); holder_base->GetMultiWait()->EraseFromList(*holder_base); holder_base->SetMultiWait(nullptr); } void UnlinkAllMultiWaitHolder(MultiWaitType *multi_wait) { auto &impl = GetMultiWaitImpl(multi_wait); AMS_ASSERT(multi_wait->state == MultiWaitType::State_Initialized); return impl.EraseAllFromList(); } void MoveAllMultiWaitHolder(MultiWaitType *_dst, MultiWaitType *_src) { auto &dst = GetMultiWaitImpl(_dst); auto &src = GetMultiWaitImpl(_src); AMS_ASSERT(_dst->state == MultiWaitType::State_Initialized); AMS_ASSERT(_src->state == MultiWaitType::State_Initialized); return dst.MoveAllFromOther(src); } void SetMultiWaitHolderUserData(MultiWaitHolderType *holder, uintptr_t user_data) { holder->user_data = user_data; } uintptr_t GetMultiWaitHolderUserData(const MultiWaitHolderType *holder) { return holder->user_data; } void InitializeMultiWaitHolder(MultiWaitHolderType *holder, NativeHandle handle) { AMS_ASSERT(handle != os::InvalidNativeHandle); util::ConstructAt(GetReference(holder->impl_storage).holder_of_native_handle_storage, handle); holder->user_data = 0; } }
5,400
C++
.cpp
114
40.27193
108
0.696092
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,697
os_virtual_address_memory.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/os_virtual_address_memory.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "impl/os_vamm_manager.hpp" namespace ams::os { void InitializeVirtualAddressMemory() { return impl::GetVammManager().InitializeIfEnabled(); } Result AllocateAddressRegion(uintptr_t *out, size_t size) { AMS_ASSERT(size > 0); AMS_ASSERT(util::IsAligned(size, MemoryPageSize)); R_RETURN(impl::GetVammManager().AllocateAddressRegion(out, size)); } Result AllocateMemory(uintptr_t *out, size_t size) { AMS_ASSERT(size > 0); AMS_ASSERT(util::IsAligned(size, MemoryPageSize)); R_RETURN(impl::GetVammManager().AllocateMemory(out, size)); } Result AllocateMemoryPages(uintptr_t address, size_t size) { AMS_ASSERT(size > 0); AMS_ASSERT(util::IsAligned(size, MemoryPageSize)); AMS_ASSERT(util::IsAligned(address, MemoryPageSize)); R_RETURN(impl::GetVammManager().AllocateMemoryPages(address, size)); } Result FreeAddressRegion(uintptr_t address) { R_RETURN(impl::GetVammManager().FreeAddressRegion(address)); } Result FreeMemoryPages(uintptr_t address, size_t size) { AMS_ASSERT(size > 0); AMS_ASSERT(util::IsAligned(size, MemoryPageSize)); AMS_ASSERT(util::IsAligned(address, MemoryPageSize)); R_RETURN(impl::GetVammManager().FreeMemoryPages(address, size)); } VirtualAddressMemoryResourceUsage GetVirtualAddressMemoryResourceUsage() { return impl::GetVammManager().GetVirtualAddressMemoryResourceUsage(); } bool IsVirtualAddressMemoryEnabled() { return impl::VammManager::IsVirtualAddressMemoryEnabled(); } }
2,294
C++
.cpp
53
37.830189
78
0.716659
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,698
os_barrier.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/os_barrier.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> namespace ams::os { namespace { ALWAYS_INLINE bool IsBarrierInitialized(const BarrierType *barrier) { return barrier->max_threads != 0; } ALWAYS_INLINE u64 GetBarrierBaseCounterImpl(const BarrierType *barrier) { /* Check pre-conditions. */ #if defined(AMS_OS_INTERNAL_CRITICAL_SECTION_IMPL_CAN_CHECK_LOCKED_BY_CURRENT_THREAD) AMS_ASSERT(util::GetReference(barrier->cs_barrier).IsLockedByCurrentThread()); #endif /* Convert two u32s to u64. */ return (static_cast<u64>(barrier->base_counter_lower) << 0) | (static_cast<u64>(barrier->base_counter_upper) << BITSIZEOF(barrier->base_counter_lower)); } ALWAYS_INLINE void SetBarrierBaseCounterImpl(BarrierType *barrier, u64 value) { /* Check pre-conditions. */ #if defined(AMS_OS_INTERNAL_CRITICAL_SECTION_IMPL_CAN_CHECK_LOCKED_BY_CURRENT_THREAD) AMS_ASSERT(util::GetReference(barrier->cs_barrier).IsLockedByCurrentThread()); #endif /* Store as two u32s. */ barrier->base_counter_lower = static_cast<u32>(value >> 0); barrier->base_counter_upper = static_cast<u32>(value >> BITSIZEOF(barrier->base_counter_lower)); } } void InitializeBarrier(BarrierType *barrier, int num_threads) { /* Check pre-conditions. */ AMS_ASSERT(num_threads >= 1); /* Construct objects. */ util::ConstructAt(barrier->cs_barrier); util::ConstructAt(barrier->cv_gathered); /* Set member variables. */ barrier->max_threads = num_threads; barrier->waiting_threads = 0; barrier->base_counter_lower = 0; barrier->base_counter_upper = 0; } void FinalizeBarrier(BarrierType *barrier) { /* Check pre-conditions. */ AMS_ASSERT(IsBarrierInitialized(barrier)); AMS_ASSERT(barrier->waiting_threads == 0); /* Clear max threads. */ barrier->max_threads = 0; /* Destroy objects. */ util::DestroyAt(barrier->cs_barrier); util::DestroyAt(barrier->cv_gathered); } void AwaitBarrier(BarrierType *barrier) { /* Check pre-conditions. */ AMS_ASSERT(IsBarrierInitialized(barrier)); /* Await the barrier. */ { /* Acquire exclusive access to the barrier. */ auto &cs = util::GetReference(barrier->cs_barrier); std::scoped_lock lk(cs); /* Read barrier state. */ const u64 base_counter = GetBarrierBaseCounterImpl(barrier); const auto max_threads = barrier->max_threads; auto waiting_threads = barrier->waiting_threads; /* Determine next base counter. */ const u64 done_base_counter = base_counter + max_threads; /* Increment waiting threads. */ ++waiting_threads; /* Check if all threads have synchronized. */ if (waiting_threads >= max_threads) { /* They have, so reset waiting thread count. */ barrier->waiting_threads = 0; /* Set the updated base counter. */ SetBarrierBaseCounterImpl(barrier, done_base_counter); /* Broadcast to our cv. */ util::GetReference(barrier->cv_gathered).Broadcast(); } else { /* More threads are needed, so update waiting thread count. */ barrier->waiting_threads = waiting_threads; /* Wait for remaining threads to await. */ while (GetBarrierBaseCounterImpl(barrier) < done_base_counter) { util::GetReference(barrier->cv_gathered).Wait(std::addressof(cs)); } } } } }
4,512
C++
.cpp
96
37.125
164
0.617486
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,699
os_semaphore.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/os_semaphore.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "impl/os_multiple_wait_object_list.hpp" #include "impl/os_multiple_wait_holder_impl.hpp" #include "impl/os_timeout_helper.hpp" namespace ams::os { void InitializeSemaphore(SemaphoreType *sema, s32 count, s32 max_count) { AMS_ASSERT(max_count >= 1); AMS_ASSERT(0 <= count && count <= max_count); /* Setup objects. */ util::ConstructAt(sema->cs_sema); util::ConstructAt(sema->cv_not_zero); /* Setup wait lists. */ util::ConstructAt(sema->waitlist); /* Set member variables. */ sema->count = count; sema->max_count = max_count; /* Mark initialized. */ sema->state = SemaphoreType::State_Initialized; } void FinalizeSemaphore(SemaphoreType *sema) { AMS_ASSERT(sema->state == SemaphoreType::State_Initialized); AMS_ASSERT(GetReference(sema->waitlist).IsEmpty()); /* Mark uninitialized. */ sema->state = SemaphoreType::State_NotInitialized; /* Destroy wait lists. */ util::DestroyAt(sema->waitlist); /* Destroy objects. */ util::DestroyAt(sema->cv_not_zero); util::DestroyAt(sema->cs_sema); } void AcquireSemaphore(SemaphoreType *sema) { AMS_ASSERT(sema->state == SemaphoreType::State_Initialized); { std::scoped_lock lk(GetReference(sema->cs_sema)); while (sema->count == 0) { GetReference(sema->cv_not_zero).Wait(GetPointer(sema->cs_sema)); } --sema->count; } } bool TryAcquireSemaphore(SemaphoreType *sema) { AMS_ASSERT(sema->state == SemaphoreType::State_Initialized); { std::scoped_lock lk(GetReference(sema->cs_sema)); if (sema->count == 0) { return false; } --sema->count; } return true; } bool TimedAcquireSemaphore(SemaphoreType *sema, TimeSpan timeout) { AMS_ASSERT(sema->state == SemaphoreType::State_Initialized); AMS_ASSERT(timeout.GetNanoSeconds() >= 0); { impl::TimeoutHelper timeout_helper(timeout); std::scoped_lock lk(GetReference(sema->cs_sema)); while (sema->count == 0) { if (timeout_helper.TimedOut()) { return false; } GetReference(sema->cv_not_zero).TimedWait(GetPointer(sema->cs_sema), timeout_helper); } --sema->count; } return true; } void ReleaseSemaphore(SemaphoreType *sema) { AMS_ASSERT(sema->state == SemaphoreType::State_Initialized); { std::scoped_lock lk(GetReference(sema->cs_sema)); AMS_ASSERT(sema->count + 1 <= sema->max_count); ++sema->count; GetReference(sema->cv_not_zero).Signal(); GetReference(sema->waitlist).WakeupAllMultiWaitThreadsUnsafe(); } } void ReleaseSemaphore(SemaphoreType *sema, s32 count) { AMS_ASSERT(sema->state == SemaphoreType::State_Initialized); { std::scoped_lock lk(GetReference(sema->cs_sema)); AMS_ASSERT(sema->count + count <= sema->max_count); sema->count += count; GetReference(sema->cv_not_zero).Broadcast(); GetReference(sema->waitlist).WakeupAllMultiWaitThreadsUnsafe(); } } s32 GetCurrentSemaphoreCount(const SemaphoreType *sema) { AMS_ASSERT(sema->state == SemaphoreType::State_Initialized); return sema->count; } void InitializeMultiWaitHolder(MultiWaitHolderType *multi_wait_holder, SemaphoreType *sema) { AMS_ASSERT(sema->state == SemaphoreType::State_Initialized); util::ConstructAt(GetReference(multi_wait_holder->impl_storage).holder_of_semaphore_storage, sema); multi_wait_holder->user_data = 0; } }
4,594
C++
.cpp
112
32.383929
107
0.624634
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,700
os_system_event.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/os_system_event.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "impl/os_multiple_wait_holder_impl.hpp" #include "impl/os_inter_process_event.hpp" #include "impl/os_timeout_helper.hpp" namespace ams::os { Result CreateSystemEvent(SystemEventType *event, EventClearMode clear_mode, bool inter_process) { if (inter_process) { R_TRY(impl::CreateInterProcessEvent(std::addressof(event->inter_process_event), clear_mode)); event->state = SystemEventType::State_InitializedAsInterProcessEvent; } else { InitializeEvent(std::addressof(event->event), false, clear_mode); event->state = SystemEventType::State_InitializedAsEvent; } R_SUCCEED(); } void DestroySystemEvent(SystemEventType *event) { auto state = event->state; event->state = SystemEventType::State_NotInitialized; switch (state) { case SystemEventType::State_InitializedAsInterProcessEvent: impl::DestroyInterProcessEvent(std::addressof(event->inter_process_event)); break; case SystemEventType::State_InitializedAsEvent: FinalizeEvent(std::addressof(event->event)); break; AMS_UNREACHABLE_DEFAULT_CASE(); } } void AttachSystemEvent(SystemEventType *event, NativeHandle read_handle, bool read_handle_managed, NativeHandle write_handle, bool write_handle_managed, EventClearMode clear_mode) { AMS_ASSERT(read_handle != os::InvalidNativeHandle || write_handle != os::InvalidNativeHandle); impl::AttachInterProcessEvent(std::addressof(event->inter_process_event), read_handle, read_handle_managed, write_handle, write_handle_managed, clear_mode); event->state = SystemEventType::State_InitializedAsInterProcessEvent; } void AttachReadableHandleToSystemEvent(SystemEventType *event, NativeHandle read_handle, bool manage_read_handle, EventClearMode clear_mode) { return AttachSystemEvent(event, read_handle, manage_read_handle, os::InvalidNativeHandle, false, clear_mode); } void AttachWritableHandleToSystemEvent(SystemEventType *event, NativeHandle write_handle, bool manage_write_handle, EventClearMode clear_mode) { return AttachSystemEvent(event, os::InvalidNativeHandle, false, write_handle, manage_write_handle, clear_mode); } NativeHandle DetachReadableHandleOfSystemEvent(SystemEventType *event) { AMS_ASSERT(event->state == SystemEventType::State_InitializedAsInterProcessEvent); return impl::DetachReadableHandleOfInterProcessEvent(std::addressof(event->inter_process_event)); } NativeHandle DetachWritableHandleOfSystemEvent(SystemEventType *event) { AMS_ASSERT(event->state == SystemEventType::State_InitializedAsInterProcessEvent); return impl::DetachWritableHandleOfInterProcessEvent(std::addressof(event->inter_process_event)); } NativeHandle GetReadableHandleOfSystemEvent(const SystemEventType *event) { AMS_ASSERT(event->state == SystemEventType::State_InitializedAsInterProcessEvent); return impl::GetReadableHandleOfInterProcessEvent(std::addressof(event->inter_process_event)); } NativeHandle GetWritableHandleOfSystemEvent(const SystemEventType *event) { AMS_ASSERT(event->state == SystemEventType::State_InitializedAsInterProcessEvent); return impl::GetWritableHandleOfInterProcessEvent(std::addressof(event->inter_process_event)); } void SignalSystemEvent(SystemEventType *event) { switch (event->state) { case SystemEventType::State_InitializedAsInterProcessEvent: return impl::SignalInterProcessEvent(std::addressof(event->inter_process_event)); case SystemEventType::State_InitializedAsEvent: return SignalEvent(std::addressof(event->event)); AMS_UNREACHABLE_DEFAULT_CASE(); } } void WaitSystemEvent(SystemEventType *event) { switch (event->state) { case SystemEventType::State_InitializedAsInterProcessEvent: return impl::WaitInterProcessEvent(std::addressof(event->inter_process_event)); case SystemEventType::State_InitializedAsEvent: return WaitEvent(std::addressof(event->event)); AMS_UNREACHABLE_DEFAULT_CASE(); } } bool TryWaitSystemEvent(SystemEventType *event) { switch (event->state) { case SystemEventType::State_InitializedAsInterProcessEvent: return impl::TryWaitInterProcessEvent(std::addressof(event->inter_process_event)); case SystemEventType::State_InitializedAsEvent: return TryWaitEvent(std::addressof(event->event)); AMS_UNREACHABLE_DEFAULT_CASE(); } } bool TimedWaitSystemEvent(SystemEventType *event, TimeSpan timeout) { AMS_ASSERT(timeout.GetNanoSeconds() >= 0); switch (event->state) { case SystemEventType::State_InitializedAsInterProcessEvent: return impl::TimedWaitInterProcessEvent(std::addressof(event->inter_process_event), timeout); case SystemEventType::State_InitializedAsEvent: return TimedWaitEvent(std::addressof(event->event), timeout); AMS_UNREACHABLE_DEFAULT_CASE(); } } void ClearSystemEvent(SystemEventType *event) { switch (event->state) { case SystemEventType::State_InitializedAsInterProcessEvent: return impl::ClearInterProcessEvent(std::addressof(event->inter_process_event)); case SystemEventType::State_InitializedAsEvent: return ClearEvent(std::addressof(event->event)); AMS_UNREACHABLE_DEFAULT_CASE(); } } void InitializeMultiWaitHolder(MultiWaitHolderType *multi_wait_holder, SystemEventType *event) { switch (event->state) { case SystemEventType::State_InitializedAsInterProcessEvent: util::ConstructAt(GetReference(multi_wait_holder->impl_storage).holder_of_inter_process_event_storage, std::addressof(event->inter_process_event)); break; case SystemEventType::State_InitializedAsEvent: util::ConstructAt(GetReference(multi_wait_holder->impl_storage).holder_of_event_storage, std::addressof(event->event)); break; AMS_UNREACHABLE_DEFAULT_CASE(); } } }
6,941
C++
.cpp
114
52.95614
185
0.722638
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,701
os_tick.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/os_tick.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "impl/os_tick_manager.hpp" namespace ams::os { Tick GetSystemTick() { return impl::GetTickManager().GetTick(); } Tick GetSystemTickOrdered() { return impl::GetTickManager().GetSystemTickOrdered(); } s64 GetSystemTickFrequency() { return impl::GetTickManager().GetTickFrequency(); } TimeSpan ConvertToTimeSpan(Tick tick) { return impl::GetTickManager().ConvertToTimeSpan(tick); } Tick ConvertToTick(TimeSpan ts) { return impl::GetTickManager().ConvertToTick(ts); } }
1,225
C++
.cpp
34
32.058824
76
0.723818
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,702
os_rw_lock.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/os_rw_lock.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "impl/os_thread_manager.hpp" #include "impl/os_rw_lock_impl.hpp" namespace ams::os { void InitalizeReaderWriterLock(ReaderWriterLockType *rw_lock) { /* Create objects. */ util::ConstructAt(impl::GetLockCount(rw_lock).cs_storage); util::ConstructAt(rw_lock->cv_read_lock._storage); util::ConstructAt(rw_lock->cv_write_lock._storage); /* Set member variables. */ impl::ClearReadLockCount(impl::GetLockCount(rw_lock)); impl::ClearWriteLocked(impl::GetLockCount(rw_lock)); impl::ClearReadLockWaiterCount(impl::GetLockCount(rw_lock)); impl::ClearWriteLockWaiterCount(impl::GetLockCount(rw_lock)); impl::ClearWriteLockCount(rw_lock); rw_lock->owner_thread = nullptr; /* Mark initialized. */ rw_lock->state = ReaderWriterLockType::State_Initialized; } void FinalizeReaderWriterLock(ReaderWriterLockType *rw_lock) { AMS_ASSERT(rw_lock->state == ReaderWriterLockType::State_Initialized); /* Don't allow finalizing a locked lock. */ AMS_ASSERT(impl::GetReadLockCount(impl::GetLockCount(rw_lock)) == 0); AMS_ASSERT(impl::GetWriteLocked(impl::GetLockCount(rw_lock)) == 0); /* Mark not initialized. */ rw_lock->state = ReaderWriterLockType::State_NotInitialized; /* Destroy objects. */ util::DestroyAt(rw_lock->cv_write_lock._storage); util::DestroyAt(rw_lock->cv_read_lock._storage); util::DestroyAt(impl::GetLockCount(rw_lock).cs_storage); } void AcquireReadLock(ReaderWriterLockType *rw_lock) { AMS_ASSERT(rw_lock->state == ReaderWriterLockType::State_Initialized); return impl::ReaderWriterLockImpl::AcquireReadLock(rw_lock); } bool TryAcquireReadLock(ReaderWriterLockType *rw_lock) { AMS_ASSERT(rw_lock->state == ReaderWriterLockType::State_Initialized); return impl::ReaderWriterLockImpl::TryAcquireReadLock(rw_lock); } void ReleaseReadLock(ReaderWriterLockType *rw_lock) { AMS_ASSERT(rw_lock->state == ReaderWriterLockType::State_Initialized); return impl::ReaderWriterLockImpl::ReleaseReadLock(rw_lock); } void AcquireWriteLock(ReaderWriterLockType *rw_lock) { AMS_ASSERT(rw_lock->state == ReaderWriterLockType::State_Initialized); return impl::ReaderWriterLockImpl::AcquireWriteLock(rw_lock); } bool TryAcquireWriteLock(ReaderWriterLockType *rw_lock) { AMS_ASSERT(rw_lock->state == ReaderWriterLockType::State_Initialized); return impl::ReaderWriterLockImpl::TryAcquireWriteLock(rw_lock); } void ReleaseWriteLock(ReaderWriterLockType *rw_lock) { AMS_ASSERT(rw_lock->state == ReaderWriterLockType::State_Initialized); AMS_ABORT_UNLESS(rw_lock->owner_thread == impl::GetCurrentThread()); return impl::ReaderWriterLockImpl::ReleaseWriteLock(rw_lock); } bool IsReadLockHeld(const ReaderWriterLockType *rw_lock) { AMS_ASSERT(rw_lock->state == ReaderWriterLockType::State_Initialized); return impl::GetReadLockCount(impl::GetLockCount(rw_lock)) != 0; } bool IsWriteLockHeldByCurrentThread(const ReaderWriterLockType *rw_lock) { AMS_ASSERT(rw_lock->state == ReaderWriterLockType::State_Initialized); return rw_lock->owner_thread == impl::GetCurrentThread() && impl::GetWriteLockCount(*rw_lock) != 0; } bool IsReaderWriterLockOwnerThread(const ReaderWriterLockType *rw_lock) { AMS_ASSERT(rw_lock->state == ReaderWriterLockType::State_Initialized); return rw_lock->owner_thread == impl::GetCurrentThread(); } }
4,314
C++
.cpp
84
44.928571
107
0.712726
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,703
os_sdk_thread_local_storage_api.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/os_sdk_thread_local_storage_api.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "impl/os_tls_manager.hpp" namespace ams::os { #if defined(ATMOSPHERE_OS_HORIZON) /* TODO: Nintendo reserves half the TLS slots for SDK usage. */ /* We don't have that ability...how should this work? */ Result SdkAllocateTlsSlot(TlsSlot *out, TlsDestructor destructor) { R_RETURN(os::AllocateTlsSlot(out, destructor)); } #else Result SdkAllocateTlsSlot(TlsSlot *out, TlsDestructor destructor) { R_UNLESS(impl::GetTlsManager().AllocateTlsSlot(out, destructor, true), os::ResultOutOfResource()); R_SUCCEED(); } #endif }
1,252
C++
.cpp
31
36.903226
106
0.729064
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,704
os_rw_busy_mutex.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/os_rw_busy_mutex.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "impl/os_thread_manager.hpp" #if defined(ATMOSPHERE_OS_HORIZON) #include "impl/os_internal_rw_busy_mutex_impl.os.horizon.hpp" #elif defined(ATMOSPHERE_OS_WINDOWS) #include "impl/os_internal_rw_busy_mutex_impl.os.windows.hpp" #elif defined(ATMOSPHERE_OS_LINUX) #include "impl/os_internal_rw_busy_mutex_impl.os.linux.hpp" #elif defined(ATMOSPHERE_OS_MACOS) #include "impl/os_internal_rw_busy_mutex_impl.os.macos.hpp" #else #error "Unknown OS for ams::os::impl::InternalReaderWriterBusyMutexImpl" #endif namespace ams::os { void InitalizeReaderWriterLockBusyMutex(ReaderWriterBusyMutexType *rw_mutex) { /* Create object. */ util::ConstructAt(rw_mutex->_storage); } void AcquireReadLockBusyMutex(ReaderWriterBusyMutexType *rw_mutex) { /* Acquire read lock. */ util::GetReference(rw_mutex->_storage).AcquireReadLock(); } void ReleaseReadLockBusyMutex(ReaderWriterBusyMutexType *rw_mutex) { /* Release read lock. */ util::GetReference(rw_mutex->_storage).ReleaseReadLock(); } void AcquireWriteLockBusyMutex(ReaderWriterBusyMutexType *rw_mutex) { /* Acquire write lock. */ util::GetReference(rw_mutex->_storage).AcquireWriteLock(); } void ReleaseWriteLockBusyMutex(ReaderWriterBusyMutexType *rw_mutex) { /* Release write lock. */ util::GetReference(rw_mutex->_storage).ReleaseWriteLock(); } }
2,106
C++
.cpp
50
37.88
82
0.73291
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,705
os_memory_heap.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/os_memory_heap.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "impl/os_memory_heap_manager.hpp" namespace ams::os { Result SetMemoryHeapSize(size_t size) { /* Check pre-conditions. */ AMS_ASSERT(util::IsAligned(size, MemoryHeapUnitSize)); /* Set the heap size. */ R_RETURN(impl::GetMemoryHeapManager().SetHeapSize(size)); } uintptr_t GetMemoryHeapAddress() { return impl::GetMemoryHeapManager().GetHeapAddress(); } size_t GetMemoryHeapSize() { return impl::GetMemoryHeapManager().GetHeapSize(); } Result AllocateMemoryBlock(uintptr_t *out_address, size_t size) { /* Check pre-conditions. */ AMS_ASSERT(size > 0); AMS_ASSERT(util::IsAligned(size, MemoryBlockUnitSize)); /* Allocate from heap. */ R_RETURN(impl::GetMemoryHeapManager().AllocateFromHeap(out_address, size)); } void FreeMemoryBlock(uintptr_t address, size_t size) { /* Get memory heap manager. */ auto &manager = impl::GetMemoryHeapManager(); /* Check pre-conditions. */ AMS_ASSERT(util::IsAligned(address, MemoryBlockUnitSize)); AMS_ASSERT(size > 0); AMS_ASSERT(util::IsAligned(size, MemoryBlockUnitSize)); AMS_ABORT_UNLESS(manager.IsRegionInMemoryHeap(address, size)); /* Release the memory block. */ manager.ReleaseToHeap(address, size); } }
2,028
C++
.cpp
49
35.795918
83
0.691057
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,706
os_cache.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/os_cache.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "impl/os_cache_impl.hpp" namespace ams::os { void FlushDataCache(const void *addr, size_t size) { return impl::FlushDataCacheImpl(addr, size); } void FlushEntireDataCache() { return impl::FlushEntireDataCacheImpl(); } }
928
C++
.cpp
25
34.12
76
0.738598
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,707
os_sdk_condition_variable.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/os_sdk_condition_variable.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "impl/os_thread_manager.hpp" #include "impl/os_timeout_helper.hpp" namespace ams::os { void SdkConditionVariableType::Wait(SdkMutexType &mutex) { /* Check that we own the mutex. */ AMS_ABORT_UNLESS(os::IsSdkMutexLockedByCurrentThread(std::addressof(mutex))); /* Wait on the mutex. */ GetReference(this->_storage).Wait(GetPointer(mutex._storage)); } bool SdkConditionVariableType::TimedWait(SdkMutexType &mutex, TimeSpan timeout) { /* Check preconditions. */ AMS_ASSERT(timeout.GetNanoSeconds() >= 0); AMS_ABORT_UNLESS(os::IsSdkMutexLockedByCurrentThread(std::addressof(mutex))); /* Handle zero timeout by unlocking and re-locking. */ if (timeout == TimeSpan(0)) { GetReference(mutex._storage).Leave(); GetReference(mutex._storage).Enter(); return false; } /* Handle timed wait. */ impl::TimeoutHelper timeout_helper(timeout); auto status = GetReference(this->_storage).TimedWait(GetPointer(mutex._storage), timeout_helper); return status == ConditionVariableStatus::Success; } void SdkConditionVariableType::Wait(SdkRecursiveMutexType &mutex) { /* Check preconditions. */ AMS_ABORT_UNLESS(os::IsSdkRecursiveMutexLockedByCurrentThread(std::addressof(mutex))); AMS_ABORT_UNLESS(mutex.recursive_count == 1); /* Decrement the mutex's recursive count. */ --mutex.recursive_count; /* Wait on the mutex. */ GetReference(this->_storage).Wait(GetPointer(mutex._storage)); /* Increment the mutex's recursive count. */ ++mutex.recursive_count; /* Check that the mutex's recursive count is valid. */ AMS_ABORT_UNLESS(mutex.recursive_count != 0); } bool SdkConditionVariableType::TimedWait(SdkRecursiveMutexType &mutex, TimeSpan timeout) { /* Check preconditions. */ AMS_ASSERT(timeout.GetNanoSeconds() >= 0); AMS_ABORT_UNLESS(os::IsSdkRecursiveMutexLockedByCurrentThread(std::addressof(mutex))); /* Handle zero timeout by unlocking and re-locking. */ if (timeout == TimeSpan(0)) { /* NOTE: Nintendo doesn't check recursive_count here...seems really suspicious? */ /* Not sure that this is correct, or if they just forgot to check. */ GetReference(mutex._storage).Leave(); GetReference(mutex._storage).Enter(); return false; } /* Check that the mutex is held exactly once. */ AMS_ABORT_UNLESS(mutex.recursive_count == 1); /* Decrement the mutex's recursive count. */ --mutex.recursive_count; /* Create timeout helper. */ impl::TimeoutHelper timeout_helper(timeout); /* Perform timed wait. */ auto status = GetReference(this->_storage).TimedWait(GetPointer(mutex._storage), timeout_helper); /* Increment the mutex's recursive count. */ ++mutex.recursive_count; /* Check that the mutex's recursive count is valid. */ AMS_ABORT_UNLESS(mutex.recursive_count != 0); /* Return whether we succeeded. */ return status == ConditionVariableStatus::Success; } }
3,925
C++
.cpp
81
41
105
0.669108
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,708
os_debug.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/os_debug.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "impl/os_debug_impl.hpp" namespace ams::os { void GetCurrentStackInfo(uintptr_t *out_stack, size_t *out_size) { /* Get the current stack info. */ uintptr_t stack_top = 0; size_t stack_size = 0; impl::DebugImpl::GetCurrentStackInfo(std::addressof(stack_top), std::addressof(stack_size)); /* Basic sanity check. */ uintptr_t sp = reinterpret_cast<uintptr_t>(std::addressof(stack_top)); AMS_ASSERT((stack_top <= sp) && (sp < (stack_top + stack_size))); AMS_UNUSED(sp); /* Set the output. */ if (out_stack != nullptr) { *out_stack = stack_top; } if (out_size != nullptr) { *out_size = stack_size; } } void QueryMemoryInfo(MemoryInfo *out) { return impl::DebugImpl::QueryMemoryInfo(out); } Tick GetIdleTickCount() { return impl::DebugImpl::GetIdleTickCount(); } int GetFreeThreadCount() { return impl::DebugImpl::GetFreeThreadCount(); } }
1,700
C++
.cpp
45
32.2
100
0.658774
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,709
os_event.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/os_event.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "impl/os_timeout_helper.hpp" #include "impl/os_multiple_wait_object_list.hpp" #include "impl/os_multiple_wait_holder_impl.hpp" namespace ams::os { namespace { ALWAYS_INLINE u64 GetBroadcastCounterUnsafe(EventType *event) { const u64 upper = event->broadcast_counter_high; return (upper << BITSIZEOF(event->broadcast_counter_low)) | event->broadcast_counter_low; } ALWAYS_INLINE void IncrementBroadcastCounterUnsafe(EventType *event) { if ((++event->broadcast_counter_low) == 0) { ++event->broadcast_counter_high; } } } void InitializeEvent(EventType *event, bool signaled, EventClearMode clear_mode) { /* Initialize internal variables. */ util::ConstructAt(event->cs_event); util::ConstructAt(event->cv_signaled); /* Initialize the multi wait object list. */ util::ConstructAt(event->multi_wait_object_list_storage); /* Initialize member variables. */ event->signaled = signaled; event->initially_signaled = signaled; event->clear_mode = static_cast<u8>(clear_mode); event->broadcast_counter_low = 0; event->broadcast_counter_high = 0; /* Mark initialized. */ event->state = EventType::State_Initialized; } void FinalizeEvent(EventType *event) { AMS_ASSERT(event->state == EventType::State_Initialized); /* Mark uninitialized. */ event->state = EventType::State_NotInitialized; /* Destroy objects. */ util::DestroyAt(event->multi_wait_object_list_storage); util::DestroyAt(event->cv_signaled); util::DestroyAt(event->cs_event); } void SignalEvent(EventType *event) { AMS_ASSERT(event->state == EventType::State_Initialized); std::scoped_lock lk(GetReference(event->cs_event)); /* If we're already signaled, nothing more to do. */ if (event->signaled) { return; } event->signaled = true; /* Signal! */ if (event->clear_mode == EventClearMode_ManualClear) { /* If we're manual clear, increment counter and wake all. */ IncrementBroadcastCounterUnsafe(event); GetReference(event->cv_signaled).Broadcast(); } else { /* If we're auto clear, signal one thread, which will clear. */ GetReference(event->cv_signaled).Signal(); } /* Wake up whatever manager, if any. */ GetReference(event->multi_wait_object_list_storage).WakeupAllMultiWaitThreadsUnsafe(); } void WaitEvent(EventType *event) { AMS_ASSERT(event->state == EventType::State_Initialized); std::scoped_lock lk(GetReference(event->cs_event)); const auto cur_counter = GetBroadcastCounterUnsafe(event); while (!event->signaled) { if (cur_counter != GetBroadcastCounterUnsafe(event)) { break; } GetReference(event->cv_signaled).Wait(GetPointer(event->cs_event)); } if (event->clear_mode == EventClearMode_AutoClear) { event->signaled = false; } } bool TryWaitEvent(EventType *event) { AMS_ASSERT(event->state == EventType::State_Initialized); std::scoped_lock lk(GetReference(event->cs_event)); const bool signaled = event->signaled; if (event->clear_mode == EventClearMode_AutoClear) { event->signaled = false; } return signaled; } bool TimedWaitEvent(EventType *event, TimeSpan timeout) { AMS_ASSERT(event->state == EventType::State_Initialized); AMS_ASSERT(timeout.GetNanoSeconds() >= 0); { impl::TimeoutHelper timeout_helper(timeout); std::scoped_lock lk(GetReference(event->cs_event)); const auto cur_counter = GetBroadcastCounterUnsafe(event); while (!event->signaled) { if (cur_counter != GetBroadcastCounterUnsafe(event)) { break; } auto wait_res = GetReference(event->cv_signaled).TimedWait(GetPointer(event->cs_event), timeout_helper); if (wait_res == ConditionVariableStatus::TimedOut) { return false; } } if (event->clear_mode == EventClearMode_AutoClear) { event->signaled = false; } } return true; } void ClearEvent(EventType *event) { AMS_ASSERT(event->state == EventType::State_Initialized); std::scoped_lock lk(GetReference(event->cs_event)); /* Clear the signaled state. */ event->signaled = false; } void InitializeMultiWaitHolder(MultiWaitHolderType *multi_wait_holder, EventType *event) { AMS_ASSERT(event->state == EventType::State_Initialized); util::ConstructAt(GetReference(multi_wait_holder->impl_storage).holder_of_event_storage, event); multi_wait_holder->user_data = 0; } }
5,787
C++
.cpp
132
34.924242
120
0.629808
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,710
os_process_memory.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/os_process_memory.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "impl/os_process_memory_impl.hpp" namespace ams::os { Result MapProcessMemory(void **out, NativeHandle handle, u64 process_address, size_t process_size, AddressSpaceGenerateRandomFunction generate_random) { R_RETURN(::ams::os::impl::ProcessMemoryImpl::Map(out, handle, process_address, process_size, generate_random)); } void UnmapProcessMemory(void *mapped_memory, NativeHandle handle, u64 process_address, size_t process_size) { return ::ams::os::impl::ProcessMemoryImpl::Unmap(mapped_memory, handle, process_address, process_size); } Result SetProcessMemoryPermission(NativeHandle handle, u64 process_address, u64 process_size, MemoryPermission perm) { R_RETURN(::ams::os::impl::ProcessMemoryImpl::SetMemoryPermission(handle, process_address, process_size, perm)); } }
1,497
C++
.cpp
28
50.071429
156
0.756148
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,711
os_timer_event.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/os_timer_event.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "impl/os_timer_event_helper.hpp" #include "impl/os_tick_manager.hpp" #include "impl/os_timeout_helper.hpp" #include "impl/os_multiple_wait_object_list.hpp" #include "impl/os_multiple_wait_holder_impl.hpp" namespace ams::os { namespace { ALWAYS_INLINE u64 GetBroadcastCounterUnsafe(TimerEventType *event) { const u64 upper = event->broadcast_counter_high; return (upper << BITSIZEOF(event->broadcast_counter_low)) | event->broadcast_counter_low; } ALWAYS_INLINE void IncrementBroadcastCounterUnsafe(TimerEventType *event) { if ((++event->broadcast_counter_low) == 0) { ++event->broadcast_counter_high; } } ALWAYS_INLINE void SignalTimerEventImplUnsafe(TimerEventType *event) { /* Set signaled. */ event->signaled = true; /* Signal! */ if (event->clear_mode == EventClearMode_ManualClear) { /* If we're manual clear, increment counter and wake all. */ IncrementBroadcastCounterUnsafe(event); } else { /* If we're auto clear, signal one thread, which will clear. */ GetReference(event->cv_signaled).Signal(); } /* Wake up whatever manager, if any. */ GetReference(event->multi_wait_object_list_storage).WakeupAllMultiWaitThreadsUnsafe(); } } void InitializeTimerEvent(TimerEventType *event, EventClearMode clear_mode) { /* Initialize internal variables. */ util::ConstructAt(event->cs_timer_event); util::ConstructAt(event->cv_signaled); /* Initialize the multi wait object list. */ util::ConstructAt(event->multi_wait_object_list_storage); /* Initialize member variables. */ event->clear_mode = static_cast<u8>(clear_mode); event->signaled = false; event->timer_state = TimerEventType::TimerState_Stop; event->broadcast_counter_low = 0; event->broadcast_counter_high = 0; GetReference(event->next_time_to_wakeup) = 0; GetReference(event->first) = 0; GetReference(event->interval) = 0; /* Mark initialized. */ event->state = TimerEventType::State_Initialized; } void FinalizeTimerEvent(TimerEventType *event) { /* Mark uninitialized. */ event->state = TimerEventType::State_NotInitialized; /* Destroy objects. */ util::DestroyAt(event->multi_wait_object_list_storage); util::DestroyAt(event->cv_signaled); util::DestroyAt(event->cs_timer_event); } void StartOneShotTimerEvent(TimerEventType *event, TimeSpan first_time) { AMS_ASSERT(event->state == TimerEventType::State_Initialized); AMS_ASSERT(first_time >= 0); { std::scoped_lock lk(GetReference(event->cs_timer_event)); /* Get the current time. */ TimeSpan cur_time = impl::GetCurrentTick().ToTimeSpan(); /* Set tracking timespans. */ GetReference(event->next_time_to_wakeup) = impl::SaturatedAdd(cur_time, first_time); GetReference(event->first) = first_time; GetReference(event->interval) = 0; /* Set state to OneShot. */ event->timer_state = TimerEventType::TimerState_OneShot; /* Signal. */ GetReference(event->cv_signaled).Broadcast(); /* Wake up whatever manager, if any. */ GetReference(event->multi_wait_object_list_storage).WakeupAllMultiWaitThreadsUnsafe(); } } void StartPeriodicTimerEvent(TimerEventType *event, TimeSpan first_time, TimeSpan interval) { AMS_ASSERT(event->state == TimerEventType::State_Initialized); AMS_ASSERT(first_time >= 0); AMS_ASSERT(interval > 0); { std::scoped_lock lk(GetReference(event->cs_timer_event)); /* Get the current time. */ TimeSpan cur_time = impl::GetCurrentTick().ToTimeSpan(); /* Set tracking timespans. */ GetReference(event->next_time_to_wakeup) = impl::SaturatedAdd(cur_time, first_time); GetReference(event->first) = first_time; GetReference(event->interval) = interval; /* Set state to Periodic. */ event->timer_state = TimerEventType::TimerState_Periodic; /* Signal. */ GetReference(event->cv_signaled).Broadcast(); /* Wake up whatever manager, if any. */ GetReference(event->multi_wait_object_list_storage).WakeupAllMultiWaitThreadsUnsafe(); } } void StopTimerEvent(TimerEventType *event) { AMS_ASSERT(event->state == TimerEventType::State_Initialized); { std::scoped_lock lk(GetReference(event->cs_timer_event)); /* Stop the event. */ impl::StopTimerUnsafe(event); /* Signal. */ GetReference(event->cv_signaled).Broadcast(); /* Wake up whatever manager, if any. */ GetReference(event->multi_wait_object_list_storage).WakeupAllMultiWaitThreadsUnsafe(); } } void WaitTimerEvent(TimerEventType *event) { AMS_ASSERT(event->state == TimerEventType::State_Initialized); { std::scoped_lock lk(GetReference(event->cs_timer_event)); const auto cur_counter = GetBroadcastCounterUnsafe(event); while (!event->signaled) { if (cur_counter != GetBroadcastCounterUnsafe(event)) { break; } /* Update. */ auto cur_time = impl::GetCurrentTick().ToTimeSpan(); if (impl::UpdateSignalStateAndRecalcNextTimeToWakeupUnsafe(event, cur_time)) { SignalTimerEventImplUnsafe(event); break; } /* Check state. */ if (event->timer_state == TimerEventType::TimerState_Stop) { GetReference(event->cv_signaled).Wait(GetPointer(event->cs_timer_event)); } else { TimeSpan next_time = GetReference(event->next_time_to_wakeup); impl::TimeoutHelper helper(next_time - cur_time); GetReference(event->cv_signaled).TimedWait(GetPointer(event->cs_timer_event), helper); } } if (event->clear_mode == EventClearMode_AutoClear) { event->signaled = false; } } } bool TryWaitTimerEvent(TimerEventType *event) { AMS_ASSERT(event->state == TimerEventType::State_Initialized); { std::scoped_lock lk(GetReference(event->cs_timer_event)); /* Update. */ auto cur_time = impl::GetCurrentTick().ToTimeSpan(); if (impl::UpdateSignalStateAndRecalcNextTimeToWakeupUnsafe(event, cur_time)) { SignalTimerEventImplUnsafe(event); } bool prev = event->signaled; if (event->clear_mode == EventClearMode_AutoClear) { event->signaled = false; } return prev; } } void SignalTimerEvent(TimerEventType *event) { AMS_ASSERT(event->state == TimerEventType::State_Initialized); { std::scoped_lock lk(GetReference(event->cs_timer_event)); /* If we're signaled, nothing to do. */ if (event->signaled) { return; } /* Update. */ auto cur_time = impl::GetCurrentTick().ToTimeSpan(); impl::UpdateSignalStateAndRecalcNextTimeToWakeupUnsafe(event, cur_time); /* Signal. */ SignalTimerEventImplUnsafe(event); } } void ClearTimerEvent(TimerEventType *event) { AMS_ASSERT(event->state == TimerEventType::State_Initialized); { std::scoped_lock lk(GetReference(event->cs_timer_event)); /* Update. */ auto cur_time = impl::GetCurrentTick().ToTimeSpan(); if (impl::UpdateSignalStateAndRecalcNextTimeToWakeupUnsafe(event, cur_time)) { SignalTimerEventImplUnsafe(event); } /* Clear. */ event->signaled = false; } } void InitializeMultiWaitHolder(MultiWaitHolderType *multi_wait_holder, TimerEventType *event) { AMS_ASSERT(event->state == EventType::State_Initialized); util::ConstructAt(GetReference(multi_wait_holder->impl_storage).holder_of_timer_event_storage, event); multi_wait_holder->user_data = 0; } }
9,476
C++
.cpp
203
35.955665
110
0.604363
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,712
os_random.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/os_random.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "impl/os_random_impl.hpp" namespace ams::os { namespace { constinit util::TinyMT g_random{util::ConstantInitialize}; constinit os::SdkMutex g_random_mutex; constinit bool g_initialized_random; template<typename T> inline T GenerateRandomTImpl(T max) { static_assert(std::is_integral<T>::value && std::is_unsigned<T>::value); const T EffectiveMax = (std::numeric_limits<T>::max() / max) * max; T cur_rnd; while (true) { os::GenerateRandomBytes(std::addressof(cur_rnd), sizeof(T)); if (cur_rnd < EffectiveMax) { return cur_rnd % max; } } } } void GenerateRandomBytes(void *dst, size_t size) { std::scoped_lock lk(g_random_mutex); if (AMS_UNLIKELY(!g_initialized_random)) { impl::InitializeRandomImpl(std::addressof(g_random)); g_initialized_random = true; } g_random.GenerateRandomBytes(dst, size); } u32 GenerateRandomU32(u32 max) { return GenerateRandomTImpl<u32>(max); } u64 GenerateRandomU64(u64 max) { return GenerateRandomTImpl<u64>(max); } }
1,910
C++
.cpp
50
31.1
84
0.647377
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,713
os_thread.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/os_thread.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "impl/os_thread_manager.hpp" #include "impl/os_timeout_helper.hpp" #include "impl/os_multiple_wait_holder_impl.hpp" namespace ams::os { namespace { size_t CheckThreadNameLength(const char *name) { const char *cur = name; for (size_t len = 0; len < ThreadNameLengthMax; ++len) { if (*(cur++) == 0) { return len; } } AMS_ABORT("ThreadNameLength too large"); } void ValidateThreadArguments(ThreadType *thread, void *stack, size_t stack_size, s32 priority) { AMS_ASSERT(stack != nullptr); AMS_ASSERT(util::IsAligned(reinterpret_cast<uintptr_t>(stack), ThreadStackAlignment)); AMS_ASSERT(stack_size > 0); AMS_ASSERT(util::IsAligned(stack_size, ThreadStackAlignment)); AMS_UNUSED(thread, stack, stack_size, priority); } } Result CreateThread(ThreadType *thread, ThreadFunction function, void *argument, void *stack, size_t stack_size, s32 priority, s32 ideal_core) { ValidateThreadArguments(thread, stack, stack_size, priority); AMS_ASSERT(GetThreadAvailableCoreMask() & (1ul << ideal_core)); R_RETURN(impl::GetThreadManager().CreateThread(thread, function, argument, stack, stack_size, priority, ideal_core)); } Result CreateThread(ThreadType *thread, ThreadFunction function, void *argument, void *stack, size_t stack_size, s32 priority) { ValidateThreadArguments(thread, stack, stack_size, priority); R_RETURN(impl::GetThreadManager().CreateThread(thread, function, argument, stack, stack_size, priority)); } void DestroyThread(ThreadType *thread) { auto &manager = impl::GetThreadManager(); AMS_ASSERT(thread->state == ThreadType::State_Initialized || thread->state == ThreadType::State_Started || thread->state == ThreadType::State_Terminated); AMS_ASSERT(thread != manager.GetMainThread()); manager.DestroyThread(thread); } void StartThread(ThreadType *thread) { AMS_ASSERT(thread->state == ThreadType::State_Initialized); impl::GetThreadManager().StartThread(thread); } ThreadType *GetCurrentThread() { return impl::GetCurrentThread(); } void WaitThread(ThreadType *thread) { AMS_ASSERT(thread != impl::GetCurrentThread()); AMS_ASSERT(thread->state == ThreadType::State_Initialized || thread->state == ThreadType::State_Started || thread->state == ThreadType::State_Terminated); return impl::GetThreadManager().WaitThread(thread); } bool TryWaitThread(ThreadType *thread) { AMS_ASSERT(thread->state == ThreadType::State_Initialized || thread->state == ThreadType::State_Started || thread->state == ThreadType::State_Terminated); return impl::GetThreadManager().TryWaitThread(thread); } void YieldThread() { return impl::GetThreadManager().YieldThread(); } void SleepThread(TimeSpan time) { impl::TimeoutHelper::Sleep(time); } s32 SuspendThread(ThreadType *thread) { AMS_ASSERT(thread->state == ThreadType::State_Started); AMS_ASSERT(thread != impl::GetCurrentThread()); return impl::GetThreadManager().SuspendThread(thread); } s32 ResumeThread(ThreadType *thread) { AMS_ASSERT(thread->state == ThreadType::State_Started); return impl::GetThreadManager().ResumeThread(thread); } s32 GetThreadSuspendCount(const ThreadType *thread) { return thread->suspend_count; } /* TODO: void GetThreadContext(ThreadContextInfo *out_context, const ThreadType *thread); */ s32 ChangeThreadPriority(ThreadType *thread, s32 priority) { AMS_ASSERT(thread->state == ThreadType::State_Initialized || thread->state == ThreadType::State_DestroyedBeforeStarted || thread->state == ThreadType::State_Started || thread->state == ThreadType::State_Terminated); { std::scoped_lock lk(GetReference(thread->cs_thread)); const s32 prev_prio = thread->base_priority; const bool success = impl::GetThreadManager().ChangePriority(thread, priority); AMS_ASSERT(success); AMS_UNUSED(success); thread->base_priority = priority; return prev_prio; } } s32 GetThreadPriority(const ThreadType *thread) { AMS_ASSERT(thread->state == ThreadType::State_Initialized || thread->state == ThreadType::State_DestroyedBeforeStarted || thread->state == ThreadType::State_Started || thread->state == ThreadType::State_Terminated); return thread->base_priority; } s32 GetThreadCurrentPriority(const ThreadType *thread) { AMS_ASSERT(thread->state == ThreadType::State_Initialized || thread->state == ThreadType::State_DestroyedBeforeStarted || thread->state == ThreadType::State_Started || thread->state == ThreadType::State_Terminated); return impl::GetThreadManager().GetCurrentPriority(thread); } void SetThreadName(ThreadType *thread, const char *name) { AMS_ASSERT(thread->state == ThreadType::State_Initialized || thread->state == ThreadType::State_DestroyedBeforeStarted || thread->state == ThreadType::State_Started || thread->state == ThreadType::State_Terminated); if (name == nullptr) { impl::GetThreadManager().SetInitialThreadNameUnsafe(thread); return; } const size_t name_size = CheckThreadNameLength(name) + 1; std::memcpy(thread->name_buffer, name, name_size); SetThreadNamePointer(thread, thread->name_buffer); } void SetThreadNamePointer(ThreadType *thread, const char *name) { AMS_ASSERT(thread->state == ThreadType::State_Initialized || thread->state == ThreadType::State_DestroyedBeforeStarted || thread->state == ThreadType::State_Started || thread->state == ThreadType::State_Terminated); if (name == nullptr) { impl::GetThreadManager().SetInitialThreadNameUnsafe(thread); return; } thread->name_pointer = name; impl::GetThreadManager().NotifyThreadNameChanged(thread); } const char *GetThreadNamePointer(const ThreadType *thread) { AMS_ASSERT(thread->state == ThreadType::State_Initialized || thread->state == ThreadType::State_DestroyedBeforeStarted || thread->state == ThreadType::State_Started || thread->state == ThreadType::State_Terminated); return thread->name_pointer; } s32 GetCurrentCoreNumber() { return impl::GetThreadManager().GetCurrentCoreNumber(); } s32 GetCurrentProcessorNumber() { return GetCurrentCoreNumber(); } void SetThreadCoreMask(ThreadType *thread, s32 ideal_core, u64 affinity_mask) { AMS_ASSERT(ideal_core == IdealCoreDontCare || ideal_core == IdealCoreUseDefault || ideal_core == IdealCoreNoUpdate || (0 <= ideal_core && ideal_core < impl::CoreAffinityMaskBitWidth)); if (ideal_core != IdealCoreUseDefault) { AMS_ASSERT(affinity_mask != 0); AMS_ASSERT((affinity_mask & ~GetThreadAvailableCoreMask()) == 0); } if (ideal_core >= 0) { AMS_ASSERT((affinity_mask & (1ul << ideal_core)) != 0); } return impl::GetThreadManager().SetThreadCoreMask(thread, ideal_core, affinity_mask); } void GetThreadCoreMask(s32 *out_ideal_core, u64 *out_affinity_mask, const ThreadType *thread) { return impl::GetThreadManager().GetThreadCoreMask(out_ideal_core, out_affinity_mask, thread); } u64 GetThreadAvailableCoreMask() { return impl::GetThreadManager().GetThreadAvailableCoreMask(); } ThreadId GetThreadId(const ThreadType *thread) { return impl::GetThreadManager().GetThreadId(thread); } }
8,509
C++
.cpp
158
46.056962
223
0.682284
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,714
os_shared_memory.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/os_shared_memory.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "impl/os_thread_manager.hpp" #include "impl/os_shared_memory_impl.hpp" namespace ams::os { namespace { void SetupSharedMemoryType(SharedMemoryType *shared_memory, size_t size, NativeHandle handle, bool managed) { /* Set members. */ shared_memory->handle = handle; shared_memory->size = size; shared_memory->address = nullptr; shared_memory->allocated = false; /* Set managed. */ shared_memory->handle_managed = managed; /* Create the critical section. */ util::ConstructAt(shared_memory->cs_shared_memory); } } Result CreateSharedMemory(SharedMemoryType *shared_memory, size_t size, MemoryPermission my_perm, MemoryPermission other_perm) { /* Check pre-conditions. */ AMS_ASSERT(size > 0); AMS_ASSERT(util::IsAligned(size, MemoryPageSize)); /* Create the memory. */ NativeHandle handle; R_TRY(impl::SharedMemoryImpl::Create(std::addressof(handle), size, my_perm, other_perm)); /* Setup the object. */ SetupSharedMemoryType(shared_memory, size, handle, true); R_SUCCEED(); } void AttachSharedMemory(SharedMemoryType *shared_memory, size_t size, NativeHandle handle, bool managed) { /* Check pre-conditions. */ AMS_ASSERT(size > 0); AMS_ASSERT(util::IsAligned(size, MemoryPageSize)); AMS_ASSERT(handle != os::InvalidNativeHandle); /* Setup the object. */ SetupSharedMemoryType(shared_memory, size, handle, managed); } void DestroySharedMemory(SharedMemoryType *shared_memory) { /* Unmap the shared memory, if required. */ if (shared_memory->state == SharedMemoryType::State_Mapped) { UnmapSharedMemory(shared_memory); } /* Check the state. */ AMS_ASSERT(shared_memory->state == SharedMemoryType::State_Initialized); /* Set state to not initialized. */ shared_memory->state = SharedMemoryType::State_NotInitialized; /* Close the handle, if it's managed. */ if (shared_memory->handle_managed) { impl::SharedMemoryImpl::Close(shared_memory->handle); } shared_memory->handle_managed = false; /* Clear members. */ shared_memory->address = nullptr; shared_memory->size = 0; shared_memory->handle = os::InvalidNativeHandle; /* Destroy the critical section. */ util::DestroyAt(shared_memory->cs_shared_memory); } void *MapSharedMemory(SharedMemoryType *shared_memory, MemoryPermission perm) { /* Lock the current thread, and then the shared memory. */ std::scoped_lock thread_lk(util::GetReference(impl::GetCurrentThread()->cs_thread)); std::scoped_lock lk(util::GetReference(shared_memory->cs_shared_memory)); /* Ensure we're in a mappable state. */ AMS_ASSERT(shared_memory->state == SharedMemoryType::State_Initialized); /* Try to map. */ void *mapped_address; if (R_FAILED(impl::SharedMemoryImpl::Map(std::addressof(mapped_address), shared_memory->handle, shared_memory->size, perm))) { return nullptr; } /* Set fields now that we've mapped successfully. */ shared_memory->allocated = true; shared_memory->address = mapped_address; shared_memory->state = SharedMemoryType::State_Mapped; return mapped_address; } void UnmapSharedMemory(SharedMemoryType *shared_memory) { /* Lock the memory. */ std::scoped_lock lk(util::GetReference(shared_memory->cs_shared_memory)); /* If the memory isn't mapped, we can't unmap it. */ if (shared_memory->state != SharedMemoryType::State_Mapped) { return; } /* Unmap the memory. */ impl::SharedMemoryImpl::Unmap(shared_memory->handle, shared_memory->address, shared_memory->size); /* Unmapped memory is necessarily not allocated. */ if (shared_memory->allocated) { shared_memory->allocated = false; } /* Clear the address. */ shared_memory->address = nullptr; shared_memory->state = SharedMemoryType::State_Initialized; } void *GetSharedMemoryAddress(const SharedMemoryType *shared_memory) { /* Check pre-conditions. */ AMS_ASSERT(shared_memory->state == SharedMemoryType::State_Initialized || shared_memory->state == SharedMemoryType::State_Mapped); return shared_memory->address; } size_t GetSharedMemorySize(const SharedMemoryType *shared_memory) { /* Check pre-conditions. */ AMS_ASSERT(shared_memory->state == SharedMemoryType::State_Initialized || shared_memory->state == SharedMemoryType::State_Mapped); return shared_memory->size; } NativeHandle GetSharedMemoryHandle(const SharedMemoryType *shared_memory) { /* Check pre-conditions. */ AMS_ASSERT(shared_memory->state == SharedMemoryType::State_Initialized || shared_memory->state == SharedMemoryType::State_Mapped); return shared_memory->handle; } }
5,867
C++
.cpp
122
40.131148
138
0.66007
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,715
os_light_semaphore.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/os_light_semaphore.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "impl/os_timeout_helper.hpp" namespace ams::os { void InitializeLightSemaphore(LightSemaphoreType *sema, s32 count, s32 max_count) { /* Check pre-conditions. */ AMS_ASSERT(max_count >= 1); AMS_ASSERT(0 <= count && count <= max_count); /* Setup objects. */ util::ConstructAt(sema->mutex); util::ConstructAt(sema->ev_not_zero, count > 0); /* Set member variables. */ sema->count = count; sema->max_count = max_count; /* Mark initialized. */ sema->state = LightSemaphoreType::State_Initialized; } void FinalizeLightSemaphore(LightSemaphoreType *sema) { /* Check pre-conditions. */ AMS_ASSERT(sema->state == LightSemaphoreType::State_Initialized); /* Mark uninitialized. */ sema->state = LightSemaphoreType::State_NotInitialized; /* Destroy objects. */ util::DestroyAt(sema->mutex); util::DestroyAt(sema->ev_not_zero); } void AcquireLightSemaphore(LightSemaphoreType *sema) { /* Check pre-conditions. */ AMS_ASSERT(sema->state == LightSemaphoreType::State_Initialized); /* Repeatedly try to acquire the semaphore. */ while (true) { /* Try to acquire the semaphore. */ { /* Acquire exclusive access to the semaphore. */ std::scoped_lock lk(util::GetReference(sema->mutex)); /* If we can, acquire. */ if (sema->count > 0) { --sema->count; return; } /* Ensure that we can wait once we're unlocked. */ util::GetReference(sema->ev_not_zero).Clear(); } /* Wait until we can try again. */ util::GetReference(sema->ev_not_zero).WaitWithManualClear(); } } bool TryAcquireLightSemaphore(LightSemaphoreType *sema) { /* Check pre-conditions. */ AMS_ASSERT(sema->state == LightSemaphoreType::State_Initialized); /* Acquire exclusive access to the semaphore. */ std::scoped_lock lk(util::GetReference(sema->mutex)); /* Try to acquire. */ if (sema->count > 0) { --sema->count; return true; } else { return false; } } bool TimedAcquireLightSemaphore(LightSemaphoreType *sema, TimeSpan timeout) { /* Check pre-conditions. */ AMS_ASSERT(sema->state == LightSemaphoreType::State_Initialized); AMS_ASSERT(timeout.GetNanoSeconds() >= 0); /* Create timeout helper. */ impl::TimeoutHelper timeout_helper(timeout); /* Repeatedly try to acquire the semaphore. */ while (true) { /* Try to acquire the semaphore. */ { /* Acquire exclusive access to the semaphore. */ std::scoped_lock lk(util::GetReference(sema->mutex)); /* If we can, acquire. */ if (sema->count > 0) { --sema->count; return true; } /* Ensure that we can wait once we're unlocked. */ util::GetReference(sema->ev_not_zero).Clear(); } /* Check if we're timed out. */ if (timeout_helper.TimedOut()) { return false; } /* Wait until we can try again. */ util::GetReference(sema->ev_not_zero).TimedWaitWithManualClear(timeout_helper); } } void ReleaseLightSemaphore(LightSemaphoreType *sema) { /* Check pre-conditions. */ AMS_ASSERT(sema->state == LightSemaphoreType::State_Initialized); /* Release the semaphore. */ { /* Acquire exclusive access to the semaphore. */ std::scoped_lock lk(util::GetReference(sema->mutex)); /* Check that we can release. */ AMS_ASSERT(sema->count + 1 <= sema->max_count); /* Release. */ ++sema->count; } /* Signal that we released. */ util::GetReference(sema->ev_not_zero).SignalWithManualClear(); } void ReleaseLightSemaphore(LightSemaphoreType *sema, s32 count) { /* Check pre-conditions. */ AMS_ASSERT(sema->state == LightSemaphoreType::State_Initialized); AMS_ASSERT(count >= 1); /* Release the semaphore. */ { /* Acquire exclusive access to the semaphore. */ std::scoped_lock lk(util::GetReference(sema->mutex)); /* Check that we can release. */ AMS_ASSERT(sema->count + count <= sema->max_count); /* Release. */ sema->count += count; } /* Signal that we released. */ util::GetReference(sema->ev_not_zero).SignalWithManualClear(); } s32 GetCurrentLightSemaphoreCount(const LightSemaphoreType *sema) { /* Check pre-conditions. */ AMS_ASSERT(sema->state == LightSemaphoreType::State_Initialized); /* Acquire exclusive access to the semaphore. */ std::scoped_lock lk(util::GetReference(sema->mutex)); /* Get the count. */ return sema->count; } }
5,922
C++
.cpp
142
31.894366
91
0.586627
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,716
os_native_handle_api.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/os_native_handle_api.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "impl/os_native_handle_impl.hpp" namespace ams::os { void CloseNativeHandle(NativeHandle handle) { if (handle != os::InvalidNativeHandle) { impl::NativeHandleImpl::Close(handle); } } }
896
C++
.cpp
24
34.125
76
0.731876
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,717
os_busy_mutex.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/os_busy_mutex.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "impl/os_thread_manager.hpp" #if defined(ATMOSPHERE_OS_HORIZON) #include "impl/os_internal_busy_mutex_impl.os.horizon.hpp" #else /* Generic implementation already included in <stratosphere.hpp> */ #endif namespace ams::os { void InitializeBusyMutex(BusyMutexType *mutex) { /* Create object. */ util::ConstructAt(mutex->_storage); /* Set member variables. */ mutex->owner_thread = nullptr; /* Mark initialized. */ mutex->state = BusyMutexType::State_Initialized; } void FinalizeBusyMutex(BusyMutexType *mutex) { /* Check pre-conditions. */ AMS_ASSERT(mutex->state == BusyMutexType::State_Initialized); AMS_ASSERT(!util::GetReference(mutex->_storage).IsLocked()); /* Mark not intialized. */ mutex->state = MutexType::State_NotInitialized; /* Destroy object. */ util::DestroyAt(mutex->_storage); } void LockBusyMutex(BusyMutexType *mutex) { /* Check pre-conditions. */ AMS_ASSERT(mutex->state == BusyMutexType::State_Initialized); /* Lock mutex. */ util::GetReference(mutex->_storage).Lock(); /* Set owner thread. */ mutex->owner_thread = impl::GetCurrentThread(); } bool TryLockBusyMutex(BusyMutexType *mutex) { /* Check pre-conditions. */ AMS_ASSERT(mutex->state == BusyMutexType::State_Initialized); /* Try to lock mutex. */ const bool locked = util::GetReference(mutex->_storage).TryLock(); /* Set owner thread. */ if (locked) { mutex->owner_thread = impl::GetCurrentThread(); } return locked; } void UnlockBusyMutex(BusyMutexType *mutex) { /* Check pre-conditions. */ AMS_ASSERT(mutex->state == BusyMutexType::State_Initialized); AMS_ASSERT(util::GetReference(mutex->_storage).IsLocked() && mutex->owner_thread == impl::GetCurrentThread()); /* Unlock. */ util::GetReference(mutex->_storage).Unlock(); } }
2,713
C++
.cpp
67
34.298507
118
0.662861
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,718
os_light_event.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/os_light_event.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "impl/os_timeout_helper.hpp" #if defined(ATMOSPHERE_OS_HORIZON) #include "impl/os_internal_light_event_impl.os.horizon.hpp" #else #include "impl/os_internal_light_event_impl.os.generic.hpp" #endif namespace ams::os { bool is_auto_clear; bool is_initialized; impl::InternalLightEventStorage storage; void InitializeLightEvent(LightEventType *event, bool signaled, EventClearMode clear_mode) { /* Set member variables. */ event->is_auto_clear = clear_mode == EventClearMode_AutoClear; event->is_initialized = true; /* Create object. */ util::ConstructAt(event->storage, signaled); } void FinalizeLightEvent(LightEventType *event) { /* Set not-initialized. */ event->is_initialized = false; /* Destroy object. */ util::DestroyAt(event->storage); } void SignalLightEvent(LightEventType *event) { /* Check pre-conditions. */ AMS_ASSERT(event->is_initialized); /* Signal. */ if (event->is_auto_clear) { return util::GetReference(event->storage).SignalWithAutoClear(); } else { return util::GetReference(event->storage).SignalWithManualClear(); } } void WaitLightEvent(LightEventType *event) { /* Check pre-conditions. */ AMS_ASSERT(event->is_initialized); /* Wait. */ if (event->is_auto_clear) { return util::GetReference(event->storage).WaitWithAutoClear(); } else { return util::GetReference(event->storage).WaitWithManualClear(); } } bool TryWaitLightEvent(LightEventType *event) { /* Check pre-conditions. */ AMS_ASSERT(event->is_initialized); /* Wait. */ if (event->is_auto_clear) { return util::GetReference(event->storage).TryWaitWithAutoClear(); } else { return util::GetReference(event->storage).TryWaitWithManualClear(); } } bool TimedWaitLightEvent(LightEventType *event, TimeSpan timeout) { /* Check pre-conditions. */ AMS_ASSERT(event->is_initialized); AMS_ASSERT(timeout.GetNanoSeconds() >= 0); /* Create timeout helper. */ impl::TimeoutHelper timeout_helper(timeout); /* Wait. */ if (event->is_auto_clear) { return util::GetReference(event->storage).TimedWaitWithAutoClear(timeout_helper); } else { return util::GetReference(event->storage).TimedWaitWithManualClear(timeout_helper); } } void ClearLightEvent(LightEventType *event) { /* Check pre-conditions. */ AMS_ASSERT(event->is_initialized); return util::GetReference(event->storage).Clear(); } }
3,448
C++
.cpp
88
32.170455
96
0.656989
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,719
os_process_code_memory.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/os_process_code_memory.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "impl/os_process_code_memory_impl.hpp" namespace ams::os { Result MapProcessCodeMemory(u64 *out, NativeHandle handle, const ProcessMemoryRegion *regions, size_t num_regions, AddressSpaceGenerateRandomFunction generate_random) { R_RETURN(::ams::os::impl::ProcessCodeMemoryImpl::Map(out, handle, regions, num_regions, generate_random)); } Result UnmapProcessCodeMemory(NativeHandle handle, u64 process_code_address, const ProcessMemoryRegion *regions, size_t num_regions) { R_RETURN(::ams::os::impl::ProcessCodeMemoryImpl::Unmap(handle, process_code_address, regions, num_regions)); } }
1,293
C++
.cpp
25
48.72
172
0.761076
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,720
os_memory_attribute.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/os_memory_attribute.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "impl/os_memory_attribute_impl.hpp" namespace ams::os { void SetMemoryAttribute(uintptr_t address, size_t size, MemoryAttribute attr) { /* Check pre-conditions. */ AMS_ASSERT(util::IsAligned(address, MemoryPageSize)); AMS_ASSERT(util::IsAligned(size, MemoryPageSize)); return impl::SetMemoryAttributeImpl(address, size, attr); } }
1,047
C++
.cpp
25
38.56
83
0.739686
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,721
os_interrupt_event.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/os_interrupt_event.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> #include "impl/os_interrupt_event_impl.hpp" #include "impl/os_multiple_wait_holder_impl.hpp" #include "impl/os_multiple_wait_object_list.hpp" namespace ams::os { void InitializeInterruptEvent(InterruptEventType *event, InterruptName name, EventClearMode clear_mode) { /* Initialize member variables. */ event->clear_mode = static_cast<u8>(clear_mode); /* Initialize implementation. */ util::ConstructAt(event->impl, name, clear_mode); /* Mark initialized. */ event->state = InterruptEventType::State_Initialized; } void FinalizeInterruptEvent(InterruptEventType *event) { AMS_ASSERT(event->state == InterruptEventType::State_Initialized); /* Mark uninitialized. */ event->state = InterruptEventType::State_NotInitialized; /* Destroy objects. */ util::DestroyAt(event->impl); } void WaitInterruptEvent(InterruptEventType *event) { AMS_ASSERT(event->state == InterruptEventType::State_Initialized); return GetReference(event->impl).Wait(); } bool TryWaitInterruptEvent(InterruptEventType *event) { AMS_ASSERT(event->state == InterruptEventType::State_Initialized); return GetReference(event->impl).TryWait(); } bool TimedWaitInterruptEvent(InterruptEventType *event, TimeSpan timeout) { AMS_ASSERT(event->state == InterruptEventType::State_Initialized); AMS_ASSERT(timeout.GetNanoSeconds() >= 0); return GetReference(event->impl).TimedWait(timeout); } void ClearInterruptEvent(InterruptEventType *event) { AMS_ASSERT(event->state == InterruptEventType::State_Initialized); return GetReference(event->impl).Clear(); } NativeHandle GetInterruptEventHandle(const InterruptEventType *event) { AMS_ASSERT(event->state == InterruptEventType::State_Initialized); return GetReference(event->impl).GetHandle(); } void InitializeMultiWaitHolder(MultiWaitHolderType *multi_wait_holder, InterruptEventType *event) { AMS_ASSERT(event->state == InterruptEventType::State_Initialized); util::ConstructAt(GetReference(multi_wait_holder->impl_storage).holder_of_interrupt_event_storage, event); multi_wait_holder->user_data = 0; } }
2,957
C++
.cpp
62
41.951613
114
0.721431
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,722
os_argument.cpp
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/os/os_argument.cpp
/* * Copyright (c) Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stratosphere.hpp> namespace ams::os { namespace { struct CommandLineParameter { int argc; char **argv; }; constinit const char *g_command_line_parameter_argv[2] = { "", nullptr }; constinit CommandLineParameter g_command_line_parameter = { 1, const_cast<char **>(g_command_line_parameter_argv), }; } void SetHostArgc(int argc) { g_command_line_parameter.argc = argc; } void SetHostArgv(char **argv) { g_command_line_parameter.argv = argv; } int GetHostArgc() { return g_command_line_parameter.argc; } char **GetHostArgv() { return g_command_line_parameter.argv; } }
1,381
C++
.cpp
41
28.195122
81
0.668421
Atmosphere-NX/Atmosphere
14,324
1,207
54
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false