Revert "hoc-clk: add live vdd2, live boost clock and basic pwm dimming"

This reverts commit 15b7df8ef1.
This commit is contained in:
souldbminersmwc
2025-11-09 16:14:52 -05:00
parent 22ec140738
commit 21a3f953d7
3804 changed files with 435 additions and 570162 deletions

View File

@@ -1,98 +0,0 @@
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "sysupdater_apply_manager.hpp"
namespace ams::mitm::sysupdater {
namespace {
alignas(os::MemoryPageSize) u8 g_boot_image_update_buffer[64_KB];
updater::BootImageUpdateType GetBootImageUpdateType() {
/* NOTE: Here Nintendo uses the value of system setting systeminitializer!boot_image_update_type...but we prefer not to take the risk. */
return updater::GetBootImageUpdateType(spl::GetHardwareType());
}
Result MarkPreCommitForBootImages() {
/* Set verification required for both normal and safe mode. */
R_TRY(updater::MarkVerifyingRequired(updater::BootModeType::Normal, g_boot_image_update_buffer, sizeof(g_boot_image_update_buffer)));
R_TRY(updater::MarkVerifyingRequired(updater::BootModeType::Safe, g_boot_image_update_buffer, sizeof(g_boot_image_update_buffer)));
/* Pre-commit is now marked. */
R_SUCCEED();
}
Result UpdateBootImages() {
/* Define a helper to update the images. */
auto UpdateBootImageImpl = [](updater::BootModeType boot_mode, updater::BootImageUpdateType boot_image_update_type) -> Result {
/* Get the boot image package id. */
ncm::SystemDataId boot_image_package_id = {};
R_TRY_CATCH(updater::GetBootImagePackageId(std::addressof(boot_image_package_id), boot_mode, g_boot_image_update_buffer, sizeof(g_boot_image_update_buffer))) {
R_CATCH(updater::ResultBootImagePackageNotFound) {
/* Nintendo simply falls through when the package is not found. */
}
} R_END_TRY_CATCH;
/* Update the boot images. */
R_TRY_CATCH(updater::UpdateBootImagesFromPackage(boot_image_package_id, boot_mode, g_boot_image_update_buffer, sizeof(g_boot_image_update_buffer), boot_image_update_type)) {
R_CATCH(updater::ResultBootImagePackageNotFound) {
/* Nintendo simply falls through when the package is not found. */
}
} R_END_TRY_CATCH;
/* Mark the images verified. */
R_TRY(updater::MarkVerified(boot_mode, g_boot_image_update_buffer, sizeof(g_boot_image_update_buffer)));
/* The boot images are updated. */
R_SUCCEED();
};
/* Get the boot image update type. */
auto boot_image_update_type = GetBootImageUpdateType();
/* Update boot images for safe mode. */
R_TRY(UpdateBootImageImpl(updater::BootModeType::Safe, boot_image_update_type));
/* Update boot images for normal mode. */
R_TRY(UpdateBootImageImpl(updater::BootModeType::Normal, boot_image_update_type));
/* Both sets of images are updated. */
R_SUCCEED();
}
}
Result SystemUpdateApplyManager::ApplyPackageTask(ncm::PackageSystemDowngradeTask *task) {
/* Lock the apply mutex. */
std::scoped_lock lk(m_apply_mutex);
/* NOTE: Here, Nintendo creates a system report for the update. */
/* Mark boot images to note that we're updating. */
R_TRY(MarkPreCommitForBootImages());
/* Commit the task. */
R_TRY(task->Commit());
/* Update the boot images. */
R_TRY(UpdateBootImages());
R_SUCCEED();
}
}

View File

@@ -1,30 +0,0 @@
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <stratosphere.hpp>
namespace ams::mitm::sysupdater {
class SystemUpdateApplyManager {
private:
os::SdkMutex m_apply_mutex;
public:
constexpr SystemUpdateApplyManager() : m_apply_mutex() { /* ... */ }
Result ApplyPackageTask(ncm::PackageSystemDowngradeTask *task);
};
}

View File

@@ -1,80 +0,0 @@
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "sysupdater_async_impl.hpp"
#include "sysupdater_async_thread_allocator.hpp"
namespace ams::mitm::sysupdater {
Result AsyncBase::ToAsyncResult(Result result) {
R_TRY_CATCH(result) {
R_CONVERT(nim::ResultHttpConnectionCanceled, ns::ResultCanceled());
R_CONVERT(ncm::ResultInstallTaskCancelled, ns::ResultCanceled());
} R_END_TRY_CATCH;
R_SUCCEED();
}
AsyncPrepareSdCardUpdateImpl::~AsyncPrepareSdCardUpdateImpl() {
if (m_thread_info) {
os::WaitThread(m_thread_info->thread);
os::DestroyThread(m_thread_info->thread);
GetAsyncThreadAllocator()->Free(*m_thread_info);
}
}
Result AsyncPrepareSdCardUpdateImpl::Run() {
/* Get a thread info. */
ThreadInfo info;
R_TRY(GetAsyncThreadAllocator()->Allocate(std::addressof(info)));
/* Set the thread info's priority. */
info.priority = AMS_GET_SYSTEM_THREAD_PRIORITY(mitm_sysupdater, AsyncPrepareSdCardUpdateTask);
/* Ensure that we clean up appropriately. */
ON_SCOPE_EXIT {
if (!m_thread_info) {
GetAsyncThreadAllocator()->Free(info);
}
};
/* Create a thread for the task. */
R_TRY(os::CreateThread(info.thread, [](void *arg) {
auto *async = reinterpret_cast<AsyncPrepareSdCardUpdateImpl *>(arg);
async->m_result = async->Execute();
async->m_event.Signal();
}, this, info.stack, info.stack_size, info.priority));
/* Set the thread name. */
os::SetThreadNamePointer(info.thread, AMS_GET_SYSTEM_THREAD_NAME(mitm_sysupdater, AsyncPrepareSdCardUpdateTask));
/* Start the thread. */
os::StartThread(info.thread);
/* Set our thread info. */
m_thread_info = info;
R_SUCCEED();
}
Result AsyncPrepareSdCardUpdateImpl::Execute() {
R_RETURN(m_task->PrepareAndExecute());
}
void AsyncPrepareSdCardUpdateImpl::CancelImpl() {
m_task->Cancel();
}
}

View File

