ncch.cpp 14 KB

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