summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorGravatar Max Thomas2017-09-25 00:17:38 -0600
committerGravatar B3n302017-09-25 08:17:38 +0200
commitc91ccbd0ba4118554d7377bbc3bd4c64f9bccf84 (patch)
treed56b08a52a11f229e9ce30aeda2b22bfccd48034 /src
parentServices/UDS: Added a function to send EAPoL-Start packets (#2920) (diff)
downloadyuzu-c91ccbd0ba4118554d7377bbc3bd4c64f9bccf84.tar.gz
yuzu-c91ccbd0ba4118554d7377bbc3bd4c64f9bccf84.tar.xz
yuzu-c91ccbd0ba4118554d7377bbc3bd4c64f9bccf84.zip
Loader/NCCH: Add support for loading application updates (#2927)
* loader/ncch: split NCCH parsing into its own file * loader/ncch: add support for loading update NCCHs from the SD card * loader/ncch: fix formatting * file_sys/ncch_container: Return a value for OpenFile * loader/ncch: cleanup, always instantiate overlay_ncch to base_ncch * file_sys/ncch_container: better encryption checks, allow non-app NCCHs to load properly and for the existence of NCCH structures to be checked * file_sys/ncch_container: pass filepath as a const reference
Diffstat (limited to '')
-rw-r--r--src/core/CMakeLists.txt1
-rw-r--r--src/core/file_sys/archive_selfncch.cpp28
-rw-r--r--src/core/file_sys/archive_selfncch.h4
-rw-r--r--src/core/file_sys/ncch_container.cpp316
-rw-r--r--src/core/file_sys/ncch_container.h244
-rw-r--r--src/core/loader/loader.h13
-rw-r--r--src/core/loader/ncch.cpp319
-rw-r--r--src/core/loader/ncch.h184
8 files changed, 670 insertions, 439 deletions
diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt
index cd1a8de2d..3ed619991 100644
--- a/src/core/CMakeLists.txt
+++ b/src/core/CMakeLists.txt
@@ -26,6 +26,7 @@ set(SRCS
26 file_sys/archive_systemsavedata.cpp 26 file_sys/archive_systemsavedata.cpp
27 file_sys/disk_archive.cpp 27 file_sys/disk_archive.cpp
28 file_sys/ivfc_archive.cpp 28 file_sys/ivfc_archive.cpp
29 file_sys/ncch_container.cpp
29 file_sys/path_parser.cpp 30 file_sys/path_parser.cpp
30 file_sys/savedata_archive.cpp 31 file_sys/savedata_archive.cpp
31 frontend/camera/blank_camera.cpp 32 frontend/camera/blank_camera.cpp
diff --git a/src/core/file_sys/archive_selfncch.cpp b/src/core/file_sys/archive_selfncch.cpp
index 298a37a44..7dc91a405 100644
--- a/src/core/file_sys/archive_selfncch.cpp
+++ b/src/core/file_sys/archive_selfncch.cpp
@@ -102,8 +102,7 @@ public:
102 102
103 switch (static_cast<SelfNCCHFilePathType>(file_path.type)) { 103 switch (static_cast<SelfNCCHFilePathType>(file_path.type)) {
104 case SelfNCCHFilePathType::UpdateRomFS: 104 case SelfNCCHFilePathType::UpdateRomFS:
105 LOG_WARNING(Service_FS, "(STUBBED) open update RomFS"); 105 return OpenUpdateRomFS();
106 return OpenRomFS();
107 106
108 case SelfNCCHFilePathType::RomFS: 107 case SelfNCCHFilePathType::RomFS:
109 return OpenRomFS(); 108 return OpenRomFS();
@@ -179,6 +178,17 @@ private:
179 } 178 }
180 } 179 }
181 180
181 ResultVal<std::unique_ptr<FileBackend>> OpenUpdateRomFS() const {
182 if (ncch_data.update_romfs_file) {
183 return MakeResult<std::unique_ptr<FileBackend>>(std::make_unique<IVFCFile>(
184 ncch_data.update_romfs_file, ncch_data.update_romfs_offset,
185 ncch_data.update_romfs_size));
186 } else {
187 LOG_INFO(Service_FS, "Unable to read update RomFS");
188 return ERROR_ROMFS_NOT_FOUND;
189 }
190 }
191
182 ResultVal<std::unique_ptr<FileBackend>> OpenExeFS(const std::string& filename) const { 192 ResultVal<std::unique_ptr<FileBackend>> OpenExeFS(const std::string& filename) const {
183 if (filename == "icon") { 193 if (filename == "icon") {
184 if (ncch_data.icon) { 194 if (ncch_data.icon) {
@@ -218,11 +228,19 @@ private:
218}; 228};
219 229
220ArchiveFactory_SelfNCCH::ArchiveFactory_SelfNCCH(Loader::AppLoader& app_loader) { 230ArchiveFactory_SelfNCCH::ArchiveFactory_SelfNCCH(Loader::AppLoader& app_loader) {
221 std::shared_ptr<FileUtil::IOFile> romfs_file_; 231 std::shared_ptr<FileUtil::IOFile> romfs_file;
232 if (Loader::ResultStatus::Success ==
233 app_loader.ReadRomFS(romfs_file, ncch_data.romfs_offset, ncch_data.romfs_size)) {
234
235 ncch_data.romfs_file = std::move(romfs_file);
236 }
237
238 std::shared_ptr<FileUtil::IOFile> update_romfs_file;
222 if (Loader::ResultStatus::Success == 239 if (Loader::ResultStatus::Success ==
223 app_loader.ReadRomFS(romfs_file_, ncch_data.romfs_offset, ncch_data.romfs_size)) { 240 app_loader.ReadUpdateRomFS(update_romfs_file, ncch_data.update_romfs_offset,
241 ncch_data.update_romfs_size)) {
224 242
225 ncch_data.romfs_file = std::move(romfs_file_); 243 ncch_data.update_romfs_file = std::move(update_romfs_file);
226 } 244 }
227 245
228 std::vector<u8> buffer; 246 std::vector<u8> buffer;
diff --git a/src/core/file_sys/archive_selfncch.h b/src/core/file_sys/archive_selfncch.h
index f1b971296..f1c659948 100644
--- a/src/core/file_sys/archive_selfncch.h
+++ b/src/core/file_sys/archive_selfncch.h
@@ -24,6 +24,10 @@ struct NCCHData {
24 std::shared_ptr<FileUtil::IOFile> romfs_file; 24 std::shared_ptr<FileUtil::IOFile> romfs_file;
25 u64 romfs_offset = 0; 25 u64 romfs_offset = 0;
26 u64 romfs_size = 0; 26 u64 romfs_size = 0;
27
28 std::shared_ptr<FileUtil::IOFile> update_romfs_file;
29 u64 update_romfs_offset = 0;
30 u64 update_romfs_size = 0;
27}; 31};
28 32
29/// File system interface to the SelfNCCH archive 33/// File system interface to the SelfNCCH archive
diff --git a/src/core/file_sys/ncch_container.cpp b/src/core/file_sys/ncch_container.cpp
new file mode 100644
index 000000000..59c72f3e9
--- /dev/null
+++ b/src/core/file_sys/ncch_container.cpp
@@ -0,0 +1,316 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#include <cinttypes>
6#include <cstring>
7#include <memory>
8#include "common/common_types.h"
9#include "common/logging/log.h"
10#include "core/core.h"
11#include "core/file_sys/ncch_container.h"
12#include "core/loader/loader.h"
13
14////////////////////////////////////////////////////////////////////////////////////////////////////
15// FileSys namespace
16
17namespace FileSys {
18
19static const int kMaxSections = 8; ///< Maximum number of sections (files) in an ExeFs
20static const int kBlockSize = 0x200; ///< Size of ExeFS blocks (in bytes)
21
22/**
23 * Get the decompressed size of an LZSS compressed ExeFS file
24 * @param buffer Buffer of compressed file
25 * @param size Size of compressed buffer
26 * @return Size of decompressed buffer
27 */
28static u32 LZSS_GetDecompressedSize(const u8* buffer, u32 size) {
29 u32 offset_size = *(u32*)(buffer + size - 4);
30 return offset_size + size;
31}
32
33/**
34 * Decompress ExeFS file (compressed with LZSS)
35 * @param compressed Compressed buffer
36 * @param compressed_size Size of compressed buffer
37 * @param decompressed Decompressed buffer
38 * @param decompressed_size Size of decompressed buffer
39 * @return True on success, otherwise false
40 */
41static bool LZSS_Decompress(const u8* compressed, u32 compressed_size, u8* decompressed,
42 u32 decompressed_size) {
43 const u8* footer = compressed + compressed_size - 8;
44 u32 buffer_top_and_bottom = *reinterpret_cast<const u32*>(footer);
45 u32 out = decompressed_size;
46 u32 index = compressed_size - ((buffer_top_and_bottom >> 24) & 0xFF);
47 u32 stop_index = compressed_size - (buffer_top_and_bottom & 0xFFFFFF);
48
49 memset(decompressed, 0, decompressed_size);
50 memcpy(decompressed, compressed, compressed_size);
51
52 while (index > stop_index) {
53 u8 control = compressed[--index];
54
55 for (unsigned i = 0; i < 8; i++) {
56 if (index <= stop_index)
57 break;
58 if (index <= 0)
59 break;
60 if (out <= 0)
61 break;
62
63 if (control & 0x80) {
64 // Check if compression is out of bounds
65 if (index < 2)
66 return false;
67 index -= 2;
68
69 u32 segment_offset = compressed[index] | (compressed[index + 1] << 8);
70 u32 segment_size = ((segment_offset >> 12) & 15) + 3;
71 segment_offset &= 0x0FFF;
72 segment_offset += 2;
73
74 // Check if compression is out of bounds
75 if (out < segment_size)
76 return false;
77
78 for (unsigned j = 0; j < segment_size; j++) {
79 // Check if compression is out of bounds
80 if (out + segment_offset >= decompressed_size)
81 return false;
82
83 u8 data = decompressed[out + segment_offset];
84 decompressed[--out] = data;
85 }
86 } else {
87 // Check if compression is out of bounds
88 if (out < 1)
89 return false;
90 decompressed[--out] = compressed[--index];
91 }
92 control <<= 1;
93 }
94 }
95 return true;
96}
97
98NCCHContainer::NCCHContainer(const std::string& filepath) : filepath(filepath) {
99 file = FileUtil::IOFile(filepath, "rb");
100}
101
102Loader::ResultStatus NCCHContainer::OpenFile(const std::string& filepath) {
103 this->filepath = filepath;
104 file = FileUtil::IOFile(filepath, "rb");
105
106 if (!file.IsOpen()) {
107 LOG_WARNING(Service_FS, "Failed to open %s", filepath.c_str());
108 return Loader::ResultStatus::Error;
109 }
110
111 LOG_DEBUG(Service_FS, "Opened %s", filepath.c_str());
112 return Loader::ResultStatus::Success;
113}
114
115Loader::ResultStatus NCCHContainer::Load() {
116 if (is_loaded)
117 return Loader::ResultStatus::Success;
118
119 // Reset read pointer in case this file has been read before.
120 file.Seek(0, SEEK_SET);
121
122 if (file.ReadBytes(&ncch_header, sizeof(NCCH_Header)) != sizeof(NCCH_Header))
123 return Loader::ResultStatus::Error;
124
125 // Skip NCSD header and load first NCCH (NCSD is just a container of NCCH files)...
126 if (Loader::MakeMagic('N', 'C', 'S', 'D') == ncch_header.magic) {
127 LOG_DEBUG(Service_FS, "Only loading the first (bootable) NCCH within the NCSD file!");
128 ncch_offset = 0x4000;
129 file.Seek(ncch_offset, SEEK_SET);
130 file.ReadBytes(&ncch_header, sizeof(NCCH_Header));
131 }
132
133 // Verify we are loading the correct file type...
134 if (Loader::MakeMagic('N', 'C', 'C', 'H') != ncch_header.magic)
135 return Loader::ResultStatus::ErrorInvalidFormat;
136
137 // System archives and DLC don't have an extended header but have RomFS
138 if (ncch_header.extended_header_size) {
139 if (file.ReadBytes(&exheader_header, sizeof(ExHeader_Header)) != sizeof(ExHeader_Header))
140 return Loader::ResultStatus::Error;
141
142 is_compressed = (exheader_header.codeset_info.flags.flag & 1) == 1;
143 u32 entry_point = exheader_header.codeset_info.text.address;
144 u32 code_size = exheader_header.codeset_info.text.code_size;
145 u32 stack_size = exheader_header.codeset_info.stack_size;
146 u32 bss_size = exheader_header.codeset_info.bss_size;
147 u32 core_version = exheader_header.arm11_system_local_caps.core_version;
148 u8 priority = exheader_header.arm11_system_local_caps.priority;
149 u8 resource_limit_category =
150 exheader_header.arm11_system_local_caps.resource_limit_category;
151
152 LOG_DEBUG(Service_FS, "Name: %s", exheader_header.codeset_info.name);
153 LOG_DEBUG(Service_FS, "Program ID: %016" PRIX64, ncch_header.program_id);
154 LOG_DEBUG(Service_FS, "Code compressed: %s", is_compressed ? "yes" : "no");
155 LOG_DEBUG(Service_FS, "Entry point: 0x%08X", entry_point);
156 LOG_DEBUG(Service_FS, "Code size: 0x%08X", code_size);
157 LOG_DEBUG(Service_FS, "Stack size: 0x%08X", stack_size);
158 LOG_DEBUG(Service_FS, "Bss size: 0x%08X", bss_size);
159 LOG_DEBUG(Service_FS, "Core version: %d", core_version);
160 LOG_DEBUG(Service_FS, "Thread priority: 0x%X", priority);
161 LOG_DEBUG(Service_FS, "Resource limit category: %d", resource_limit_category);
162 LOG_DEBUG(Service_FS, "System Mode: %d",
163 static_cast<int>(exheader_header.arm11_system_local_caps.system_mode));
164
165 if (exheader_header.system_info.jump_id != ncch_header.program_id) {
166 LOG_ERROR(Service_FS, "ExHeader Program ID mismatch: the ROM is probably encrypted.");
167 return Loader::ResultStatus::ErrorEncrypted;
168 }
169
170 has_exheader = true;
171 }
172
173 // DLC can have an ExeFS and a RomFS but no extended header
174 if (ncch_header.exefs_size) {
175 exefs_offset = ncch_header.exefs_offset * kBlockSize;
176 u32 exefs_size = ncch_header.exefs_size * kBlockSize;
177
178 LOG_DEBUG(Service_FS, "ExeFS offset: 0x%08X", exefs_offset);
179 LOG_DEBUG(Service_FS, "ExeFS size: 0x%08X", exefs_size);
180
181 file.Seek(exefs_offset + ncch_offset, SEEK_SET);
182 if (file.ReadBytes(&exefs_header, sizeof(ExeFs_Header)) != sizeof(ExeFs_Header))
183 return Loader::ResultStatus::Error;
184
185 has_exefs = true;
186 }
187
188 if (ncch_header.romfs_offset != 0 && ncch_header.romfs_size != 0)
189 has_romfs = true;
190
191 is_loaded = true;
192 return Loader::ResultStatus::Success;
193}
194
195Loader::ResultStatus NCCHContainer::LoadSectionExeFS(const char* name, std::vector<u8>& buffer) {
196 if (!file.IsOpen())
197 return Loader::ResultStatus::Error;
198
199 Loader::ResultStatus result = Load();
200 if (result != Loader::ResultStatus::Success)
201 return result;
202
203 if (!has_exefs)
204 return Loader::ResultStatus::ErrorNotUsed;
205
206 LOG_DEBUG(Service_FS, "%d sections:", kMaxSections);
207 // Iterate through the ExeFs archive until we find a section with the specified name...
208 for (unsigned section_number = 0; section_number < kMaxSections; section_number++) {
209 const auto& section = exefs_header.section[section_number];
210
211 // Load the specified section...
212 if (strcmp(section.name, name) == 0) {
213 LOG_DEBUG(Service_FS, "%d - offset: 0x%08X, size: 0x%08X, name: %s", section_number,
214 section.offset, section.size, section.name);
215
216 s64 section_offset =
217 (section.offset + exefs_offset + sizeof(ExeFs_Header) + ncch_offset);
218 file.Seek(section_offset, SEEK_SET);
219
220 if (strcmp(section.name, ".code") == 0 && is_compressed) {
221 // Section is compressed, read compressed .code section...
222 std::unique_ptr<u8[]> temp_buffer;
223 try {
224 temp_buffer.reset(new u8[section.size]);
225 } catch (std::bad_alloc&) {
226 return Loader::ResultStatus::ErrorMemoryAllocationFailed;
227 }
228
229 if (file.ReadBytes(&temp_buffer[0], section.size) != section.size)
230 return Loader::ResultStatus::Error;
231
232 // Decompress .code section...
233 u32 decompressed_size = LZSS_GetDecompressedSize(&temp_buffer[0], section.size);
234 buffer.resize(decompressed_size);
235 if (!LZSS_Decompress(&temp_buffer[0], section.size, &buffer[0], decompressed_size))
236 return Loader::ResultStatus::ErrorInvalidFormat;
237 } else {
238 // Section is uncompressed...
239 buffer.resize(section.size);
240 if (file.ReadBytes(&buffer[0], section.size) != section.size)
241 return Loader::ResultStatus::Error;
242 }
243 return Loader::ResultStatus::Success;
244 }
245 }
246 return Loader::ResultStatus::ErrorNotUsed;
247}
248
249Loader::ResultStatus NCCHContainer::ReadRomFS(std::shared_ptr<FileUtil::IOFile>& romfs_file,
250 u64& offset, u64& size) {
251 if (!file.IsOpen())
252 return Loader::ResultStatus::Error;
253
254 Loader::ResultStatus result = Load();
255 if (result != Loader::ResultStatus::Success)
256 return result;
257
258 if (!has_romfs) {
259 LOG_DEBUG(Service_FS, "RomFS requested from NCCH which has no RomFS");
260 return Loader::ResultStatus::ErrorNotUsed;
261 }
262
263 u32 romfs_offset = ncch_offset + (ncch_header.romfs_offset * kBlockSize) + 0x1000;
264 u32 romfs_size = (ncch_header.romfs_size * kBlockSize) - 0x1000;
265
266 LOG_DEBUG(Service_FS, "RomFS offset: 0x%08X", romfs_offset);
267 LOG_DEBUG(Service_FS, "RomFS size: 0x%08X", romfs_size);
268
269 if (file.GetSize() < romfs_offset + romfs_size)
270 return Loader::ResultStatus::Error;
271
272 // We reopen the file, to allow its position to be independent from file's
273 romfs_file = std::make_shared<FileUtil::IOFile>(filepath, "rb");
274 if (!romfs_file->IsOpen())
275 return Loader::ResultStatus::Error;
276
277 offset = romfs_offset;
278 size = romfs_size;
279
280 return Loader::ResultStatus::Success;
281}
282
283Loader::ResultStatus NCCHContainer::ReadProgramId(u64_le& program_id) {
284 Loader::ResultStatus result = Load();
285 if (result != Loader::ResultStatus::Success)
286 return result;
287
288 program_id = ncch_header.program_id;
289 return Loader::ResultStatus::Success;
290}
291
292bool NCCHContainer::HasExeFS() {
293 Loader::ResultStatus result = Load();
294 if (result != Loader::ResultStatus::Success)
295 return false;
296
297 return has_exefs;
298}
299
300bool NCCHContainer::HasRomFS() {
301 Loader::ResultStatus result = Load();
302 if (result != Loader::ResultStatus::Success)
303 return false;
304
305 return has_romfs;
306}
307
308bool NCCHContainer::HasExHeader() {
309 Loader::ResultStatus result = Load();
310 if (result != Loader::ResultStatus::Success)
311 return false;
312
313 return has_exheader;
314}
315
316} // namespace FileSys
diff --git a/src/core/file_sys/ncch_container.h b/src/core/file_sys/ncch_container.h
new file mode 100644
index 000000000..8af9032b4
--- /dev/null
+++ b/src/core/file_sys/ncch_container.h
@@ -0,0 +1,244 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include <cstddef>
8#include <memory>
9#include <string>
10#include <vector>
11#include "common/bit_field.h"
12#include "common/common_types.h"
13#include "common/file_util.h"
14#include "common/swap.h"
15#include "core/core.h"
16
17////////////////////////////////////////////////////////////////////////////////////////////////////
18/// NCCH header (Note: "NCCH" appears to be a publicly unknown acronym)
19
20struct NCCH_Header {
21 u8 signature[0x100];
22 u32_le magic;
23 u32_le content_size;
24 u8 partition_id[8];
25 u16_le maker_code;
26 u16_le version;
27 u8 reserved_0[4];
28 u64_le program_id;
29 u8 reserved_1[0x10];
30 u8 logo_region_hash[0x20];
31 u8 product_code[0x10];
32 u8 extended_header_hash[0x20];
33 u32_le extended_header_size;
34 u8 reserved_2[4];
35 u8 flags[8];
36 u32_le plain_region_offset;
37 u32_le plain_region_size;
38 u32_le logo_region_offset;
39 u32_le logo_region_size;
40 u32_le exefs_offset;
41 u32_le exefs_size;
42 u32_le exefs_hash_region_size;
43 u8 reserved_3[4];
44 u32_le romfs_offset;
45 u32_le romfs_size;
46 u32_le romfs_hash_region_size;
47 u8 reserved_4[4];
48 u8 exefs_super_block_hash[0x20];
49 u8 romfs_super_block_hash[0x20];
50};
51
52static_assert(sizeof(NCCH_Header) == 0x200, "NCCH header structure size is wrong");
53
54////////////////////////////////////////////////////////////////////////////////////////////////////
55// ExeFS (executable file system) headers
56
57struct ExeFs_SectionHeader {
58 char name[8];
59 u32 offset;
60 u32 size;
61};
62
63struct ExeFs_Header {
64 ExeFs_SectionHeader section[8];
65 u8 reserved[0x80];
66 u8 hashes[8][0x20];
67};
68
69////////////////////////////////////////////////////////////////////////////////////////////////////
70// ExHeader (executable file system header) headers
71
72struct ExHeader_SystemInfoFlags {
73 u8 reserved[5];
74 u8 flag;
75 u8 remaster_version[2];
76};
77
78struct ExHeader_CodeSegmentInfo {
79 u32 address;
80 u32 num_max_pages;
81 u32 code_size;
82};
83
84struct ExHeader_CodeSetInfo {
85 u8 name[8];
86 ExHeader_SystemInfoFlags flags;
87 ExHeader_CodeSegmentInfo text;
88 u32 stack_size;
89 ExHeader_CodeSegmentInfo ro;
90 u8 reserved[4];
91 ExHeader_CodeSegmentInfo data;
92 u32 bss_size;
93};
94
95struct ExHeader_DependencyList {
96 u8 program_id[0x30][8];
97};
98
99struct ExHeader_SystemInfo {
100 u64 save_data_size;
101 u64_le jump_id;
102 u8 reserved_2[0x30];
103};
104
105struct ExHeader_StorageInfo {
106 u8 ext_save_data_id[8];
107 u8 system_save_data_id[8];
108 u8 reserved[8];
109 u8 access_info[7];
110 u8 other_attributes;
111};
112
113struct ExHeader_ARM11_SystemLocalCaps {
114 u64_le program_id;
115 u32_le core_version;
116 u8 reserved_flags[2];
117 union {
118 u8 flags0;
119 BitField<0, 2, u8> ideal_processor;
120 BitField<2, 2, u8> affinity_mask;
121 BitField<4, 4, u8> system_mode;
122 };
123 u8 priority;
124 u8 resource_limit_descriptor[0x10][2];
125 ExHeader_StorageInfo storage_info;
126 u8 service_access_control[0x20][8];
127 u8 ex_service_access_control[0x2][8];
128 u8 reserved[0xf];
129 u8 resource_limit_category;
130};
131
132struct ExHeader_ARM11_KernelCaps {
133 u32_le descriptors[28];
134 u8 reserved[0x10];
135};
136
137struct ExHeader_ARM9_AccessControl {
138 u8 descriptors[15];
139 u8 descversion;
140};
141
142struct ExHeader_Header {
143 ExHeader_CodeSetInfo codeset_info;
144 ExHeader_DependencyList dependency_list;
145 ExHeader_SystemInfo system_info;
146 ExHeader_ARM11_SystemLocalCaps arm11_system_local_caps;
147 ExHeader_ARM11_KernelCaps arm11_kernel_caps;
148 ExHeader_ARM9_AccessControl arm9_access_control;
149 struct {
150 u8 signature[0x100];
151 u8 ncch_public_key_modulus[0x100];
152 ExHeader_ARM11_SystemLocalCaps arm11_system_local_caps;
153 ExHeader_ARM11_KernelCaps arm11_kernel_caps;
154 ExHeader_ARM9_AccessControl arm9_access_control;
155 } access_desc;
156};
157
158static_assert(sizeof(ExHeader_Header) == 0x800, "ExHeader structure size is wrong");
159
160////////////////////////////////////////////////////////////////////////////////////////////////////
161// FileSys namespace
162
163namespace FileSys {
164
165/**
166 * Helper which implements an interface to deal with NCCH containers which can
167 * contain ExeFS archives or RomFS archives for games or other applications.
168 */
169class NCCHContainer {
170public:
171 NCCHContainer(const std::string& filepath);
172 NCCHContainer() {}
173
174 Loader::ResultStatus OpenFile(const std::string& filepath);
175
176 /**
177 * Ensure ExeFS and exheader is loaded and ready for reading sections
178 * @return ResultStatus result of function
179 */
180 Loader::ResultStatus Load();
181
182 /**
183 * Reads an application ExeFS section of an NCCH file (e.g. .code, .logo, etc.)
184 * @param name Name of section to read out of NCCH file
185 * @param buffer Vector to read data into
186 * @return ResultStatus result of function
187 */
188 Loader::ResultStatus LoadSectionExeFS(const char* name, std::vector<u8>& buffer);
189
190 /**
191 * Get the RomFS of the NCCH container
192 * Since the RomFS can be huge, we return a file reference instead of copying to a buffer
193 * @param romfs_file The file containing the RomFS
194 * @param offset The offset the romfs begins on
195 * @param size The size of the romfs
196 * @return ResultStatus result of function
197 */
198 Loader::ResultStatus ReadRomFS(std::shared_ptr<FileUtil::IOFile>& romfs_file, u64& offset,
199 u64& size);
200
201 /**
202 * Get the Program ID of the NCCH container
203 * @return ResultStatus result of function
204 */
205 Loader::ResultStatus ReadProgramId(u64_le& program_id);
206
207 /**
208 * Checks whether the NCCH container contains an ExeFS
209 * @return bool check result
210 */
211 bool HasExeFS();
212
213 /**
214 * Checks whether the NCCH container contains a RomFS
215 * @return bool check result
216 */
217 bool HasRomFS();
218
219 /**
220 * Checks whether the NCCH container contains an ExHeader
221 * @return bool check result
222 */
223 bool HasExHeader();
224
225 NCCH_Header ncch_header;
226 ExeFs_Header exefs_header;
227 ExHeader_Header exheader_header;
228
229private:
230 bool has_exheader = false;
231 bool has_exefs = false;
232 bool has_romfs = false;
233
234 bool is_loaded = false;
235 bool is_compressed = false;
236
237 u32 ncch_offset = 0; // Offset to NCCH header, can be 0 or after NCSD header
238 u32 exefs_offset = 0;
239
240 std::string filepath;
241 FileUtil::IOFile file;
242};
243
244} // namespace FileSys
diff --git a/src/core/loader/loader.h b/src/core/loader/loader.h
index e731888a2..3160fd2fd 100644
--- a/src/core/loader/loader.h
+++ b/src/core/loader/loader.h
@@ -167,6 +167,19 @@ public:
167 } 167 }
168 168
169 /** 169 /**
170 * Get the update RomFS of the application
171 * Since the RomFS can be huge, we return a file reference instead of copying to a buffer
172 * @param romfs_file The file containing the RomFS
173 * @param offset The offset the romfs begins on
174 * @param size The size of the romfs
175 * @return ResultStatus result of function
176 */
177 virtual ResultStatus ReadUpdateRomFS(std::shared_ptr<FileUtil::IOFile>& romfs_file, u64& offset,
178 u64& size) {
179 return ResultStatus::ErrorNotImplemented;
180 }
181
182 /**
170 * Get the title of the application 183 * Get the title of the application
171 * @param title Reference to store the application title into 184 * @param title Reference to store the application title into
172 * @return ResultStatus result of function 185 * @return ResultStatus result of function
diff --git a/src/core/loader/ncch.cpp b/src/core/loader/ncch.cpp
index 79ea50147..bef7fa567 100644
--- a/src/core/loader/ncch.cpp
+++ b/src/core/loader/ncch.cpp
@@ -13,6 +13,7 @@
13#include "common/swap.h" 13#include "common/swap.h"
14#include "core/core.h" 14#include "core/core.h"
15#include "core/file_sys/archive_selfncch.h" 15#include "core/file_sys/archive_selfncch.h"
16#include "core/file_sys/ncch_container.h"
16#include "core/hle/kernel/process.h" 17#include "core/hle/kernel/process.h"
17#include "core/hle/kernel/resource_limit.h" 18#include "core/hle/kernel/resource_limit.h"
18#include "core/hle/service/cfg/cfg.h" 19#include "core/hle/service/cfg/cfg.h"
@@ -27,87 +28,7 @@
27 28
28namespace Loader { 29namespace Loader {
29 30
30static const int kMaxSections = 8; ///< Maximum number of sections (files) in an ExeFs 31static const u64 UPDATE_MASK = 0x0000000e00000000;
31static const int kBlockSize = 0x200; ///< Size of ExeFS blocks (in bytes)
32
33/**
34 * Get the decompressed size of an LZSS compressed ExeFS file
35 * @param buffer Buffer of compressed file
36 * @param size Size of compressed buffer
37 * @return Size of decompressed buffer
38 */
39static u32 LZSS_GetDecompressedSize(const u8* buffer, u32 size) {
40 u32 offset_size = *(u32*)(buffer + size - 4);
41 return offset_size + size;
42}
43
44/**
45 * Decompress ExeFS file (compressed with LZSS)
46 * @param compressed Compressed buffer
47 * @param compressed_size Size of compressed buffer
48 * @param decompressed Decompressed buffer
49 * @param decompressed_size Size of decompressed buffer
50 * @return True on success, otherwise false
51 */
52static bool LZSS_Decompress(const u8* compressed, u32 compressed_size, u8* decompressed,
53 u32 decompressed_size) {
54 const u8* footer = compressed + compressed_size - 8;
55 u32 buffer_top_and_bottom = *reinterpret_cast<const u32*>(footer);
56 u32 out = decompressed_size;
57 u32 index = compressed_size - ((buffer_top_and_bottom >> 24) & 0xFF);
58 u32 stop_index = compressed_size - (buffer_top_and_bottom & 0xFFFFFF);
59
60 memset(decompressed, 0, decompressed_size);
61 memcpy(decompressed, compressed, compressed_size);
62
63 while (index > stop_index) {
64 u8 control = compressed[--index];
65
66 for (unsigned i = 0; i < 8; i++) {
67 if (index <= stop_index)
68 break;
69 if (index <= 0)
70 break;
71 if (out <= 0)
72 break;
73
74 if (control & 0x80) {
75 // Check if compression is out of bounds
76 if (index < 2)
77 return false;
78 index -= 2;
79
80 u32 segment_offset = compressed[index] | (compressed[index + 1] << 8);
81 u32 segment_size = ((segment_offset >> 12) & 15) + 3;
82 segment_offset &= 0x0FFF;
83 segment_offset += 2;
84
85 // Check if compression is out of bounds
86 if (out < segment_size)
87 return false;
88
89 for (unsigned j = 0; j < segment_size; j++) {
90 // Check if compression is out of bounds
91 if (out + segment_offset >= decompressed_size)
92 return false;
93
94 u8 data = decompressed[out + segment_offset];
95 decompressed[--out] = data;
96 }
97 } else {
98 // Check if compression is out of bounds
99 if (out < 1)
100 return false;
101 decompressed[--out] = compressed[--index];
102 }
103 control <<= 1;
104 }
105 }
106 return true;
107}
108
109////////////////////////////////////////////////////////////////////////////////////////////////////
110// AppLoader_NCCH class
111 32
112FileType AppLoader_NCCH::IdentifyType(FileUtil::IOFile& file) { 33FileType AppLoader_NCCH::IdentifyType(FileUtil::IOFile& file) {
113 u32 magic; 34 u32 magic;
@@ -124,15 +45,25 @@ FileType AppLoader_NCCH::IdentifyType(FileUtil::IOFile& file) {
124 return FileType::Error; 45 return FileType::Error;
125} 46}
126 47
48static std::string GetUpdateNCCHPath(u64_le program_id) {
49 u32 high = static_cast<u32>((program_id | UPDATE_MASK) >> 32);
50 u32 low = static_cast<u32>((program_id | UPDATE_MASK) & 0xFFFFFFFF);
51
52 return Common::StringFromFormat("%sNintendo 3DS/%s/%s/title/%08x/%08x/content/00000000.app",
53 FileUtil::GetUserPath(D_SDMC_IDX).c_str(), SYSTEM_ID, SDCARD_ID,
54 high, low);
55}
56
127std::pair<boost::optional<u32>, ResultStatus> AppLoader_NCCH::LoadKernelSystemMode() { 57std::pair<boost::optional<u32>, ResultStatus> AppLoader_NCCH::LoadKernelSystemMode() {
128 if (!is_loaded) { 58 if (!is_loaded) {
129 ResultStatus res = LoadExeFS(); 59 ResultStatus res = base_ncch.Load();
130 if (res != ResultStatus::Success) { 60 if (res != ResultStatus::Success) {
131 return std::make_pair(boost::none, res); 61 return std::make_pair(boost::none, res);
132 } 62 }
133 } 63 }
64
134 // Set the system mode as the one from the exheader. 65 // Set the system mode as the one from the exheader.
135 return std::make_pair(exheader_header.arm11_system_local_caps.system_mode.Value(), 66 return std::make_pair(overlay_ncch->exheader_header.arm11_system_local_caps.system_mode.Value(),
136 ResultStatus::Success); 67 ResultStatus::Success);
137} 68}
138 69
@@ -144,29 +75,34 @@ ResultStatus AppLoader_NCCH::LoadExec() {
144 return ResultStatus::ErrorNotLoaded; 75 return ResultStatus::ErrorNotLoaded;
145 76
146 std::vector<u8> code; 77 std::vector<u8> code;
147 if (ResultStatus::Success == ReadCode(code)) { 78 u64_le program_id;
79 if (ResultStatus::Success == ReadCode(code) &&
80 ResultStatus::Success == ReadProgramId(program_id)) {
148 std::string process_name = Common::StringFromFixedZeroTerminatedBuffer( 81 std::string process_name = Common::StringFromFixedZeroTerminatedBuffer(
149 (const char*)exheader_header.codeset_info.name, 8); 82 (const char*)overlay_ncch->exheader_header.codeset_info.name, 8);
150 83
151 SharedPtr<CodeSet> codeset = CodeSet::Create(process_name, ncch_header.program_id); 84 SharedPtr<CodeSet> codeset = CodeSet::Create(process_name, program_id);
152 85
153 codeset->code.offset = 0; 86 codeset->code.offset = 0;
154 codeset->code.addr = exheader_header.codeset_info.text.address; 87 codeset->code.addr = overlay_ncch->exheader_header.codeset_info.text.address;
155 codeset->code.size = exheader_header.codeset_info.text.num_max_pages * Memory::PAGE_SIZE; 88 codeset->code.size =
89 overlay_ncch->exheader_header.codeset_info.text.num_max_pages * Memory::PAGE_SIZE;
156 90
157 codeset->rodata.offset = codeset->code.offset + codeset->code.size; 91 codeset->rodata.offset = codeset->code.offset + codeset->code.size;
158 codeset->rodata.addr = exheader_header.codeset_info.ro.address; 92 codeset->rodata.addr = overlay_ncch->exheader_header.codeset_info.ro.address;
159 codeset->rodata.size = exheader_header.codeset_info.ro.num_max_pages * Memory::PAGE_SIZE; 93 codeset->rodata.size =
94 overlay_ncch->exheader_header.codeset_info.ro.num_max_pages * Memory::PAGE_SIZE;
160 95
161 // TODO(yuriks): Not sure if the bss size is added to the page-aligned .data size or just 96 // TODO(yuriks): Not sure if the bss size is added to the page-aligned .data size or just
162 // to the regular size. Playing it safe for now. 97 // to the regular size. Playing it safe for now.
163 u32 bss_page_size = (exheader_header.codeset_info.bss_size + 0xFFF) & ~0xFFF; 98 u32 bss_page_size = (overlay_ncch->exheader_header.codeset_info.bss_size + 0xFFF) & ~0xFFF;
164 code.resize(code.size() + bss_page_size, 0); 99 code.resize(code.size() + bss_page_size, 0);
165 100
166 codeset->data.offset = codeset->rodata.offset + codeset->rodata.size; 101 codeset->data.offset = codeset->rodata.offset + codeset->rodata.size;
167 codeset->data.addr = exheader_header.codeset_info.data.address; 102 codeset->data.addr = overlay_ncch->exheader_header.codeset_info.data.address;
168 codeset->data.size = 103 codeset->data.size =
169 exheader_header.codeset_info.data.num_max_pages * Memory::PAGE_SIZE + bss_page_size; 104 overlay_ncch->exheader_header.codeset_info.data.num_max_pages * Memory::PAGE_SIZE +
105 bss_page_size;
170 106
171 codeset->entrypoint = codeset->code.addr; 107 codeset->entrypoint = codeset->code.addr;
172 codeset->memory = std::make_shared<std::vector<u8>>(std::move(code)); 108 codeset->memory = std::make_shared<std::vector<u8>>(std::move(code));
@@ -177,150 +113,27 @@ ResultStatus AppLoader_NCCH::LoadExec() {
177 // Attach a resource limit to the process based on the resource limit category 113 // Attach a resource limit to the process based on the resource limit category
178 Kernel::g_current_process->resource_limit = 114 Kernel::g_current_process->resource_limit =
179 Kernel::ResourceLimit::GetForCategory(static_cast<Kernel::ResourceLimitCategory>( 115 Kernel::ResourceLimit::GetForCategory(static_cast<Kernel::ResourceLimitCategory>(
180 exheader_header.arm11_system_local_caps.resource_limit_category)); 116 overlay_ncch->exheader_header.arm11_system_local_caps.resource_limit_category));
181 117
182 // Set the default CPU core for this process 118 // Set the default CPU core for this process
183 Kernel::g_current_process->ideal_processor = 119 Kernel::g_current_process->ideal_processor =
184 exheader_header.arm11_system_local_caps.ideal_processor; 120 overlay_ncch->exheader_header.arm11_system_local_caps.ideal_processor;
185 121
186 // Copy data while converting endianness 122 // Copy data while converting endianness
187 std::array<u32, ARRAY_SIZE(exheader_header.arm11_kernel_caps.descriptors)> kernel_caps; 123 std::array<u32, ARRAY_SIZE(overlay_ncch->exheader_header.arm11_kernel_caps.descriptors)>
188 std::copy_n(exheader_header.arm11_kernel_caps.descriptors, kernel_caps.size(), 124 kernel_caps;
125 std::copy_n(overlay_ncch->exheader_header.arm11_kernel_caps.descriptors, kernel_caps.size(),
189 begin(kernel_caps)); 126 begin(kernel_caps));
190 Kernel::g_current_process->ParseKernelCaps(kernel_caps.data(), kernel_caps.size()); 127 Kernel::g_current_process->ParseKernelCaps(kernel_caps.data(), kernel_caps.size());
191 128
192 s32 priority = exheader_header.arm11_system_local_caps.priority; 129 s32 priority = overlay_ncch->exheader_header.arm11_system_local_caps.priority;
193 u32 stack_size = exheader_header.codeset_info.stack_size; 130 u32 stack_size = overlay_ncch->exheader_header.codeset_info.stack_size;
194 Kernel::g_current_process->Run(priority, stack_size); 131 Kernel::g_current_process->Run(priority, stack_size);
195 return ResultStatus::Success; 132 return ResultStatus::Success;
196 } 133 }
197 return ResultStatus::Error; 134 return ResultStatus::Error;
198} 135}
199 136
200ResultStatus AppLoader_NCCH::LoadSectionExeFS(const char* name, std::vector<u8>& buffer) {
201 if (!file.IsOpen())
202 return ResultStatus::Error;
203
204 ResultStatus result = LoadExeFS();
205 if (result != ResultStatus::Success)
206 return result;
207
208 LOG_DEBUG(Loader, "%d sections:", kMaxSections);
209 // Iterate through the ExeFs archive until we find a section with the specified name...
210 for (unsigned section_number = 0; section_number < kMaxSections; section_number++) {
211 const auto& section = exefs_header.section[section_number];
212
213 // Load the specified section...
214 if (strcmp(section.name, name) == 0) {
215 LOG_DEBUG(Loader, "%d - offset: 0x%08X, size: 0x%08X, name: %s", section_number,
216 section.offset, section.size, section.name);
217
218 s64 section_offset =
219 (section.offset + exefs_offset + sizeof(ExeFs_Header) + ncch_offset);
220 file.Seek(section_offset, SEEK_SET);
221
222 if (strcmp(section.name, ".code") == 0 && is_compressed) {
223 // Section is compressed, read compressed .code section...
224 std::unique_ptr<u8[]> temp_buffer;
225 try {
226 temp_buffer.reset(new u8[section.size]);
227 } catch (std::bad_alloc&) {
228 return ResultStatus::ErrorMemoryAllocationFailed;
229 }
230
231 if (file.ReadBytes(&temp_buffer[0], section.size) != section.size)
232 return ResultStatus::Error;
233
234 // Decompress .code section...
235 u32 decompressed_size = LZSS_GetDecompressedSize(&temp_buffer[0], section.size);
236 buffer.resize(decompressed_size);
237 if (!LZSS_Decompress(&temp_buffer[0], section.size, &buffer[0], decompressed_size))
238 return ResultStatus::ErrorInvalidFormat;
239 } else {
240 // Section is uncompressed...
241 buffer.resize(section.size);
242 if (file.ReadBytes(&buffer[0], section.size) != section.size)
243 return ResultStatus::Error;
244 }
245 return ResultStatus::Success;
246 }
247 }
248 return ResultStatus::ErrorNotUsed;
249}
250
251ResultStatus AppLoader_NCCH::LoadExeFS() {
252 if (is_exefs_loaded)
253 return ResultStatus::Success;
254
255 if (!file.IsOpen())
256 return ResultStatus::Error;
257
258 // Reset read pointer in case this file has been read before.
259 file.Seek(0, SEEK_SET);
260
261 if (file.ReadBytes(&ncch_header, sizeof(NCCH_Header)) != sizeof(NCCH_Header))
262 return ResultStatus::Error;
263
264 // Skip NCSD header and load first NCCH (NCSD is just a container of NCCH files)...
265 if (MakeMagic('N', 'C', 'S', 'D') == ncch_header.magic) {
266 LOG_DEBUG(Loader, "Only loading the first (bootable) NCCH within the NCSD file!");
267 ncch_offset = 0x4000;
268 file.Seek(ncch_offset, SEEK_SET);
269 file.ReadBytes(&ncch_header, sizeof(NCCH_Header));
270 }
271
272 // Verify we are loading the correct file type...
273 if (MakeMagic('N', 'C', 'C', 'H') != ncch_header.magic)
274 return ResultStatus::ErrorInvalidFormat;
275
276 // Read ExHeader...
277
278 if (file.ReadBytes(&exheader_header, sizeof(ExHeader_Header)) != sizeof(ExHeader_Header))
279 return ResultStatus::Error;
280
281 is_compressed = (exheader_header.codeset_info.flags.flag & 1) == 1;
282 entry_point = exheader_header.codeset_info.text.address;
283 code_size = exheader_header.codeset_info.text.code_size;
284 stack_size = exheader_header.codeset_info.stack_size;
285 bss_size = exheader_header.codeset_info.bss_size;
286 core_version = exheader_header.arm11_system_local_caps.core_version;
287 priority = exheader_header.arm11_system_local_caps.priority;
288 resource_limit_category = exheader_header.arm11_system_local_caps.resource_limit_category;
289
290 LOG_DEBUG(Loader, "Name: %s", exheader_header.codeset_info.name);
291 LOG_DEBUG(Loader, "Program ID: %016" PRIX64, ncch_header.program_id);
292 LOG_DEBUG(Loader, "Code compressed: %s", is_compressed ? "yes" : "no");
293 LOG_DEBUG(Loader, "Entry point: 0x%08X", entry_point);
294 LOG_DEBUG(Loader, "Code size: 0x%08X", code_size);
295 LOG_DEBUG(Loader, "Stack size: 0x%08X", stack_size);
296 LOG_DEBUG(Loader, "Bss size: 0x%08X", bss_size);
297 LOG_DEBUG(Loader, "Core version: %d", core_version);
298 LOG_DEBUG(Loader, "Thread priority: 0x%X", priority);
299 LOG_DEBUG(Loader, "Resource limit category: %d", resource_limit_category);
300 LOG_DEBUG(Loader, "System Mode: %d",
301 static_cast<int>(exheader_header.arm11_system_local_caps.system_mode));
302
303 if (exheader_header.arm11_system_local_caps.program_id != ncch_header.program_id) {
304 LOG_ERROR(Loader, "ExHeader Program ID mismatch: the ROM is probably encrypted.");
305 return ResultStatus::ErrorEncrypted;
306 }
307
308 // Read ExeFS...
309
310 exefs_offset = ncch_header.exefs_offset * kBlockSize;
311 u32 exefs_size = ncch_header.exefs_size * kBlockSize;
312
313 LOG_DEBUG(Loader, "ExeFS offset: 0x%08X", exefs_offset);
314 LOG_DEBUG(Loader, "ExeFS size: 0x%08X", exefs_size);
315
316 file.Seek(exefs_offset + ncch_offset, SEEK_SET);
317 if (file.ReadBytes(&exefs_header, sizeof(ExeFs_Header)) != sizeof(ExeFs_Header))
318 return ResultStatus::Error;
319
320 is_exefs_loaded = true;
321 return ResultStatus::Success;
322}
323
324void AppLoader_NCCH::ParseRegionLockoutInfo() { 137void AppLoader_NCCH::ParseRegionLockoutInfo() {
325 std::vector<u8> smdh_buffer; 138 std::vector<u8> smdh_buffer;
326 if (ReadIcon(smdh_buffer) == ResultStatus::Success && smdh_buffer.size() >= sizeof(SMDH)) { 139 if (ReadIcon(smdh_buffer) == ResultStatus::Success && smdh_buffer.size() >= sizeof(SMDH)) {
@@ -339,23 +152,32 @@ void AppLoader_NCCH::ParseRegionLockoutInfo() {
339} 152}
340 153
341ResultStatus AppLoader_NCCH::Load() { 154ResultStatus AppLoader_NCCH::Load() {
155 u64_le ncch_program_id;
156
342 if (is_loaded) 157 if (is_loaded)
343 return ResultStatus::ErrorAlreadyLoaded; 158 return ResultStatus::ErrorAlreadyLoaded;
344 159
345 ResultStatus result = LoadExeFS(); 160 ResultStatus result = base_ncch.Load();
346 if (result != ResultStatus::Success) 161 if (result != ResultStatus::Success)
347 return result; 162 return result;
348 163
349 std::string program_id{Common::StringFromFormat("%016" PRIX64, ncch_header.program_id)}; 164 ReadProgramId(ncch_program_id);
165 std::string program_id{Common::StringFromFormat("%016" PRIX64, ncch_program_id)};
350 166
351 LOG_INFO(Loader, "Program ID: %s", program_id.c_str()); 167 LOG_INFO(Loader, "Program ID: %s", program_id.c_str());
352 168
169 update_ncch.OpenFile(GetUpdateNCCHPath(ncch_program_id));
170 result = update_ncch.Load();
171 if (result == ResultStatus::Success) {
172 overlay_ncch = &update_ncch;
173 }
174
353 Core::Telemetry().AddField(Telemetry::FieldType::Session, "ProgramId", program_id); 175 Core::Telemetry().AddField(Telemetry::FieldType::Session, "ProgramId", program_id);
354 176
355 if (auto room_member = Network::GetRoomMember().lock()) { 177 if (auto room_member = Network::GetRoomMember().lock()) {
356 Network::GameInfo game_info; 178 Network::GameInfo game_info;
357 ReadTitle(game_info.name); 179 ReadTitle(game_info.name);
358 game_info.id = ncch_header.program_id; 180 game_info.id = ncch_program_id;
359 room_member->SendGameInfo(game_info); 181 room_member->SendGameInfo(game_info);
360 } 182 }
361 183
@@ -374,61 +196,40 @@ ResultStatus AppLoader_NCCH::Load() {
374} 196}
375 197
376ResultStatus AppLoader_NCCH::ReadCode(std::vector<u8>& buffer) { 198ResultStatus AppLoader_NCCH::ReadCode(std::vector<u8>& buffer) {
377 return LoadSectionExeFS(".code", buffer); 199 return overlay_ncch->LoadSectionExeFS(".code", buffer);
378} 200}
379 201
380ResultStatus AppLoader_NCCH::ReadIcon(std::vector<u8>& buffer) { 202ResultStatus AppLoader_NCCH::ReadIcon(std::vector<u8>& buffer) {
381 return LoadSectionExeFS("icon", buffer); 203 return overlay_ncch->LoadSectionExeFS("icon", buffer);
382} 204}
383 205
384ResultStatus AppLoader_NCCH::ReadBanner(std::vector<u8>& buffer) { 206ResultStatus AppLoader_NCCH::ReadBanner(std::vector<u8>& buffer) {
385 return LoadSectionExeFS("banner", buffer); 207 return overlay_ncch->LoadSectionExeFS("banner", buffer);
386} 208}
387 209
388ResultStatus AppLoader_NCCH::ReadLogo(std::vector<u8>& buffer) { 210ResultStatus AppLoader_NCCH::ReadLogo(std::vector<u8>& buffer) {
389 return LoadSectionExeFS("logo", buffer); 211 return overlay_ncch->LoadSectionExeFS("logo", buffer);
390} 212}
391 213
392ResultStatus AppLoader_NCCH::ReadProgramId(u64& out_program_id) { 214ResultStatus AppLoader_NCCH::ReadProgramId(u64& out_program_id) {
393 if (!file.IsOpen()) 215 ResultStatus result = base_ncch.ReadProgramId(out_program_id);
394 return ResultStatus::Error;
395
396 ResultStatus result = LoadExeFS();
397 if (result != ResultStatus::Success) 216 if (result != ResultStatus::Success)
398 return result; 217 return result;
399 218
400 out_program_id = ncch_header.program_id;
401 return ResultStatus::Success; 219 return ResultStatus::Success;
402} 220}
403 221
404ResultStatus AppLoader_NCCH::ReadRomFS(std::shared_ptr<FileUtil::IOFile>& romfs_file, u64& offset, 222ResultStatus AppLoader_NCCH::ReadRomFS(std::shared_ptr<FileUtil::IOFile>& romfs_file, u64& offset,
405 u64& size) { 223 u64& size) {
406 if (!file.IsOpen()) 224 return base_ncch.ReadRomFS(romfs_file, offset, size);
407 return ResultStatus::Error; 225}
408
409 // Check if the NCCH has a RomFS...
410 if (ncch_header.romfs_offset != 0 && ncch_header.romfs_size != 0) {
411 u32 romfs_offset = ncch_offset + (ncch_header.romfs_offset * kBlockSize) + 0x1000;
412 u32 romfs_size = (ncch_header.romfs_size * kBlockSize) - 0x1000;
413
414 LOG_DEBUG(Loader, "RomFS offset: 0x%08X", romfs_offset);
415 LOG_DEBUG(Loader, "RomFS size: 0x%08X", romfs_size);
416
417 if (file.GetSize() < romfs_offset + romfs_size)
418 return ResultStatus::Error;
419
420 // We reopen the file, to allow its position to be independent from file's
421 romfs_file = std::make_shared<FileUtil::IOFile>(filepath, "rb");
422 if (!romfs_file->IsOpen())
423 return ResultStatus::Error;
424 226
425 offset = romfs_offset; 227ResultStatus AppLoader_NCCH::ReadUpdateRomFS(std::shared_ptr<FileUtil::IOFile>& romfs_file,
426 size = romfs_size; 228 u64& offset, u64& size) {
229 ResultStatus result = update_ncch.ReadRomFS(romfs_file, offset, size);
427 230
428 return ResultStatus::Success; 231 if (result != ResultStatus::Success)
429 } 232 return base_ncch.ReadRomFS(romfs_file, offset, size);
430 LOG_DEBUG(Loader, "NCCH has no RomFS");
431 return ResultStatus::ErrorNotUsed;
432} 233}
433 234
434ResultStatus AppLoader_NCCH::ReadTitle(std::string& title) { 235ResultStatus AppLoader_NCCH::ReadTitle(std::string& title) {
diff --git a/src/core/loader/ncch.h b/src/core/loader/ncch.h
index e40cef764..9b56465cb 100644
--- a/src/core/loader/ncch.h
+++ b/src/core/loader/ncch.h
@@ -5,155 +5,12 @@
5#pragma once 5#pragma once
6 6
7#include <memory> 7#include <memory>
8#include "common/bit_field.h"
9#include "common/common_types.h" 8#include "common/common_types.h"
10#include "common/swap.h" 9#include "common/swap.h"
10#include "core/file_sys/ncch_container.h"
11#include "core/loader/loader.h" 11#include "core/loader/loader.h"
12 12
13//////////////////////////////////////////////////////////////////////////////////////////////////// 13////////////////////////////////////////////////////////////////////////////////////////////////////
14/// NCCH header (Note: "NCCH" appears to be a publicly unknown acronym)
15
16struct NCCH_Header {
17 u8 signature[0x100];
18 u32_le magic;
19 u32_le content_size;
20 u8 partition_id[8];
21 u16_le maker_code;
22 u16_le version;
23 u8 reserved_0[4];
24 u64_le program_id;
25 u8 reserved_1[0x10];
26 u8 logo_region_hash[0x20];
27 u8 product_code[0x10];
28 u8 extended_header_hash[0x20];
29 u32_le extended_header_size;
30 u8 reserved_2[4];
31 u8 flags[8];
32 u32_le plain_region_offset;
33 u32_le plain_region_size;
34 u32_le logo_region_offset;
35 u32_le logo_region_size;
36 u32_le exefs_offset;
37 u32_le exefs_size;
38 u32_le exefs_hash_region_size;
39 u8 reserved_3[4];
40 u32_le romfs_offset;
41 u32_le romfs_size;
42 u32_le romfs_hash_region_size;
43 u8 reserved_4[4];
44 u8 exefs_super_block_hash[0x20];
45 u8 romfs_super_block_hash[0x20];
46};
47
48static_assert(sizeof(NCCH_Header) == 0x200, "NCCH header structure size is wrong");
49
50////////////////////////////////////////////////////////////////////////////////////////////////////
51// ExeFS (executable file system) headers
52
53struct ExeFs_SectionHeader {
54 char name[8];
55 u32 offset;
56 u32 size;
57};
58
59struct ExeFs_Header {
60 ExeFs_SectionHeader section[8];
61 u8 reserved[0x80];
62 u8 hashes[8][0x20];
63};
64
65////////////////////////////////////////////////////////////////////////////////////////////////////
66// ExHeader (executable file system header) headers
67
68struct ExHeader_SystemInfoFlags {
69 u8 reserved[5];
70 u8 flag;
71 u8 remaster_version[2];
72};
73
74struct ExHeader_CodeSegmentInfo {
75 u32 address;
76 u32 num_max_pages;
77 u32 code_size;
78};
79
80struct ExHeader_CodeSetInfo {
81 u8 name[8];
82 ExHeader_SystemInfoFlags flags;
83 ExHeader_CodeSegmentInfo text;
84 u32 stack_size;
85 ExHeader_CodeSegmentInfo ro;
86 u8 reserved[4];
87 ExHeader_CodeSegmentInfo data;
88 u32 bss_size;
89};
90
91struct ExHeader_DependencyList {
92 u8 program_id[0x30][8];
93};
94
95struct ExHeader_SystemInfo {
96 u64 save_data_size;
97 u8 jump_id[8];
98 u8 reserved_2[0x30];
99};
100
101struct ExHeader_StorageInfo {
102 u8 ext_save_data_id[8];
103 u8 system_save_data_id[8];
104 u8 reserved[8];
105 u8 access_info[7];
106 u8 other_attributes;
107};
108
109struct ExHeader_ARM11_SystemLocalCaps {
110 u64_le program_id;
111 u32_le core_version;
112 u8 reserved_flags[2];
113 union {
114 u8 flags0;
115 BitField<0, 2, u8> ideal_processor;
116 BitField<2, 2, u8> affinity_mask;
117 BitField<4, 4, u8> system_mode;
118 };
119 u8 priority;
120 u8 resource_limit_descriptor[0x10][2];
121 ExHeader_StorageInfo storage_info;
122 u8 service_access_control[0x20][8];
123 u8 ex_service_access_control[0x2][8];
124 u8 reserved[0xf];
125 u8 resource_limit_category;
126};
127
128struct ExHeader_ARM11_KernelCaps {
129 u32_le descriptors[28];
130 u8 reserved[0x10];
131};
132
133struct ExHeader_ARM9_AccessControl {
134 u8 descriptors[15];
135 u8 descversion;
136};
137
138struct ExHeader_Header {
139 ExHeader_CodeSetInfo codeset_info;
140 ExHeader_DependencyList dependency_list;
141 ExHeader_SystemInfo system_info;
142 ExHeader_ARM11_SystemLocalCaps arm11_system_local_caps;
143 ExHeader_ARM11_KernelCaps arm11_kernel_caps;
144 ExHeader_ARM9_AccessControl arm9_access_control;
145 struct {
146 u8 signature[0x100];
147 u8 ncch_public_key_modulus[0x100];
148 ExHeader_ARM11_SystemLocalCaps arm11_system_local_caps;
149 ExHeader_ARM11_KernelCaps arm11_kernel_caps;
150 ExHeader_ARM9_AccessControl arm9_access_control;
151 } access_desc;
152};
153
154static_assert(sizeof(ExHeader_Header) == 0x800, "ExHeader structure size is wrong");
155
156////////////////////////////////////////////////////////////////////////////////////////////////////
157// Loader namespace 14// Loader namespace
158 15
159namespace Loader { 16namespace Loader {
@@ -162,7 +19,8 @@ namespace Loader {
162class AppLoader_NCCH final : public AppLoader { 19class AppLoader_NCCH final : public AppLoader {
163public: 20public:
164 AppLoader_NCCH(FileUtil::IOFile&& file, const std::string& filepath) 21 AppLoader_NCCH(FileUtil::IOFile&& file, const std::string& filepath)
165 : AppLoader(std::move(file)), filepath(filepath) {} 22 : AppLoader(std::move(file)), filepath(filepath), base_ncch(filepath),
23 overlay_ncch(&base_ncch) {}
166 24
167 /** 25 /**
168 * Returns the type of the file 26 * Returns the type of the file
@@ -196,48 +54,24 @@ public:
196 ResultStatus ReadRomFS(std::shared_ptr<FileUtil::IOFile>& romfs_file, u64& offset, 54 ResultStatus ReadRomFS(std::shared_ptr<FileUtil::IOFile>& romfs_file, u64& offset,
197 u64& size) override; 55 u64& size) override;
198 56
57 ResultStatus ReadUpdateRomFS(std::shared_ptr<FileUtil::IOFile>& romfs_file, u64& offset,
58 u64& size) override;
59
199 ResultStatus ReadTitle(std::string& title) override; 60 ResultStatus ReadTitle(std::string& title) override;
200 61
201private: 62private:
202 /** 63 /**
203 * Reads an application ExeFS section of an NCCH file into AppLoader (e.g. .code, .logo, etc.)
204 * @param name Name of section to read out of NCCH file
205 * @param buffer Vector to read data into
206 * @return ResultStatus result of function
207 */
208 ResultStatus LoadSectionExeFS(const char* name, std::vector<u8>& buffer);
209
210 /**
211 * Loads .code section into memory for booting 64 * Loads .code section into memory for booting
212 * @return ResultStatus result of function 65 * @return ResultStatus result of function
213 */ 66 */
214 ResultStatus LoadExec(); 67 ResultStatus LoadExec();
215 68
216 /**
217 * Ensure ExeFS is loaded and ready for reading sections
218 * @return ResultStatus result of function
219 */
220 ResultStatus LoadExeFS();
221
222 /// Reads the region lockout info in the SMDH and send it to CFG service 69 /// Reads the region lockout info in the SMDH and send it to CFG service
223 void ParseRegionLockoutInfo(); 70 void ParseRegionLockoutInfo();
224 71
225 bool is_exefs_loaded = false; 72 FileSys::NCCHContainer base_ncch;
226 bool is_compressed = false; 73 FileSys::NCCHContainer update_ncch;
227 74 FileSys::NCCHContainer* overlay_ncch;
228 u32 entry_point = 0;
229 u32 code_size = 0;
230 u32 stack_size = 0;
231 u32 bss_size = 0;
232 u32 core_version = 0;
233 u8 priority = 0;
234 u8 resource_limit_category = 0;
235 u32 ncch_offset = 0; // Offset to NCCH header, can be 0 or after NCSD header
236 u32 exefs_offset = 0;
237
238 NCCH_Header ncch_header;
239 ExeFs_Header exefs_header;
240 ExHeader_Header exheader_header;
241 75
242 std::string filepath; 76 std::string filepath;
243}; 77};