3dsx.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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_romfs.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::SharedPtr;
  82. using Kernel::CodeSet;
  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 =
  154. static_cast<u32>(reinterpret_cast<u8*>(pos) - program_image.data());
  155. u32 addr = TranslateAddr(*pos, &loadinfo, offsets);
  156. LOG_TRACE(Loader, "Patching %08X <-- rel(%08X,%d) (%08X)",
  157. base_addr + in_addr, addr, current_segment_reloc_table, *pos);
  158. switch (current_segment_reloc_table) {
  159. case 0:
  160. *pos = (addr);
  161. break;
  162. case 1:
  163. *pos = static_cast<u32>(addr - in_addr);
  164. break;
  165. default:
  166. break; // this should never happen
  167. }
  168. pos++;
  169. num_patches--;
  170. }
  171. }
  172. }
  173. }
  174. }
  175. // Create the CodeSet
  176. SharedPtr<CodeSet> code_set = CodeSet::Create("", 0);
  177. code_set->code.offset = loadinfo.seg_ptrs[0] - program_image.data();
  178. code_set->code.addr = loadinfo.seg_addrs[0];
  179. code_set->code.size = loadinfo.seg_sizes[0];
  180. code_set->rodata.offset = loadinfo.seg_ptrs[1] - program_image.data();
  181. code_set->rodata.addr = loadinfo.seg_addrs[1];
  182. code_set->rodata.size = loadinfo.seg_sizes[1];
  183. code_set->data.offset = loadinfo.seg_ptrs[2] - program_image.data();
  184. code_set->data.addr = loadinfo.seg_addrs[2];
  185. code_set->data.size = loadinfo.seg_sizes[2];
  186. code_set->entrypoint = code_set->code.addr;
  187. code_set->memory = std::make_shared<std::vector<u8>>(std::move(program_image));
  188. LOG_DEBUG(Loader, "code size: 0x%X", loadinfo.seg_sizes[0]);
  189. LOG_DEBUG(Loader, "rodata size: 0x%X", loadinfo.seg_sizes[1]);
  190. LOG_DEBUG(Loader, "data size: 0x%X (including 0x%X of bss)", loadinfo.seg_sizes[2],
  191. hdr.bss_size);
  192. *out_codeset = code_set;
  193. return ERROR_NONE;
  194. }
  195. FileType AppLoader_THREEDSX::IdentifyType(FileUtil::IOFile& file) {
  196. u32 magic;
  197. file.Seek(0, SEEK_SET);
  198. if (1 != file.ReadArray<u32>(&magic, 1))
  199. return FileType::Error;
  200. if (MakeMagic('3', 'D', 'S', 'X') == magic)
  201. return FileType::THREEDSX;
  202. return FileType::Error;
  203. }
  204. ResultStatus AppLoader_THREEDSX::Load() {
  205. if (is_loaded)
  206. return ResultStatus::ErrorAlreadyLoaded;
  207. if (!file.IsOpen())
  208. return ResultStatus::Error;
  209. SharedPtr<CodeSet> codeset;
  210. if (Load3DSXFile(file, Memory::PROCESS_IMAGE_VADDR, &codeset) != ERROR_NONE)
  211. return ResultStatus::Error;
  212. codeset->name = filename;
  213. Kernel::g_current_process = Kernel::Process::Create(std::move(codeset));
  214. Kernel::g_current_process->svc_access_mask.set();
  215. Kernel::g_current_process->address_mappings = default_address_mappings;
  216. // Attach the default resource limit (APPLICATION) to the process
  217. Kernel::g_current_process->resource_limit =
  218. Kernel::ResourceLimit::GetForCategory(Kernel::ResourceLimitCategory::APPLICATION);
  219. Kernel::g_current_process->Run(48, Kernel::DEFAULT_STACK_SIZE);
  220. Service::FS::RegisterArchiveType(std::make_unique<FileSys::ArchiveFactory_RomFS>(*this),
  221. Service::FS::ArchiveIdCode::RomFS);
  222. is_loaded = true;
  223. return ResultStatus::Success;
  224. }
  225. ResultStatus AppLoader_THREEDSX::ReadRomFS(std::shared_ptr<FileUtil::IOFile>& romfs_file,
  226. u64& offset, u64& size) {
  227. if (!file.IsOpen())
  228. return ResultStatus::Error;
  229. // Reset read pointer in case this file has been read before.
  230. file.Seek(0, SEEK_SET);
  231. THREEDSX_Header hdr;
  232. if (file.ReadBytes(&hdr, sizeof(THREEDSX_Header)) != sizeof(THREEDSX_Header))
  233. return ResultStatus::Error;
  234. if (hdr.header_size != sizeof(THREEDSX_Header))
  235. return ResultStatus::Error;
  236. // Check if the 3DSX has a RomFS...
  237. if (hdr.fs_offset != 0) {
  238. u32 romfs_offset = hdr.fs_offset;
  239. u32 romfs_size = static_cast<u32>(file.GetSize()) - hdr.fs_offset;
  240. LOG_DEBUG(Loader, "RomFS offset: 0x%08X", romfs_offset);
  241. LOG_DEBUG(Loader, "RomFS size: 0x%08X", romfs_size);
  242. // We reopen the file, to allow its position to be independent from file's
  243. romfs_file = std::make_shared<FileUtil::IOFile>(filepath, "rb");
  244. if (!romfs_file->IsOpen())
  245. return ResultStatus::Error;
  246. offset = romfs_offset;
  247. size = romfs_size;
  248. return ResultStatus::Success;
  249. }
  250. LOG_DEBUG(Loader, "3DSX has no RomFS");
  251. return ResultStatus::ErrorNotUsed;
  252. }
  253. ResultStatus AppLoader_THREEDSX::ReadIcon(std::vector<u8>& buffer) {
  254. if (!file.IsOpen())
  255. return ResultStatus::Error;
  256. // Reset read pointer in case this file has been read before.
  257. file.Seek(0, SEEK_SET);
  258. THREEDSX_Header hdr;
  259. if (file.ReadBytes(&hdr, sizeof(THREEDSX_Header)) != sizeof(THREEDSX_Header))
  260. return ResultStatus::Error;
  261. if (hdr.header_size != sizeof(THREEDSX_Header))
  262. return ResultStatus::Error;
  263. // Check if the 3DSX has a SMDH...
  264. if (hdr.smdh_offset != 0) {
  265. file.Seek(hdr.smdh_offset, SEEK_SET);
  266. buffer.resize(hdr.smdh_size);
  267. if (file.ReadBytes(&buffer[0], hdr.smdh_size) != hdr.smdh_size)
  268. return ResultStatus::Error;
  269. return ResultStatus::Success;
  270. }
  271. return ResultStatus::ErrorNotUsed;
  272. }
  273. } // namespace Loader