summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-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/hle/service/nwm/nwm_uds.cpp275
-rw-r--r--src/core/hle/service/nwm/uds_connection.cpp9
-rw-r--r--src/core/hle/service/nwm/uds_connection.h5
-rw-r--r--src/core/hle/service/nwm/uds_data.cpp21
-rw-r--r--src/core/hle/service/nwm/uds_data.h28
-rw-r--r--src/core/hle/service/sm/sm.cpp4
-rw-r--r--src/core/hle/service/sm/sm.h3
-rw-r--r--src/core/hle/service/sm/srv.cpp26
-rw-r--r--src/core/hle/service/sm/srv.h1
-rw-r--r--src/core/loader/loader.h13
-rw-r--r--src/core/loader/ncch.cpp319
-rw-r--r--src/core/loader/ncch.h184
-rw-r--r--src/video_core/pica_types.h18
18 files changed, 960 insertions, 539 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/hle/service/nwm/nwm_uds.cpp b/src/core/hle/service/nwm/nwm_uds.cpp
index 893bbb1e7..4e2af9ae6 100644
--- a/src/core/hle/service/nwm/nwm_uds.cpp
+++ b/src/core/hle/service/nwm/nwm_uds.cpp
@@ -2,8 +2,10 @@
2// Licensed under GPLv2 or any later version 2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included. 3// Refer to the license.txt file included.
4 4
5#include <algorithm>
5#include <array> 6#include <array>
6#include <cstring> 7#include <cstring>
8#include <list>
7#include <mutex> 9#include <mutex>
8#include <unordered_map> 10#include <unordered_map>
9#include <vector> 11#include <vector>
@@ -37,9 +39,12 @@ static ConnectionStatus connection_status{};
37/* Node information about the current network. 39/* Node information about the current network.
38 * The amount of elements in this vector is always the maximum number 40 * The amount of elements in this vector is always the maximum number
39 * of nodes specified in the network configuration. 41 * of nodes specified in the network configuration.
40 * The first node is always the host, so this always contains at least 1 entry. 42 * The first node is always the host.
41 */ 43 */
42static NodeList node_info(1); 44static NodeList node_info;
45
46// Node information about our own system.
47static NodeInfo current_node;
43 48
44// Mapping of bind node ids to their respective events. 49// Mapping of bind node ids to their respective events.
45static std::unordered_map<u32, Kernel::SharedPtr<Kernel::Event>> bind_node_events; 50static std::unordered_map<u32, Kernel::SharedPtr<Kernel::Event>> bind_node_events;
@@ -54,6 +59,10 @@ static NetworkInfo network_info;
54// Event that will generate and send the 802.11 beacon frames. 59// Event that will generate and send the 802.11 beacon frames.
55static int beacon_broadcast_event; 60static int beacon_broadcast_event;
56 61
62// Mutex to synchronize access to the connection status between the emulation thread and the
63// network thread.
64static std::mutex connection_status_mutex;
65
57// Mutex to synchronize access to the list of received beacons between the emulation thread and the 66// Mutex to synchronize access to the list of received beacons between the emulation thread and the
58// network thread. 67// network thread.
59static std::mutex beacon_mutex; 68static std::mutex beacon_mutex;
@@ -63,14 +72,26 @@ static std::mutex beacon_mutex;
63constexpr size_t MaxBeaconFrames = 15; 72constexpr size_t MaxBeaconFrames = 15;
64 73
65// List of the last <MaxBeaconFrames> beacons received from the network. 74// List of the last <MaxBeaconFrames> beacons received from the network.
66static std::deque<Network::WifiPacket> received_beacons; 75static std::list<Network::WifiPacket> received_beacons;
67 76
68/** 77/**
69 * Returns a list of received 802.11 beacon frames from the specified sender since the last call. 78 * Returns a list of received 802.11 beacon frames from the specified sender since the last call.
70 */ 79 */
71std::deque<Network::WifiPacket> GetReceivedBeacons(const MacAddress& sender) { 80std::list<Network::WifiPacket> GetReceivedBeacons(const MacAddress& sender) {
72 std::lock_guard<std::mutex> lock(beacon_mutex); 81 std::lock_guard<std::mutex> lock(beacon_mutex);
73 // TODO(Subv): Filter by sender. 82 if (sender != Network::BroadcastMac) {
83 std::list<Network::WifiPacket> filtered_list;
84 const auto beacon = std::find_if(received_beacons.begin(), received_beacons.end(),
85 [&sender](const Network::WifiPacket& packet) {
86 return packet.transmitter_address == sender;
87 });
88 if (beacon != received_beacons.end()) {
89 filtered_list.push_back(*beacon);
90 // TODO(B3N30): Check if the complete deque is cleared or just the fetched entries
91 received_beacons.erase(beacon);
92 }
93 return filtered_list;
94 }
74 return std::move(received_beacons); 95 return std::move(received_beacons);
75} 96}
76 97
@@ -83,6 +104,15 @@ void SendPacket(Network::WifiPacket& packet) {
83// limit is exceeded. 104// limit is exceeded.
84void HandleBeaconFrame(const Network::WifiPacket& packet) { 105void HandleBeaconFrame(const Network::WifiPacket& packet) {
85 std::lock_guard<std::mutex> lock(beacon_mutex); 106 std::lock_guard<std::mutex> lock(beacon_mutex);
107 const auto unique_beacon =
108 std::find_if(received_beacons.begin(), received_beacons.end(),
109 [&packet](const Network::WifiPacket& new_packet) {
110 return new_packet.transmitter_address == packet.transmitter_address;
111 });
112 if (unique_beacon != received_beacons.end()) {
113 // We already have a beacon from the same mac in the deque, remove the old one;
114 received_beacons.erase(unique_beacon);
115 }
86 116
87 received_beacons.emplace_back(packet); 117 received_beacons.emplace_back(packet);
88 118
@@ -91,14 +121,33 @@ void HandleBeaconFrame(const Network::WifiPacket& packet) {
91 received_beacons.pop_front(); 121 received_beacons.pop_front();
92} 122}
93 123
124void HandleAssociationResponseFrame(const Network::WifiPacket& packet) {
125 auto assoc_result = GetAssociationResult(packet.data);
126
127 ASSERT_MSG(std::get<AssocStatus>(assoc_result) == AssocStatus::Successful,
128 "Could not join network");
129 {
130 std::lock_guard<std::mutex> lock(connection_status_mutex);
131 ASSERT(connection_status.status == static_cast<u32>(NetworkStatus::Connecting));
132 }
133
134 // Send the EAPoL-Start packet to the server.
135 using Network::WifiPacket;
136 WifiPacket eapol_start;
137 eapol_start.channel = network_channel;
138 eapol_start.data = GenerateEAPoLStartFrame(std::get<u16>(assoc_result), current_node);
139 // TODO(B3N30): Encrypt the packet.
140 eapol_start.destination_address = packet.transmitter_address;
141 eapol_start.type = WifiPacket::PacketType::Data;
142
143 SendPacket(eapol_start);
144}
145
94/* 146/*
95 * Returns an available index in the nodes array for the 147 * Returns an available index in the nodes array for the
96 * currently-hosted UDS network. 148 * currently-hosted UDS network.
97 */ 149 */
98static u16 GetNextAvailableNodeId() { 150static u16 GetNextAvailableNodeId() {
99 ASSERT_MSG(connection_status.status == static_cast<u32>(NetworkStatus::ConnectedAsHost),
100 "Can not accept clients if we're not hosting a network");
101
102 for (u16 index = 0; index < connection_status.max_nodes; ++index) { 151 for (u16 index = 0; index < connection_status.max_nodes; ++index) {
103 if ((connection_status.node_bitmask & (1 << index)) == 0) 152 if ((connection_status.node_bitmask & (1 << index)) == 0)
104 return index; 153 return index;
@@ -113,35 +162,46 @@ static u16 GetNextAvailableNodeId() {
113 * authentication frame with SEQ1. 162 * authentication frame with SEQ1.
114 */ 163 */
115void StartConnectionSequence(const MacAddress& server) { 164void StartConnectionSequence(const MacAddress& server) {
116 ASSERT(connection_status.status == static_cast<u32>(NetworkStatus::NotConnected));
117
118 // TODO(Subv): Handle timeout.
119
120 // Send an authentication frame with SEQ1
121 using Network::WifiPacket; 165 using Network::WifiPacket;
122 WifiPacket auth_request; 166 WifiPacket auth_request;
123 auth_request.channel = network_channel; 167 {
124 auth_request.data = GenerateAuthenticationFrame(AuthenticationSeq::SEQ1); 168 std::lock_guard<std::mutex> lock(connection_status_mutex);
125 auth_request.destination_address = server; 169 ASSERT(connection_status.status == static_cast<u32>(NetworkStatus::NotConnected));
126 auth_request.type = WifiPacket::PacketType::Authentication; 170
171 // TODO(Subv): Handle timeout.
172
173 // Send an authentication frame with SEQ1
174 auth_request.channel = network_channel;
175 auth_request.data = GenerateAuthenticationFrame(AuthenticationSeq::SEQ1);
176 auth_request.destination_address = server;
177 auth_request.type = WifiPacket::PacketType::Authentication;
178 }
127 179
128 SendPacket(auth_request); 180 SendPacket(auth_request);
129} 181}
130 182
131/// Sends an Association Response frame to the specified mac address 183/// Sends an Association Response frame to the specified mac address
132void SendAssociationResponseFrame(const MacAddress& address) { 184void SendAssociationResponseFrame(const MacAddress& address) {
133 ASSERT_MSG(connection_status.status == static_cast<u32>(NetworkStatus::ConnectedAsHost));
134
135 using Network::WifiPacket; 185 using Network::WifiPacket;
136 WifiPacket assoc_response; 186 WifiPacket assoc_response;
137 assoc_response.channel = network_channel; 187
138 // TODO(Subv): This will cause multiple clients to end up with the same association id, but 188 {
139 // we're not using that for anything. 189 std::lock_guard<std::mutex> lock(connection_status_mutex);
140 u16 association_id = 1; 190 if (connection_status.status != static_cast<u32>(NetworkStatus::ConnectedAsHost)) {
141 assoc_response.data = GenerateAssocResponseFrame(AssocStatus::Successful, association_id, 191 LOG_ERROR(Service_NWM, "Connection sequence aborted, because connection status is %u",
142 network_info.network_id); 192 connection_status.status);
143 assoc_response.destination_address = address; 193 return;
144 assoc_response.type = WifiPacket::PacketType::AssociationResponse; 194 }
195
196 assoc_response.channel = network_channel;
197 // TODO(Subv): This will cause multiple clients to end up with the same association id, but
198 // we're not using that for anything.
199 u16 association_id = 1;
200 assoc_response.data = GenerateAssocResponseFrame(AssocStatus::Successful, association_id,
201 network_info.network_id);
202 assoc_response.destination_address = address;
203 assoc_response.type = WifiPacket::PacketType::AssociationResponse;
204 }
145 205
146 SendPacket(assoc_response); 206 SendPacket(assoc_response);
147} 207}
@@ -155,16 +215,23 @@ void SendAssociationResponseFrame(const MacAddress& address) {
155void HandleAuthenticationFrame(const Network::WifiPacket& packet) { 215void HandleAuthenticationFrame(const Network::WifiPacket& packet) {
156 // Only the SEQ1 auth frame is handled here, the SEQ2 frame doesn't need any special behavior 216 // Only the SEQ1 auth frame is handled here, the SEQ2 frame doesn't need any special behavior
157 if (GetAuthenticationSeqNumber(packet.data) == AuthenticationSeq::SEQ1) { 217 if (GetAuthenticationSeqNumber(packet.data) == AuthenticationSeq::SEQ1) {
158 ASSERT_MSG(connection_status.status == static_cast<u32>(NetworkStatus::ConnectedAsHost));
159
160 // Respond with an authentication response frame with SEQ2
161 using Network::WifiPacket; 218 using Network::WifiPacket;
162 WifiPacket auth_request; 219 WifiPacket auth_request;
163 auth_request.channel = network_channel; 220 {
164 auth_request.data = GenerateAuthenticationFrame(AuthenticationSeq::SEQ2); 221 std::lock_guard<std::mutex> lock(connection_status_mutex);
165 auth_request.destination_address = packet.transmitter_address; 222 if (connection_status.status != static_cast<u32>(NetworkStatus::ConnectedAsHost)) {
166 auth_request.type = WifiPacket::PacketType::Authentication; 223 LOG_ERROR(Service_NWM,
167 224 "Connection sequence aborted, because connection status is %u",
225 connection_status.status);
226 return;
227 }
228
229 // Respond with an authentication response frame with SEQ2
230 auth_request.channel = network_channel;
231 auth_request.data = GenerateAuthenticationFrame(AuthenticationSeq::SEQ2);
232 auth_request.destination_address = packet.transmitter_address;
233 auth_request.type = WifiPacket::PacketType::Authentication;
234 }
168 SendPacket(auth_request); 235 SendPacket(auth_request);
169 236
170 SendAssociationResponseFrame(packet.transmitter_address); 237 SendAssociationResponseFrame(packet.transmitter_address);
@@ -180,6 +247,9 @@ void OnWifiPacketReceived(const Network::WifiPacket& packet) {
180 case Network::WifiPacket::PacketType::Authentication: 247 case Network::WifiPacket::PacketType::Authentication:
181 HandleAuthenticationFrame(packet); 248 HandleAuthenticationFrame(packet);
182 break; 249 break;
250 case Network::WifiPacket::PacketType::AssociationResponse:
251 HandleAssociationResponseFrame(packet);
252 break;
183 } 253 }
184} 254}
185 255
@@ -305,7 +375,7 @@ static void InitializeWithVersion(Interface* self) {
305 u32 sharedmem_size = rp.Pop<u32>(); 375 u32 sharedmem_size = rp.Pop<u32>();
306 376
307 // Update the node information with the data the game gave us. 377 // Update the node information with the data the game gave us.
308 rp.PopRaw(node_info[0]); 378 rp.PopRaw(current_node);
309 379
310 u16 version = rp.Pop<u16>(); 380 u16 version = rp.Pop<u16>();
311 381
@@ -315,10 +385,14 @@ static void InitializeWithVersion(Interface* self) {
315 385
316 ASSERT_MSG(recv_buffer_memory->size == sharedmem_size, "Invalid shared memory size."); 386 ASSERT_MSG(recv_buffer_memory->size == sharedmem_size, "Invalid shared memory size.");
317 387
318 // Reset the connection status, it contains all zeros after initialization, 388 {
319 // except for the actual status value. 389 std::lock_guard<std::mutex> lock(connection_status_mutex);
320 connection_status = {}; 390
321 connection_status.status = static_cast<u32>(NetworkStatus::NotConnected); 391 // Reset the connection status, it contains all zeros after initialization,
392 // except for the actual status value.
393 connection_status = {};
394 connection_status.status = static_cast<u32>(NetworkStatus::NotConnected);
395 }
322 396
323 IPC::RequestBuilder rb = rp.MakeBuilder(1, 2); 397 IPC::RequestBuilder rb = rp.MakeBuilder(1, 2);
324 rb.Push(RESULT_SUCCESS); 398 rb.Push(RESULT_SUCCESS);
@@ -348,12 +422,16 @@ static void GetConnectionStatus(Interface* self) {
348 IPC::RequestBuilder rb = rp.MakeBuilder(13, 0); 422 IPC::RequestBuilder rb = rp.MakeBuilder(13, 0);
349 423
350 rb.Push(RESULT_SUCCESS); 424 rb.Push(RESULT_SUCCESS);
351 rb.PushRaw(connection_status); 425 {
352 426 std::lock_guard<std::mutex> lock(connection_status_mutex);
353 // Reset the bitmask of changed nodes after each call to this 427 rb.PushRaw(connection_status);
354 // function to prevent falsely informing games of outstanding 428
355 // changes in subsequent calls. 429 // Reset the bitmask of changed nodes after each call to this
356 connection_status.changed_nodes = 0; 430 // function to prevent falsely informing games of outstanding
431 // changes in subsequent calls.
432 // TODO(Subv): Find exactly where the NWM module resets this value.
433 connection_status.changed_nodes = 0;
434 }
357 435
358 LOG_DEBUG(Service_NWM, "called"); 436 LOG_DEBUG(Service_NWM, "called");
359} 437}
@@ -434,31 +512,36 @@ static void BeginHostingNetwork(Interface* self) {
434 // The real UDS module throws a fatal error if this assert fails. 512 // The real UDS module throws a fatal error if this assert fails.
435 ASSERT_MSG(network_info.max_nodes > 1, "Trying to host a network of only one member."); 513 ASSERT_MSG(network_info.max_nodes > 1, "Trying to host a network of only one member.");
436 514
437 connection_status.status = static_cast<u32>(NetworkStatus::ConnectedAsHost); 515 {
438 516 std::lock_guard<std::mutex> lock(connection_status_mutex);
439 // Ensure the application data size is less than the maximum value. 517 connection_status.status = static_cast<u32>(NetworkStatus::ConnectedAsHost);
440 ASSERT_MSG(network_info.application_data_size <= ApplicationDataSize, "Data size is too big."); 518
441 519 // Ensure the application data size is less than the maximum value.
442 // Set up basic information for this network. 520 ASSERT_MSG(network_info.application_data_size <= ApplicationDataSize,
443 network_info.oui_value = NintendoOUI; 521 "Data size is too big.");
444 network_info.oui_type = static_cast<u8>(NintendoTagId::NetworkInfo); 522
445 523 // Set up basic information for this network.
446 connection_status.max_nodes = network_info.max_nodes; 524 network_info.oui_value = NintendoOUI;
447 525 network_info.oui_type = static_cast<u8>(NintendoTagId::NetworkInfo);
448 // Resize the nodes list to hold max_nodes. 526
449 node_info.resize(network_info.max_nodes); 527 connection_status.max_nodes = network_info.max_nodes;
450 528
451 // There's currently only one node in the network (the host). 529 // Resize the nodes list to hold max_nodes.
452 connection_status.total_nodes = 1; 530 node_info.resize(network_info.max_nodes);
453 network_info.total_nodes = 1; 531
454 // The host is always the first node 532 // There's currently only one node in the network (the host).
455 connection_status.network_node_id = 1; 533 connection_status.total_nodes = 1;
456 node_info[0].network_node_id = 1; 534 network_info.total_nodes = 1;
457 connection_status.nodes[0] = connection_status.network_node_id; 535 // The host is always the first node
458 // Set the bit 0 in the nodes bitmask to indicate that node 1 is already taken. 536 connection_status.network_node_id = 1;
459 connection_status.node_bitmask |= 1; 537 current_node.network_node_id = 1;
460 // Notify the application that the first node was set. 538 connection_status.nodes[0] = connection_status.network_node_id;
461 connection_status.changed_nodes |= 1; 539 // Set the bit 0 in the nodes bitmask to indicate that node 1 is already taken.
540 connection_status.node_bitmask |= 1;
541 // Notify the application that the first node was set.
542 connection_status.changed_nodes |= 1;
543 node_info[0] = current_node;
544 }
462 545
463 // If the game has a preferred channel, use that instead. 546 // If the game has a preferred channel, use that instead.
464 if (network_info.channel != 0) 547 if (network_info.channel != 0)
@@ -495,9 +578,13 @@ static void DestroyNetwork(Interface* self) {
495 // Unschedule the beacon broadcast event. 578 // Unschedule the beacon broadcast event.
496 CoreTiming::UnscheduleEvent(beacon_broadcast_event, 0); 579 CoreTiming::UnscheduleEvent(beacon_broadcast_event, 0);
497 580
498 // TODO(Subv): Check if connection_status is indeed reset after this call. 581 {
499 connection_status = {}; 582 std::lock_guard<std::mutex> lock(connection_status_mutex);
500 connection_status.status = static_cast<u8>(NetworkStatus::NotConnected); 583
584 // TODO(Subv): Check if connection_status is indeed reset after this call.
585 connection_status = {};
586 connection_status.status = static_cast<u8>(NetworkStatus::NotConnected);
587 }
501 connection_status_event->Signal(); 588 connection_status_event->Signal();
502 589
503 IPC::RequestBuilder rb = rp.MakeBuilder(1, 0); 590 IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
@@ -540,17 +627,24 @@ static void SendTo(Interface* self) {
540 627
541 IPC::RequestBuilder rb = rp.MakeBuilder(1, 0); 628 IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
542 629
543 if (connection_status.status != static_cast<u32>(NetworkStatus::ConnectedAsClient) && 630 u16 network_node_id;
544 connection_status.status != static_cast<u32>(NetworkStatus::ConnectedAsHost)) {
545 rb.Push(ResultCode(ErrorDescription::NotAuthorized, ErrorModule::UDS,
546 ErrorSummary::InvalidState, ErrorLevel::Status));
547 return;
548 }
549 631
550 if (dest_node_id == connection_status.network_node_id) { 632 {
551 rb.Push(ResultCode(ErrorDescription::NotFound, ErrorModule::UDS, 633 std::lock_guard<std::mutex> lock(connection_status_mutex);
552 ErrorSummary::WrongArgument, ErrorLevel::Status)); 634 if (connection_status.status != static_cast<u32>(NetworkStatus::ConnectedAsClient) &&
553 return; 635 connection_status.status != static_cast<u32>(NetworkStatus::ConnectedAsHost)) {
636 rb.Push(ResultCode(ErrorDescription::NotAuthorized, ErrorModule::UDS,
637 ErrorSummary::InvalidState, ErrorLevel::Status));
638 return;
639 }
640
641 if (dest_node_id == connection_status.network_node_id) {
642 rb.Push(ResultCode(ErrorDescription::NotFound, ErrorModule::UDS,
643 ErrorSummary::WrongArgument, ErrorLevel::Status));
644 return;
645 }
646
647 network_node_id = connection_status.network_node_id;
554 } 648 }
555 649
556 // TODO(Subv): Do something with the flags. 650 // TODO(Subv): Do something with the flags.
@@ -567,8 +661,8 @@ static void SendTo(Interface* self) {
567 661
568 // TODO(Subv): Increment the sequence number after each sent packet. 662 // TODO(Subv): Increment the sequence number after each sent packet.
569 u16 sequence_number = 0; 663 u16 sequence_number = 0;
570 std::vector<u8> data_payload = GenerateDataPayload( 664 std::vector<u8> data_payload =
571 data, data_channel, dest_node_id, connection_status.network_node_id, sequence_number); 665 GenerateDataPayload(data, data_channel, dest_node_id, network_node_id, sequence_number);
572 666
573 // TODO(Subv): Retrieve the MAC address of the dest_node_id and our own to encrypt 667 // TODO(Subv): Retrieve the MAC address of the dest_node_id and our own to encrypt
574 // and encapsulate the payload. 668 // and encapsulate the payload.
@@ -595,6 +689,7 @@ static void GetChannel(Interface* self) {
595 IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x1A, 0, 0); 689 IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x1A, 0, 0);
596 IPC::RequestBuilder rb = rp.MakeBuilder(2, 0); 690 IPC::RequestBuilder rb = rp.MakeBuilder(2, 0);
597 691
692 std::lock_guard<std::mutex> lock(connection_status_mutex);
598 bool is_connected = connection_status.status != static_cast<u32>(NetworkStatus::NotConnected); 693 bool is_connected = connection_status.status != static_cast<u32>(NetworkStatus::NotConnected);
599 694
600 u8 channel = is_connected ? network_channel : 0; 695 u8 channel = is_connected ? network_channel : 0;
@@ -766,6 +861,7 @@ static void BeaconBroadcastCallback(u64 userdata, int cycles_late) {
766 * @param network_node_id Network Node Id of the connecting client. 861 * @param network_node_id Network Node Id of the connecting client.
767 */ 862 */
768void OnClientConnected(u16 network_node_id) { 863void OnClientConnected(u16 network_node_id) {
864 std::lock_guard<std::mutex> lock(connection_status_mutex);
769 ASSERT_MSG(connection_status.status == static_cast<u32>(NetworkStatus::ConnectedAsHost), 865 ASSERT_MSG(connection_status.status == static_cast<u32>(NetworkStatus::ConnectedAsHost),
770 "Can not accept clients if we're not hosting a network"); 866 "Can not accept clients if we're not hosting a network");
771 ASSERT_MSG(connection_status.total_nodes < connection_status.max_nodes, 867 ASSERT_MSG(connection_status.total_nodes < connection_status.max_nodes,
@@ -827,8 +923,11 @@ NWM_UDS::~NWM_UDS() {
827 connection_status_event = nullptr; 923 connection_status_event = nullptr;
828 recv_buffer_memory = nullptr; 924 recv_buffer_memory = nullptr;
829 925
830 connection_status = {}; 926 {
831 connection_status.status = static_cast<u32>(NetworkStatus::NotConnected); 927 std::lock_guard<std::mutex> lock(connection_status_mutex);
928 connection_status = {};
929 connection_status.status = static_cast<u32>(NetworkStatus::NotConnected);
930 }
832 931
833 CoreTiming::UnscheduleEvent(beacon_broadcast_event, 0); 932 CoreTiming::UnscheduleEvent(beacon_broadcast_event, 0);
834} 933}
diff --git a/src/core/hle/service/nwm/uds_connection.cpp b/src/core/hle/service/nwm/uds_connection.cpp
index c8a76ec2a..c74f51253 100644
--- a/src/core/hle/service/nwm/uds_connection.cpp
+++ b/src/core/hle/service/nwm/uds_connection.cpp
@@ -75,5 +75,14 @@ std::vector<u8> GenerateAssocResponseFrame(AssocStatus status, u16 association_i
75 return data; 75 return data;
76} 76}
77 77
78std::tuple<AssocStatus, u16> GetAssociationResult(const std::vector<u8>& body) {
79 AssociationResponseFrame frame;
80 memcpy(&frame, body.data(), sizeof(frame));
81
82 constexpr u16 AssociationIdMask = 0x3FFF;
83 return std::make_tuple(static_cast<AssocStatus>(frame.status_code),
84 frame.assoc_id & AssociationIdMask);
85}
86
78} // namespace NWM 87} // namespace NWM
79} // namespace Service 88} // namespace Service
diff --git a/src/core/hle/service/nwm/uds_connection.h b/src/core/hle/service/nwm/uds_connection.h
index 73f55a4fd..a664f8471 100644
--- a/src/core/hle/service/nwm/uds_connection.h
+++ b/src/core/hle/service/nwm/uds_connection.h
@@ -4,6 +4,7 @@
4 4
5#pragma once 5#pragma once
6 6
7#include <tuple>
7#include <vector> 8#include <vector>
8#include "common/common_types.h" 9#include "common/common_types.h"
9#include "common/swap.h" 10#include "common/swap.h"
@@ -47,5 +48,9 @@ AuthenticationSeq GetAuthenticationSeqNumber(const std::vector<u8>& body);
47/// network id, starting at the frame body. 48/// network id, starting at the frame body.
48std::vector<u8> GenerateAssocResponseFrame(AssocStatus status, u16 association_id, u32 network_id); 49std::vector<u8> GenerateAssocResponseFrame(AssocStatus status, u16 association_id, u32 network_id);
49 50
51/// Returns a tuple of (association status, association id) from the body of an AssociationResponse
52/// frame.
53std::tuple<AssocStatus, u16> GetAssociationResult(const std::vector<u8>& body);
54
50} // namespace NWM 55} // namespace NWM
51} // namespace Service 56} // namespace Service
diff --git a/src/core/hle/service/nwm/uds_data.cpp b/src/core/hle/service/nwm/uds_data.cpp
index 8c6742dba..0fd9b8b8c 100644
--- a/src/core/hle/service/nwm/uds_data.cpp
+++ b/src/core/hle/service/nwm/uds_data.cpp
@@ -274,5 +274,26 @@ std::vector<u8> GenerateDataPayload(const std::vector<u8>& data, u8 channel, u16
274 return buffer; 274 return buffer;
275} 275}
276 276
277std::vector<u8> GenerateEAPoLStartFrame(u16 association_id, const NodeInfo& node_info) {
278 EAPoLStartPacket eapol_start{};
279 eapol_start.association_id = association_id;
280 eapol_start.friend_code_seed = node_info.friend_code_seed;
281
282 for (int i = 0; i < node_info.username.size(); ++i)
283 eapol_start.username[i] = node_info.username[i];
284
285 // Note: The network_node_id and unknown bytes seem to be uninitialized in the NWM module.
286 // TODO(B3N30): The last 8 bytes seem to have a fixed value of 07 88 15 00 04 e9 13 00 in
287 // EAPoL-Start packets from different 3DSs to the same host during a Super Smash Bros. 4 game.
288 // Find out what that means.
289
290 std::vector<u8> eapol_buffer(sizeof(EAPoLStartPacket));
291 std::memcpy(eapol_buffer.data(), &eapol_start, sizeof(eapol_start));
292
293 std::vector<u8> buffer = GenerateLLCHeader(EtherType::EAPoL);
294 buffer.insert(buffer.end(), eapol_buffer.begin(), eapol_buffer.end());
295 return buffer;
296}
297
277} // namespace NWM 298} // namespace NWM
278} // namespace Service 299} // namespace Service
diff --git a/src/core/hle/service/nwm/uds_data.h b/src/core/hle/service/nwm/uds_data.h
index a23520a41..76e8f546b 100644
--- a/src/core/hle/service/nwm/uds_data.h
+++ b/src/core/hle/service/nwm/uds_data.h
@@ -67,6 +67,27 @@ struct DataFrameCryptoCTR {
67 67
68static_assert(sizeof(DataFrameCryptoCTR) == 16, "DataFrameCryptoCTR has the wrong size"); 68static_assert(sizeof(DataFrameCryptoCTR) == 16, "DataFrameCryptoCTR has the wrong size");
69 69
70constexpr u16 EAPoLStartMagic = 0x201;
71
72/*
73 * Nintendo EAPoLStartPacket, is used to initaliaze a connection between client and host
74 */
75struct EAPoLStartPacket {
76 u16_be magic = EAPoLStartMagic;
77 u16_be association_id;
78 // This value is hardcoded to 1 in the NWM module.
79 u16_be unknown = 1;
80 INSERT_PADDING_BYTES(2);
81
82 u64_be friend_code_seed;
83 std::array<u16_be, 10> username;
84 INSERT_PADDING_BYTES(4);
85 u16_be network_node_id;
86 INSERT_PADDING_BYTES(6);
87};
88
89static_assert(sizeof(EAPoLStartPacket) == 0x30, "EAPoLStartPacket has the wrong size");
90
70/** 91/**
71 * Generates an unencrypted 802.11 data payload. 92 * Generates an unencrypted 802.11 data payload.
72 * @returns The generated frame payload. 93 * @returns The generated frame payload.
@@ -74,5 +95,12 @@ static_assert(sizeof(DataFrameCryptoCTR) == 16, "DataFrameCryptoCTR has the wron
74std::vector<u8> GenerateDataPayload(const std::vector<u8>& data, u8 channel, u16 dest_node, 95std::vector<u8> GenerateDataPayload(const std::vector<u8>& data, u8 channel, u16 dest_node,
75 u16 src_node, u16 sequence_number); 96 u16 src_node, u16 sequence_number);
76 97
98/*
99 * Generates an unencrypted 802.11 data frame body with the EAPoL-Start format for UDS
100 * communication.
101 * @returns The generated frame body.
102 */
103std::vector<u8> GenerateEAPoLStartFrame(u16 association_id, const NodeInfo& node_info);
104
77} // namespace NWM 105} // namespace NWM
78} // namespace Service 106} // namespace Service
diff --git a/src/core/hle/service/sm/sm.cpp b/src/core/hle/service/sm/sm.cpp
index 5e7fc68f9..854ab9a05 100644
--- a/src/core/hle/service/sm/sm.cpp
+++ b/src/core/hle/service/sm/sm.cpp
@@ -36,6 +36,10 @@ ResultVal<Kernel::SharedPtr<Kernel::ServerPort>> ServiceManager::RegisterService
36 std::string name, unsigned int max_sessions) { 36 std::string name, unsigned int max_sessions) {
37 37
38 CASCADE_CODE(ValidateServiceName(name)); 38 CASCADE_CODE(ValidateServiceName(name));
39
40 if (registered_services.find(name) != registered_services.end())
41 return ERR_ALREADY_REGISTERED;
42
39 Kernel::SharedPtr<Kernel::ServerPort> server_port; 43 Kernel::SharedPtr<Kernel::ServerPort> server_port;
40 Kernel::SharedPtr<Kernel::ClientPort> client_port; 44 Kernel::SharedPtr<Kernel::ClientPort> client_port;
41 std::tie(server_port, client_port) = Kernel::ServerPort::CreatePortPair(max_sessions, name); 45 std::tie(server_port, client_port) = Kernel::ServerPort::CreatePortPair(max_sessions, name);
diff --git a/src/core/hle/service/sm/sm.h b/src/core/hle/service/sm/sm.h
index 8f0dbf2db..9f60a7965 100644
--- a/src/core/hle/service/sm/sm.h
+++ b/src/core/hle/service/sm/sm.h
@@ -32,6 +32,9 @@ constexpr ResultCode ERR_ACCESS_DENIED(6, ErrorModule::SRV, ErrorSummary::Invali
32 ErrorLevel::Permanent); // 0xD8E06406 32 ErrorLevel::Permanent); // 0xD8E06406
33constexpr ResultCode ERR_NAME_CONTAINS_NUL(7, ErrorModule::SRV, ErrorSummary::WrongArgument, 33constexpr ResultCode ERR_NAME_CONTAINS_NUL(7, ErrorModule::SRV, ErrorSummary::WrongArgument,
34 ErrorLevel::Permanent); // 0xD9006407 34 ErrorLevel::Permanent); // 0xD9006407
35constexpr ResultCode ERR_ALREADY_REGISTERED(ErrorDescription::AlreadyExists, ErrorModule::OS,
36 ErrorSummary::WrongArgument,
37 ErrorLevel::Permanent); // 0xD9001BFC
35 38
36class ServiceManager { 39class ServiceManager {
37public: 40public:
diff --git a/src/core/hle/service/sm/srv.cpp b/src/core/hle/service/sm/srv.cpp
index 352941e69..5c955cf54 100644
--- a/src/core/hle/service/sm/srv.cpp
+++ b/src/core/hle/service/sm/srv.cpp
@@ -13,6 +13,7 @@
13#include "core/hle/kernel/errors.h" 13#include "core/hle/kernel/errors.h"
14#include "core/hle/kernel/hle_ipc.h" 14#include "core/hle/kernel/hle_ipc.h"
15#include "core/hle/kernel/semaphore.h" 15#include "core/hle/kernel/semaphore.h"
16#include "core/hle/kernel/server_port.h"
16#include "core/hle/kernel/server_session.h" 17#include "core/hle/kernel/server_session.h"
17#include "core/hle/service/sm/sm.h" 18#include "core/hle/service/sm/sm.h"
18#include "core/hle/service/sm/srv.h" 19#include "core/hle/service/sm/srv.h"
@@ -184,12 +185,35 @@ void SRV::PublishToSubscriber(Kernel::HLERequestContext& ctx) {
184 flags); 185 flags);
185} 186}
186 187
188void SRV::RegisterService(Kernel::HLERequestContext& ctx) {
189 IPC::RequestParser rp(ctx, 0x3, 4, 0);
190
191 auto name_buf = rp.PopRaw<std::array<char, 8>>();
192 size_t name_len = rp.Pop<u32>();
193 u32 max_sessions = rp.Pop<u32>();
194
195 std::string name(name_buf.data(), std::min(name_len, name_buf.size()));
196
197 auto port = service_manager->RegisterService(name, max_sessions);
198
199 if (port.Failed()) {
200 IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
201 rb.Push(port.Code());
202 LOG_ERROR(Service_SRV, "called service=%s -> error 0x%08X", name.c_str(), port.Code().raw);
203 return;
204 }
205
206 IPC::RequestBuilder rb = rp.MakeBuilder(1, 2);
207 rb.Push(RESULT_SUCCESS);
208 rb.PushObjects(port.Unwrap());
209}
210
187SRV::SRV(std::shared_ptr<ServiceManager> service_manager) 211SRV::SRV(std::shared_ptr<ServiceManager> service_manager)
188 : ServiceFramework("srv:", 4), service_manager(std::move(service_manager)) { 212 : ServiceFramework("srv:", 4), service_manager(std::move(service_manager)) {
189 static const FunctionInfo functions[] = { 213 static const FunctionInfo functions[] = {
190 {0x00010002, &SRV::RegisterClient, "RegisterClient"}, 214 {0x00010002, &SRV::RegisterClient, "RegisterClient"},
191 {0x00020000, &SRV::EnableNotification, "EnableNotification"}, 215 {0x00020000, &SRV::EnableNotification, "EnableNotification"},
192 {0x00030100, nullptr, "RegisterService"}, 216 {0x00030100, &SRV::RegisterService, "RegisterService"},
193 {0x000400C0, nullptr, "UnregisterService"}, 217 {0x000400C0, nullptr, "UnregisterService"},
194 {0x00050100, &SRV::GetServiceHandle, "GetServiceHandle"}, 218 {0x00050100, &SRV::GetServiceHandle, "GetServiceHandle"},
195 {0x000600C2, nullptr, "RegisterPort"}, 219 {0x000600C2, nullptr, "RegisterPort"},
diff --git a/src/core/hle/service/sm/srv.h b/src/core/hle/service/sm/srv.h
index 75cca5184..aad839563 100644
--- a/src/core/hle/service/sm/srv.h
+++ b/src/core/hle/service/sm/srv.h
@@ -28,6 +28,7 @@ private:
28 void Subscribe(Kernel::HLERequestContext& ctx); 28 void Subscribe(Kernel::HLERequestContext& ctx);
29 void Unsubscribe(Kernel::HLERequestContext& ctx); 29 void Unsubscribe(Kernel::HLERequestContext& ctx);
30 void PublishToSubscriber(Kernel::HLERequestContext& ctx); 30 void PublishToSubscriber(Kernel::HLERequestContext& ctx);
31 void RegisterService(Kernel::HLERequestContext& ctx);
31 32
32 std::shared_ptr<ServiceManager> service_manager; 33 std::shared_ptr<ServiceManager> service_manager;
33 Kernel::SharedPtr<Kernel::Semaphore> notification_semaphore; 34 Kernel::SharedPtr<Kernel::Semaphore> notification_semaphore;
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};
diff --git a/src/video_core/pica_types.h b/src/video_core/pica_types.h
index 5d7e10066..2eafa7e9e 100644
--- a/src/video_core/pica_types.h
+++ b/src/video_core/pica_types.h
@@ -58,11 +58,12 @@ public:
58 } 58 }
59 59
60 Float<M, E> operator*(const Float<M, E>& flt) const { 60 Float<M, E> operator*(const Float<M, E>& flt) const {
61 if ((this->value == 0.f && !std::isnan(flt.value)) || 61 float result = value * flt.ToFloat32();
62 (flt.value == 0.f && !std::isnan(this->value))) 62 // PICA gives 0 instead of NaN when multiplying by inf
63 // PICA gives 0 instead of NaN when multiplying by inf 63 if (!std::isnan(value) && !std::isnan(flt.ToFloat32()))
64 return Zero(); 64 if (std::isnan(result))
65 return Float<M, E>::FromFloat32(ToFloat32() * flt.ToFloat32()); 65 result = 0.f;
66 return Float<M, E>::FromFloat32(result);
66 } 67 }
67 68
68 Float<M, E> operator/(const Float<M, E>& flt) const { 69 Float<M, E> operator/(const Float<M, E>& flt) const {
@@ -78,12 +79,7 @@ public:
78 } 79 }
79 80
80 Float<M, E>& operator*=(const Float<M, E>& flt) { 81 Float<M, E>& operator*=(const Float<M, E>& flt) {
81 if ((this->value == 0.f && !std::isnan(flt.value)) || 82 value = operator*(flt).value;
82 (flt.value == 0.f && !std::isnan(this->value)))
83 // PICA gives 0 instead of NaN when multiplying by inf
84 *this = Zero();
85 else
86 value *= flt.ToFloat32();
87 return *this; 83 return *this;
88 } 84 }
89 85