@@ -1,112 +0,0 @@
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <stratosphere.hpp>
#include "sysupdater_thread_allocator.hpp"
namespace ams::mitm::sysupdater {
class ErrorContextHolder {
private:
err::ErrorContext m_error_context;
public:
constexpr ErrorContextHolder() : m_error_context{} { /* ... */ }
virtual ~ErrorContextHolder() { /* ... */ }
template<typename T>
Result SaveErrorContextIfFailed(T &async, Result result) {
ON_RESULT_FAILURE { async.GetErrorContext(std::addressof(m_error_context)); };
R_RETURN(result);
}
template<typename T>
Result GetAndSaveErrorContext(T &async) {
R_RETURN(this->SaveErrorContextIfFailed(async, async.Get()));
}
template<typename T>
Result SaveInternalTaskErrorContextIfFailed(T &async, Result result) {
ON_RESULT_FAILURE { async.CreateErrorContext(std::addressof(m_error_context)); };
R_RETURN(result);
}
const err::ErrorContext &GetErrorContextImpl() {
return m_error_context;
}
};
class AsyncBase {
public:
virtual ~AsyncBase() { /* ... */ }
static Result ToAsyncResult(Result result);
Result Cancel() {
this->CancelImpl();
R_SUCCEED();
}
virtual Result GetErrorContext(sf::Out<err::ErrorContext> out) {
*out = {};
R_SUCCEED();
}
private:
virtual void CancelImpl() = 0;
};
class AsyncResultBase : public AsyncBase {
public:
virtual ~AsyncResultBase() { /* ... */ }
Result Get() {
R_RETURN(ToAsyncResult(this->GetImpl()));
}
private:
virtual Result GetImpl() = 0;
};
static_assert(ns::impl::IsIAsyncResult<AsyncResultBase>);
/* NOTE: Based off of ns AsyncPrepareCardUpdateImpl. */
/* We don't implement the RequestServer::ManagedStop details, as we don't implement stoppable request list. */
class AsyncPrepareSdCardUpdateImpl : public AsyncResultBase, private ErrorContextHolder {
private:
Result m_result;
os::SystemEvent m_event;
util::optional<ThreadInfo> m_thread_info;
ncm::InstallTaskBase *m_task;
public:
AsyncPrepareSdCardUpdateImpl(ncm::InstallTaskBase *task) : m_result(ResultSuccess()), m_event(os::EventClearMode_ManualClear, true), m_thread_info(), m_task(task) { /* ... */ }
virtual ~AsyncPrepareSdCardUpdateImpl();
os::SystemEvent &GetEvent() { return m_event; }
virtual Result GetErrorContext(sf::Out<err::ErrorContext> out) override {
*out = ErrorContextHolder::GetErrorContextImpl();
R_SUCCEED();
}
Result Run();
private:
Result Execute();
virtual void CancelImpl() override;
virtual Result GetImpl() override { return m_result; }
};
}

View File

@@ -1,38 +0,0 @@
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "sysupdater_async_thread_allocator.hpp"
namespace ams::mitm::sysupdater {
namespace {
constexpr inline int AsyncThreadCount = 1;
constexpr inline size_t AsyncThreadStackSize = 32_KB;
os::ThreadType g_async_threads[AsyncThreadCount];
alignas(os::ThreadStackAlignment) u8 g_async_thread_stack_heap[AsyncThreadCount * AsyncThreadStackSize];
constinit ThreadAllocator g_async_thread_allocator(g_async_threads, AsyncThreadCount, os::InvalidThreadPriority, g_async_thread_stack_heap, sizeof(g_async_thread_stack_heap), AsyncThreadStackSize);
}
ThreadAllocator *GetAsyncThreadAllocator() {
return std::addressof(g_async_thread_allocator);
}
}

View File

@@ -1,24 +0,0 @@
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <stratosphere.hpp>
#include "sysupdater_thread_allocator.hpp"
namespace ams::mitm::sysupdater {
ThreadAllocator *GetAsyncThreadAllocator();
}

View File

