nso.cpp 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. // Copyright 2018 yuzu emulator team
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <cinttypes>
  5. #include <vector>
  6. #include <lz4.h>
  7. #include "common/common_funcs.h"
  8. #include "common/file_util.h"
  9. #include "common/hex_util.h"
  10. #include "common/logging/log.h"
  11. #include "common/swap.h"
  12. #include "core/core.h"
  13. #include "core/file_sys/patch_manager.h"
  14. #include "core/gdbstub/gdbstub.h"
  15. #include "core/hle/kernel/code_set.h"
  16. #include "core/hle/kernel/process.h"
  17. #include "core/hle/kernel/vm_manager.h"
  18. #include "core/loader/nso.h"
  19. #include "core/memory.h"
  20. #include "core/settings.h"
  21. namespace Loader {
  22. struct NsoSegmentHeader {
  23. u32_le offset;
  24. u32_le location;
  25. u32_le size;
  26. union {
  27. u32_le alignment;
  28. u32_le bss_size;
  29. };
  30. };
  31. static_assert(sizeof(NsoSegmentHeader) == 0x10, "NsoSegmentHeader has incorrect size.");
  32. struct NsoHeader {
  33. u32_le magic;
  34. u32_le version;
  35. INSERT_PADDING_WORDS(1);
  36. u8 flags;
  37. std::array<NsoSegmentHeader, 3> segments; // Text, RoData, Data (in that order)
  38. std::array<u8, 0x20> build_id;
  39. std::array<u32_le, 3> segments_compressed_size;
  40. bool IsSegmentCompressed(size_t segment_num) const {
  41. ASSERT_MSG(segment_num < 3, "Invalid segment {}", segment_num);
  42. return ((flags >> segment_num) & 1);
  43. }
  44. };
  45. static_assert(sizeof(NsoHeader) == 0x6c, "NsoHeader has incorrect size.");
  46. static_assert(std::is_trivially_copyable_v<NsoHeader>, "NsoHeader isn't trivially copyable.");
  47. struct ModHeader {
  48. u32_le magic;
  49. u32_le dynamic_offset;
  50. u32_le bss_start_offset;
  51. u32_le bss_end_offset;
  52. u32_le eh_frame_hdr_start_offset;
  53. u32_le eh_frame_hdr_end_offset;
  54. u32_le module_offset; // Offset to runtime-generated module object. typically equal to .bss base
  55. };
  56. static_assert(sizeof(ModHeader) == 0x1c, "ModHeader has incorrect size.");
  57. AppLoader_NSO::AppLoader_NSO(FileSys::VirtualFile file) : AppLoader(std::move(file)) {}
  58. FileType AppLoader_NSO::IdentifyType(const FileSys::VirtualFile& file) {
  59. u32 magic = 0;
  60. if (file->ReadObject(&magic) != sizeof(magic)) {
  61. return FileType::Error;
  62. }
  63. if (Common::MakeMagic('N', 'S', 'O', '0') != magic) {
  64. return FileType::Error;
  65. }
  66. return FileType::NSO;
  67. }
  68. static std::vector<u8> DecompressSegment(const std::vector<u8>& compressed_data,
  69. const NsoSegmentHeader& header) {
  70. std::vector<u8> uncompressed_data(header.size);
  71. const int bytes_uncompressed =
  72. LZ4_decompress_safe(reinterpret_cast<const char*>(compressed_data.data()),
  73. reinterpret_cast<char*>(uncompressed_data.data()),
  74. static_cast<int>(compressed_data.size()), header.size);
  75. ASSERT_MSG(bytes_uncompressed == static_cast<int>(header.size) &&
  76. bytes_uncompressed == static_cast<int>(uncompressed_data.size()),
  77. "{} != {} != {}", bytes_uncompressed, header.size, uncompressed_data.size());
  78. return uncompressed_data;
  79. }
  80. static constexpr u32 PageAlignSize(u32 size) {
  81. return (size + Memory::PAGE_MASK) & ~Memory::PAGE_MASK;
  82. }
  83. std::optional<VAddr> AppLoader_NSO::LoadModule(Kernel::Process& process,
  84. const FileSys::VfsFile& file, VAddr load_base,
  85. bool should_pass_arguments,
  86. std::optional<FileSys::PatchManager> pm) {
  87. if (file.GetSize() < sizeof(NsoHeader))
  88. return {};
  89. NsoHeader nso_header{};
  90. if (sizeof(NsoHeader) != file.ReadObject(&nso_header))
  91. return {};
  92. if (nso_header.magic != Common::MakeMagic('N', 'S', 'O', '0'))
  93. return {};
  94. // Build program image
  95. Kernel::CodeSet codeset;
  96. std::vector<u8> program_image;
  97. for (std::size_t i = 0; i < nso_header.segments.size(); ++i) {
  98. std::vector<u8> data =
  99. file.ReadBytes(nso_header.segments_compressed_size[i], nso_header.segments[i].offset);
  100. if (nso_header.IsSegmentCompressed(i)) {
  101. data = DecompressSegment(data, nso_header.segments[i]);
  102. }
  103. program_image.resize(nso_header.segments[i].location);
  104. program_image.insert(program_image.end(), data.begin(), data.end());
  105. codeset.segments[i].addr = nso_header.segments[i].location;
  106. codeset.segments[i].offset = nso_header.segments[i].location;
  107. codeset.segments[i].size = PageAlignSize(static_cast<u32>(data.size()));
  108. }
  109. if (should_pass_arguments && !Settings::values.program_args.empty()) {
  110. const auto arg_data = Settings::values.program_args;
  111. codeset.DataSegment().size += NSO_ARGUMENT_DATA_ALLOCATION_SIZE;
  112. NSOArgumentHeader args_header{
  113. NSO_ARGUMENT_DATA_ALLOCATION_SIZE, static_cast<u32_le>(arg_data.size()), {}};
  114. const auto end_offset = program_image.size();
  115. program_image.resize(static_cast<u32>(program_image.size()) +
  116. NSO_ARGUMENT_DATA_ALLOCATION_SIZE);
  117. std::memcpy(program_image.data() + end_offset, &args_header, sizeof(NSOArgumentHeader));
  118. std::memcpy(program_image.data() + end_offset + sizeof(NSOArgumentHeader), arg_data.data(),
  119. arg_data.size());
  120. }
  121. // MOD header pointer is at .text offset + 4
  122. u32 module_offset;
  123. std::memcpy(&module_offset, program_image.data() + 4, sizeof(u32));
  124. // Read MOD header
  125. ModHeader mod_header{};
  126. // Default .bss to size in segment header if MOD0 section doesn't exist
  127. u32 bss_size{PageAlignSize(nso_header.segments[2].bss_size)};
  128. std::memcpy(&mod_header, program_image.data() + module_offset, sizeof(ModHeader));
  129. const bool has_mod_header{mod_header.magic == Common::MakeMagic('M', 'O', 'D', '0')};
  130. if (has_mod_header) {
  131. // Resize program image to include .bss section and page align each section
  132. bss_size = PageAlignSize(mod_header.bss_end_offset - mod_header.bss_start_offset);
  133. }
  134. codeset.DataSegment().size += bss_size;
  135. const u32 image_size{PageAlignSize(static_cast<u32>(program_image.size()) + bss_size)};
  136. program_image.resize(image_size);
  137. // Apply patches if necessary
  138. if (pm && (pm->HasNSOPatch(nso_header.build_id) || Settings::values.dump_nso)) {
  139. std::vector<u8> pi_header(program_image.size() + 0x100);
  140. std::memcpy(pi_header.data(), &nso_header, sizeof(NsoHeader));
  141. std::memcpy(pi_header.data() + 0x100, program_image.data(), program_image.size());
  142. pi_header = pm->PatchNSO(pi_header);
  143. std::memcpy(program_image.data(), pi_header.data() + 0x100, program_image.size());
  144. }
  145. // Apply cheats if they exist and the program has a valid title ID
  146. if (pm) {
  147. auto& system = Core::System::GetInstance();
  148. const auto cheats = pm->CreateCheatList(system, nso_header.build_id);
  149. if (!cheats.empty()) {
  150. system.RegisterCheatList(cheats, Common::HexArrayToString(nso_header.build_id),
  151. load_base, load_base + program_image.size());
  152. }
  153. }
  154. // Load codeset for current process
  155. codeset.memory = std::make_shared<std::vector<u8>>(std::move(program_image));
  156. process.LoadModule(std::move(codeset), load_base);
  157. // Register module with GDBStub
  158. GDBStub::RegisterModule(file.GetName(), load_base, load_base);
  159. return load_base + image_size;
  160. }
  161. ResultStatus AppLoader_NSO::Load(Kernel::Process& process) {
  162. if (is_loaded) {
  163. return ResultStatus::ErrorAlreadyLoaded;
  164. }
  165. // Load module
  166. const VAddr base_address = process.VMManager().GetCodeRegionBaseAddress();
  167. if (!LoadModule(process, *file, base_address, true)) {
  168. return ResultStatus::ErrorLoadingNSO;
  169. }
  170. LOG_DEBUG(Loader, "loaded module {} @ 0x{:X}", file->GetName(), base_address);
  171. process.Run(base_address, Kernel::THREADPRIO_DEFAULT, Memory::DEFAULT_STACK_SIZE);
  172. is_loaded = true;
  173. return ResultStatus::Success;
  174. }
  175. } // namespace Loader