nca.cpp 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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. if (nca->GetRomFS() != nullptr && nca->GetRomFS()->GetSize() > 0) {
  60. system.GetFileSystemController().RegisterRomFS(std::make_unique<FileSys::RomFSFactory>(
  61. *this, system.GetContentProvider(), system.GetFileSystemController()));
  62. }
  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({ mbedtls_sha256_free(&ctx); });
  94. // Declare counters.
  95. const size_t total_size = file->GetSize();
  96. size_t processed_size = 0;
  97. // Begin iterating the file.
  98. while (processed_size < total_size) {
  99. // Refill the buffer.
  100. const size_t intended_read_size = std::min(buffer.size(), total_size - processed_size);
  101. const size_t read_size = file->Read(buffer.data(), intended_read_size, processed_size);
  102. // Update the hash function with the buffer contents.
  103. mbedtls_sha256_update_ret(&ctx, buffer.data(), read_size);
  104. // Update counters.
  105. processed_size += read_size;
  106. // Call the progress function.
  107. if (!progress_callback(processed_size, total_size)) {
  108. return ResultStatus::ErrorIntegrityVerificationFailed;
  109. }
  110. }
  111. // Finalize context and compute the output hash.
  112. std::array<u8, NcaSha256HashLength> output_hash;
  113. mbedtls_sha256_finish_ret(&ctx, output_hash.data());
  114. // Compare to expected.
  115. if (std::memcmp(input_hash.data(), output_hash.data(), NcaSha256HalfHashLength) != 0) {
  116. LOG_ERROR(Loader, "NCA hash mismatch detected for file {}", name);
  117. return ResultStatus::ErrorIntegrityVerificationFailed;
  118. }
  119. // File verified.
  120. return ResultStatus::Success;
  121. }
  122. ResultStatus AppLoader_NCA::ReadRomFS(FileSys::VirtualFile& dir) {
  123. if (nca == nullptr) {
  124. return ResultStatus::ErrorNotInitialized;
  125. }
  126. if (nca->GetRomFS() == nullptr || nca->GetRomFS()->GetSize() == 0) {
  127. return ResultStatus::ErrorNoRomFS;
  128. }
  129. dir = nca->GetRomFS();
  130. return ResultStatus::Success;
  131. }
  132. ResultStatus AppLoader_NCA::ReadProgramId(u64& out_program_id) {
  133. if (nca == nullptr || nca->GetStatus() != ResultStatus::Success) {
  134. return ResultStatus::ErrorNotInitialized;
  135. }
  136. out_program_id = nca->GetTitleId();
  137. return ResultStatus::Success;
  138. }
  139. ResultStatus AppLoader_NCA::ReadBanner(std::vector<u8>& buffer) {
  140. if (nca == nullptr || nca->GetStatus() != ResultStatus::Success) {
  141. return ResultStatus::ErrorNotInitialized;
  142. }
  143. const auto logo = nca->GetLogoPartition();
  144. if (logo == nullptr) {
  145. return ResultStatus::ErrorNoIcon;
  146. }
  147. buffer = logo->GetFile("StartupMovie.gif")->ReadAllBytes();
  148. return ResultStatus::Success;
  149. }
  150. ResultStatus AppLoader_NCA::ReadLogo(std::vector<u8>& buffer) {
  151. if (nca == nullptr || nca->GetStatus() != ResultStatus::Success) {
  152. return ResultStatus::ErrorNotInitialized;
  153. }
  154. const auto logo = nca->GetLogoPartition();
  155. if (logo == nullptr) {
  156. return ResultStatus::ErrorNoIcon;
  157. }
  158. buffer = logo->GetFile("NintendoLogo.png")->ReadAllBytes();
  159. return ResultStatus::Success;
  160. }
  161. ResultStatus AppLoader_NCA::ReadNSOModules(Modules& modules) {
  162. if (directory_loader == nullptr) {
  163. return ResultStatus::ErrorNotInitialized;
  164. }
  165. return directory_loader->ReadNSOModules(modules);
  166. }
  167. } // namespace Loader