nso.cpp 7.4 KB

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