ncch.cpp 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. // Copyright 2014 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <memory>
  5. #include "core/loader/ncch.h"
  6. #include "core/hle/kernel/kernel.h"
  7. #include "core/mem_map.h"
  8. ////////////////////////////////////////////////////////////////////////////////////////////////////
  9. // Loader namespace
  10. namespace Loader {
  11. static const int kMaxSections = 8; ///< Maximum number of sections (files) in an ExeFs
  12. static const int kBlockSize = 0x200; ///< Size of ExeFS blocks (in bytes)
  13. /**
  14. * Get the decompressed size of an LZSS compressed ExeFS file
  15. * @param buffer Buffer of compressed file
  16. * @param size Size of compressed buffer
  17. * @return Size of decompressed buffer
  18. */
  19. static u32 LZSS_GetDecompressedSize(const u8* buffer, u32 size) {
  20. u32 offset_size = *(u32*)(buffer + size - 4);
  21. return offset_size + size;
  22. }
  23. /**
  24. * Decompress ExeFS file (compressed with LZSS)
  25. * @param compressed Compressed buffer
  26. * @param compressed_size Size of compressed buffer
  27. * @param decompressed Decompressed buffer
  28. * @param decompressed_size Size of decompressed buffer
  29. * @return True on success, otherwise false
  30. */
  31. static bool LZSS_Decompress(const u8* compressed, u32 compressed_size, u8* decompressed, u32 decompressed_size) {
  32. const u8* footer = compressed + compressed_size - 8;
  33. u32 buffer_top_and_bottom = *reinterpret_cast<const u32*>(footer);
  34. u32 out = decompressed_size;
  35. u32 index = compressed_size - ((buffer_top_and_bottom >> 24) & 0xFF);
  36. u32 stop_index = compressed_size - (buffer_top_and_bottom & 0xFFFFFF);
  37. memset(decompressed, 0, decompressed_size);
  38. memcpy(decompressed, compressed, compressed_size);
  39. while (index > stop_index) {
  40. u8 control = compressed[--index];
  41. for (unsigned i = 0; i < 8; i++) {
  42. if (index <= stop_index)
  43. break;
  44. if (index <= 0)
  45. break;
  46. if (out <= 0)
  47. break;
  48. if (control & 0x80) {
  49. // Check if compression is out of bounds
  50. if (index < 2)
  51. return false;
  52. index -= 2;
  53. u32 segment_offset = compressed[index] | (compressed[index + 1] << 8);
  54. u32 segment_size = ((segment_offset >> 12) & 15) + 3;
  55. segment_offset &= 0x0FFF;
  56. segment_offset += 2;
  57. // Check if compression is out of bounds
  58. if (out < segment_size)
  59. return false;
  60. for (unsigned j = 0; j < segment_size; j++) {
  61. // Check if compression is out of bounds
  62. if (out + segment_offset >= decompressed_size)
  63. return false;
  64. u8 data = decompressed[out + segment_offset];
  65. decompressed[--out] = data;
  66. }
  67. } else {
  68. // Check if compression is out of bounds
  69. if (out < 1)
  70. return false;
  71. decompressed[--out] = compressed[--index];
  72. }
  73. control <<= 1;
  74. }
  75. }
  76. return true;
  77. }
  78. ////////////////////////////////////////////////////////////////////////////////////////////////////
  79. // AppLoader_NCCH class
  80. FileType AppLoader_NCCH::IdentifyType(FileUtil::IOFile& file) {
  81. u32 magic;
  82. file.Seek(0x100, SEEK_SET);
  83. if (1 != file.ReadArray<u32>(&magic, 1))
  84. return FileType::Error;
  85. if (MakeMagic('N', 'C', 'S', 'D') == magic)
  86. return FileType::CCI;
  87. if (MakeMagic('N', 'C', 'C', 'H') == magic)
  88. return FileType::CXI;
  89. return FileType::Error;
  90. }
  91. ResultStatus AppLoader_NCCH::LoadExec() const {
  92. if (!is_loaded)
  93. return ResultStatus::ErrorNotLoaded;
  94. std::vector<u8> code;
  95. if (ResultStatus::Success == ReadCode(code)) {
  96. Memory::WriteBlock(entry_point, &code[0], code.size());
  97. Kernel::LoadExec(entry_point);
  98. return ResultStatus::Success;
  99. }
  100. return ResultStatus::Error;
  101. }
  102. ResultStatus AppLoader_NCCH::LoadSectionExeFS(const char* name, std::vector<u8>& buffer) const {
  103. if (!file->IsOpen())
  104. return ResultStatus::Error;
  105. LOG_DEBUG(Loader, "%d sections:", kMaxSections);
  106. // Iterate through the ExeFs archive until we find the .code file...
  107. for (unsigned section_number = 0; section_number < kMaxSections; section_number++) {
  108. const auto& section = exefs_header.section[section_number];
  109. // Load the specified section...
  110. if (strcmp(section.name, name) == 0) {
  111. LOG_DEBUG(Loader, "%d - offset: 0x%08X, size: 0x%08X, name: %s", section_number,
  112. section.offset, section.size, section.name);
  113. s64 section_offset = (section.offset + exefs_offset + sizeof(ExeFs_Header) + ncch_offset);
  114. file->Seek(section_offset, SEEK_SET);
  115. if (is_compressed) {
  116. // Section is compressed, read compressed .code section...
  117. std::unique_ptr<u8[]> temp_buffer;
  118. try {
  119. temp_buffer.reset(new u8[section.size]);
  120. } catch (std::bad_alloc&) {
  121. return ResultStatus::ErrorMemoryAllocationFailed;
  122. }
  123. if (file->ReadBytes(&temp_buffer[0], section.size) != section.size)
  124. return ResultStatus::Error;
  125. // Decompress .code section...
  126. u32 decompressed_size = LZSS_GetDecompressedSize(&temp_buffer[0], section.size);
  127. buffer.resize(decompressed_size);
  128. if (!LZSS_Decompress(&temp_buffer[0], section.size, &buffer[0], decompressed_size))
  129. return ResultStatus::ErrorInvalidFormat;
  130. } else {
  131. // Section is uncompressed...
  132. buffer.resize(section.size);
  133. if (file->ReadBytes(&buffer[0], section.size) != section.size)
  134. return ResultStatus::Error;
  135. }
  136. return ResultStatus::Success;
  137. }
  138. }
  139. return ResultStatus::ErrorNotUsed;
  140. }
  141. ResultStatus AppLoader_NCCH::Load() {
  142. if (is_loaded)
  143. return ResultStatus::ErrorAlreadyLoaded;
  144. if (!file->IsOpen())
  145. return ResultStatus::Error;
  146. // Reset read pointer in case this file has been read before.
  147. file->Seek(0, SEEK_SET);
  148. if (file->ReadBytes(&ncch_header, sizeof(NCCH_Header)) != sizeof(NCCH_Header))
  149. return ResultStatus::Error;
  150. // Skip NCSD header and load first NCCH (NCSD is just a container of NCCH files)...
  151. if (MakeMagic('N', 'C', 'S', 'D') == ncch_header.magic) {
  152. LOG_WARNING(Loader, "Only loading the first (bootable) NCCH within the NCSD file!");
  153. ncch_offset = 0x4000;
  154. file->Seek(ncch_offset, SEEK_SET);
  155. file->ReadBytes(&ncch_header, sizeof(NCCH_Header));
  156. }
  157. // Verify we are loading the correct file type...
  158. if (MakeMagic('N', 'C', 'C', 'H') != ncch_header.magic)
  159. return ResultStatus::ErrorInvalidFormat;
  160. // Read ExHeader...
  161. if (file->ReadBytes(&exheader_header, sizeof(ExHeader_Header)) != sizeof(ExHeader_Header))
  162. return ResultStatus::Error;
  163. is_compressed = (exheader_header.codeset_info.flags.flag & 1) == 1;
  164. entry_point = exheader_header.codeset_info.text.address;
  165. LOG_INFO(Loader, "Name: %s", exheader_header.codeset_info.name);
  166. LOG_DEBUG(Loader, "Code compressed: %s", is_compressed ? "yes" : "no");
  167. LOG_DEBUG(Loader, "Entry point: 0x%08X", entry_point);
  168. // Read ExeFS...
  169. exefs_offset = ncch_header.exefs_offset * kBlockSize;
  170. u32 exefs_size = ncch_header.exefs_size * kBlockSize;
  171. LOG_DEBUG(Loader, "ExeFS offset: 0x%08X", exefs_offset);
  172. LOG_DEBUG(Loader, "ExeFS size: 0x%08X", exefs_size);
  173. file->Seek(exefs_offset + ncch_offset, SEEK_SET);
  174. if (file->ReadBytes(&exefs_header, sizeof(ExeFs_Header)) != sizeof(ExeFs_Header))
  175. return ResultStatus::Error;
  176. is_loaded = true; // Set state to loaded
  177. return LoadExec(); // Load the executable into memory for booting
  178. }
  179. ResultStatus AppLoader_NCCH::ReadCode(std::vector<u8>& buffer) const {
  180. return LoadSectionExeFS(".code", buffer);
  181. }
  182. ResultStatus AppLoader_NCCH::ReadIcon(std::vector<u8>& buffer) const {
  183. return LoadSectionExeFS("icon", buffer);
  184. }
  185. ResultStatus AppLoader_NCCH::ReadBanner(std::vector<u8>& buffer) const {
  186. return LoadSectionExeFS("banner", buffer);
  187. }
  188. ResultStatus AppLoader_NCCH::ReadLogo(std::vector<u8>& buffer) const {
  189. return LoadSectionExeFS("logo", buffer);
  190. }
  191. ResultStatus AppLoader_NCCH::ReadRomFS(std::vector<u8>& buffer) const {
  192. if (!file->IsOpen())
  193. return ResultStatus::Error;
  194. // Check if the NCCH has a RomFS...
  195. if (ncch_header.romfs_offset != 0 && ncch_header.romfs_size != 0) {
  196. u32 romfs_offset = ncch_offset + (ncch_header.romfs_offset * kBlockSize) + 0x1000;
  197. u32 romfs_size = (ncch_header.romfs_size * kBlockSize) - 0x1000;
  198. LOG_DEBUG(Loader, "RomFS offset: 0x%08X", romfs_offset);
  199. LOG_DEBUG(Loader, "RomFS size: 0x%08X", romfs_size);
  200. buffer.resize(romfs_size);
  201. file->Seek(romfs_offset, SEEK_SET);
  202. if (file->ReadBytes(&buffer[0], romfs_size) != romfs_size)
  203. return ResultStatus::Error;
  204. return ResultStatus::Success;
  205. }
  206. LOG_DEBUG(Loader, "NCCH has no RomFS");
  207. return ResultStatus::ErrorNotUsed;
  208. }
  209. u64 AppLoader_NCCH::GetProgramId() const {
  210. return *reinterpret_cast<u64 const*>(&ncch_header.program_id[0]);
  211. }
  212. } // namespace Loader