@@ -1,257 +0,0 @@
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "sysupdater_fs_utils.hpp"
namespace ams::mitm::sysupdater {
namespace {
constexpr inline const char * const NcaExtension = ".nca";
constexpr inline const char * const NspExtension = ".nsp";
constexpr inline const size_t NcaExtensionSize = 4;
constexpr inline const size_t NspExtensionSize = 4;
constexpr const ams::fs::PathFlags SdCardContentMetaPathNormalizePathFlags = [] {
fs::PathFlags flags{};
flags.AllowMountName();
return flags;
}();
static_assert(NcaExtensionSize == NspExtensionSize);
constexpr inline const size_t NcaNspExtensionSize = NcaExtensionSize;
Result CheckNcaOrNsp(const char **path) {
/* Ensure that the path is currently at the mount name delimeter. */
R_UNLESS(util::Strncmp(*path, ams::fs::impl::MountNameDelimiter, util::Strnlen(ams::fs::impl::MountNameDelimiter, ams::fs::EntryNameLengthMax)) == 0, fs::ResultPathNotFound());
/* Advance past the :. */
static_assert(ams::fs::impl::MountNameDelimiter[0] == ':');
*path += 1;
/* Ensure path is long enough for the extension. */
const size_t path_len = util::Strnlen(*path, ams::fs::EntryNameLengthMax);
R_UNLESS(path_len > NcaNspExtensionSize, fs::ResultPathNotFound());
/* Get the extension. */
const char * const extension = *path + path_len - NcaNspExtensionSize;
/* Ensure nca or nsp. */
const bool is_nca = util::Strnicmp(extension, NcaExtension, NcaNspExtensionSize) == 0;
const bool is_nsp = util::Strnicmp(extension, NspExtension, NcaNspExtensionSize) == 0;
R_UNLESS(is_nca || is_nsp, fs::ResultPathNotFound());
R_SUCCEED();
}
Result ParseMountName(const char **path, std::shared_ptr<ams::fs::fsa::IFileSystem> *out) {
/* The equivalent function here supports all the common mount names; we'll only support the SD card, system content storage. */
if (const auto mount_len = util::Strnlen(ams::fs::impl::SdCardFileSystemMountName, ams::fs::MountNameLengthMax); util::Strncmp(*path, ams::fs::impl::SdCardFileSystemMountName, mount_len) == 0) {
/* Advance the path. */
*path += mount_len;
/* Open the SD card. This uses libnx bindings. */
FsFileSystem fs;
R_TRY(fsOpenSdCardFileSystem(std::addressof(fs)));
/* Allocate a new filesystem wrapper. */
auto fsa = std::make_shared<ams::fs::RemoteFileSystem>(fs);
R_UNLESS(fsa != nullptr, fs::ResultAllocationMemoryFailedInSdCardA());
/* Set the output fs. */
*out = std::move(fsa);
} else if (const auto mount_len = util::Strnlen(ams::fs::impl::ContentStorageSystemMountName, ams::fs::MountNameLengthMax); util::Strncmp(*path, ams::fs::impl::ContentStorageSystemMountName, mount_len) == 0) {
/* Advance the path. */
*path += mount_len;
/* Open the system content storage. This uses libnx bindings. */
FsFileSystem fs;
R_TRY(fsOpenContentStorageFileSystem(std::addressof(fs), FsContentStorageId_System));
/* Allocate a new filesystem wrapper. */
auto fsa = std::make_shared<ams::fs::RemoteFileSystem>(fs);
R_UNLESS(fsa != nullptr, fs::ResultAllocationMemoryFailedInContentStorageA());
/* Set the output fs. */
*out = std::move(fsa);
} else {
R_THROW(fs::ResultPathNotFound());
}
/* Ensure that there's something that could be a mount name delimiter. */
R_UNLESS(util::Strnlen(*path, fs::EntryNameLengthMax) != 0, fs::ResultPathNotFound());
R_SUCCEED();
}
Result ParseNsp(const char **path, std::shared_ptr<ams::fs::fsa::IFileSystem> *out, std::shared_ptr<ams::fs::fsa::IFileSystem> base_fs) {
const char *work_path = *path;
/* Advance to the nsp extension. */
while (true) {
if (util::Strnicmp(work_path, NspExtension, NspExtensionSize) == 0) {
if (work_path[NspExtensionSize] == '\x00' || work_path[NspExtensionSize] == '/') {
break;
}
work_path += NspExtensionSize;
} else {
R_UNLESS(*work_path != '\x00', fs::ResultPathNotFound());
work_path += 1;
}
}
/* Advance past the extension. */
work_path += NspExtensionSize;
/* Get the nsp path. */
ams::fs::Path nsp_path;
R_TRY(nsp_path.InitializeWithNormalization(*path, work_path - *path));
/* Open the file storage. */
std::shared_ptr<ams::fs::FileStorageBasedFileSystem> file_storage = fssystem::AllocateShared<ams::fs::FileStorageBasedFileSystem>();
R_UNLESS(file_storage != nullptr, fs::ResultAllocationMemoryFailedInNcaFileSystemServiceImplA());
R_TRY(file_storage->Initialize(std::move(base_fs), nsp_path, ams::fs::OpenMode_Read));
/* Create a partition fs. */
R_TRY(fssystem::GetFileSystemCreatorInterfaces()->partition_fs_creator->Create(out, std::move(file_storage)));
/* Update the path. */
*path = work_path;
R_SUCCEED();
}
Result ParseNca(const char **path, std::shared_ptr<fssystem::NcaReader> *out, std::shared_ptr<ams::fs::fsa::IFileSystem> base_fs) {
/* Open the file storage. */
std::shared_ptr<ams::fs::FileStorageBasedFileSystem> file_storage = fssystem::AllocateShared<ams::fs::FileStorageBasedFileSystem>();
R_UNLESS(file_storage != nullptr, fs::ResultAllocationMemoryFailedInNcaFileSystemServiceImplB());
/* Get the nca path. */
ams::fs::Path nca_path;
R_TRY(nca_path.InitializeWithNormalization(*path));
R_TRY(file_storage->Initialize(std::move(base_fs), nca_path, ams::fs::OpenMode_Read));
/* Create the nca reader. */
std::shared_ptr<fssystem::NcaReader> nca_reader;
R_TRY(fssystem::GetFileSystemCreatorInterfaces()->storage_on_nca_creator->CreateNcaReader(std::addressof(nca_reader), file_storage));
/* NOTE: Here Nintendo validates program ID, but this does not need checking in the meta case. */
/* Set output reader. */
*out = std::move(nca_reader);
R_SUCCEED();
}
Result OpenMetaStorage(std::shared_ptr<ams::fs::IStorage> *out, std::shared_ptr<fssystem::IAsynchronousAccessSplitter> *out_splitter, std::shared_ptr<fssystem::NcaReader> nca_reader, fssystem::NcaFsHeader::FsType *out_fs_type) {
/* Ensure the nca is a meta nca. */
R_UNLESS(nca_reader->GetContentType() == fssystem::NcaHeader::ContentType::Meta, fs::ResultPreconditionViolation());
/* We only support SD card ncas, so ensure this isn't a gamecard nca. */
R_UNLESS(nca_reader->GetDistributionType() != fssystem::NcaHeader::DistributionType::GameCard, fs::ResultPermissionDenied());
/* Here Nintendo would call GetPartitionIndex(), but we don't need to, because it's meta. */
constexpr int MetaPartitionIndex = 0;
/* Open fs header reader. */
fssystem::NcaFsHeaderReader fs_header_reader;
R_TRY(fssystem::GetFileSystemCreatorInterfaces()->storage_on_nca_creator->Create(out, out_splitter, std::addressof(fs_header_reader), std::move(nca_reader), MetaPartitionIndex));
/* Set the output fs type. */
*out_fs_type = fs_header_reader.GetFsType();
R_SUCCEED();
}
Result OpenContentMetaFileSystem(std::shared_ptr<ams::fs::fsa::IFileSystem> *out, const char *path) {
/* Parse the mount name to get a filesystem. */
const char *cur_path = path;
std::shared_ptr<ams::fs::fsa::IFileSystem> base_fs;
R_TRY(ParseMountName(std::addressof(cur_path), std::addressof(base_fs)));
/* Ensure the path is an nca or nsp. */
R_TRY(CheckNcaOrNsp(std::addressof(cur_path)));
/* Try to parse as nsp. */
std::shared_ptr<ams::fs::fsa::IFileSystem> nsp_fs;
if (R_SUCCEEDED(ParseNsp(std::addressof(cur_path), std::addressof(nsp_fs), base_fs))) {
/* nsp target is only allowed for type package, and we're assuming type meta. */
R_UNLESS(*path != '\x00', fs::ResultInvalidArgument());
/* Use the nsp fs as the base fs. */
base_fs = std::move(nsp_fs);
}
/* Parse as nca. */
std::shared_ptr<fssystem::NcaReader> nca_reader;
R_TRY(ParseNca(std::addressof(cur_path), std::addressof(nca_reader), std::move(base_fs)));
/* Open meta storage. */
std::shared_ptr<ams::fs::IStorage> storage;
std::shared_ptr<fssystem::IAsynchronousAccessSplitter> splitter;
fssystem::NcaFsHeader::FsType fs_type = static_cast<fssystem::NcaFsHeader::FsType>(~0);
R_TRY(OpenMetaStorage(std::addressof(storage), std::addressof(splitter), std::move(nca_reader), std::addressof(fs_type)));
/* Open the appropriate interface. */
const auto * const creator_intfs = fssystem::GetFileSystemCreatorInterfaces();
switch (fs_type) {
case fssystem::NcaFsHeader::FsType::PartitionFs: R_RETURN(creator_intfs->partition_fs_creator->Create(out, std::move(storage)));
case fssystem::NcaFsHeader::FsType::RomFs: R_RETURN(creator_intfs->rom_fs_creator->Create(out, std::move(storage)));
default:
R_THROW(fs::ResultInvalidNcaFileSystemType());
}
}
}
bool PathView::HasPrefix(util::string_view prefix) const {
return m_path.compare(0, prefix.length(), prefix) == 0;
}
bool PathView::HasSuffix(util::string_view suffix) const {
return m_path.compare(m_path.length() - suffix.length(), suffix.length(), suffix) == 0;
}
util::string_view PathView::GetFileName() const {
auto pos = m_path.find_last_of("/");
return pos != util::string_view::npos ? m_path.substr(pos + 1) : m_path;
}
Result MountSdCardContentMeta(const char *mount_name, const char *path, ams::fs::ContentAttributes attr) {
/* TODO: What does attributes actually get used for? */
AMS_UNUSED(attr);
/* Sanitize input. */
/* NOTE: This is an internal API, so we won't bother with mount name sanitization. */
R_UNLESS(path != nullptr, fs::ResultInvalidPath());
/* Normalize the path. */
char normalized_path[fs::EntryNameLengthMax + 1];
R_TRY(ams::fs::PathFormatter::Normalize(normalized_path, sizeof(normalized_path), path, std::strlen(path) + 1, SdCardContentMetaPathNormalizePathFlags));
/* Open the filesystem. */
std::shared_ptr<ams::fs::fsa::IFileSystem> fs;
R_TRY(OpenContentMetaFileSystem(std::addressof(fs), normalized_path));
/* Create a holder for the fs. */
std::unique_ptr unique_fs = std::make_unique<fssystem::ForwardingFileSystem>(std::move(fs));
R_UNLESS(unique_fs != nullptr, fs::ResultAllocationMemoryFailedNew());
/* Register the fs. */
R_RETURN(ams::fs::fsa::Register(mount_name, std::move(unique_fs)));
}
}

