3dsx.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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 <vector>
  6. #include "common/logging/log.h"
  7. #include "core/file_sys/archive_selfncch.h"
  8. #include "core/hle/kernel/process.h"
  9. #include "core/hle/kernel/resource_limit.h"
  10. #include "core/hle/service/fs/archive.h"
  11. #include "core/loader/3dsx.h"
  12. #include "core/memory.h"
  13. namespace Loader {
  14. /*
  15. * File layout:
  16. * - File header
  17. * - Code, rodata and data relocation table headers
  18. * - Code segment
  19. * - Rodata segment
  20. * - Loadable (non-BSS) part of the data segment
  21. * - Code relocation table
  22. * - Rodata relocation table
  23. * - Data relocation table
  24. *
  25. * Memory layout before relocations are applied:
  26. * [0..codeSegSize) -> code segment
  27. * [codeSegSize..rodataSegSize) -> rodata segment
  28. * [rodataSegSize..dataSegSize) -> data segment
  29. *
  30. * Memory layout after relocations are applied: well, however the loader sets it up :)
  31. * The entrypoint is always the start of the code segment.
  32. * The BSS section must be cleared manually by the application.
  33. */
  34. enum THREEDSX_Error { ERROR_NONE = 0, ERROR_READ = 1, ERROR_FILE = 2, ERROR_ALLOC = 3 };
  35. static const u32 RELOCBUFSIZE = 512;
  36. static const unsigned int NUM_SEGMENTS = 3;
  37. // File header
  38. #pragma pack(1)
  39. struct THREEDSX_Header {
  40. u32 magic;
  41. u16 header_size, reloc_hdr_size;
  42. u32 format_ver;
  43. u32 flags;
  44. // Sizes of the code, rodata and data segments +
  45. // size of the BSS section (uninitialized latter half of the data segment)
  46. u32 code_seg_size, rodata_seg_size, data_seg_size, bss_size;
  47. // offset and size of smdh
  48. u32 smdh_offset, smdh_size;
  49. // offset to filesystem
  50. u32 fs_offset;
  51. };
  52. // Relocation header: all fields (even extra unknown fields) are guaranteed to be relocation counts.
  53. struct THREEDSX_RelocHdr {
  54. // # of absolute relocations (that is, fix address to post-relocation memory layout)
  55. u32 cross_segment_absolute;
  56. // # of cross-segment relative relocations (that is, 32bit signed offsets that need to be
  57. // patched)
  58. u32 cross_segment_relative;
  59. // more?
  60. // Relocations are written in this order:
  61. // - Absolute relocations
  62. // - Relative relocations
  63. };
  64. // Relocation entry: from the current pointer, skip X words and patch Y words
  65. struct THREEDSX_Reloc {
  66. u16 skip, patch;
  67. };
  68. #pragma pack()
  69. struct THREEloadinfo {
  70. u8* seg_ptrs[3]; // code, rodata & data
  71. u32 seg_addrs[3];
  72. u32 seg_sizes[3];
  73. };
  74. static u32 TranslateAddr(u32 addr, const THREEloadinfo* loadinfo, u32* offsets) {
  75. if (addr < offsets[0])
  76. return loadinfo->seg_addrs[0] + addr;
  77. if (addr < offsets[1])
  78. return loadinfo->seg_addrs[1] + addr - offsets[0];
  79. return loadinfo->seg_addrs[2] + addr - offsets[1];
  80. }
  81. using Kernel::CodeSet;
  82. using Kernel::SharedPtr;
  83. static THREEDSX_Error Load3DSXFile(FileUtil::IOFile& file, u32 base_addr,
  84. SharedPtr<CodeSet>* out_codeset) {
  85. if (!file.IsOpen())
  86. return ERROR_FILE;
  87. // Reset read pointer in case this file has been read before.
  88. file.Seek(0, SEEK_SET);
  89. THREEDSX_Header hdr;
  90. if (file.ReadBytes(&hdr, sizeof(hdr)) != sizeof(hdr))
  91. return ERROR_READ;
  92. THREEloadinfo loadinfo;
  93. // loadinfo segments must be a multiple of 0x1000
  94. loadinfo.seg_sizes[0] = (hdr.code_seg_size + 0xFFF) & ~0xFFF;
  95. loadinfo.seg_sizes[1] = (hdr.rodata_seg_size + 0xFFF) & ~0xFFF;
  96. loadinfo.seg_sizes[2] = (hdr.data_seg_size + 0xFFF) & ~0xFFF;
  97. u32 offsets[2] = {loadinfo.seg_sizes[0], loadinfo.seg_sizes[0] + loadinfo.seg_sizes[1]};
  98. u32 n_reloc_tables = hdr.reloc_hdr_size / sizeof(u32);
  99. std::vector<u8> program_image(loadinfo.seg_sizes[0] + loadinfo.seg_sizes[1] +
  100. loadinfo.seg_sizes[2]);
  101. loadinfo.seg_addrs[0] = base_addr;
  102. loadinfo.seg_addrs[1] = loadinfo.seg_addrs[0] + loadinfo.seg_sizes[0];
  103. loadinfo.seg_addrs[2] = loadinfo.seg_addrs[1] + loadinfo.seg_sizes[1];
  104. loadinfo.seg_ptrs[0] = program_image.data();
  105. loadinfo.seg_ptrs[1] = loadinfo.seg_ptrs[0] + loadinfo.seg_sizes[0];
  106. loadinfo.seg_ptrs[2] = loadinfo.seg_ptrs[1] + loadinfo.seg_sizes[1];
  107. // Skip header for future compatibility
  108. file.Seek(hdr.header_size, SEEK_SET);
  109. // Read the relocation headers
  110. std::vector<u32> relocs(n_reloc_tables * NUM_SEGMENTS);
  111. for (unsigned int current_segment = 0; current_segment < NUM_SEGMENTS; ++current_segment) {
  112. size_t size = n_reloc_tables * sizeof(u32);
  113. if (file.ReadBytes(&relocs[current_segment * n_reloc_tables], size) != size)
  114. return ERROR_READ;
  115. }
  116. // Read the segments
  117. if (file.ReadBytes(loadinfo.seg_ptrs[0], hdr.code_seg_size) != hdr.code_seg_size)
  118. return ERROR_READ;
  119. if (file.ReadBytes(loadinfo.seg_ptrs[1], hdr.rodata_seg_size) != hdr.rodata_seg_size)
  120. return ERROR_READ;
  121. if (file.ReadBytes(loadinfo.seg_ptrs[2], hdr.data_seg_size - hdr.bss_size) !=
  122. hdr.data_seg_size - hdr.bss_size)
  123. return ERROR_READ;
  124. // BSS clear
  125. memset((char*)loadinfo.seg_ptrs[2] + hdr.data_seg_size - hdr.bss_size, 0, hdr.bss_size);
  126. // Relocate the segments
  127. for (unsigned int current_segment = 0; current_segment < NUM_SEGMENTS; ++current_segment) {
  128. for (unsigned current_segment_reloc_table = 0; current_segment_reloc_table < n_reloc_tables;
  129. current_segment_reloc_table++) {
  130. u32 n_relocs = relocs[current_segment * n_reloc_tables + current_segment_reloc_table];
  131. if (current_segment_reloc_table >= 2) {
  132. // We are not using this table - ignore it because we don't know what it dose
  133. file.Seek(n_relocs * sizeof(THREEDSX_Reloc), SEEK_CUR);
  134. continue;
  135. }
  136. THREEDSX_Reloc reloc_table[RELOCBUFSIZE];
  137. u32* pos = (u32*)loadinfo.seg_ptrs[current_segment];
  138. const u32* end_pos = pos + (loadinfo.seg_sizes[current_segment] / 4);
  139. while (n_relocs) {
  140. u32 remaining = std::min(RELOCBUFSIZE, n_relocs);
  141. n_relocs -= remaining;
  142. if (file.ReadBytes(reloc_table, remaining * sizeof(THREEDSX_Reloc)) !=
  143. remaining * sizeof(THREEDSX_Reloc))
  144. return ERROR_READ;
  145. for (unsigned current_inprogress = 0;
  146. current_inprogress < remaining && pos < end_pos; current_inprogress++) {
  147. const auto& table = reloc_table[current_inprogress];
  148. LOG_TRACE(Loader, "(t=%d,skip=%u,patch=%u)", current_segment_reloc_table,
  149. static_cast<u32>(table.skip), static_cast<u32>(table.patch));
  150. pos += table.skip;
  151. s32 num_patches = table.patch;
  152. while (0 < num_patches && pos < end_pos) {
  153. u32 in_addr = base_addr + static_cast<u32>(reinterpret_cast<u8*>(pos) -
  154. program_image.data());
  155. u32 orig_data = *pos;
  156. u32 sub_type = orig_data >> (32 - 4);
  157. u32 addr = TranslateAddr(orig_data & ~0xF0000000, &loadinfo, offsets);
  158. LOG_TRACE(Loader, "Patching %08X <-- rel(%08X,%d) (%08X)", in_addr, addr,
  159. current_segment_reloc_table, *pos);
  160. switch (current_segment_reloc_table) {
  161. case 0: {
  162. if (sub_type != 0)
  163. return ERROR_READ;
  164. *pos = addr;
  165. break;
  166. }
  167. case 1: {
  168. u32 data = addr - in_addr;
  169. switch (sub_type) {
  170. case 0: // 32-bit signed offset
  171. *pos = data;
  172. break;
  173. case 1: // 31-bit signed offset
  174. *pos = data & ~(1U << 31);
  175. break;
  176. default:
  177. return ERROR_READ;
  178. }
  179. break;
  180. }
  181. default:
  182. break; // this should never happen
  183. }
  184. pos++;
  185. num_patches--;
  186. }
  187. }
  188. }
  189. }
  190. }
  191. // Create the CodeSet
  192. SharedPtr<CodeSet> code_set = CodeSet::Create("", 0);
  193. code_set->code.offset = loadinfo.seg_ptrs[0] - program_image.data();
  194. code_set->code.addr = loadinfo.seg_addrs[0];
  195. code_set->code.size = loadinfo.seg_sizes[0];
  196. code_set->rodata.offset = loadinfo.seg_ptrs[1] - program_image.data();
  197. code_set->rodata.addr = loadinfo.seg_addrs[1];
  198. code_set->rodata.size = loadinfo.seg_sizes[1];
  199. code_set->data.offset = loadinfo.seg_ptrs[2] - program_image.data();
  200. code_set->data.addr = loadinfo.seg_addrs[2];
  201. code_set->data.size = loadinfo.seg_sizes[2];
  202. code_set->entrypoint = code_set->code.addr;
  203. code_set->memory = std::make_shared<std::vector<u8>>(std::move(program_image));
  204. LOG_DEBUG(Loader, "code size: 0x%X", loadinfo.seg_sizes[0]);
  205. LOG_DEBUG(Loader, "rodata size: 0x%X", loadinfo.seg_sizes[1]);
  206. LOG_DEBUG(Loader, "data size: 0x%X (including 0x%X of bss)", loadinfo.seg_sizes[2],
  207. hdr.bss_size);
  208. *out_codeset = code_set;
  209. return ERROR_NONE;
  210. }
  211. FileType AppLoader_THREEDSX::IdentifyType(FileUtil::IOFile& file) {
  212. u32 magic;
  213. file.Seek(0, SEEK_SET);
  214. if (1 != file.ReadArray<u32>(&magic, 1))
  215. return FileType::Error;
  216. if (MakeMagic('3', 'D', 'S', 'X') == magic)
  217. return FileType::THREEDSX;
  218. return FileType::Error;
  219. }
  220. ResultStatus AppLoader_THREEDSX::Load(Kernel::SharedPtr<Kernel::Process>& process) {
  221. if (is_loaded)
  222. return ResultStatus::ErrorAlreadyLoaded;
  223. if (!file.IsOpen())
  224. return ResultStatus::Error;
  225. SharedPtr<CodeSet> codeset;
  226. if (Load3DSXFile(file, Memory::PROCESS_IMAGE_VADDR, &codeset) != ERROR_NONE)
  227. return ResultStatus::Error;
  228. codeset->name = filename;
  229. process = Kernel::Process::Create("main");
  230. process->LoadModule(codeset, codeset->entrypoint);
  231. process->svc_access_mask.set();
  232. process->address_mappings = default_address_mappings;
  233. // Attach the default resource limit (APPLICATION) to the process
  234. process->resource_limit =
  235. Kernel::ResourceLimit::GetForCategory(Kernel::ResourceLimitCategory::APPLICATION);
  236. process->Run(codeset->entrypoint, 48, Kernel::DEFAULT_STACK_SIZE);
  237. Service::FS::RegisterSelfNCCH(*this);
  238. is_loaded = true;
  239. return ResultStatus::Success;
  240. }
  241. ResultStatus AppLoader_THREEDSX::ReadRomFS(std::shared_ptr<FileUtil::IOFile>& romfs_file,
  242. u64& offset, u64& size) {
  243. if (!file.IsOpen())
  244. return ResultStatus::Error;
  245. // Reset read pointer in case this file has been read before.
  246. file.Seek(0, SEEK_SET);
  247. THREEDSX_Header hdr;
  248. if (file.ReadBytes(&hdr, sizeof(THREEDSX_Header)) != sizeof(THREEDSX_Header))
  249. return ResultStatus::Error;
  250. if (hdr.header_size != sizeof(THREEDSX_Header))
  251. return ResultStatus::Error;
  252. // Check if the 3DSX has a RomFS...
  253. if (hdr.fs_offset != 0) {
  254. u32 romfs_offset = hdr.fs_offset;
  255. u32 romfs_size = static_cast<u32>(file.GetSize()) - hdr.fs_offset;
  256. LOG_DEBUG(Loader, "RomFS offset: 0x%08X", romfs_offset);
  257. LOG_DEBUG(Loader, "RomFS size: 0x%08X", romfs_size);
  258. // We reopen the file, to allow its position to be independent from file's
  259. romfs_file = std::make_shared<FileUtil::IOFile>(filepath, "rb");
  260. if (!romfs_file->IsOpen())
  261. return ResultStatus::Error;
  262. offset = romfs_offset;
  263. size = romfs_size;
  264. return ResultStatus::Success;
  265. }
  266. LOG_DEBUG(Loader, "3DSX has no RomFS");
  267. return ResultStatus::ErrorNotUsed;
  268. }
  269. ResultStatus AppLoader_THREEDSX::ReadIcon(std::vector<u8>& buffer) {
  270. if (!file.IsOpen())
  271. return ResultStatus::Error;
  272. // Reset read pointer in case this file has been read before.
  273. file.Seek(0, SEEK_SET);
  274. THREEDSX_Header hdr;
  275. if (file.ReadBytes(&hdr, sizeof(THREEDSX_Header)) != sizeof(THREEDSX_Header))
  276. return ResultStatus::Error;
  277. if (hdr.header_size != sizeof(THREEDSX_Header))
  278. return ResultStatus::Error;
  279. // Check if the 3DSX has a SMDH...
  280. if (hdr.smdh_offset != 0) {
  281. file.Seek(hdr.smdh_offset, SEEK_SET);
  282. buffer.resize(hdr.smdh_size);
  283. if (file.ReadBytes(&buffer[0], hdr.smdh_size) != hdr.smdh_size)
  284. return ResultStatus::Error;
  285. return ResultStatus::Success;
  286. }
  287. return ResultStatus::ErrorNotUsed;
  288. }
  289. } // namespace Loader