ncch.cpp 16 KB

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