nro.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. // SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include <utility>
  4. #include <vector>
  5. #include "common/common_funcs.h"
  6. #include "common/common_types.h"
  7. #include "common/logging/log.h"
  8. #include "common/settings.h"
  9. #include "common/swap.h"
  10. #include "core/core.h"
  11. #include "core/file_sys/control_metadata.h"
  12. #include "core/file_sys/romfs_factory.h"
  13. #include "core/file_sys/vfs_offset.h"
  14. #include "core/hle/kernel/code_set.h"
  15. #include "core/hle/kernel/k_page_table.h"
  16. #include "core/hle/kernel/k_process.h"
  17. #include "core/hle/kernel/k_thread.h"
  18. #include "core/hle/service/filesystem/filesystem.h"
  19. #include "core/loader/nro.h"
  20. #include "core/loader/nso.h"
  21. #include "core/memory.h"
  22. #ifdef HAS_NCE
  23. #include "core/arm/nce/patcher.h"
  24. #endif
  25. namespace Loader {
  26. struct NroSegmentHeader {
  27. u32_le offset;
  28. u32_le size;
  29. };
  30. static_assert(sizeof(NroSegmentHeader) == 0x8, "NroSegmentHeader has incorrect size.");
  31. struct NroHeader {
  32. INSERT_PADDING_BYTES(0x4);
  33. u32_le module_header_offset;
  34. u32 magic_ext1;
  35. u32 magic_ext2;
  36. u32_le magic;
  37. INSERT_PADDING_BYTES(0x4);
  38. u32_le file_size;
  39. INSERT_PADDING_BYTES(0x4);
  40. std::array<NroSegmentHeader, 3> segments; // Text, RoData, Data (in that order)
  41. u32_le bss_size;
  42. INSERT_PADDING_BYTES(0x44);
  43. };
  44. static_assert(sizeof(NroHeader) == 0x80, "NroHeader has incorrect size.");
  45. struct ModHeader {
  46. u32_le magic;
  47. u32_le dynamic_offset;
  48. u32_le bss_start_offset;
  49. u32_le bss_end_offset;
  50. u32_le unwind_start_offset;
  51. u32_le unwind_end_offset;
  52. u32_le module_offset; // Offset to runtime-generated module object. typically equal to .bss base
  53. };
  54. static_assert(sizeof(ModHeader) == 0x1c, "ModHeader has incorrect size.");
  55. struct AssetSection {
  56. u64_le offset;
  57. u64_le size;
  58. };
  59. static_assert(sizeof(AssetSection) == 0x10, "AssetSection has incorrect size.");
  60. struct AssetHeader {
  61. u32_le magic;
  62. u32_le format_version;
  63. AssetSection icon;
  64. AssetSection nacp;
  65. AssetSection romfs;
  66. };
  67. static_assert(sizeof(AssetHeader) == 0x38, "AssetHeader has incorrect size.");
  68. AppLoader_NRO::AppLoader_NRO(FileSys::VirtualFile file_) : AppLoader(std::move(file_)) {
  69. NroHeader nro_header{};
  70. if (file->ReadObject(&nro_header) != sizeof(NroHeader)) {
  71. return;
  72. }
  73. if (file->GetSize() >= nro_header.file_size + sizeof(AssetHeader)) {
  74. const u64 offset = nro_header.file_size;
  75. AssetHeader asset_header{};
  76. if (file->ReadObject(&asset_header, offset) != sizeof(AssetHeader)) {
  77. return;
  78. }
  79. if (asset_header.format_version != 0) {
  80. LOG_WARNING(Loader,
  81. "NRO Asset Header has format {}, currently supported format is 0. If "
  82. "strange glitches occur with metadata, check NRO assets.",
  83. asset_header.format_version);
  84. }
  85. if (asset_header.magic != Common::MakeMagic('A', 'S', 'E', 'T')) {
  86. return;
  87. }
  88. if (asset_header.nacp.size > 0) {
  89. nacp = std::make_unique<FileSys::NACP>(std::make_shared<FileSys::OffsetVfsFile>(
  90. file, asset_header.nacp.size, offset + asset_header.nacp.offset, "Control.nacp"));
  91. }
  92. if (asset_header.romfs.size > 0) {
  93. romfs = std::make_shared<FileSys::OffsetVfsFile>(
  94. file, asset_header.romfs.size, offset + asset_header.romfs.offset, "game.romfs");
  95. }
  96. if (asset_header.icon.size > 0) {
  97. icon_data = file->ReadBytes(asset_header.icon.size, offset + asset_header.icon.offset);
  98. }
  99. }
  100. }
  101. AppLoader_NRO::~AppLoader_NRO() = default;
  102. FileType AppLoader_NRO::IdentifyType(const FileSys::VirtualFile& nro_file) {
  103. // Read NSO header
  104. NroHeader nro_header{};
  105. if (sizeof(NroHeader) != nro_file->ReadObject(&nro_header)) {
  106. return FileType::Error;
  107. }
  108. if (nro_header.magic == Common::MakeMagic('N', 'R', 'O', '0')) {
  109. return FileType::NRO;
  110. }
  111. return FileType::Error;
  112. }
  113. bool AppLoader_NRO::IsHomebrew() {
  114. // Read NSO header
  115. NroHeader nro_header{};
  116. if (sizeof(NroHeader) != file->ReadObject(&nro_header)) {
  117. return false;
  118. }
  119. return nro_header.magic_ext1 == Common::MakeMagic('H', 'O', 'M', 'E') &&
  120. nro_header.magic_ext2 == Common::MakeMagic('B', 'R', 'E', 'W');
  121. }
  122. static constexpr u32 PageAlignSize(u32 size) {
  123. return static_cast<u32>((size + Core::Memory::YUZU_PAGEMASK) & ~Core::Memory::YUZU_PAGEMASK);
  124. }
  125. static bool LoadNroImpl(Core::System& system, Kernel::KProcess& process,
  126. const std::vector<u8>& data) {
  127. if (data.size() < sizeof(NroHeader)) {
  128. return {};
  129. }
  130. // Read NSO header
  131. NroHeader nro_header{};
  132. std::memcpy(&nro_header, data.data(), sizeof(NroHeader));
  133. if (nro_header.magic != Common::MakeMagic('N', 'R', 'O', '0')) {
  134. return {};
  135. }
  136. // Build program image
  137. Kernel::PhysicalMemory program_image(PageAlignSize(nro_header.file_size));
  138. std::memcpy(program_image.data(), data.data(), program_image.size());
  139. if (program_image.size() != PageAlignSize(nro_header.file_size)) {
  140. return {};
  141. }
  142. Kernel::CodeSet codeset;
  143. for (std::size_t i = 0; i < nro_header.segments.size(); ++i) {
  144. codeset.segments[i].addr = nro_header.segments[i].offset;
  145. codeset.segments[i].offset = nro_header.segments[i].offset;
  146. codeset.segments[i].size = PageAlignSize(nro_header.segments[i].size);
  147. }
  148. if (!Settings::values.program_args.GetValue().empty()) {
  149. const auto arg_data = Settings::values.program_args.GetValue();
  150. codeset.DataSegment().size += NSO_ARGUMENT_DATA_ALLOCATION_SIZE;
  151. NSOArgumentHeader args_header{
  152. NSO_ARGUMENT_DATA_ALLOCATION_SIZE, static_cast<u32_le>(arg_data.size()), {}};
  153. const auto end_offset = program_image.size();
  154. program_image.resize(static_cast<u32>(program_image.size()) +
  155. NSO_ARGUMENT_DATA_ALLOCATION_SIZE);
  156. std::memcpy(program_image.data() + end_offset, &args_header, sizeof(NSOArgumentHeader));
  157. std::memcpy(program_image.data() + end_offset + sizeof(NSOArgumentHeader), arg_data.data(),
  158. arg_data.size());
  159. }
  160. // Default .bss to NRO header bss size if MOD0 section doesn't exist
  161. u32 bss_size{PageAlignSize(nro_header.bss_size)};
  162. // Read MOD header
  163. ModHeader mod_header{};
  164. std::memcpy(&mod_header, program_image.data() + nro_header.module_header_offset,
  165. sizeof(ModHeader));
  166. const bool has_mod_header{mod_header.magic == Common::MakeMagic('M', 'O', 'D', '0')};
  167. if (has_mod_header) {
  168. // Resize program image to include .bss section and page align each section
  169. bss_size = PageAlignSize(mod_header.bss_end_offset - mod_header.bss_start_offset);
  170. }
  171. codeset.DataSegment().size += bss_size;
  172. program_image.resize(static_cast<u32>(program_image.size()) + bss_size);
  173. size_t image_size = program_image.size();
  174. #ifdef HAS_NCE
  175. const auto& code = codeset.CodeSegment();
  176. // NROs always have a 39-bit address space.
  177. Settings::SetNceEnabled(true);
  178. // Create NCE patcher
  179. Core::NCE::Patcher patch{};
  180. if (Settings::IsNceEnabled()) {
  181. // Patch SVCs and MRS calls in the guest code
  182. patch.PatchText(program_image, code);
  183. // We only support PostData patching for NROs.
  184. ASSERT(patch.GetPatchMode() == Core::NCE::PatchMode::PostData);
  185. // Update patch section.
  186. auto& patch_segment = codeset.PatchSegment();
  187. patch_segment.addr = image_size;
  188. patch_segment.size = static_cast<u32>(patch.GetSectionSize());
  189. // Add patch section size to the module size.
  190. image_size += patch_segment.size;
  191. }
  192. #endif
  193. // Enable direct memory mapping in case of NCE.
  194. const u64 fastmem_base = [&]() -> size_t {
  195. if (Settings::IsNceEnabled()) {
  196. auto& buffer = system.DeviceMemory().buffer;
  197. buffer.EnableDirectMappedAddress();
  198. return reinterpret_cast<u64>(buffer.VirtualBasePointer());
  199. }
  200. return 0;
  201. }();
  202. // Setup the process code layout
  203. if (process
  204. .LoadFromMetadata(FileSys::ProgramMetadata::GetDefault(), image_size, fastmem_base,
  205. false)
  206. .IsError()) {
  207. return false;
  208. }
  209. // Relocate code patch and copy to the program_image if running under NCE.
  210. // This needs to be after LoadFromMetadata so we can use the process entry point.
  211. #ifdef HAS_NCE
  212. if (Settings::IsNceEnabled()) {
  213. patch.RelocateAndCopy(process.GetEntryPoint(), code, program_image,
  214. &process.GetPostHandlers());
  215. }
  216. #endif
  217. // Load codeset for current process
  218. codeset.memory = std::move(program_image);
  219. process.LoadModule(std::move(codeset), process.GetEntryPoint());
  220. return true;
  221. }
  222. bool AppLoader_NRO::LoadNro(Core::System& system, Kernel::KProcess& process,
  223. const FileSys::VfsFile& nro_file) {
  224. return LoadNroImpl(system, process, nro_file.ReadAllBytes());
  225. }
  226. AppLoader_NRO::LoadResult AppLoader_NRO::Load(Kernel::KProcess& process, Core::System& system) {
  227. if (is_loaded) {
  228. return {ResultStatus::ErrorAlreadyLoaded, {}};
  229. }
  230. if (!LoadNro(system, process, *file)) {
  231. return {ResultStatus::ErrorLoadingNRO, {}};
  232. }
  233. u64 program_id{};
  234. ReadProgramId(program_id);
  235. system.GetFileSystemController().RegisterProcess(
  236. process.GetProcessId(), program_id,
  237. std::make_unique<FileSys::RomFSFactory>(*this, system.GetContentProvider(),
  238. system.GetFileSystemController()));
  239. is_loaded = true;
  240. return {ResultStatus::Success, LoadParameters{Kernel::KThread::DefaultThreadPriority,
  241. Core::Memory::DEFAULT_STACK_SIZE}};
  242. }
  243. ResultStatus AppLoader_NRO::ReadIcon(std::vector<u8>& buffer) {
  244. if (icon_data.empty()) {
  245. return ResultStatus::ErrorNoIcon;
  246. }
  247. buffer = icon_data;
  248. return ResultStatus::Success;
  249. }
  250. ResultStatus AppLoader_NRO::ReadProgramId(u64& out_program_id) {
  251. if (nacp == nullptr) {
  252. return ResultStatus::ErrorNoControl;
  253. }
  254. out_program_id = nacp->GetTitleId();
  255. return ResultStatus::Success;
  256. }
  257. ResultStatus AppLoader_NRO::ReadRomFS(FileSys::VirtualFile& dir) {
  258. if (romfs == nullptr) {
  259. return ResultStatus::ErrorNoRomFS;
  260. }
  261. dir = romfs;
  262. return ResultStatus::Success;
  263. }
  264. ResultStatus AppLoader_NRO::ReadTitle(std::string& title) {
  265. if (nacp == nullptr) {
  266. return ResultStatus::ErrorNoControl;
  267. }
  268. title = nacp->GetApplicationName();
  269. return ResultStatus::Success;
  270. }
  271. ResultStatus AppLoader_NRO::ReadControlData(FileSys::NACP& control) {
  272. if (nacp == nullptr) {
  273. return ResultStatus::ErrorNoControl;
  274. }
  275. control = *nacp;
  276. return ResultStatus::Success;
  277. }
  278. bool AppLoader_NRO::IsRomFSUpdatable() const {
  279. return false;
  280. }
  281. } // namespace Loader