View File

@@ -1,33 +0,0 @@
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <stratosphere.hpp>
namespace ams::mitm::sysupdater {
class PathView {
private:
util::string_view m_path;
public:
PathView(util::string_view p) : m_path(p) { /* ...*/ }
bool HasPrefix(util::string_view prefix) const;
bool HasSuffix(util::string_view suffix) const;
util::string_view GetFileName() const;
};
Result MountSdCardContentMeta(const char *mount_name, const char *path, ams::fs::ContentAttributes attr);
}

View File

@@ -1,65 +0,0 @@
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "../amsmitm_initialization.hpp"
#include "sysupdater_module.hpp"
#include "sysupdater_service.hpp"
#include "sysupdater_async_impl.hpp"
namespace ams::mitm::sysupdater {
namespace {
enum PortIndex {
PortIndex_Sysupdater,
PortIndex_Count,
};
constexpr sm::ServiceName SystemUpdateServiceName = sm::ServiceName::Encode("ams:su");
constexpr size_t SystemUpdateMaxSessions = 1;
constexpr size_t MaxSessions = SystemUpdateMaxSessions + 3;
struct ServerOptions {
static constexpr size_t PointerBufferSize = 1_KB;
static constexpr size_t MaxDomains = 0;
static constexpr size_t MaxDomainObjects = 0;
static constexpr bool CanDeferInvokeRequest = false;
static constexpr bool CanManageMitmServers = false;
};
sf::hipc::ServerManager<PortIndex_Count, ServerOptions, MaxSessions> g_server_manager;
constinit sf::UnmanagedServiceObject<sysupdater::impl::ISystemUpdateInterface, sysupdater::SystemUpdateService> g_system_update_service_object;
}
void MitmModule::ThreadFunction(void *) {
/* Wait until initialization is complete. */
mitm::WaitInitialized();
/* Connect to nim. */
nim::InitializeForNetworkInstallManager();
ON_SCOPE_EXIT { nim::FinalizeForNetworkInstallManager(); };
/* Register ams:su. */
R_ABORT_UNLESS(g_server_manager.RegisterObjectForServer(g_system_update_service_object.GetShared(), SystemUpdateServiceName, SystemUpdateMaxSessions));
/* Loop forever, servicing our services. */
g_server_manager.LoopProcess();
}
}

View File

@@ -1,24 +0,0 @@
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <stratosphere.hpp>
#include "../amsmitm_module.hpp"
namespace ams::mitm::sysupdater {
DEFINE_MITM_MODULE_CLASS(0x8000, AMS_GET_SYSTEM_THREAD_PRIORITY(mitm_sysupdater, IpcServer));
}

View File

