mirror of
https://github.com/Atmosphere-NX/Atmosphere.git
synced 2024-12-28 21:26:14 +00:00
c7026b9094
* Implement NCM * Modernize ncm_main * Remove unnecessary smExit * Give access to svcCallSecureMonitor * Stack size bump * Fix incorrect setup for NandUser's content storage entry * Fix a potential data abort when flushing the placeholder accessor cache * Fix HasFile and HasDirectory * Use r+b, not w+b * Misc fixes * errno begone * Fixed more stdio error handling * More main fixes * Various command improvements * Make dispatch tables great again * Fix logic inversion * Fixed content path generation * Bump heap size, fix CleanupAllPlaceHolder * Various fixes. Note: This contains debug stuff which will be removed later. I was getting tired of having to cherrypick tiny changes * Fixed placeholder/content deletion * Fixed incorrect content manager destruction * Prevent automatic placeholder creation on open * Fixed List implementation. Also lots of debug logging. * Removed debug code * Added a scope guard for WritePlaceHolder * Manually prevent placeholder/content appending * Revert "Removed debug code" This reverts commitd6ff261fcc
. * Always cache placeholder file. Switch to ftell for preventing appending * Universally use EnsureEnabled * Abstract away file writing logic * Misc cleanup * Refactor placeholder cacheing * Remove debug code (again) * Revert "Remove debug code (again)" This reverts commit168447d80e
. * Misc changes * Fixed file modes * Fixed ContentId/PlaceHolderId alignment * Improved type safety * Fixed reinitialization * Fixed doubleup on path creation * Remove debug code * Fixed 1.0.0 booting * Correct amount of add on content * Correct main thread stack size * lr: Introducing registered data * Reorder stratosphere Makefile * Move results to libstrat * lr: Cleanup lr_redirection * lr: lr_manager tweaks * lr: Imrpoved path handling and adjust ResolveAddOnContentPath order * lr: Organise types * Add eof newlines * lr: Eliminate unnecessary vars * lr: Unnecessary vars 2 electric boogaloo * lr: Various helpers * lr: RegisteredLocationResolver helpers * ncm: Move ncm_types to libstrat * ncm: Misc cleanup * Implement NCM * Modernize ncm_main * Remove unnecessary smExit * Give access to svcCallSecureMonitor * Stack size bump * Fix incorrect setup for NandUser's content storage entry * Fix a potential data abort when flushing the placeholder accessor cache * Fix HasFile and HasDirectory * Use r+b, not w+b * Misc fixes * errno begone * Fixed more stdio error handling * More main fixes * Various command improvements * Make dispatch tables great again * Fix logic inversion * Fixed content path generation * Bump heap size, fix CleanupAllPlaceHolder * Various fixes. Note: This contains debug stuff which will be removed later. I was getting tired of having to cherrypick tiny changes * Fixed placeholder/content deletion * Fixed incorrect content manager destruction * Prevent automatic placeholder creation on open * Fixed List implementation. Also lots of debug logging. * Removed debug code * Added a scope guard for WritePlaceHolder * Manually prevent placeholder/content appending * Revert "Removed debug code" This reverts commitd6ff261fcc
. * Always cache placeholder file. Switch to ftell for preventing appending * Universally use EnsureEnabled * Abstract away file writing logic * Misc cleanup * Refactor placeholder cacheing * Remove debug code (again) * Revert "Remove debug code (again)" This reverts commit168447d80e
. * Misc changes * Fixed file modes * Fixed ContentId/PlaceHolderId alignment * Improved type safety * Fixed reinitialization * Fixed doubleup on path creation * Remove debug code * Fixed 1.0.0 booting * Correct amount of add on content * Correct main thread stack size * lr: Introducing registered data * Reorder stratosphere Makefile * Move results to libstrat * lr: Cleanup lr_redirection * lr: lr_manager tweaks * lr: Imrpoved path handling and adjust ResolveAddOnContentPath order * lr: Organise types * Add eof newlines * lr: Eliminate unnecessary vars * lr: Unnecessary vars 2 electric boogaloo * lr: Various helpers * lr: RegisteredLocationResolver helpers * ncm: Move ncm_types to libstrat * ncm: Misc cleanup * Updated AddOnContentLocationResolver and RegisteredLocationResolver to 9.0.0 * Finished updating lr to 9.0.0 * Updated NCM to 9.0.0 * Fix libstrat includes * Fixed application launching * title_id_2 -> owner_tid * Updated to new-ipc * Change to using pure virtuals * Title Id -> Program Id * Fixed compilation against master * std::scoped_lock<> -> std::scoped_lock * Adopted R_UNLESS and R_CONVERT * Prefix namespace to Results * Adopt std::numeric_limits * Fixed incorrect error handling in ReadFile * Adopted AMS_ABORT_UNLESS * Adopt util::GenerateUuid() * Syntax improvements * ncm_types: Address review * Address more review comments * Updated copyrights * Address more feedback * More feedback addressed * More changes * Move dispatch tables out of interface files * Addressed remaining comments * lr: move into libstratosphere * ncm: Fix logic inversion * lr: Add comments * lr: Remove whitespace * ncm: Start addressing feedback * ncm: Cleanup InitializeContentManager * lr: support client-side usage * lr_service -> lr_api * ncm: Begin refactoring content manager * ncm: More content manager improvements * ncm: Content manager mount improvements * ldr: use lr bindings * lr bindings usage: minor fixes * ncm/lr: Pointer placement * ncm: placeholder accessor cleanup * ncm: minor fixes * ncm: refactor rights cache * ncm: content meta database cleanup * ncm: move content meta database impl out of interface file * ncm: Use const ContentMetaKey & * ncm: fix other non-const ContentMetaKey references * ncm: content meta database cleanup * ncm: content storage fixes for 2.0.0 * ncm: add missing end of file newlines * ncm: implement ContentMetaReader * ncm: client-side api * ncm: trim trailing spaces * ncm: FS_MAX_PATH-1 -> fs::EntryNameLengthMax * ncm: Use PathString and Path * fs: implement accessor wrappers for ncm * fs: implement user fs wrappers * fs: add MountSdCard * ncm: move to content manager impl * ncm: fix up main * kvdb: use fs:: * fs: Add wrappers needed for ncm * ncm: use fs bindings, other refactoring * ncm: minor fixes * fsa: fix ReadFile without size output * fs: add substorage, rom path tool * ncm: fix dangling fsdev usage * fs: fix bug in Commit * fs: fixed incorrect mode check * fs: implement Mount(System)Data * ncm: don't delete hos * results: add R_SUCCEED_IF * ams-except-ncm: use R_SUCCEED_IF * ncm: added comments * ncm: fix api definitions * ncm: use R_SUCCEED_IF * pm: think of the savings * ncm: employ kernel strats * ncm: Nintendo has 5 MiB of heap. Give ourselves 4 to be safe, pending analysis * ncm: refactor IDs, split types header into many headers * ams.mitm: use fs bindings instead of stdio * fs: SystemData uses SystemDataId * ncm: improve meta-db accuracy * ncm: inline getlatestkey * fs: improve UnsupportedOperation results * fs: modernize mount utils * ams: misc fixes for merge-errors * fs: improve unsupportedoperation results * git subrepo pull emummc subrepo: subdir: "emummc" merged: "d12dd546" upstream: origin: "https://github.com/m4xw/emuMMC" branch: "develop" commit: "d12dd546" git-subrepo: version: "0.4.1" origin: "???" commit: "???" * util: add boundedmap * ncm: minor style fixes * ncm: don't unmount if mounting fails * lr: bug fixes * ncm: implement ncm.for-initialize + ncm.for-safemode * lr: ncm::ProgramId::Invalid -> ncm::InvalidProgramId * ncm: fix open directory mode on 1.0.0 * ncm: fix fs use, implement more of < 4.0.0 for-initialize/safemode * ncm: implement packagedcontent -> content for building metadb * ncm: fix save data flag management * ncm: address some review suggestions (thanks @leoetlino!) * updater: use fs bindings * fs: implement MountCode * fs: prefer make_unique to operator new * ncm: implement remaining ContentMetaDatabaseBuilder functionality Co-authored-by: Michael Scire <SciresM@gmail.com>
525 lines
27 KiB
C++
525 lines
27 KiB
C++
/*
|
|
* Copyright (c) 2018-2020 Atmosphère-NX
|
|
*
|
|
* This program is free software; you can redistribute it and/or modify it
|
|
* under the terms and conditions of the GNU General Public License,
|
|
* version 2, as published by the Free Software Foundation.
|
|
*
|
|
* This program is distributed in the hope it will be useful, but WITHOUT
|
|
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
|
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
|
* more details.
|
|
*
|
|
* You should have received a copy of the GNU General Public License
|
|
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
*/
|
|
|
|
#include <switch.h>
|
|
#include <stratosphere.hpp>
|
|
#include <stratosphere/updater.hpp>
|
|
|
|
#include "updater_bis_save.hpp"
|
|
#include "updater_files.hpp"
|
|
#include "updater_paths.hpp"
|
|
|
|
namespace ams::updater {
|
|
|
|
namespace {
|
|
|
|
/* Validation Prototypes. */
|
|
Result ValidateWorkBuffer(const void *work_buffer, size_t work_buffer_size);
|
|
|
|
/* Configuration Prototypes. */
|
|
bool HasEks(BootImageUpdateType boot_image_update_type);
|
|
bool HasAutoRcmPreserve(BootImageUpdateType boot_image_update_type);
|
|
ncm::ContentMetaType GetContentMetaType(BootModeType mode);
|
|
Result GetBootImagePackageId(ncm::SystemDataId *out_data_id, BootModeType mode, void *work_buffer, size_t work_buffer_size);
|
|
|
|
/* Verification Prototypes. */
|
|
Result GetVerificationState(VerificationState *out, void *work_buffer, size_t work_buffer_size);
|
|
Result VerifyBootImages(ncm::SystemDataId data_id, BootModeType mode, void *work_buffer, size_t work_buffer_size, BootImageUpdateType boot_image_update_type);
|
|
Result VerifyBootImagesNormal(ncm::SystemDataId data_id, void *work_buffer, size_t work_buffer_size, BootImageUpdateType boot_image_update_type);
|
|
Result VerifyBootImagesSafe(ncm::SystemDataId data_id, void *work_buffer, size_t work_buffer_size, BootImageUpdateType boot_image_update_type);
|
|
|
|
/* Update Prototypes. */
|
|
Result SetVerificationNeeded(BootModeType mode, bool needed, void *work_buffer, size_t work_buffer_size);
|
|
Result UpdateBootImages(ncm::SystemDataId data_id, BootModeType mode, void *work_buffer, size_t work_buffer_size, BootImageUpdateType boot_image_update_type);
|
|
Result UpdateBootImagesNormal(ncm::SystemDataId data_id, void *work_buffer, size_t work_buffer_size, BootImageUpdateType boot_image_update_type);
|
|
Result UpdateBootImagesSafe(ncm::SystemDataId data_id, void *work_buffer, size_t work_buffer_size, BootImageUpdateType boot_image_update_type);
|
|
|
|
/* Package helpers. */
|
|
Result ValidateBctFileHash(Boot0Accessor &accessor, Boot0Partition which, const void *stored_hash, void *work_buffer, size_t work_buffer_size, BootImageUpdateType boot_image_update_type);
|
|
Result GetPackage2Hash(void *dst_hash, size_t package2_size, void *work_buffer, size_t work_buffer_size, Package2Type which);
|
|
Result WritePackage2(void *work_buffer, size_t work_buffer_size, Package2Type which, BootImageUpdateType boot_image_update_type);
|
|
Result CompareHash(const void *lhs, const void *rhs, size_t size);
|
|
|
|
/* Implementations. */
|
|
Result ValidateWorkBuffer(const void *work_buffer, size_t work_buffer_size) {
|
|
R_UNLESS(work_buffer_size >= BctSize + EksSize, ResultTooSmallWorkBuffer());
|
|
R_UNLESS(util::IsAligned(work_buffer, os::MemoryPageSize), ResultNotAlignedWorkBuffer());
|
|
R_UNLESS(util::IsAligned(work_buffer_size, 0x200), ResultNotAlignedWorkBuffer());
|
|
return ResultSuccess();
|
|
}
|
|
|
|
bool HasEks(BootImageUpdateType boot_image_update_type) {
|
|
switch (boot_image_update_type) {
|
|
case BootImageUpdateType::Erista:
|
|
return true;
|
|
case BootImageUpdateType::Mariko:
|
|
return false;
|
|
AMS_UNREACHABLE_DEFAULT_CASE();
|
|
}
|
|
}
|
|
|
|
bool HasAutoRcmPreserve(BootImageUpdateType boot_image_update_type) {
|
|
switch (boot_image_update_type) {
|
|
case BootImageUpdateType::Erista:
|
|
return true;
|
|
case BootImageUpdateType::Mariko:
|
|
return false;
|
|
AMS_UNREACHABLE_DEFAULT_CASE();
|
|
}
|
|
}
|
|
|
|
ncm::ContentMetaType GetContentMetaType(BootModeType mode) {
|
|
switch (mode) {
|
|
case BootModeType::Normal:
|
|
return ncm::ContentMetaType::BootImagePackage;
|
|
case BootModeType::Safe:
|
|
return ncm::ContentMetaType::BootImagePackageSafe;
|
|
AMS_UNREACHABLE_DEFAULT_CASE();
|
|
}
|
|
}
|
|
|
|
Result GetVerificationState(VerificationState *out, void *work_buffer, size_t work_buffer_size) {
|
|
/* Always set output to true before doing anything else. */
|
|
out->needs_verify_normal = true;
|
|
out->needs_verify_safe = true;
|
|
|
|
/* Ensure work buffer is big enough for us to do what we want to do. */
|
|
R_TRY(ValidateWorkBuffer(work_buffer, work_buffer_size));
|
|
|
|
/* Initialize boot0 save accessor. */
|
|
BisSave save;
|
|
R_TRY(save.Initialize(work_buffer, work_buffer_size));
|
|
ON_SCOPE_EXIT { save.Finalize(); };
|
|
|
|
/* Load save from NAND. */
|
|
R_TRY(save.Load());
|
|
|
|
/* Read data from save. */
|
|
out->needs_verify_normal = save.GetNeedsVerification(BootModeType::Normal);
|
|
out->needs_verify_safe = save.GetNeedsVerification(BootModeType::Safe);
|
|
return ResultSuccess();
|
|
}
|
|
|
|
Result VerifyBootImagesAndRepairIfNeeded(bool *out_repaired, BootModeType mode, void *work_buffer, size_t work_buffer_size, BootImageUpdateType boot_image_update_type) {
|
|
/* Get system data id for boot images (819/81A/81B/81C). */
|
|
ncm::SystemDataId bip_data_id;
|
|
R_TRY(GetBootImagePackageId(&bip_data_id, mode, work_buffer, work_buffer_size));
|
|
|
|
/* Verify the boot images in NAND. */
|
|
R_TRY_CATCH(VerifyBootImages(bip_data_id, mode, work_buffer, work_buffer_size, boot_image_update_type)) {
|
|
R_CATCH(ResultNeedsRepairBootImages) {
|
|
/* Perform repair. */
|
|
*out_repaired = true;
|
|
R_TRY(UpdateBootImages(bip_data_id, mode, work_buffer, work_buffer_size, boot_image_update_type));
|
|
}
|
|
} R_END_TRY_CATCH;
|
|
|
|
/* We've either just verified or just repaired. Either way, we don't need to verify any more. */
|
|
return SetVerificationNeeded(mode, false, work_buffer, work_buffer_size);
|
|
}
|
|
|
|
Result GetBootImagePackageId(ncm::SystemDataId *out_data_id, BootModeType mode, void *work_buffer, size_t work_buffer_size) {
|
|
/* Ensure we can read content metas. */
|
|
constexpr size_t MaxContentMetas = 0x40;
|
|
AMS_ABORT_UNLESS(work_buffer_size >= sizeof(ncm::ContentMetaKey) * MaxContentMetas);
|
|
|
|
/* Open NAND System meta database, list contents. */
|
|
ncm::ContentMetaDatabase db;
|
|
R_TRY(ncm::OpenContentMetaDatabase(std::addressof(db), ncm::StorageId::BuiltInSystem));
|
|
|
|
ncm::ContentMetaKey *keys = reinterpret_cast<ncm::ContentMetaKey *>(work_buffer);
|
|
const auto content_meta_type = GetContentMetaType(mode);
|
|
|
|
auto count = db.ListContentMeta(keys, MaxContentMetas, content_meta_type);
|
|
R_UNLESS(count.total > 0, ResultBootImagePackageNotFound());
|
|
|
|
/* Output is sorted, return the lowest valid exfat entry. */
|
|
if (count.total > 1) {
|
|
for (auto i = 0; i < count.total; i++) {
|
|
u8 attr;
|
|
R_TRY(db.GetAttributes(std::addressof(attr), keys[i]));
|
|
|
|
if (attr & ncm::ContentMetaAttribute_IncludesExFatDriver) {
|
|
out_data_id->value = keys[i].id;
|
|
return ResultSuccess();
|
|
}
|
|
}
|
|
}
|
|
|
|
/* If there's only one entry or no exfat entries, return that entry. */
|
|
out_data_id->value = keys[0].id;
|
|
return ResultSuccess();
|
|
}
|
|
|
|
Result VerifyBootImages(ncm::SystemDataId data_id, BootModeType mode, void *work_buffer, size_t work_buffer_size, BootImageUpdateType boot_image_update_type) {
|
|
switch (mode) {
|
|
case BootModeType::Normal:
|
|
return VerifyBootImagesNormal(data_id, work_buffer, work_buffer_size, boot_image_update_type);
|
|
case BootModeType::Safe:
|
|
return VerifyBootImagesSafe(data_id, work_buffer, work_buffer_size, boot_image_update_type);
|
|
AMS_UNREACHABLE_DEFAULT_CASE();
|
|
}
|
|
}
|
|
|
|
Result VerifyBootImagesNormal(ncm::SystemDataId data_id, void *work_buffer, size_t work_buffer_size, BootImageUpdateType boot_image_update_type) {
|
|
/* Ensure work buffer is big enough for us to do what we want to do. */
|
|
R_TRY(ValidateWorkBuffer(work_buffer, work_buffer_size));
|
|
|
|
/* Mount the boot image package. */
|
|
const char *mount_name = GetMountName();
|
|
R_TRY_CATCH(fs::MountSystemData(mount_name, data_id)) {
|
|
R_CONVERT(fs::ResultTargetNotFound, ResultBootImagePackageNotFound())
|
|
} R_END_TRY_CATCH;
|
|
ON_SCOPE_EXIT { fs::Unmount(mount_name); };
|
|
|
|
/* Read and validate hashes of boot images. */
|
|
{
|
|
size_t size;
|
|
u8 nand_hash[crypto::Sha256Generator::HashSize];
|
|
u8 file_hash[crypto::Sha256Generator::HashSize];
|
|
|
|
Boot0Accessor boot0_accessor;
|
|
R_TRY(boot0_accessor.Initialize());
|
|
ON_SCOPE_EXIT { boot0_accessor.Finalize(); };
|
|
|
|
/* Compare BCT hashes. */
|
|
R_TRY(boot0_accessor.GetHash(nand_hash, BctSize, work_buffer, work_buffer_size, Boot0Partition::BctNormalMain));
|
|
R_TRY(ValidateBctFileHash(boot0_accessor, Boot0Partition::BctNormalMain, nand_hash, work_buffer, work_buffer_size, boot_image_update_type));
|
|
|
|
/* Compare BCT Sub hashes. */
|
|
R_TRY(boot0_accessor.GetHash(nand_hash, BctSize, work_buffer, work_buffer_size, Boot0Partition::BctNormalSub));
|
|
R_TRY(ValidateBctFileHash(boot0_accessor, Boot0Partition::BctNormalSub, nand_hash, work_buffer, work_buffer_size, boot_image_update_type));
|
|
|
|
/* Compare Package1 Normal/Sub hashes. */
|
|
R_TRY(GetFileHash(&size, file_hash, GetPackage1Path(boot_image_update_type), work_buffer, work_buffer_size));
|
|
|
|
R_TRY(boot0_accessor.GetHash(nand_hash, size, work_buffer, work_buffer_size, Boot0Partition::Package1NormalMain));
|
|
R_TRY(CompareHash(file_hash, nand_hash, sizeof(file_hash)));
|
|
|
|
R_TRY(boot0_accessor.GetHash(nand_hash, size, work_buffer, work_buffer_size, Boot0Partition::Package1NormalSub));
|
|
R_TRY(CompareHash(file_hash, nand_hash, sizeof(file_hash)));
|
|
|
|
/* Compare Package2 Normal/Sub hashes. */
|
|
R_TRY(GetFileHash(&size, file_hash, GetPackage2Path(boot_image_update_type), work_buffer, work_buffer_size));
|
|
|
|
R_TRY(GetPackage2Hash(nand_hash, size, work_buffer, work_buffer_size, Package2Type::NormalMain));
|
|
R_TRY(CompareHash(file_hash, nand_hash, sizeof(file_hash)));
|
|
|
|
R_TRY(GetPackage2Hash(nand_hash, size, work_buffer, work_buffer_size, Package2Type::NormalSub));
|
|
R_TRY(CompareHash(file_hash, nand_hash, sizeof(file_hash)));
|
|
}
|
|
|
|
return ResultSuccess();
|
|
}
|
|
|
|
Result VerifyBootImagesSafe(ncm::SystemDataId data_id, void *work_buffer, size_t work_buffer_size, BootImageUpdateType boot_image_update_type) {
|
|
/* Ensure work buffer is big enough for us to do what we want to do. */
|
|
R_TRY(ValidateWorkBuffer(work_buffer, work_buffer_size));
|
|
|
|
/* Mount the boot image package. */
|
|
const char *mount_name = GetMountName();
|
|
R_TRY_CATCH(fs::MountSystemData(mount_name, data_id)) {
|
|
R_CONVERT(fs::ResultTargetNotFound, ResultBootImagePackageNotFound())
|
|
} R_END_TRY_CATCH;
|
|
ON_SCOPE_EXIT { fs::Unmount(mount_name); };
|
|
|
|
/* Read and validate hashes of boot images. */
|
|
{
|
|
size_t size;
|
|
u8 nand_hash[crypto::Sha256Generator::HashSize];
|
|
u8 file_hash[crypto::Sha256Generator::HashSize];
|
|
|
|
Boot0Accessor boot0_accessor;
|
|
R_TRY(boot0_accessor.Initialize());
|
|
ON_SCOPE_EXIT { boot0_accessor.Finalize(); };
|
|
|
|
Boot1Accessor boot1_accessor;
|
|
R_TRY(boot1_accessor.Initialize());
|
|
ON_SCOPE_EXIT { boot1_accessor.Finalize(); };
|
|
|
|
|
|
/* Compare BCT hashes. */
|
|
R_TRY(boot0_accessor.GetHash(nand_hash, BctSize, work_buffer, work_buffer_size, Boot0Partition::BctSafeMain));
|
|
R_TRY(ValidateBctFileHash(boot0_accessor, Boot0Partition::BctSafeMain, nand_hash, work_buffer, work_buffer_size, boot_image_update_type));
|
|
|
|
/* Compare BCT Sub hashes. */
|
|
R_TRY(boot0_accessor.GetHash(nand_hash, BctSize, work_buffer, work_buffer_size, Boot0Partition::BctSafeSub));
|
|
R_TRY(ValidateBctFileHash(boot0_accessor, Boot0Partition::BctSafeSub, nand_hash, work_buffer, work_buffer_size, boot_image_update_type));
|
|
|
|
/* Compare Package1 Normal/Sub hashes. */
|
|
R_TRY(GetFileHash(&size, file_hash, GetPackage1Path(boot_image_update_type), work_buffer, work_buffer_size));
|
|
|
|
R_TRY(boot1_accessor.GetHash(nand_hash, size, work_buffer, work_buffer_size, Boot1Partition::Package1SafeMain));
|
|
R_TRY(CompareHash(file_hash, nand_hash, sizeof(file_hash)));
|
|
|
|
R_TRY(boot1_accessor.GetHash(nand_hash, size, work_buffer, work_buffer_size, Boot1Partition::Package1SafeSub));
|
|
R_TRY(CompareHash(file_hash, nand_hash, sizeof(file_hash)));
|
|
|
|
/* Compare Package2 Normal/Sub hashes. */
|
|
R_TRY(GetFileHash(&size, file_hash, GetPackage2Path(boot_image_update_type), work_buffer, work_buffer_size));
|
|
|
|
R_TRY(GetPackage2Hash(nand_hash, size, work_buffer, work_buffer_size, Package2Type::SafeMain));
|
|
R_TRY(CompareHash(file_hash, nand_hash, sizeof(file_hash)));
|
|
|
|
R_TRY(GetPackage2Hash(nand_hash, size, work_buffer, work_buffer_size, Package2Type::SafeSub));
|
|
R_TRY(CompareHash(file_hash, nand_hash, sizeof(file_hash)));
|
|
}
|
|
|
|
return ResultSuccess();
|
|
}
|
|
|
|
Result UpdateBootImages(ncm::SystemDataId data_id, BootModeType mode, void *work_buffer, size_t work_buffer_size, BootImageUpdateType boot_image_update_type) {
|
|
switch (mode) {
|
|
case BootModeType::Normal:
|
|
return UpdateBootImagesNormal(data_id, work_buffer, work_buffer_size, boot_image_update_type);
|
|
case BootModeType::Safe:
|
|
return UpdateBootImagesSafe(data_id, work_buffer, work_buffer_size, boot_image_update_type);
|
|
AMS_UNREACHABLE_DEFAULT_CASE();
|
|
}
|
|
}
|
|
|
|
Result UpdateBootImagesNormal(ncm::SystemDataId data_id, void *work_buffer, size_t work_buffer_size, BootImageUpdateType boot_image_update_type) {
|
|
/* Ensure work buffer is big enough for us to do what we want to do. */
|
|
R_TRY(ValidateWorkBuffer(work_buffer, work_buffer_size));
|
|
|
|
/* Mount the boot image package. */
|
|
const char *mount_name = GetMountName();
|
|
R_TRY_CATCH(fs::MountSystemData(mount_name, data_id)) {
|
|
R_CONVERT(fs::ResultTargetNotFound, ResultBootImagePackageNotFound())
|
|
} R_END_TRY_CATCH;
|
|
ON_SCOPE_EXIT { fs::Unmount(mount_name); };
|
|
|
|
{
|
|
Boot0Accessor boot0_accessor;
|
|
R_TRY(boot0_accessor.Initialize());
|
|
ON_SCOPE_EXIT { boot0_accessor.Finalize(); };
|
|
|
|
/* Write Package1 sub. */
|
|
R_TRY(boot0_accessor.Clear(work_buffer, work_buffer_size, Boot0Partition::Package1NormalSub));
|
|
R_TRY(boot0_accessor.Write(GetPackage1Path(boot_image_update_type), work_buffer, work_buffer_size, Boot0Partition::Package1NormalSub));
|
|
|
|
/* Write Package2 sub. */
|
|
R_TRY(WritePackage2(work_buffer, work_buffer_size, Package2Type::NormalSub, boot_image_update_type));
|
|
|
|
/* Write BCT sub + BCT main, in that order. */
|
|
{
|
|
void *bct = reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(work_buffer) + 0);
|
|
void *work = reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(work_buffer) + BctSize);
|
|
|
|
size_t size;
|
|
R_TRY(ReadFile(&size, bct, BctSize, GetBctPath(boot_image_update_type)));
|
|
if (HasEks(boot_image_update_type)) {
|
|
R_TRY(boot0_accessor.UpdateEks(bct, work));
|
|
}
|
|
|
|
/* Only preserve autorcm if on a unit with unpatched rcm bug. */
|
|
if (HasAutoRcmPreserve(boot_image_update_type) && !exosphere::IsRcmBugPatched()) {
|
|
R_TRY(boot0_accessor.PreserveAutoRcm(bct, work, Boot0Partition::BctNormalSub));
|
|
R_TRY(boot0_accessor.Write(bct, BctSize, Boot0Partition::BctNormalSub));
|
|
R_TRY(boot0_accessor.PreserveAutoRcm(bct, work, Boot0Partition::BctNormalMain));
|
|
R_TRY(boot0_accessor.Write(bct, BctSize, Boot0Partition::BctNormalMain));
|
|
} else {
|
|
R_TRY(boot0_accessor.Write(bct, BctSize, Boot0Partition::BctNormalSub));
|
|
R_TRY(boot0_accessor.Write(bct, BctSize, Boot0Partition::BctNormalMain));
|
|
}
|
|
}
|
|
|
|
/* Write Package2 main. */
|
|
R_TRY(WritePackage2(work_buffer, work_buffer_size, Package2Type::NormalMain, boot_image_update_type));
|
|
|
|
/* Write Package1 main. */
|
|
R_TRY(boot0_accessor.Clear(work_buffer, work_buffer_size, Boot0Partition::Package1NormalMain));
|
|
R_TRY(boot0_accessor.Write(GetPackage1Path(boot_image_update_type), work_buffer, work_buffer_size, Boot0Partition::Package1NormalMain));
|
|
}
|
|
|
|
return ResultSuccess();
|
|
}
|
|
|
|
Result UpdateBootImagesSafe(ncm::SystemDataId data_id, void *work_buffer, size_t work_buffer_size, BootImageUpdateType boot_image_update_type) {
|
|
/* Ensure work buffer is big enough for us to do what we want to do. */
|
|
R_TRY(ValidateWorkBuffer(work_buffer, work_buffer_size));
|
|
|
|
/* Mount the boot image package. */
|
|
const char *mount_name = GetMountName();
|
|
R_TRY_CATCH(fs::MountSystemData(mount_name, data_id)) {
|
|
R_CONVERT(fs::ResultTargetNotFound, ResultBootImagePackageNotFound())
|
|
} R_END_TRY_CATCH;
|
|
ON_SCOPE_EXIT { fs::Unmount(mount_name); };
|
|
|
|
{
|
|
Boot0Accessor boot0_accessor;
|
|
R_TRY(boot0_accessor.Initialize());
|
|
ON_SCOPE_EXIT { boot0_accessor.Finalize(); };
|
|
|
|
Boot1Accessor boot1_accessor;
|
|
R_TRY(boot1_accessor.Initialize());
|
|
ON_SCOPE_EXIT { boot1_accessor.Finalize(); };
|
|
|
|
|
|
/* Write Package1 sub. */
|
|
R_TRY(boot1_accessor.Clear(work_buffer, work_buffer_size, Boot1Partition::Package1SafeSub));
|
|
R_TRY(boot1_accessor.Write(GetPackage1Path(boot_image_update_type), work_buffer, work_buffer_size, Boot1Partition::Package1SafeSub));
|
|
|
|
/* Write Package2 sub. */
|
|
R_TRY(WritePackage2(work_buffer, work_buffer_size, Package2Type::SafeSub, boot_image_update_type));
|
|
|
|
/* Write BCT sub + BCT main, in that order. */
|
|
{
|
|
void *bct = reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(work_buffer) + 0);
|
|
void *work = reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(work_buffer) + BctSize);
|
|
|
|
size_t size;
|
|
R_TRY(ReadFile(&size, bct, BctSize, GetBctPath(boot_image_update_type)));
|
|
if (HasEks(boot_image_update_type)) {
|
|
R_TRY(boot0_accessor.UpdateEks(bct, work));
|
|
}
|
|
/* Only preserve autorcm if on a unit with unpatched rcm bug. */
|
|
if (HasAutoRcmPreserve(boot_image_update_type) && !exosphere::IsRcmBugPatched()) {
|
|
R_TRY(boot0_accessor.PreserveAutoRcm(bct, work, Boot0Partition::BctSafeSub));
|
|
R_TRY(boot0_accessor.Write(bct, BctSize, Boot0Partition::BctSafeSub));
|
|
R_TRY(boot0_accessor.PreserveAutoRcm(bct, work, Boot0Partition::BctSafeMain));
|
|
R_TRY(boot0_accessor.Write(bct, BctSize, Boot0Partition::BctSafeMain));
|
|
} else {
|
|
R_TRY(boot0_accessor.Write(bct, BctSize, Boot0Partition::BctSafeSub));
|
|
R_TRY(boot0_accessor.Write(bct, BctSize, Boot0Partition::BctSafeMain));
|
|
}
|
|
}
|
|
|
|
/* Write Package2 main. */
|
|
R_TRY(WritePackage2(work_buffer, work_buffer_size, Package2Type::SafeMain, boot_image_update_type));
|
|
|
|
/* Write Package1 main. */
|
|
R_TRY(boot1_accessor.Clear(work_buffer, work_buffer_size, Boot1Partition::Package1SafeMain));
|
|
R_TRY(boot1_accessor.Write(GetPackage1Path(boot_image_update_type), work_buffer, work_buffer_size, Boot1Partition::Package1SafeMain));
|
|
}
|
|
|
|
return ResultSuccess();
|
|
}
|
|
|
|
Result SetVerificationNeeded(BootModeType mode, bool needed, void *work_buffer, size_t work_buffer_size) {
|
|
/* Ensure work buffer is big enough for us to do what we want to do. */
|
|
R_TRY(ValidateWorkBuffer(work_buffer, work_buffer_size));
|
|
|
|
/* Initialize boot0 save accessor. */
|
|
BisSave save;
|
|
R_TRY(save.Initialize(work_buffer, work_buffer_size));
|
|
ON_SCOPE_EXIT { save.Finalize(); };
|
|
|
|
/* Load save from NAND. */
|
|
R_TRY(save.Load());
|
|
|
|
/* Set whether we need to verify, then save to nand. */
|
|
save.SetNeedsVerification(mode, needed);
|
|
R_TRY(save.Save());
|
|
|
|
return ResultSuccess();
|
|
}
|
|
|
|
Result ValidateBctFileHash(Boot0Accessor &accessor, Boot0Partition which, const void *stored_hash, void *work_buffer, size_t work_buffer_size, BootImageUpdateType boot_image_update_type) {
|
|
/* Ensure work buffer is big enough for us to do what we want to do. */
|
|
R_TRY(ValidateWorkBuffer(work_buffer, work_buffer_size));
|
|
|
|
void *bct = reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(work_buffer) + 0);
|
|
void *work = reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(work_buffer) + BctSize);
|
|
|
|
size_t size;
|
|
R_TRY(ReadFile(&size, bct, BctSize, GetBctPath(boot_image_update_type)));
|
|
if (HasEks(boot_image_update_type)) {
|
|
R_TRY(accessor.UpdateEks(bct, work));
|
|
}
|
|
if (HasAutoRcmPreserve(boot_image_update_type)) {
|
|
R_TRY(accessor.PreserveAutoRcm(bct, work, which));
|
|
}
|
|
|
|
u8 file_hash[crypto::Sha256Generator::HashSize];
|
|
crypto::GenerateSha256Hash(file_hash, sizeof(file_hash), bct, BctSize);
|
|
|
|
return CompareHash(file_hash, stored_hash, sizeof(file_hash));
|
|
}
|
|
|
|
Result GetPackage2Hash(void *dst_hash, size_t package2_size, void *work_buffer, size_t work_buffer_size, Package2Type which) {
|
|
Package2Accessor accessor(which);
|
|
R_TRY(accessor.Initialize());
|
|
ON_SCOPE_EXIT { accessor.Finalize(); };
|
|
|
|
return accessor.GetHash(dst_hash, package2_size, work_buffer, work_buffer_size, Package2Partition::Package2);
|
|
}
|
|
|
|
Result WritePackage2(void *work_buffer, size_t work_buffer_size, Package2Type which, BootImageUpdateType boot_image_update_type) {
|
|
Package2Accessor accessor(which);
|
|
R_TRY(accessor.Initialize());
|
|
ON_SCOPE_EXIT { accessor.Finalize(); };
|
|
|
|
return accessor.Write(GetPackage2Path(boot_image_update_type), work_buffer, work_buffer_size, Package2Partition::Package2);
|
|
}
|
|
|
|
Result CompareHash(const void *lhs, const void *rhs, size_t size) {
|
|
R_UNLESS(crypto::IsSameBytes(lhs, rhs, size), ResultNeedsRepairBootImages());
|
|
return ResultSuccess();
|
|
}
|
|
|
|
}
|
|
|
|
BootImageUpdateType GetBootImageUpdateType(spl::HardwareType hw_type) {
|
|
switch (hw_type) {
|
|
case spl::HardwareType::Icosa:
|
|
case spl::HardwareType::Copper:
|
|
return BootImageUpdateType::Erista;
|
|
case spl::HardwareType::Hoag:
|
|
case spl::HardwareType::Iowa:
|
|
return BootImageUpdateType::Mariko;
|
|
AMS_UNREACHABLE_DEFAULT_CASE();
|
|
}
|
|
}
|
|
|
|
Result VerifyBootImagesAndRepairIfNeeded(bool *out_repaired_normal, bool *out_repaired_safe, void *work_buffer, size_t work_buffer_size, BootImageUpdateType boot_image_update_type) {
|
|
/* Always set output to false before doing anything else. */
|
|
*out_repaired_normal = false;
|
|
*out_repaired_safe = false;
|
|
|
|
/* Ensure work buffer is big enough for us to do what we want to do. */
|
|
R_TRY(ValidateWorkBuffer(work_buffer, work_buffer_size));
|
|
|
|
/* Get verification state from NAND. */
|
|
VerificationState verification_state;
|
|
R_TRY(GetVerificationState(&verification_state, work_buffer, work_buffer_size));
|
|
|
|
/* If we don't need to verify anything, we're done. */
|
|
if (!verification_state.needs_verify_normal && !verification_state.needs_verify_safe) {
|
|
return ResultSuccess();
|
|
}
|
|
|
|
/* Get a session to ncm. */
|
|
sm::ScopedServiceHolder<ncm::Initialize, ncm::Finalize> ncm_holder;
|
|
R_ABORT_UNLESS(ncm_holder.GetResult());
|
|
|
|
/* Verify normal, verify safe as needed. */
|
|
if (verification_state.needs_verify_normal) {
|
|
R_TRY_CATCH(VerifyBootImagesAndRepairIfNeeded(out_repaired_normal, BootModeType::Normal, work_buffer, work_buffer_size, boot_image_update_type)) {
|
|
R_CATCH(ResultBootImagePackageNotFound) { /* Nintendo considers failure to locate bip a success. TODO: don't do that? */ }
|
|
} R_END_TRY_CATCH;
|
|
}
|
|
|
|
if (verification_state.needs_verify_safe) {
|
|
R_TRY_CATCH(VerifyBootImagesAndRepairIfNeeded(out_repaired_safe, BootModeType::Safe, work_buffer, work_buffer_size, boot_image_update_type)) {
|
|
R_CATCH(ResultBootImagePackageNotFound) { /* Nintendo considers failure to locate bip a success. TODO: don't do that? */ }
|
|
} R_END_TRY_CATCH;
|
|
}
|
|
|
|
return ResultSuccess();
|
|
}
|
|
|
|
}
|