nca.cpp 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. // SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include <utility>
  4. #include "common/hex_util.h"
  5. #include "common/scope_exit.h"
  6. #include "core/core.h"
  7. #include "core/file_sys/content_archive.h"
  8. #include "core/file_sys/nca_metadata.h"
  9. #include "core/file_sys/registered_cache.h"
  10. #include "core/file_sys/romfs_factory.h"
  11. #include "core/hle/kernel/k_process.h"
  12. #include "core/hle/service/filesystem/filesystem.h"
  13. #include "core/loader/deconstructed_rom_directory.h"
  14. #include "core/loader/nca.h"
  15. #include "mbedtls/sha256.h"
  16. namespace Loader {
  17. AppLoader_NCA::AppLoader_NCA(FileSys::VirtualFile file_)
  18. : AppLoader(std::move(file_)), nca(std::make_unique<FileSys::NCA>(file)) {}
  19. AppLoader_NCA::~AppLoader_NCA() = default;
  20. FileType AppLoader_NCA::IdentifyType(const FileSys::VirtualFile& nca_file) {
  21. const FileSys::NCA nca(nca_file);
  22. if (nca.GetStatus() == ResultStatus::Success &&
  23. nca.GetType() == FileSys::NCAContentType::Program) {
  24. return FileType::NCA;
  25. }
  26. return FileType::Error;
  27. }
  28. AppLoader_NCA::LoadResult AppLoader_NCA::Load(Kernel::KProcess& process, Core::System& system) {
  29. if (is_loaded) {
  30. return {ResultStatus::ErrorAlreadyLoaded, {}};
  31. }
  32. const auto result = nca->GetStatus();
  33. if (result != ResultStatus::Success) {
  34. return {result, {}};
  35. }
  36. if (nca->GetType() != FileSys::NCAContentType::Program) {
  37. return {ResultStatus::ErrorNCANotProgram, {}};
  38. }
  39. auto exefs = nca->GetExeFS();
  40. if (exefs == nullptr) {
  41. LOG_INFO(Loader, "No ExeFS found in NCA, looking for ExeFS from update");
  42. // This NCA may be a sparse base of an installed title.
  43. // Try to fetch the ExeFS from the installed update.
  44. const auto& installed = system.GetContentProvider();
  45. const auto update_nca = installed.GetEntry(FileSys::GetUpdateTitleID(nca->GetTitleId()),
  46. FileSys::ContentRecordType::Program);
  47. if (update_nca) {
  48. exefs = update_nca->GetExeFS();
  49. }
  50. if (exefs == nullptr) {
  51. return {ResultStatus::ErrorNoExeFS, {}};
  52. }
  53. }
  54. directory_loader = std::make_unique<AppLoader_DeconstructedRomDirectory>(exefs, true);
  55. const auto load_result = directory_loader->Load(process, system);
  56. if (load_result.first != ResultStatus::Success) {
  57. return load_result;
  58. }
  59. system.GetFileSystemController().RegisterProcess(
  60. process.GetProcessId(), nca->GetTitleId(),
  61. std::make_shared<FileSys::RomFSFactory>(*this, system.GetContentProvider(),
  62. system.GetFileSystemController()));
  63. is_loaded = true;
  64. return load_result;
  65. }
  66. ResultStatus AppLoader_NCA::VerifyIntegrity(std::function<bool(size_t, size_t)> progress_callback) {
  67. using namespace Common::Literals;
  68. constexpr size_t NcaFileNameWithHashLength = 36;
  69. constexpr size_t NcaFileNameHashLength = 32;
  70. constexpr size_t NcaSha256HashLength = 32;
  71. constexpr size_t NcaSha256HalfHashLength = NcaSha256HashLength / 2;
  72. // Get the file name.
  73. const auto name = file->GetName();
  74. // We won't try to verify meta NCAs.
  75. if (name.ends_with(".cnmt.nca")) {
  76. return ResultStatus::Success;
  77. }
  78. // Check if we can verify this file. NCAs should be named after their hashes.
  79. if (!name.ends_with(".nca") || name.size() != NcaFileNameWithHashLength) {
  80. LOG_WARNING(Loader, "Unable to validate NCA with name {}", name);
  81. return ResultStatus::ErrorIntegrityVerificationNotImplemented;
  82. }
  83. // Get the expected truncated hash of the NCA.
  84. const auto input_hash =
  85. Common::HexStringToVector(file->GetName().substr(0, NcaFileNameHashLength), false);
  86. // Declare buffer to read into.
  87. std::vector<u8> buffer(4_MiB);
  88. // Initialize sha256 verification context.
  89. mbedtls_sha256_context ctx;
  90. mbedtls_sha256_init(&ctx);
  91. mbedtls_sha256_starts_ret(&ctx, 0);
  92. // Ensure we maintain a clean state on exit.
  93. SCOPE_EXIT {
  94. mbedtls_sha256_free(&ctx);
  95. };
  96. // Declare counters.
  97. const size_t total_size = file->GetSize();
  98. size_t processed_size = 0;
  99. // Begin iterating the file.
  100. while (processed_size < total_size) {
  101. // Refill the buffer.
  102. const size_t intended_read_size = std::min(buffer.size(), total_size - processed_size);
  103. const size_t read_size = file->Read(buffer.data(), intended_read_size, processed_size);
  104. // Update the hash function with the buffer contents.
  105. mbedtls_sha256_update_ret(&ctx, buffer.data(), read_size);
  106. // Update counters.
  107. processed_size += read_size;
  108. // Call the progress function.
  109. if (!progress_callback(processed_size, total_size)) {
  110. return ResultStatus::ErrorIntegrityVerificationFailed;
  111. }
  112. }
  113. // Finalize context and compute the output hash.
  114. std::array<u8, NcaSha256HashLength> output_hash;
  115. mbedtls_sha256_finish_ret(&ctx, output_hash.data());
  116. // Compare to expected.
  117. if (std::memcmp(input_hash.data(), output_hash.data(), NcaSha256HalfHashLength) != 0) {
  118. LOG_ERROR(Loader, "NCA hash mismatch detected for file {}", name);
  119. return ResultStatus::ErrorIntegrityVerificationFailed;
  120. }
  121. // File verified.
  122. return ResultStatus::Success;
  123. }
  124. ResultStatus AppLoader_NCA::ReadRomFS(FileSys::VirtualFile& dir) {
  125. if (nca == nullptr) {
  126. return ResultStatus::ErrorNotInitialized;
  127. }
  128. if (nca->GetRomFS() == nullptr || nca->GetRomFS()->GetSize() == 0) {
  129. return ResultStatus::ErrorNoRomFS;
  130. }
  131. dir = nca->GetRomFS();
  132. return ResultStatus::Success;
  133. }
  134. ResultStatus AppLoader_NCA::ReadProgramId(u64& out_program_id) {
  135. if (nca == nullptr || nca->GetStatus() != ResultStatus::Success) {
  136. return ResultStatus::ErrorNotInitialized;
  137. }
  138. out_program_id = nca->GetTitleId();
  139. return ResultStatus::Success;
  140. }
  141. ResultStatus AppLoader_NCA::ReadBanner(std::vector<u8>& buffer) {
  142. if (nca == nullptr || nca->GetStatus() != ResultStatus::Success) {
  143. return ResultStatus::ErrorNotInitialized;
  144. }
  145. const auto logo = nca->GetLogoPartition();
  146. if (logo == nullptr) {
  147. return ResultStatus::ErrorNoIcon;
  148. }
  149. buffer = logo->GetFile("StartupMovie.gif")->ReadAllBytes();
  150. return ResultStatus::Success;
  151. }
  152. ResultStatus AppLoader_NCA::ReadLogo(std::vector<u8>& buffer) {
  153. if (nca == nullptr || nca->GetStatus() != ResultStatus::Success) {
  154. return ResultStatus::ErrorNotInitialized;
  155. }
  156. const auto logo = nca->GetLogoPartition();
  157. if (logo == nullptr) {
  158. return ResultStatus::ErrorNoIcon;
  159. }
  160. buffer = logo->GetFile("NintendoLogo.png")->ReadAllBytes();
  161. return ResultStatus::Success;
  162. }
  163. ResultStatus AppLoader_NCA::ReadNSOModules(Modules& modules) {
  164. if (directory_loader == nullptr) {
  165. return ResultStatus::ErrorNotInitialized;
  166. }
  167. return directory_loader->ReadNSOModules(modules);
  168. }
  169. } // namespace Loader