@@ -1,522 +0,0 @@
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "sysupdater_service.hpp"
#include "sysupdater_async_impl.hpp"
#include "sysupdater_fs_utils.hpp"
namespace ams::mitm::sysupdater {
namespace {
/* ExFat NCAs prior to 2.0.0 do not actually include the exfat driver, and don't boot. */
constexpr inline u32 MinimumVersionForExFatDriver = 65536;
bool IsExFatDriverSupported(const ncm::ContentMetaInfo &info) {
return info.version >= MinimumVersionForExFatDriver && ((info.attributes & ncm::ContentMetaAttribute_IncludesExFatDriver) != 0);
}
template<typename F>
Result ForEachFileInDirectory(const char *root_path, F f) {
/* Open the directory. */
fs::DirectoryHandle dir;
R_TRY(fs::OpenDirectory(std::addressof(dir), root_path, fs::OpenDirectoryMode_File));
ON_SCOPE_EXIT { fs::CloseDirectory(dir); };
while (true) {
/* Read the current entry. */
s64 count;
fs::DirectoryEntry entry;
R_TRY(fs::ReadDirectory(std::addressof(count), std::addressof(entry), dir, 1));
if (count == 0) {
break;
}
/* Invoke our handler on the entry. */
bool done;
R_TRY(f(std::addressof(done), entry));
R_SUCCEED_IF(done);
}
R_SUCCEED();
}
Result ConvertToFsCommonPath(char *dst, size_t dst_size, const char *package_root_path, const char *entry_path) {
char package_path[ams::fs::EntryNameLengthMax];
const size_t path_len = util::SNPrintf(package_path, sizeof(package_path), "%s%s", package_root_path, entry_path);
AMS_ABORT_UNLESS(path_len < ams::fs::EntryNameLengthMax);
R_RETURN(ams::fs::ConvertToFsCommonPath(dst, dst_size, package_path));
}
Result LoadContentMeta(ncm::AutoBuffer *out, const char *package_root_path, const fs::DirectoryEntry &entry) {
AMS_ABORT_UNLESS(PathView(entry.name).HasSuffix(".cnmt.nca"));
char path[ams::fs::EntryNameLengthMax];
R_TRY(ConvertToFsCommonPath(path, sizeof(path), package_root_path, entry.name));
R_RETURN(ncm::TryReadContentMetaPath(out, path, ncm::ReadContentMetaPathAlongWithExtendedDataAndDigest));
}
Result ReadContentMetaPath(ncm::AutoBuffer *out, const char *package_root, const ncm::ContentInfo &content_info) {
/* Get the .cnmt.nca path for the info. */
char cnmt_nca_name[ncm::ContentIdStringLength + 10];
ncm::GetStringFromContentId(cnmt_nca_name, sizeof(cnmt_nca_name), content_info.GetId());
std::memcpy(cnmt_nca_name + ncm::ContentIdStringLength, ".cnmt.nca", std::strlen(".cnmt.nca"));
cnmt_nca_name[sizeof(cnmt_nca_name) - 1] = '\x00';
/* Create a new path. */
ncm::Path content_path;
R_TRY(ConvertToFsCommonPath(content_path.str, sizeof(content_path.str), package_root, cnmt_nca_name));
/* Read the content meta path. */
R_RETURN(ncm::TryReadContentMetaPath(out, content_path.str, ncm::ReadContentMetaPathAlongWithExtendedDataAndDigest));
}
Result GetSystemUpdateUpdateContentInfoFromPackage(ncm::ContentInfo *out, const char *package_root) {
bool found_system_update = false;
/* Iterate over all files to find the system update meta. */
R_TRY(ForEachFileInDirectory(package_root, [&](bool *done, const fs::DirectoryEntry &entry) -> Result {
/* Don't early terminate by default. */
*done = false;
/* We have nothing to list if we're not looking at a meta. */
R_SUCCEED_IF(!PathView(entry.name).HasSuffix(".cnmt.nca"));
/* Read the content meta path, and build. */
ncm::AutoBuffer package_meta;
R_TRY(LoadContentMeta(std::addressof(package_meta), package_root, entry));
/* Create a reader. */
const auto reader = ncm::PackagedContentMetaReader(package_meta.Get(), package_meta.GetSize());
/* If we find a system update, we're potentially done. */
if (reader.GetHeader()->type == ncm::ContentMetaType::SystemUpdate) {
/* Try to parse a content id from the name. */
auto content_id = ncm::GetContentIdFromString(entry.name, sizeof(entry.name));
R_UNLESS(content_id, ncm::ResultInvalidPackageFormat());
/* We're done. */
*done = true;
found_system_update = true;
*out = ncm::ContentInfo::Make(*content_id, entry.file_size, ncm::ContentInfo::DefaultContentAttributes, ncm::ContentType::Meta);
}
R_SUCCEED();
}));
/* If we didn't find anything, error. */
R_UNLESS(found_system_update, ncm::ResultSystemUpdateNotFoundInPackage());
R_SUCCEED();
}
Result ValidateSystemUpdate(Result *out_result, Result *out_exfat_result, UpdateValidationInfo *out_info, const ncm::PackagedContentMetaReader &update_reader, const char *package_root) {
/* Clear output. */
*out_result = ResultSuccess();
*out_exfat_result = ResultSuccess();
/* We want to track all content the update requires. */
const size_t num_content_metas = update_reader.GetContentMetaCount();
bool content_meta_valid[num_content_metas] = {};
/* Allocate a buffer to use for validation. */
size_t data_buffer_size = 1_MB;
void *data_buffer;
do {
data_buffer = std::malloc(data_buffer_size);
if (data_buffer != nullptr) {
break;
}
data_buffer_size /= 2;
} while (data_buffer_size >= 16_KB);
R_UNLESS(data_buffer != nullptr, fs::ResultAllocationMemoryFailedNew());
ON_SCOPE_EXIT { std::free(data_buffer); };
/* Declare helper for result validation. */
auto ValidateResult = [&](Result result) ALWAYS_INLINE_LAMBDA -> Result {
*out_result = result;
R_RETURN(result);
};
/* Iterate over all files to find all content metas. */
R_TRY(ForEachFileInDirectory(package_root, [&](bool *done, const fs::DirectoryEntry &entry) -> Result {
/* Clear output. */
*out_info = {};
/* Don't early terminate by default. */
*done = false;
/* We have nothing to list if we're not looking at a meta. */
R_SUCCEED_IF(!PathView(entry.name).HasSuffix(".cnmt.nca"));
/* Read the content meta path, and build. */
ncm::AutoBuffer package_meta;
R_TRY(LoadContentMeta(std::addressof(package_meta), package_root, entry));
/* Create a reader. */
const auto reader = ncm::PackagedContentMetaReader(package_meta.Get(), package_meta.GetSize());
/* Get the key for the reader. */
const auto key = reader.GetKey();
/* Check if we need to validate this content. */
bool need_validate = false;
size_t validation_index = 0;
for (size_t i = 0; i < num_content_metas; ++i) {
if (update_reader.GetContentMetaInfo(i)->ToKey() == key) {
need_validate = true;
validation_index = i;
break;
}
}
/* If we don't need to validate, continue. */
R_SUCCEED_IF(!need_validate);
/* We're validating. */
out_info->invalid_key = key;
/* Validate all contents. */
for (size_t i = 0; i < reader.GetContentCount(); ++i) {
const auto *content_info = reader.GetContentInfo(i);
const auto &content_id = content_info->GetId();
const s64 content_size = content_info->info.GetSize();
out_info->invalid_content_id = content_id;
/* Get the content id string. */
auto content_id_str = ncm::GetContentIdString(content_id);
/* Open the file. */
fs::FileHandle file;
{
char path[fs::EntryNameLengthMax];
util::SNPrintf(path, sizeof(path), "%s%s%s", package_root, content_id_str.data, content_info->GetType() == ncm::ContentType::Meta ? ".cnmt.nca" : ".nca");
if (R_FAILED(ValidateResult(fs::OpenFile(std::addressof(file), path, ams::fs::OpenMode_Read)))) {
*done = true;
R_SUCCEED();
}
}
ON_SCOPE_EXIT { fs::CloseFile(file); };
/* Validate the file size is correct. */
s64 file_size;
if (R_FAILED(ValidateResult(fs::GetFileSize(std::addressof(file_size), file)))) {
*done = true;
R_SUCCEED();
}
if (file_size != content_size) {
*out_result = ncm::ResultInvalidContentHash();
*done = true;
R_SUCCEED();
}
/* Read and hash the file in chunks. */
crypto::Sha256Generator sha;
sha.Initialize();
s64 ofs = 0;
while (ofs < content_size) {
const size_t cur_size = std::min(static_cast<size_t>(content_size - ofs), data_buffer_size);
if (R_FAILED(ValidateResult(fs::ReadFile(file, ofs, data_buffer, cur_size)))) {
*done = true;
R_SUCCEED();
}
sha.Update(data_buffer, cur_size);
ofs += cur_size;
}
/* Get the hash. */
ncm::Digest calc_digest;
sha.GetHash(std::addressof(calc_digest), sizeof(calc_digest));
/* Validate the hash. */
if (std::memcmp(std::addressof(calc_digest), std::addressof(content_info->digest), sizeof(ncm::Digest)) != 0) {
*out_result = ncm::ResultInvalidContentHash();
*done = true;
R_SUCCEED();
}
}
/* Mark the relevant content as validated. */
content_meta_valid[validation_index] = true;
*out_info = {};
R_SUCCEED();
}));
/* If we're otherwise going to succeed, ensure that every content was found. */
if (R_SUCCEEDED(*out_result)) {
for (size_t i = 0; i < num_content_metas; ++i) {
if (!content_meta_valid[i]) {
const ncm::ContentMetaInfo *info = update_reader.GetContentMetaInfo(i);
*out_info = { .invalid_key = info->ToKey(), };
if (IsExFatDriverSupported(*info)) {
*out_exfat_result = fs::ResultPathNotFound();
/* Continue, in case there's a non-exFAT failure result. */
} else {
*out_result = fs::ResultPathNotFound();
break;
}
}
}
}
R_SUCCEED();
}
Result FormatUserPackagePath(ncm::Path *out, const ncm::Path &user_path) {
/* Ensure that the user path is valid. */
R_UNLESS(user_path.str[0] == '/', fs::ResultInvalidPath());
/* Print as @Sdcard:<user_path>/ */
util::SNPrintf(out->str, sizeof(out->str), "%s:%s/", ams::fs::impl::SdCardFileSystemMountName, user_path.str);
/* Normalize, if the user provided an ending / */
const size_t len = std::strlen(out->str);
if (out->str[len - 1] == '/' && out->str[len - 2] == '/') {
out->str[len - 1] = '\x00';
}
R_SUCCEED();
}
const char *GetFirmwareVariationSettingName(settings::system::PlatformRegion region) {
switch (region) {
case settings::system::PlatformRegion_Global: return "firmware_variation";
case settings::system::PlatformRegion_China: return "t_firmware_variation";
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
ncm::FirmwareVariationId GetFirmwareVariationId() {
/* Get the firmware variation setting name. */
const char * const setting_name = GetFirmwareVariationSettingName(settings::system::GetPlatformRegion());
/* Retrieve the firmware variation id. */
ncm::FirmwareVariationId id = {};
settings::fwdbg::GetSettingsItemValue(std::addressof(id.value), sizeof(u8), "ns.systemupdate", setting_name);
return id;
}
}
Result SystemUpdateService::GetUpdateInformation(sf::Out<UpdateInformation> out, const ncm::Path &path) {
/* Adjust the path. */
ncm::Path package_root;
R_TRY(FormatUserPackagePath(std::addressof(package_root), path));
/* Create a new update information. */
UpdateInformation update_info = {};
/* Parse the update. */
{
/* Get the content info for the system update. */
ncm::ContentInfo content_info;
R_TRY(GetSystemUpdateUpdateContentInfoFromPackage(std::addressof(content_info), package_root.str));
/* Read the content meta. */
ncm::AutoBuffer content_meta_buffer;
R_TRY(ReadContentMetaPath(std::addressof(content_meta_buffer), package_root.str, content_info));
/* Create a reader. */
const auto reader = ncm::PackagedContentMetaReader(content_meta_buffer.Get(), content_meta_buffer.GetSize());
/* Get the version from the header. */
update_info.version = reader.GetHeader()->version;
/* Iterate over infos to find the system update info. */
for (size_t i = 0; i < reader.GetContentMetaCount(); ++i) {
const auto &meta_info = *reader.GetContentMetaInfo(i);
switch (meta_info.type) {
case ncm::ContentMetaType::BootImagePackage:
/* Detect exFAT support. */
update_info.exfat_supported |= IsExFatDriverSupported(meta_info);
break;
default:
break;
}
}
/* Default to no firmware variations. */
update_info.firmware_variation_count = 0;
/* Parse firmware variations if relevant. */
if (reader.GetExtendedDataSize() != 0) {
/* Get the actual firmware variation count. */
ncm::SystemUpdateMetaExtendedDataReader extended_data_reader(reader.GetExtendedData(), reader.GetExtendedDataSize());
update_info.firmware_variation_count = extended_data_reader.GetFirmwareVariationCount();
/* NOTE: Update this if Nintendo ever actually releases an update with this many variations? */
R_UNLESS(update_info.firmware_variation_count <= FirmwareVariationCountMax, ncm::ResultInvalidFirmwareVariation());
for (size_t i = 0; i < update_info.firmware_variation_count; ++i) {
update_info.firmware_variation_ids[i] = *extended_data_reader.GetFirmwareVariationId(i);
}
}
}
/* Set the parsed update info. */
out.SetValue(update_info);
R_SUCCEED();
}
Result SystemUpdateService::ValidateUpdate(sf::Out<Result> out_validate_result, sf::Out<Result> out_validate_exfat_result, sf::Out<UpdateValidationInfo> out_validate_info, const ncm::Path &path) {
/* Adjust the path. */
ncm::Path package_root;
R_TRY(FormatUserPackagePath(std::addressof(package_root), path));
/* Parse the update. */
{
/* Get the content info for the system update. */
ncm::ContentInfo content_info;
R_TRY(GetSystemUpdateUpdateContentInfoFromPackage(std::addressof(content_info), package_root.str));
/* Read the content meta. */
ncm::AutoBuffer content_meta_buffer;
R_TRY(ReadContentMetaPath(std::addressof(content_meta_buffer), package_root.str, content_info));
/* Create a reader. */
const auto reader = ncm::PackagedContentMetaReader(content_meta_buffer.Get(), content_meta_buffer.GetSize());
/* Validate the update. */
R_TRY(ValidateSystemUpdate(out_validate_result.GetPointer(), out_validate_exfat_result.GetPointer(), out_validate_info.GetPointer(), reader, package_root.str));
}
R_SUCCEED();
};
Result SystemUpdateService::SetupUpdate(sf::CopyHandle &&transfer_memory, u64 transfer_memory_size, const ncm::Path &path, bool exfat) {
R_RETURN(this->SetupUpdateImpl(std::move(transfer_memory), transfer_memory_size, path, exfat, GetFirmwareVariationId()));
}
Result SystemUpdateService::SetupUpdateWithVariation(sf::CopyHandle &&transfer_memory, u64 transfer_memory_size, const ncm::Path &path, bool exfat, ncm::FirmwareVariationId firmware_variation_id) {
R_RETURN(this->SetupUpdateImpl(std::move(transfer_memory), transfer_memory_size, path, exfat, firmware_variation_id));
}
Result SystemUpdateService::RequestPrepareUpdate(sf::OutCopyHandle out_event_handle, sf::Out<sf::SharedPointer<ns::impl::IAsyncResult>> out_async) {
/* Ensure the update is setup but not prepared. */
R_UNLESS(m_setup_update, ns::ResultCardUpdateNotSetup());
R_UNLESS(!m_requested_update, ns::ResultPrepareCardUpdateAlreadyRequested());
/* Create the async result. */
auto async_result = sf::CreateSharedObjectEmplaced<ns::impl::IAsyncResult, AsyncPrepareSdCardUpdateImpl>(std::addressof(*m_update_task));
R_UNLESS(async_result != nullptr, ns::ResultOutOfMaxRunningTask());
/* Run the task. */
R_TRY(async_result.GetImpl().Run());
/* We prepared the task! */
m_requested_update = true;
out_event_handle.SetValue(async_result.GetImpl().GetEvent().GetReadableHandle(), false);
*out_async = std::move(async_result);
R_SUCCEED();
}
Result SystemUpdateService::GetPrepareUpdateProgress(sf::Out<SystemUpdateProgress> out) {
/* Ensure the update is setup. */
R_UNLESS(m_setup_update, ns::ResultCardUpdateNotSetup());
/* Get the progress. */
auto install_progress = m_update_task->GetProgress();
out.SetValue({ .current_size = install_progress.installed_size, .total_size = install_progress.total_size });
R_SUCCEED();
}
Result SystemUpdateService::HasPreparedUpdate(sf::Out<bool> out) {
/* Ensure the update is setup. */
R_UNLESS(m_setup_update, ns::ResultCardUpdateNotSetup());
out.SetValue(m_update_task->GetProgress().state == ncm::InstallProgressState::Downloaded);
R_SUCCEED();
}
Result SystemUpdateService::ApplyPreparedUpdate() {
/* Ensure the update is setup. */
R_UNLESS(m_setup_update, ns::ResultCardUpdateNotSetup());
/* Ensure the update is prepared. */
R_UNLESS(m_update_task->GetProgress().state == ncm::InstallProgressState::Downloaded, ns::ResultCardUpdateNotPrepared());
/* Apply the task. */
R_TRY(m_apply_manager.ApplyPackageTask(std::addressof(*m_update_task)));
R_SUCCEED();
}
Result SystemUpdateService::SetupUpdateImpl(sf::NativeHandle &&transfer_memory, u64 transfer_memory_size, const ncm::Path &path, bool exfat, ncm::FirmwareVariationId firmware_variation_id) {
/* Ensure we don't already have an update set up. */
R_UNLESS(!m_setup_update, ns::ResultCardUpdateAlreadySetup());
/* Destroy any existing update tasks. */
nim::SystemUpdateTaskId id;
auto count = nim::ListSystemUpdateTask(std::addressof(id), 1);
if (count > 0) {
R_TRY(nim::DestroySystemUpdateTask(id));
}
/* Initialize the update task. */
R_TRY(InitializeUpdateTask(std::move(transfer_memory), transfer_memory_size, path, exfat, firmware_variation_id));
/* The update is now set up. */
m_setup_update = true;
R_SUCCEED();
}
Result SystemUpdateService::InitializeUpdateTask(sf::NativeHandle &&transfer_memory, u64 transfer_memory_size, const ncm::Path &path, bool exfat, ncm::FirmwareVariationId firmware_variation_id) {
/* Map the transfer memory. */
const size_t tmem_buffer_size = static_cast<size_t>(transfer_memory_size);
m_update_transfer_memory.emplace(tmem_buffer_size, transfer_memory.GetOsHandle(), transfer_memory.IsManaged());
transfer_memory.Detach();
void *tmem_buffer;
R_TRY(m_update_transfer_memory->Map(std::addressof(tmem_buffer), os::MemoryPermission_None));
auto tmem_guard = SCOPE_GUARD {
m_update_transfer_memory->Unmap();
m_update_transfer_memory = util::nullopt;
};
/* Adjust the package root. */
ncm::Path package_root;
R_TRY(FormatUserPackagePath(std::addressof(package_root), path));
/* Ensure that we can create an update context. */
R_TRY(fs::EnsureDirectory("@Sdcard:/atmosphere/update/"));
const char *context_path = "@Sdcard:/atmosphere/update/cup.ctx";
/* Create and initialize the update task. */
m_update_task.emplace();
R_TRY(m_update_task->Initialize(package_root.str, context_path, tmem_buffer, tmem_buffer_size, exfat, firmware_variation_id));
/* We successfully setup the update. */
tmem_guard.Cancel();
R_SUCCEED();
}
}

View File

@@ -1,81 +0,0 @@
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <stratosphere.hpp>
#include "sysupdater_apply_manager.hpp"
namespace ams::mitm::sysupdater {
constexpr inline size_t FirmwareVariationCountMax = 16;
struct UpdateInformation {
u32 version;
bool exfat_supported;
u32 firmware_variation_count;
ncm::FirmwareVariationId firmware_variation_ids[FirmwareVariationCountMax];
};
struct UpdateValidationInfo {
ncm::ContentMetaKey invalid_key;
ncm::ContentId invalid_content_id;
};
struct SystemUpdateProgress {
s64 current_size;
s64 total_size;
};
}
#define AMS_SYSUPDATER_SYSTEM_UPDATE_INTERFACE_INFO(C, H) \
AMS_SF_METHOD_INFO(C, H, 0, Result, GetUpdateInformation, (sf::Out<mitm::sysupdater::UpdateInformation> out, const ncm::Path &path), (out, path)) \
AMS_SF_METHOD_INFO(C, H, 1, Result, ValidateUpdate, (sf::Out<Result> out_validate_result, sf::Out<Result> out_validate_exfat_result, sf::Out<mitm::sysupdater::UpdateValidationInfo> out_validate_info, const ncm::Path &path), (out_validate_result, out_validate_exfat_result, out_validate_info, path)) \
AMS_SF_METHOD_INFO(C, H, 2, Result, SetupUpdate, (sf::CopyHandle &&transfer_memory, u64 transfer_memory_size, const ncm::Path &path, bool exfat), (std::move(transfer_memory), transfer_memory_size, path, exfat)) \
AMS_SF_METHOD_INFO(C, H, 3, Result, SetupUpdateWithVariation, (sf::CopyHandle &&transfer_memory, u64 transfer_memory_size, const ncm::Path &path, bool exfat, ncm::FirmwareVariationId firmware_variation_id), (std::move(transfer_memory), transfer_memory_size, path, exfat, firmware_variation_id)) \
AMS_SF_METHOD_INFO(C, H, 4, Result, RequestPrepareUpdate, (sf::OutCopyHandle out_event_handle, sf::Out<sf::SharedPointer<ns::impl::IAsyncResult>> out_async), (out_event_handle, out_async)) \
AMS_SF_METHOD_INFO(C, H, 5, Result, GetPrepareUpdateProgress, (sf::Out<mitm::sysupdater::SystemUpdateProgress> out), (out)) \
AMS_SF_METHOD_INFO(C, H, 6, Result, HasPreparedUpdate, (sf::Out<bool> out), (out)) \
AMS_SF_METHOD_INFO(C, H, 7, Result, ApplyPreparedUpdate, (), ())
AMS_SF_DEFINE_INTERFACE(ams::mitm::sysupdater::impl, ISystemUpdateInterface, AMS_SYSUPDATER_SYSTEM_UPDATE_INTERFACE_INFO, 0x00000000)
namespace ams::mitm::sysupdater {
class SystemUpdateService {
private:
SystemUpdateApplyManager m_apply_manager;
util::optional<ncm::PackageSystemDowngradeTask> m_update_task;
util::optional<os::TransferMemory> m_update_transfer_memory;
bool m_setup_update;
bool m_requested_update;
public:
constexpr SystemUpdateService() : m_apply_manager(), m_update_task(), m_update_transfer_memory(), m_setup_update(false), m_requested_update(false) { /* ... */ }
private:
Result SetupUpdateImpl(sf::NativeHandle &&transfer_memory, u64 transfer_memory_size, const ncm::Path &path, bool exfat, ncm::FirmwareVariationId firmware_variation_id);
Result InitializeUpdateTask(sf::NativeHandle &&transfer_memory, u64 transfer_memory_size, const ncm::Path &path, bool exfat, ncm::FirmwareVariationId firmware_variation_id);
public:
Result GetUpdateInformation(sf::Out<UpdateInformation> out, const ncm::Path &path);
Result ValidateUpdate(sf::Out<Result> out_validate_result, sf::Out<Result> out_validate_exfat_result, sf::Out<UpdateValidationInfo> out_validate_info, const ncm::Path &path);
Result SetupUpdate(sf::CopyHandle &&transfer_memory, u64 transfer_memory_size, const ncm::Path &path, bool exfat);
Result SetupUpdateWithVariation(sf::CopyHandle &&transfer_memory, u64 transfer_memory_size, const ncm::Path &path, bool exfat, ncm::FirmwareVariationId firmware_variation_id);
Result RequestPrepareUpdate(sf::OutCopyHandle out_event_handle, sf::Out<sf::SharedPointer<ns::impl::IAsyncResult>> out_async);
Result GetPrepareUpdateProgress(sf::Out<SystemUpdateProgress> out);
Result HasPreparedUpdate(sf::Out<bool> out);
Result ApplyPreparedUpdate();
};
static_assert(impl::IsISystemUpdateInterface<SystemUpdateService>);
}

View File

@@ -1,55 +0,0 @@
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "sysupdater_thread_allocator.hpp"
namespace ams::mitm::sysupdater {
Result ThreadAllocator::Allocate(ThreadInfo *out) {
std::scoped_lock lk(m_mutex);
for (int i = 0; i < m_thread_count; ++i) {
const u64 mask = (static_cast<u64>(1) << i);
if ((m_bitmap & mask) == 0) {
*out = {
.thread = m_thread_list + i,
.priority = m_thread_priority,
.stack = m_stack_heap + (m_stack_size * i),
.stack_size = m_stack_size,
};
m_bitmap |= mask;
R_SUCCEED();
}
}
R_THROW(ns::ResultOutOfMaxRunningTask());
}
void ThreadAllocator::Free(const ThreadInfo &info) {
std::scoped_lock lk(m_mutex);
for (int i = 0; i < m_thread_count; ++i) {
if (info.thread == std::addressof(m_thread_list[i])) {
const u64 mask = (static_cast<u64>(1) << i);
m_bitmap &= ~mask;
return;
}
}
AMS_ABORT("Invalid thread passed to ThreadAllocator::Free");
}
}

View File

@@ -1,51 +0,0 @@
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <stratosphere.hpp>
namespace ams::mitm::sysupdater {
struct ThreadInfo {
os::ThreadType *thread;
int priority;
void *stack;
size_t stack_size;
};
/* NOTE: Nintendo uses a util::BitArray, but this seems excessive. */
class ThreadAllocator {
private:
os::ThreadType *m_thread_list;
const int m_thread_priority;
const int m_thread_count;
u8 *m_stack_heap;
const size_t m_stack_heap_size;
const size_t m_stack_size;
u64 m_bitmap;
os::SdkMutex m_mutex;
public:
constexpr ThreadAllocator(os::ThreadType *thread_list, int count, int priority, u8 *stack_heap, size_t stack_heap_size, size_t stack_size)
: m_thread_list(thread_list), m_thread_priority(priority), m_thread_count(count), m_stack_heap(stack_heap), m_stack_heap_size(stack_heap_size), m_stack_size(stack_size), m_bitmap()
{
AMS_ASSERT(count <= static_cast<int>(stack_heap_size / stack_size));
AMS_ASSERT(count <= static_cast<int>(BITSIZEOF(m_bitmap)));
}
Result Allocate(ThreadInfo *out);
void Free(const ThreadInfo &info);
};
}