summaryrefslogtreecommitdiff
path: root/src/core/loader/nca.cpp
diff options
context:
space:
mode:
authorGravatar Zach Hilman2018-06-21 11:16:23 -0400
committerGravatar bunnei2018-06-21 11:16:23 -0400
commit63f26d5c40adb49094b03b232528672f526afe49 (patch)
treeb76a154e17c819df7803d5860f08406446507a5c /src/core/loader/nca.cpp
parentMerge pull request #576 from Subv/warnings1 (diff)
downloadyuzu-63f26d5c40adb49094b03b232528672f526afe49.tar.gz
yuzu-63f26d5c40adb49094b03b232528672f526afe49.tar.xz
yuzu-63f26d5c40adb49094b03b232528672f526afe49.zip
Add support for decrypted NCA files (#567)
* Start to add NCA support in loader * More nca stuff * More changes to nca.cpp * Now identifies decrypted NCA cont. * Game list fixes and more structs and stuff * More updates to Nca class * Now reads ExeFs (i think) * ACTUALLY LOADS EXEFS! * RomFS loads and games execute * Cleanup and Finalize * plumbing, cleanup and testing * fix some things that i didnt think of before * Preliminary Review Changes * Review changes for bunnei and subv
Diffstat (limited to 'src/core/loader/nca.cpp')
-rw-r--r--src/core/loader/nca.cpp303
1 files changed, 303 insertions, 0 deletions
diff --git a/src/core/loader/nca.cpp b/src/core/loader/nca.cpp
new file mode 100644
index 000000000..067945d46
--- /dev/null
+++ b/src/core/loader/nca.cpp
@@ -0,0 +1,303 @@
1// Copyright 2018 yuzu emulator team
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#include <vector>
6
7#include "common/common_funcs.h"
8#include "common/file_util.h"
9#include "common/logging/log.h"
10#include "common/swap.h"
11#include "core/core.h"
12#include "core/file_sys/program_metadata.h"
13#include "core/file_sys/romfs_factory.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
21namespace Loader {
22
23// Media offsets in headers are stored divided by 512. Mult. by this to get real offset.
24constexpr u64 MEDIA_OFFSET_MULTIPLIER = 0x200;
25
26constexpr u64 SECTION_HEADER_SIZE = 0x200;
27constexpr u64 SECTION_HEADER_OFFSET = 0x400;
28
29enum class NcaContentType : u8 { Program = 0, Meta = 1, Control = 2, Manual = 3, Data = 4 };
30
31enum class NcaSectionFilesystemType : u8 { PFS0 = 0x2, ROMFS = 0x3 };
32
33struct NcaSectionTableEntry {
34 u32_le media_offset;
35 u32_le media_end_offset;
36 INSERT_PADDING_BYTES(0x8);
37};
38static_assert(sizeof(NcaSectionTableEntry) == 0x10, "NcaSectionTableEntry has incorrect size.");
39
40struct NcaHeader {
41 std::array<u8, 0x100> rsa_signature_1;
42 std::array<u8, 0x100> rsa_signature_2;
43 u32_le magic;
44 u8 is_system;
45 NcaContentType content_type;
46 u8 crypto_type;
47 u8 key_index;
48 u64_le size;
49 u64_le title_id;
50 INSERT_PADDING_BYTES(0x4);
51 u32_le sdk_version;
52 u8 crypto_type_2;
53 INSERT_PADDING_BYTES(15);
54 std::array<u8, 0x10> rights_id;
55 std::array<NcaSectionTableEntry, 0x4> section_tables;
56 std::array<std::array<u8, 0x20>, 0x4> hash_tables;
57 std::array<std::array<u8, 0x10>, 0x4> key_area;
58 INSERT_PADDING_BYTES(0xC0);
59};
60static_assert(sizeof(NcaHeader) == 0x400, "NcaHeader has incorrect size.");
61
62struct NcaSectionHeaderBlock {
63 INSERT_PADDING_BYTES(3);
64 NcaSectionFilesystemType filesystem_type;
65 u8 crypto_type;
66 INSERT_PADDING_BYTES(3);
67};
68static_assert(sizeof(NcaSectionHeaderBlock) == 0x8, "NcaSectionHeaderBlock has incorrect size.");
69
70struct Pfs0Superblock {
71 NcaSectionHeaderBlock header_block;
72 std::array<u8, 0x20> hash;
73 u32_le size;
74 INSERT_PADDING_BYTES(4);
75 u64_le hash_table_offset;
76 u64_le hash_table_size;
77 u64_le pfs0_header_offset;
78 u64_le pfs0_size;
79 INSERT_PADDING_BYTES(432);
80};
81static_assert(sizeof(Pfs0Superblock) == 0x200, "Pfs0Superblock has incorrect size.");
82
83static bool IsValidNca(const NcaHeader& header) {
84 return header.magic == Common::MakeMagic('N', 'C', 'A', '2') ||
85 header.magic == Common::MakeMagic('N', 'C', 'A', '3');
86}
87
88// TODO(DarkLordZach): Add support for encrypted.
89class Nca final {
90 std::vector<FileSys::PartitionFilesystem> pfs;
91 std::vector<u64> pfs_offset;
92
93 u64 romfs_offset = 0;
94 u64 romfs_size = 0;
95
96 boost::optional<u8> exefs_id = boost::none;
97
98 FileUtil::IOFile file;
99 std::string path;
100
101 u64 GetExeFsFileOffset(const std::string& file_name) const;
102 u64 GetExeFsFileSize(const std::string& file_name) const;
103
104public:
105 ResultStatus Load(FileUtil::IOFile&& file, std::string path);
106
107 FileSys::PartitionFilesystem GetPfs(u8 id) const;
108
109 u64 GetRomFsOffset() const;
110 u64 GetRomFsSize() const;
111
112 std::vector<u8> GetExeFsFile(const std::string& file_name);
113};
114
115static bool IsPfsExeFs(const FileSys::PartitionFilesystem& pfs) {
116 // According to switchbrew, an exefs must only contain these two files:
117 return pfs.GetFileSize("main") > 0 && pfs.GetFileSize("main.npdm") > 0;
118}
119
120ResultStatus Nca::Load(FileUtil::IOFile&& in_file, std::string in_path) {
121 file = std::move(in_file);
122 path = in_path;
123 file.Seek(0, SEEK_SET);
124 std::array<u8, sizeof(NcaHeader)> header_array{};
125 if (sizeof(NcaHeader) != file.ReadBytes(header_array.data(), sizeof(NcaHeader)))
126 NGLOG_CRITICAL(Loader, "File reader errored out during header read.");
127
128 NcaHeader header{};
129 std::memcpy(&header, header_array.data(), sizeof(NcaHeader));
130 if (!IsValidNca(header))
131 return ResultStatus::ErrorInvalidFormat;
132
133 int number_sections =
134 std::count_if(std::begin(header.section_tables), std::end(header.section_tables),
135 [](NcaSectionTableEntry entry) { return entry.media_offset > 0; });
136
137 for (int i = 0; i < number_sections; ++i) {
138 // Seek to beginning of this section.
139 file.Seek(SECTION_HEADER_OFFSET + i * SECTION_HEADER_SIZE, SEEK_SET);
140 std::array<u8, sizeof(NcaSectionHeaderBlock)> array{};
141 if (sizeof(NcaSectionHeaderBlock) !=
142 file.ReadBytes(array.data(), sizeof(NcaSectionHeaderBlock)))
143 NGLOG_CRITICAL(Loader, "File reader errored out during header read.");
144
145 NcaSectionHeaderBlock block{};
146 std::memcpy(&block, array.data(), sizeof(NcaSectionHeaderBlock));
147
148 if (block.filesystem_type == NcaSectionFilesystemType::ROMFS) {
149 romfs_offset = header.section_tables[i].media_offset * MEDIA_OFFSET_MULTIPLIER;
150 romfs_size =
151 header.section_tables[i].media_end_offset * MEDIA_OFFSET_MULTIPLIER - romfs_offset;
152 } else if (block.filesystem_type == NcaSectionFilesystemType::PFS0) {
153 Pfs0Superblock sb{};
154 // Seek back to beginning of this section.
155 file.Seek(SECTION_HEADER_OFFSET + i * SECTION_HEADER_SIZE, SEEK_SET);
156 if (sizeof(Pfs0Superblock) != file.ReadBytes(&sb, sizeof(Pfs0Superblock)))
157 NGLOG_CRITICAL(Loader, "File reader errored out during header read.");
158
159 u64 offset = (static_cast<u64>(header.section_tables[i].media_offset) *
160 MEDIA_OFFSET_MULTIPLIER) +
161 sb.pfs0_header_offset;
162 FileSys::PartitionFilesystem npfs{};
163 ResultStatus status = npfs.Load(path, offset);
164
165 if (status == ResultStatus::Success) {
166 pfs.emplace_back(std::move(npfs));
167 pfs_offset.emplace_back(offset);
168 }
169 }
170 }
171
172 for (size_t i = 0; i < pfs.size(); ++i) {
173 if (IsPfsExeFs(pfs[i]))
174 exefs_id = i;
175 }
176
177 return ResultStatus::Success;
178}
179
180FileSys::PartitionFilesystem Nca::GetPfs(u8 id) const {
181 return pfs[id];
182}
183
184u64 Nca::GetExeFsFileOffset(const std::string& file_name) const {
185 if (exefs_id == boost::none)
186 return 0;
187 return pfs[*exefs_id].GetFileOffset(file_name) + pfs_offset[*exefs_id];
188}
189
190u64 Nca::GetExeFsFileSize(const std::string& file_name) const {
191 if (exefs_id == boost::none)
192 return 0;
193 return pfs[*exefs_id].GetFileSize(file_name);
194}
195
196u64 Nca::GetRomFsOffset() const {
197 return romfs_offset;
198}
199
200u64 Nca::GetRomFsSize() const {
201 return romfs_size;
202}
203
204std::vector<u8> Nca::GetExeFsFile(const std::string& file_name) {
205 std::vector<u8> out(GetExeFsFileSize(file_name));
206 file.Seek(GetExeFsFileOffset(file_name), SEEK_SET);
207 file.ReadBytes(out.data(), GetExeFsFileSize(file_name));
208 return out;
209}
210
211AppLoader_NCA::AppLoader_NCA(FileUtil::IOFile&& file, std::string filepath)
212 : AppLoader(std::move(file)), filepath(std::move(filepath)) {}
213
214FileType AppLoader_NCA::IdentifyType(FileUtil::IOFile& file, const std::string&) {
215 file.Seek(0, SEEK_SET);
216 std::array<u8, 0x400> header_enc_array{};
217 if (0x400 != file.ReadBytes(header_enc_array.data(), 0x400))
218 return FileType::Error;
219
220 // TODO(DarkLordZach): Assuming everything is decrypted. Add crypto support.
221 NcaHeader header{};
222 std::memcpy(&header, header_enc_array.data(), sizeof(NcaHeader));
223
224 if (IsValidNca(header) && header.content_type == NcaContentType::Program)
225 return FileType::NCA;
226
227 return FileType::Error;
228}
229
230ResultStatus AppLoader_NCA::Load(Kernel::SharedPtr<Kernel::Process>& process) {
231 if (is_loaded) {
232 return ResultStatus::ErrorAlreadyLoaded;
233 }
234 if (!file.IsOpen()) {
235 return ResultStatus::Error;
236 }
237
238 nca = std::make_unique<Nca>();
239 ResultStatus result = nca->Load(std::move(file), filepath);
240 if (result != ResultStatus::Success) {
241 return result;
242 }
243
244 result = metadata.Load(nca->GetExeFsFile("main.npdm"));
245 if (result != ResultStatus::Success) {
246 return result;
247 }
248 metadata.Print();
249
250 const FileSys::ProgramAddressSpaceType arch_bits{metadata.GetAddressSpaceType()};
251 if (arch_bits == FileSys::ProgramAddressSpaceType::Is32Bit) {
252 return ResultStatus::ErrorUnsupportedArch;
253 }
254
255 VAddr next_load_addr{Memory::PROCESS_IMAGE_VADDR};
256 for (const auto& module : {"rtld", "main", "subsdk0", "subsdk1", "subsdk2", "subsdk3",
257 "subsdk4", "subsdk5", "subsdk6", "subsdk7", "sdk"}) {
258 const VAddr load_addr = next_load_addr;
259 next_load_addr = AppLoader_NSO::LoadModule(module, nca->GetExeFsFile(module), load_addr);
260 if (next_load_addr) {
261 NGLOG_DEBUG(Loader, "loaded module {} @ 0x{:X}", module, load_addr);
262 } else {
263 next_load_addr = load_addr;
264 }
265 }
266
267 process->program_id = metadata.GetTitleID();
268 process->svc_access_mask.set();
269 process->address_mappings = default_address_mappings;
270 process->resource_limit =
271 Kernel::ResourceLimit::GetForCategory(Kernel::ResourceLimitCategory::APPLICATION);
272 process->Run(Memory::PROCESS_IMAGE_VADDR, metadata.GetMainThreadPriority(),
273 metadata.GetMainThreadStackSize());
274
275 if (nca->GetRomFsSize() > 0)
276 Service::FileSystem::RegisterFileSystem(std::make_unique<FileSys::RomFS_Factory>(*this),
277 Service::FileSystem::Type::RomFS);
278
279 is_loaded = true;
280 return ResultStatus::Success;
281}
282
283ResultStatus AppLoader_NCA::ReadRomFS(std::shared_ptr<FileUtil::IOFile>& romfs_file, u64& offset,
284 u64& size) {
285 if (nca->GetRomFsSize() == 0) {
286 NGLOG_DEBUG(Loader, "No RomFS available");
287 return ResultStatus::ErrorNotUsed;
288 }
289
290 romfs_file = std::make_shared<FileUtil::IOFile>(filepath, "rb");
291
292 offset = nca->GetRomFsOffset();
293 size = nca->GetRomFsSize();
294
295 NGLOG_DEBUG(Loader, "RomFS offset: 0x{:016X}", offset);
296 NGLOG_DEBUG(Loader, "RomFS size: 0x{:016X}", size);
297
298 return ResultStatus::Success;
299}
300
301AppLoader_NCA::~AppLoader_NCA() = default;
302
303} // namespace Loader