ncch.cpp 13 KB

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