nca.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. // Copyright 2018 yuzu emulator team
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <vector>
  5. #include "common/common_funcs.h"
  6. #include "common/file_util.h"
  7. #include "common/logging/log.h"
  8. #include "common/string_util.h"
  9. #include "common/swap.h"
  10. #include "core/core.h"
  11. #include "core/file_sys/program_metadata.h"
  12. #include "core/file_sys/romfs_factory.h"
  13. #include "core/gdbstub/gdbstub.h"
  14. #include "core/hle/kernel/process.h"
  15. #include "core/hle/kernel/resource_limit.h"
  16. #include "core/hle/service/filesystem/filesystem.h"
  17. #include "core/loader/nca.h"
  18. #include "core/loader/nso.h"
  19. #include "core/memory.h"
  20. namespace Loader {
  21. // Media offsets in headers are stored divided by 512. Mult. by this to get real offset.
  22. constexpr u64 MEDIA_OFFSET_MULTIPLIER = 0x200;
  23. constexpr u64 SECTION_HEADER_SIZE = 0x200;
  24. constexpr u64 SECTION_HEADER_OFFSET = 0x400;
  25. enum class NcaContentType : u8 { Program = 0, Meta = 1, Control = 2, Manual = 3, Data = 4 };
  26. enum class NcaSectionFilesystemType : u8 { PFS0 = 0x2, ROMFS = 0x3 };
  27. struct NcaSectionTableEntry {
  28. u32_le media_offset;
  29. u32_le media_end_offset;
  30. INSERT_PADDING_BYTES(0x8);
  31. };
  32. static_assert(sizeof(NcaSectionTableEntry) == 0x10, "NcaSectionTableEntry has incorrect size.");
  33. struct NcaHeader {
  34. std::array<u8, 0x100> rsa_signature_1;
  35. std::array<u8, 0x100> rsa_signature_2;
  36. u32_le magic;
  37. u8 is_system;
  38. NcaContentType content_type;
  39. u8 crypto_type;
  40. u8 key_index;
  41. u64_le size;
  42. u64_le title_id;
  43. INSERT_PADDING_BYTES(0x4);
  44. u32_le sdk_version;
  45. u8 crypto_type_2;
  46. INSERT_PADDING_BYTES(15);
  47. std::array<u8, 0x10> rights_id;
  48. std::array<NcaSectionTableEntry, 0x4> section_tables;
  49. std::array<std::array<u8, 0x20>, 0x4> hash_tables;
  50. std::array<std::array<u8, 0x10>, 0x4> key_area;
  51. INSERT_PADDING_BYTES(0xC0);
  52. };
  53. static_assert(sizeof(NcaHeader) == 0x400, "NcaHeader has incorrect size.");
  54. struct NcaSectionHeaderBlock {
  55. INSERT_PADDING_BYTES(3);
  56. NcaSectionFilesystemType filesystem_type;
  57. u8 crypto_type;
  58. INSERT_PADDING_BYTES(3);
  59. };
  60. static_assert(sizeof(NcaSectionHeaderBlock) == 0x8, "NcaSectionHeaderBlock has incorrect size.");
  61. struct Pfs0Superblock {
  62. NcaSectionHeaderBlock header_block;
  63. std::array<u8, 0x20> hash;
  64. u32_le size;
  65. INSERT_PADDING_BYTES(4);
  66. u64_le hash_table_offset;
  67. u64_le hash_table_size;
  68. u64_le pfs0_header_offset;
  69. u64_le pfs0_size;
  70. INSERT_PADDING_BYTES(432);
  71. };
  72. static_assert(sizeof(Pfs0Superblock) == 0x200, "Pfs0Superblock has incorrect size.");
  73. static bool IsValidNca(const NcaHeader& header) {
  74. return header.magic == Common::MakeMagic('N', 'C', 'A', '2') ||
  75. header.magic == Common::MakeMagic('N', 'C', 'A', '3');
  76. }
  77. // TODO(DarkLordZach): Add support for encrypted.
  78. class Nca final {
  79. std::vector<FileSys::PartitionFilesystem> pfs;
  80. std::vector<u64> pfs_offset;
  81. u64 romfs_offset = 0;
  82. u64 romfs_size = 0;
  83. boost::optional<u8> exefs_id = boost::none;
  84. FileUtil::IOFile file;
  85. std::string path;
  86. u64 GetExeFsFileOffset(const std::string& file_name) const;
  87. u64 GetExeFsFileSize(const std::string& file_name) const;
  88. public:
  89. ResultStatus Load(FileUtil::IOFile&& file, std::string path);
  90. FileSys::PartitionFilesystem GetPfs(u8 id) const;
  91. u64 GetRomFsOffset() const;
  92. u64 GetRomFsSize() const;
  93. std::vector<u8> GetExeFsFile(const std::string& file_name);
  94. };
  95. static bool IsPfsExeFs(const FileSys::PartitionFilesystem& pfs) {
  96. // According to switchbrew, an exefs must only contain these two files:
  97. return pfs.GetFileSize("main") > 0 && pfs.GetFileSize("main.npdm") > 0;
  98. }
  99. ResultStatus Nca::Load(FileUtil::IOFile&& in_file, std::string in_path) {
  100. file = std::move(in_file);
  101. path = in_path;
  102. file.Seek(0, SEEK_SET);
  103. std::array<u8, sizeof(NcaHeader)> header_array{};
  104. if (sizeof(NcaHeader) != file.ReadBytes(header_array.data(), sizeof(NcaHeader)))
  105. LOG_CRITICAL(Loader, "File reader errored out during header read.");
  106. NcaHeader header{};
  107. std::memcpy(&header, header_array.data(), sizeof(NcaHeader));
  108. if (!IsValidNca(header))
  109. return ResultStatus::ErrorInvalidFormat;
  110. int number_sections =
  111. std::count_if(std::begin(header.section_tables), std::end(header.section_tables),
  112. [](NcaSectionTableEntry entry) { return entry.media_offset > 0; });
  113. for (int i = 0; i < number_sections; ++i) {
  114. // Seek to beginning of this section.
  115. file.Seek(SECTION_HEADER_OFFSET + i * SECTION_HEADER_SIZE, SEEK_SET);
  116. std::array<u8, sizeof(NcaSectionHeaderBlock)> array{};
  117. if (sizeof(NcaSectionHeaderBlock) !=
  118. file.ReadBytes(array.data(), sizeof(NcaSectionHeaderBlock)))
  119. LOG_CRITICAL(Loader, "File reader errored out during header read.");
  120. NcaSectionHeaderBlock block{};
  121. std::memcpy(&block, array.data(), sizeof(NcaSectionHeaderBlock));
  122. if (block.filesystem_type == NcaSectionFilesystemType::ROMFS) {
  123. romfs_offset = header.section_tables[i].media_offset * MEDIA_OFFSET_MULTIPLIER;
  124. romfs_size =
  125. header.section_tables[i].media_end_offset * MEDIA_OFFSET_MULTIPLIER - romfs_offset;
  126. } else if (block.filesystem_type == NcaSectionFilesystemType::PFS0) {
  127. Pfs0Superblock sb{};
  128. // Seek back to beginning of this section.
  129. file.Seek(SECTION_HEADER_OFFSET + i * SECTION_HEADER_SIZE, SEEK_SET);
  130. if (sizeof(Pfs0Superblock) != file.ReadBytes(&sb, sizeof(Pfs0Superblock)))
  131. LOG_CRITICAL(Loader, "File reader errored out during header read.");
  132. u64 offset = (static_cast<u64>(header.section_tables[i].media_offset) *
  133. MEDIA_OFFSET_MULTIPLIER) +
  134. sb.pfs0_header_offset;
  135. FileSys::PartitionFilesystem npfs{};
  136. ResultStatus status = npfs.Load(path, offset);
  137. if (status == ResultStatus::Success) {
  138. pfs.emplace_back(std::move(npfs));
  139. pfs_offset.emplace_back(offset);
  140. }
  141. }
  142. }
  143. for (size_t i = 0; i < pfs.size(); ++i) {
  144. if (IsPfsExeFs(pfs[i]))
  145. exefs_id = i;
  146. }
  147. return ResultStatus::Success;
  148. }
  149. FileSys::PartitionFilesystem Nca::GetPfs(u8 id) const {
  150. return pfs[id];
  151. }
  152. u64 Nca::GetExeFsFileOffset(const std::string& file_name) const {
  153. if (exefs_id == boost::none)
  154. return 0;
  155. return pfs[*exefs_id].GetFileOffset(file_name) + pfs_offset[*exefs_id];
  156. }
  157. u64 Nca::GetExeFsFileSize(const std::string& file_name) const {
  158. if (exefs_id == boost::none)
  159. return 0;
  160. return pfs[*exefs_id].GetFileSize(file_name);
  161. }
  162. u64 Nca::GetRomFsOffset() const {
  163. return romfs_offset;
  164. }
  165. u64 Nca::GetRomFsSize() const {
  166. return romfs_size;
  167. }
  168. std::vector<u8> Nca::GetExeFsFile(const std::string& file_name) {
  169. std::vector<u8> out(GetExeFsFileSize(file_name));
  170. file.Seek(GetExeFsFileOffset(file_name), SEEK_SET);
  171. file.ReadBytes(out.data(), GetExeFsFileSize(file_name));
  172. return out;
  173. }
  174. AppLoader_NCA::AppLoader_NCA(FileUtil::IOFile&& file, std::string filepath)
  175. : AppLoader(std::move(file)), filepath(std::move(filepath)) {}
  176. FileType AppLoader_NCA::IdentifyType(FileUtil::IOFile& file, const std::string&) {
  177. file.Seek(0, SEEK_SET);
  178. std::array<u8, 0x400> header_enc_array{};
  179. if (0x400 != file.ReadBytes(header_enc_array.data(), 0x400))
  180. return FileType::Error;
  181. // TODO(DarkLordZach): Assuming everything is decrypted. Add crypto support.
  182. NcaHeader header{};
  183. std::memcpy(&header, header_enc_array.data(), sizeof(NcaHeader));
  184. if (IsValidNca(header) && header.content_type == NcaContentType::Program)
  185. return FileType::NCA;
  186. return FileType::Error;
  187. }
  188. ResultStatus AppLoader_NCA::Load(Kernel::SharedPtr<Kernel::Process>& process) {
  189. if (is_loaded) {
  190. return ResultStatus::ErrorAlreadyLoaded;
  191. }
  192. if (!file.IsOpen()) {
  193. return ResultStatus::Error;
  194. }
  195. nca = std::make_unique<Nca>();
  196. ResultStatus result = nca->Load(std::move(file), filepath);
  197. if (result != ResultStatus::Success) {
  198. return result;
  199. }
  200. result = metadata.Load(nca->GetExeFsFile("main.npdm"));
  201. if (result != ResultStatus::Success) {
  202. return result;
  203. }
  204. metadata.Print();
  205. const FileSys::ProgramAddressSpaceType arch_bits{metadata.GetAddressSpaceType()};
  206. if (arch_bits == FileSys::ProgramAddressSpaceType::Is32Bit) {
  207. return ResultStatus::ErrorUnsupportedArch;
  208. }
  209. VAddr next_load_addr{Memory::PROCESS_IMAGE_VADDR};
  210. for (const auto& module : {"rtld", "main", "subsdk0", "subsdk1", "subsdk2", "subsdk3",
  211. "subsdk4", "subsdk5", "subsdk6", "subsdk7", "sdk"}) {
  212. const VAddr load_addr = next_load_addr;
  213. next_load_addr = AppLoader_NSO::LoadModule(module, nca->GetExeFsFile(module), load_addr);
  214. if (next_load_addr) {
  215. LOG_DEBUG(Loader, "loaded module {} @ 0x{:X}", module, load_addr);
  216. // Register module with GDBStub
  217. GDBStub::RegisterModule(module, load_addr, next_load_addr - 1, false);
  218. } else {
  219. next_load_addr = load_addr;
  220. }
  221. }
  222. process->program_id = metadata.GetTitleID();
  223. process->svc_access_mask.set();
  224. process->address_mappings = default_address_mappings;
  225. process->resource_limit =
  226. Kernel::ResourceLimit::GetForCategory(Kernel::ResourceLimitCategory::APPLICATION);
  227. process->Run(Memory::PROCESS_IMAGE_VADDR, metadata.GetMainThreadPriority(),
  228. metadata.GetMainThreadStackSize());
  229. if (nca->GetRomFsSize() > 0)
  230. Service::FileSystem::RegisterRomFS(std::make_unique<FileSys::RomFSFactory>(*this));
  231. is_loaded = true;
  232. return ResultStatus::Success;
  233. }
  234. ResultStatus AppLoader_NCA::ReadRomFS(std::shared_ptr<FileUtil::IOFile>& romfs_file, u64& offset,
  235. u64& size) {
  236. if (nca->GetRomFsSize() == 0) {
  237. LOG_DEBUG(Loader, "No RomFS available");
  238. return ResultStatus::ErrorNotUsed;
  239. }
  240. romfs_file = std::make_shared<FileUtil::IOFile>(filepath, "rb");
  241. offset = nca->GetRomFsOffset();
  242. size = nca->GetRomFsSize();
  243. LOG_DEBUG(Loader, "RomFS offset: 0x{:016X}", offset);
  244. LOG_DEBUG(Loader, "RomFS size: 0x{:016X}", size);
  245. return ResultStatus::Success;
  246. }
  247. AppLoader_NCA::~AppLoader_NCA() = default;
  248. } // namespace Loader