ncch.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. // Copyright 2014 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <algorithm>
  5. #include <cinttypes>
  6. #include <codecvt>
  7. #include <cstring>
  8. #include <locale>
  9. #include <memory>
  10. #include "common/logging/log.h"
  11. #include "common/string_util.h"
  12. #include "common/swap.h"
  13. #include "core/core.h"
  14. #include "core/file_sys/archive_selfncch.h"
  15. #include "core/hle/kernel/process.h"
  16. #include "core/hle/kernel/resource_limit.h"
  17. #include "core/hle/service/cfg/cfg.h"
  18. #include "core/hle/service/fs/archive.h"
  19. #include "core/loader/ncch.h"
  20. #include "core/loader/smdh.h"
  21. #include "core/memory.h"
  22. #include "network/network.h"
  23. ////////////////////////////////////////////////////////////////////////////////////////////////////
  24. // Loader namespace
  25. namespace Loader {
  26. static const int kMaxSections = 8; ///< Maximum number of sections (files) in an ExeFs
  27. static const int kBlockSize = 0x200; ///< Size of ExeFS blocks (in bytes)
  28. /**
  29. * Get the decompressed size of an LZSS compressed ExeFS file
  30. * @param buffer Buffer of compressed file
  31. * @param size Size of compressed buffer
  32. * @return Size of decompressed buffer
  33. */
  34. static u32 LZSS_GetDecompressedSize(const u8* buffer, u32 size) {
  35. u32 offset_size = *(u32*)(buffer + size - 4);
  36. return offset_size + size;
  37. }
  38. /**
  39. * Decompress ExeFS file (compressed with LZSS)
  40. * @param compressed Compressed buffer
  41. * @param compressed_size Size of compressed buffer
  42. * @param decompressed Decompressed buffer
  43. * @param decompressed_size Size of decompressed buffer
  44. * @return True on success, otherwise false
  45. */
  46. static bool LZSS_Decompress(const u8* compressed, u32 compressed_size, u8* decompressed,
  47. u32 decompressed_size) {
  48. const u8* footer = compressed + compressed_size - 8;
  49. u32 buffer_top_and_bottom = *reinterpret_cast<const u32*>(footer);
  50. u32 out = decompressed_size;
  51. u32 index = compressed_size - ((buffer_top_and_bottom >> 24) & 0xFF);
  52. u32 stop_index = compressed_size - (buffer_top_and_bottom & 0xFFFFFF);
  53. memset(decompressed, 0, decompressed_size);
  54. memcpy(decompressed, compressed, compressed_size);
  55. while (index > stop_index) {
  56. u8 control = compressed[--index];
  57. for (unsigned i = 0; i < 8; i++) {
  58. if (index <= stop_index)
  59. break;
  60. if (index <= 0)
  61. break;
  62. if (out <= 0)
  63. break;
  64. if (control & 0x80) {
  65. // Check if compression is out of bounds
  66. if (index < 2)
  67. return false;
  68. index -= 2;
  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. // Check if compression is out of bounds
  74. if (out < segment_size)
  75. return false;
  76. for (unsigned j = 0; j < segment_size; j++) {
  77. // Check if compression is out of bounds
  78. if (out + segment_offset >= decompressed_size)
  79. return false;
  80. u8 data = decompressed[out + segment_offset];
  81. decompressed[--out] = data;
  82. }
  83. } else {
  84. // Check if compression is out of bounds
  85. if (out < 1)
  86. return false;
  87. decompressed[--out] = compressed[--index];
  88. }
  89. control <<= 1;
  90. }
  91. }
  92. return true;
  93. }
  94. ////////////////////////////////////////////////////////////////////////////////////////////////////
  95. // AppLoader_NCCH class
  96. FileType AppLoader_NCCH::IdentifyType(FileUtil::IOFile& file) {
  97. u32 magic;
  98. file.Seek(0x100, SEEK_SET);
  99. if (1 != file.ReadArray<u32>(&magic, 1))
  100. return FileType::Error;
  101. if (MakeMagic('N', 'C', 'S', 'D') == magic)
  102. return FileType::CCI;
  103. if (MakeMagic('N', 'C', 'C', 'H') == magic)
  104. return FileType::CXI;
  105. return FileType::Error;
  106. }
  107. std::pair<boost::optional<u32>, ResultStatus> AppLoader_NCCH::LoadKernelSystemMode() {
  108. if (!is_loaded) {
  109. ResultStatus res = LoadExeFS();
  110. if (res != ResultStatus::Success) {
  111. return std::make_pair(boost::none, res);
  112. }
  113. }
  114. // Set the system mode as the one from the exheader.
  115. return std::make_pair(exheader_header.arm11_system_local_caps.system_mode.Value(),
  116. ResultStatus::Success);
  117. }
  118. ResultStatus AppLoader_NCCH::LoadExec() {
  119. using Kernel::SharedPtr;
  120. using Kernel::CodeSet;
  121. if (!is_loaded)
  122. return ResultStatus::ErrorNotLoaded;
  123. std::vector<u8> code;
  124. if (ResultStatus::Success == ReadCode(code)) {
  125. std::string process_name = Common::StringFromFixedZeroTerminatedBuffer(
  126. (const char*)exheader_header.codeset_info.name, 8);
  127. SharedPtr<CodeSet> codeset = CodeSet::Create(process_name, ncch_header.program_id);
  128. codeset->code.offset = 0;
  129. codeset->code.addr = exheader_header.codeset_info.text.address;
  130. codeset->code.size = exheader_header.codeset_info.text.num_max_pages * Memory::PAGE_SIZE;
  131. codeset->rodata.offset = codeset->code.offset + codeset->code.size;
  132. codeset->rodata.addr = exheader_header.codeset_info.ro.address;
  133. codeset->rodata.size = exheader_header.codeset_info.ro.num_max_pages * Memory::PAGE_SIZE;
  134. // TODO(yuriks): Not sure if the bss size is added to the page-aligned .data size or just
  135. // to the regular size. Playing it safe for now.
  136. u32 bss_page_size = (exheader_header.codeset_info.bss_size + 0xFFF) & ~0xFFF;
  137. code.resize(code.size() + bss_page_size, 0);
  138. codeset->data.offset = codeset->rodata.offset + codeset->rodata.size;
  139. codeset->data.addr = exheader_header.codeset_info.data.address;
  140. codeset->data.size =
  141. exheader_header.codeset_info.data.num_max_pages * Memory::PAGE_SIZE + bss_page_size;
  142. codeset->entrypoint = codeset->code.addr;
  143. codeset->memory = std::make_shared<std::vector<u8>>(std::move(code));
  144. Kernel::g_current_process = Kernel::Process::Create(std::move(codeset));
  145. Memory::current_page_table = &Kernel::g_current_process->vm_manager.page_table;
  146. // Attach a resource limit to the process based on the resource limit category
  147. Kernel::g_current_process->resource_limit =
  148. Kernel::ResourceLimit::GetForCategory(static_cast<Kernel::ResourceLimitCategory>(
  149. exheader_header.arm11_system_local_caps.resource_limit_category));
  150. // Set the default CPU core for this process
  151. Kernel::g_current_process->ideal_processor =
  152. exheader_header.arm11_system_local_caps.ideal_processor;
  153. // Copy data while converting endianness
  154. std::array<u32, ARRAY_SIZE(exheader_header.arm11_kernel_caps.descriptors)> kernel_caps;
  155. std::copy_n(exheader_header.arm11_kernel_caps.descriptors, kernel_caps.size(),
  156. begin(kernel_caps));
  157. Kernel::g_current_process->ParseKernelCaps(kernel_caps.data(), kernel_caps.size());
  158. s32 priority = exheader_header.arm11_system_local_caps.priority;
  159. u32 stack_size = exheader_header.codeset_info.stack_size;
  160. Kernel::g_current_process->Run(priority, stack_size);
  161. return ResultStatus::Success;
  162. }
  163. return ResultStatus::Error;
  164. }
  165. ResultStatus AppLoader_NCCH::LoadSectionExeFS(const char* name, std::vector<u8>& buffer) {
  166. if (!file.IsOpen())
  167. return ResultStatus::Error;
  168. ResultStatus result = LoadExeFS();
  169. if (result != ResultStatus::Success)
  170. return result;
  171. LOG_DEBUG(Loader, "%d sections:", kMaxSections);
  172. // Iterate through the ExeFs archive until we find a section with the specified name...
  173. for (unsigned section_number = 0; section_number < kMaxSections; section_number++) {
  174. const auto& section = exefs_header.section[section_number];
  175. // Load the specified section...
  176. if (strcmp(section.name, name) == 0) {
  177. LOG_DEBUG(Loader, "%d - offset: 0x%08X, size: 0x%08X, name: %s", section_number,
  178. section.offset, section.size, section.name);
  179. s64 section_offset =
  180. (section.offset + exefs_offset + sizeof(ExeFs_Header) + ncch_offset);
  181. file.Seek(section_offset, SEEK_SET);
  182. if (strcmp(section.name, ".code") == 0 && is_compressed) {
  183. // Section is compressed, read compressed .code section...
  184. std::unique_ptr<u8[]> temp_buffer;
  185. try {
  186. temp_buffer.reset(new u8[section.size]);
  187. } catch (std::bad_alloc&) {
  188. return ResultStatus::ErrorMemoryAllocationFailed;
  189. }
  190. if (file.ReadBytes(&temp_buffer[0], section.size) != section.size)
  191. return ResultStatus::Error;
  192. // Decompress .code section...
  193. u32 decompressed_size = LZSS_GetDecompressedSize(&temp_buffer[0], section.size);
  194. buffer.resize(decompressed_size);
  195. if (!LZSS_Decompress(&temp_buffer[0], section.size, &buffer[0], decompressed_size))
  196. return ResultStatus::ErrorInvalidFormat;
  197. } else {
  198. // Section is uncompressed...
  199. buffer.resize(section.size);
  200. if (file.ReadBytes(&buffer[0], section.size) != section.size)
  201. return ResultStatus::Error;
  202. }
  203. return ResultStatus::Success;
  204. }
  205. }
  206. return ResultStatus::ErrorNotUsed;
  207. }
  208. ResultStatus AppLoader_NCCH::LoadExeFS() {
  209. if (is_exefs_loaded)
  210. return ResultStatus::Success;
  211. if (!file.IsOpen())
  212. return ResultStatus::Error;
  213. // Reset read pointer in case this file has been read before.
  214. file.Seek(0, SEEK_SET);
  215. if (file.ReadBytes(&ncch_header, sizeof(NCCH_Header)) != sizeof(NCCH_Header))
  216. return ResultStatus::Error;
  217. // Skip NCSD header and load first NCCH (NCSD is just a container of NCCH files)...
  218. if (MakeMagic('N', 'C', 'S', 'D') == ncch_header.magic) {
  219. LOG_DEBUG(Loader, "Only loading the first (bootable) NCCH within the NCSD file!");
  220. ncch_offset = 0x4000;
  221. file.Seek(ncch_offset, SEEK_SET);
  222. file.ReadBytes(&ncch_header, sizeof(NCCH_Header));
  223. }
  224. // Verify we are loading the correct file type...
  225. if (MakeMagic('N', 'C', 'C', 'H') != ncch_header.magic)
  226. return ResultStatus::ErrorInvalidFormat;
  227. // Read ExHeader...
  228. if (file.ReadBytes(&exheader_header, sizeof(ExHeader_Header)) != sizeof(ExHeader_Header))
  229. return ResultStatus::Error;
  230. is_compressed = (exheader_header.codeset_info.flags.flag & 1) == 1;
  231. entry_point = exheader_header.codeset_info.text.address;
  232. code_size = exheader_header.codeset_info.text.code_size;
  233. stack_size = exheader_header.codeset_info.stack_size;
  234. bss_size = exheader_header.codeset_info.bss_size;
  235. core_version = exheader_header.arm11_system_local_caps.core_version;
  236. priority = exheader_header.arm11_system_local_caps.priority;
  237. resource_limit_category = exheader_header.arm11_system_local_caps.resource_limit_category;
  238. LOG_DEBUG(Loader, "Name: %s", exheader_header.codeset_info.name);
  239. LOG_DEBUG(Loader, "Program ID: %016" PRIX64, ncch_header.program_id);
  240. LOG_DEBUG(Loader, "Code compressed: %s", is_compressed ? "yes" : "no");
  241. LOG_DEBUG(Loader, "Entry point: 0x%08X", entry_point);
  242. LOG_DEBUG(Loader, "Code size: 0x%08X", code_size);
  243. LOG_DEBUG(Loader, "Stack size: 0x%08X", stack_size);
  244. LOG_DEBUG(Loader, "Bss size: 0x%08X", bss_size);
  245. LOG_DEBUG(Loader, "Core version: %d", core_version);
  246. LOG_DEBUG(Loader, "Thread priority: 0x%X", priority);
  247. LOG_DEBUG(Loader, "Resource limit category: %d", resource_limit_category);
  248. LOG_DEBUG(Loader, "System Mode: %d",
  249. static_cast<int>(exheader_header.arm11_system_local_caps.system_mode));
  250. if (exheader_header.arm11_system_local_caps.program_id != ncch_header.program_id) {
  251. LOG_ERROR(Loader, "ExHeader Program ID mismatch: the ROM is probably encrypted.");
  252. return ResultStatus::ErrorEncrypted;
  253. }
  254. // Read ExeFS...
  255. exefs_offset = ncch_header.exefs_offset * kBlockSize;
  256. u32 exefs_size = ncch_header.exefs_size * kBlockSize;
  257. LOG_DEBUG(Loader, "ExeFS offset: 0x%08X", exefs_offset);
  258. LOG_DEBUG(Loader, "ExeFS size: 0x%08X", exefs_size);
  259. file.Seek(exefs_offset + ncch_offset, SEEK_SET);
  260. if (file.ReadBytes(&exefs_header, sizeof(ExeFs_Header)) != sizeof(ExeFs_Header))
  261. return ResultStatus::Error;
  262. is_exefs_loaded = true;
  263. return ResultStatus::Success;
  264. }
  265. void AppLoader_NCCH::ParseRegionLockoutInfo() {
  266. std::vector<u8> smdh_buffer;
  267. if (ReadIcon(smdh_buffer) == ResultStatus::Success && smdh_buffer.size() >= sizeof(SMDH)) {
  268. SMDH smdh;
  269. memcpy(&smdh, smdh_buffer.data(), sizeof(SMDH));
  270. u32 region_lockout = smdh.region_lockout;
  271. constexpr u32 REGION_COUNT = 7;
  272. for (u32 region = 0; region < REGION_COUNT; ++region) {
  273. if (region_lockout & 1) {
  274. Service::CFG::SetPreferredRegionCode(region);
  275. break;
  276. }
  277. region_lockout >>= 1;
  278. }
  279. }
  280. }
  281. ResultStatus AppLoader_NCCH::Load() {
  282. if (is_loaded)
  283. return ResultStatus::ErrorAlreadyLoaded;
  284. ResultStatus result = LoadExeFS();
  285. if (result != ResultStatus::Success)
  286. return result;
  287. std::string program_id{Common::StringFromFormat("%016" PRIX64, ncch_header.program_id)};
  288. LOG_INFO(Loader, "Program ID: %s", program_id.c_str());
  289. Core::Telemetry().AddField(Telemetry::FieldType::Session, "ProgramId", program_id);
  290. if (auto room_member = Network::GetRoomMember().lock()) {
  291. Network::GameInfo game_info;
  292. ReadTitle(game_info.name);
  293. game_info.id = ncch_header.program_id;
  294. room_member->SendGameInfo(game_info);
  295. }
  296. is_loaded = true; // Set state to loaded
  297. result = LoadExec(); // Load the executable into memory for booting
  298. if (ResultStatus::Success != result)
  299. return result;
  300. Service::FS::RegisterArchiveType(std::make_unique<FileSys::ArchiveFactory_SelfNCCH>(*this),
  301. Service::FS::ArchiveIdCode::SelfNCCH);
  302. ParseRegionLockoutInfo();
  303. return ResultStatus::Success;
  304. }
  305. ResultStatus AppLoader_NCCH::ReadCode(std::vector<u8>& buffer) {
  306. return LoadSectionExeFS(".code", buffer);
  307. }
  308. ResultStatus AppLoader_NCCH::ReadIcon(std::vector<u8>& buffer) {
  309. return LoadSectionExeFS("icon", buffer);
  310. }
  311. ResultStatus AppLoader_NCCH::ReadBanner(std::vector<u8>& buffer) {
  312. return LoadSectionExeFS("banner", buffer);
  313. }
  314. ResultStatus AppLoader_NCCH::ReadLogo(std::vector<u8>& buffer) {
  315. return LoadSectionExeFS("logo", buffer);
  316. }
  317. ResultStatus AppLoader_NCCH::ReadProgramId(u64& out_program_id) {
  318. if (!file.IsOpen())
  319. return ResultStatus::Error;
  320. ResultStatus result = LoadExeFS();
  321. if (result != ResultStatus::Success)
  322. return result;
  323. out_program_id = ncch_header.program_id;
  324. return ResultStatus::Success;
  325. }
  326. ResultStatus AppLoader_NCCH::ReadRomFS(std::shared_ptr<FileUtil::IOFile>& romfs_file, u64& offset,
  327. u64& size) {
  328. if (!file.IsOpen())
  329. return ResultStatus::Error;
  330. // Check if the NCCH has a RomFS...
  331. if (ncch_header.romfs_offset != 0 && ncch_header.romfs_size != 0) {
  332. u32 romfs_offset = ncch_offset + (ncch_header.romfs_offset * kBlockSize) + 0x1000;
  333. u32 romfs_size = (ncch_header.romfs_size * kBlockSize) - 0x1000;
  334. LOG_DEBUG(Loader, "RomFS offset: 0x%08X", romfs_offset);
  335. LOG_DEBUG(Loader, "RomFS size: 0x%08X", romfs_size);
  336. if (file.GetSize() < romfs_offset + romfs_size)
  337. return ResultStatus::Error;
  338. // We reopen the file, to allow its position to be independent from file's
  339. romfs_file = std::make_shared<FileUtil::IOFile>(filepath, "rb");
  340. if (!romfs_file->IsOpen())
  341. return ResultStatus::Error;
  342. offset = romfs_offset;
  343. size = romfs_size;
  344. return ResultStatus::Success;
  345. }
  346. LOG_DEBUG(Loader, "NCCH has no RomFS");
  347. return ResultStatus::ErrorNotUsed;
  348. }
  349. ResultStatus AppLoader_NCCH::ReadTitle(std::string& title) {
  350. std::vector<u8> data;
  351. Loader::SMDH smdh;
  352. ReadIcon(data);
  353. if (!Loader::IsValidSMDH(data)) {
  354. return ResultStatus::ErrorInvalidFormat;
  355. }
  356. memcpy(&smdh, data.data(), sizeof(Loader::SMDH));
  357. const auto& short_title = smdh.GetShortTitle(SMDH::TitleLanguage::English);
  358. auto title_end = std::find(short_title.begin(), short_title.end(), u'\0');
  359. title = Common::UTF16ToUTF8(std::u16string{short_title.begin(), title_end});
  360. return ResultStatus::Success;
  361. }
  362. } // namespace Loader