summaryrefslogtreecommitdiff
path: root/src/core/loader
diff options
context:
space:
mode:
Diffstat (limited to 'src/core/loader')
-rw-r--r--src/core/loader/deconstructed_rom_directory.cpp113
-rw-r--r--src/core/loader/deconstructed_rom_directory.h14
-rw-r--r--src/core/loader/elf.cpp24
-rw-r--r--src/core/loader/elf.h12
-rw-r--r--src/core/loader/loader.cpp63
-rw-r--r--src/core/loader/loader.h30
-rw-r--r--src/core/loader/nca.cpp252
-rw-r--r--src/core/loader/nca.h19
-rw-r--r--src/core/loader/nro.cpp32
-rw-r--r--src/core/loader/nro.h13
-rw-r--r--src/core/loader/nso.cpp91
-rw-r--r--src/core/loader/nso.h17
12 files changed, 540 insertions, 140 deletions
diff --git a/src/core/loader/deconstructed_rom_directory.cpp b/src/core/loader/deconstructed_rom_directory.cpp
index 0b3b4cd73..eb7feb617 100644
--- a/src/core/loader/deconstructed_rom_directory.cpp
+++ b/src/core/loader/deconstructed_rom_directory.cpp
@@ -4,10 +4,11 @@
4 4
5#include <cinttypes> 5#include <cinttypes>
6#include "common/common_funcs.h" 6#include "common/common_funcs.h"
7#include "common/common_paths.h"
7#include "common/file_util.h" 8#include "common/file_util.h"
8#include "common/logging/log.h" 9#include "common/logging/log.h"
9#include "common/string_util.h" 10#include "common/string_util.h"
10#include "core/file_sys/content_archive.h" 11#include "core/file_sys/romfs_factory.h"
11#include "core/hle/kernel/process.h" 12#include "core/hle/kernel/process.h"
12#include "core/hle/kernel/resource_limit.h" 13#include "core/hle/kernel/resource_limit.h"
13#include "core/hle/service/filesystem/filesystem.h" 14#include "core/hle/service/filesystem/filesystem.h"
@@ -45,11 +46,55 @@ static std::string FindRomFS(const std::string& directory) {
45 return filepath_romfs; 46 return filepath_romfs;
46} 47}
47 48
48AppLoader_DeconstructedRomDirectory::AppLoader_DeconstructedRomDirectory(FileSys::VirtualFile file) 49AppLoader_DeconstructedRomDirectory::AppLoader_DeconstructedRomDirectory(FileUtil::IOFile&& file,
49 : AppLoader(std::move(file)) {} 50 std::string filepath)
51 : AppLoader(std::move(file)), filepath(std::move(filepath)) {}
52
53FileType AppLoader_DeconstructedRomDirectory::IdentifyType(FileUtil::IOFile& file,
54 const std::string& filepath) {
55 bool is_main_found{};
56 bool is_npdm_found{};
57 bool is_rtld_found{};
58 bool is_sdk_found{};
59
60 const auto callback = [&](unsigned* num_entries_out, const std::string& directory,
61 const std::string& virtual_name) -> bool {
62 // Skip directories
63 std::string physical_name = directory + virtual_name;
64 if (FileUtil::IsDirectory(physical_name)) {
65 return true;
66 }
67
68 // Verify filename
69 if (Common::ToLower(virtual_name) == "main") {
70 is_main_found = true;
71 } else if (Common::ToLower(virtual_name) == "main.npdm") {
72 is_npdm_found = true;
73 return true;
74 } else if (Common::ToLower(virtual_name) == "rtld") {
75 is_rtld_found = true;
76 } else if (Common::ToLower(virtual_name) == "sdk") {
77 is_sdk_found = true;
78 } else {
79 // Continue searching
80 return true;
81 }
82
83 // Verify file is an NSO
84 FileUtil::IOFile file(physical_name, "rb");
85 if (AppLoader_NSO::IdentifyType(file, physical_name) != FileType::NSO) {
86 return false;
87 }
88
89 // We are done if we've found and verified all required NSOs
90 return !(is_main_found && is_npdm_found && is_rtld_found && is_sdk_found);
91 };
92
93 // Search the directory recursively, looking for the required modules
94 const std::string directory = filepath.substr(0, filepath.find_last_of("/\\")) + DIR_SEP;
95 FileUtil::ForeachDirectoryEntry(nullptr, directory, callback);
50 96
51FileType AppLoader_DeconstructedRomDirectory::IdentifyType(const FileSys::VirtualFile& file) { 97 if (is_main_found && is_npdm_found && is_rtld_found && is_sdk_found) {
52 if (FileSys::IsDirectoryExeFS(file->GetContainingDirectory())) {
53 return FileType::DeconstructedRomDirectory; 98 return FileType::DeconstructedRomDirectory;
54 } 99 }
55 100
@@ -61,13 +106,14 @@ ResultStatus AppLoader_DeconstructedRomDirectory::Load(
61 if (is_loaded) { 106 if (is_loaded) {
62 return ResultStatus::ErrorAlreadyLoaded; 107 return ResultStatus::ErrorAlreadyLoaded;
63 } 108 }
109 if (!file.IsOpen()) {
110 return ResultStatus::Error;
111 }
64 112
65 const FileSys::VirtualDir dir = file->GetContainingDirectory(); 113 const std::string directory = filepath.substr(0, filepath.find_last_of("/\\")) + DIR_SEP;
66 const FileSys::VirtualFile npdm = dir->GetFile("main.npdm"); 114 const std::string npdm_path = directory + DIR_SEP + "main.npdm";
67 if (npdm == nullptr)
68 return ResultStatus::ErrorInvalidFormat;
69 115
70 ResultStatus result = metadata.Load(npdm); 116 ResultStatus result = metadata.Load(npdm_path);
71 if (result != ResultStatus::Success) { 117 if (result != ResultStatus::Success) {
72 return result; 118 return result;
73 } 119 }
@@ -82,10 +128,9 @@ ResultStatus AppLoader_DeconstructedRomDirectory::Load(
82 VAddr next_load_addr{Memory::PROCESS_IMAGE_VADDR}; 128 VAddr next_load_addr{Memory::PROCESS_IMAGE_VADDR};
83 for (const auto& module : {"rtld", "main", "subsdk0", "subsdk1", "subsdk2", "subsdk3", 129 for (const auto& module : {"rtld", "main", "subsdk0", "subsdk1", "subsdk2", "subsdk3",
84 "subsdk4", "subsdk5", "subsdk6", "subsdk7", "sdk"}) { 130 "subsdk4", "subsdk5", "subsdk6", "subsdk7", "sdk"}) {
131 const std::string path = directory + DIR_SEP + module;
85 const VAddr load_addr = next_load_addr; 132 const VAddr load_addr = next_load_addr;
86 const FileSys::VirtualFile module_file = dir->GetFile(module); 133 next_load_addr = AppLoader_NSO::LoadModule(path, load_addr);
87 if (module_file != nullptr)
88 next_load_addr = AppLoader_NSO::LoadModule(module_file, load_addr);
89 if (next_load_addr) { 134 if (next_load_addr) {
90 LOG_DEBUG(Loader, "loaded module {} @ 0x{:X}", module, load_addr); 135 LOG_DEBUG(Loader, "loaded module {} @ 0x{:X}", module, load_addr);
91 } else { 136 } else {
@@ -102,20 +147,42 @@ ResultStatus AppLoader_DeconstructedRomDirectory::Load(
102 metadata.GetMainThreadStackSize()); 147 metadata.GetMainThreadStackSize());
103 148
104 // Find the RomFS by searching for a ".romfs" file in this directory 149 // Find the RomFS by searching for a ".romfs" file in this directory
105 const auto& files = dir->GetFiles(); 150 filepath_romfs = FindRomFS(directory);
106 const auto romfs_iter =
107 std::find_if(files.begin(), files.end(), [](const FileSys::VirtualFile& file) {
108 return file->GetName().find(".romfs") != std::string::npos;
109 });
110
111 // TODO(DarkLordZach): Identify RomFS if its a subdirectory.
112 const auto romfs = (romfs_iter == files.end()) ? nullptr : *romfs_iter;
113 151
114 if (romfs != nullptr) 152 // Register the RomFS if a ".romfs" file was found
115 Service::FileSystem::RegisterRomFS(romfs); 153 if (!filepath_romfs.empty()) {
154 Service::FileSystem::RegisterFileSystem(std::make_unique<FileSys::RomFS_Factory>(*this),
155 Service::FileSystem::Type::RomFS);
156 }
116 157
117 is_loaded = true; 158 is_loaded = true;
118 return ResultStatus::Success; 159 return ResultStatus::Success;
119} 160}
120 161
162ResultStatus AppLoader_DeconstructedRomDirectory::ReadRomFS(
163 std::shared_ptr<FileUtil::IOFile>& romfs_file, u64& offset, u64& size) {
164
165 if (filepath_romfs.empty()) {
166 LOG_DEBUG(Loader, "No RomFS available");
167 return ResultStatus::ErrorNotUsed;
168 }
169
170 // We reopen the file, to allow its position to be independent
171 romfs_file = std::make_shared<FileUtil::IOFile>(filepath_romfs, "rb");
172 if (!romfs_file->IsOpen()) {
173 return ResultStatus::Error;
174 }
175
176 offset = 0;
177 size = romfs_file->GetSize();
178
179 LOG_DEBUG(Loader, "RomFS offset: 0x{:016X}", offset);
180 LOG_DEBUG(Loader, "RomFS size: 0x{:016X}", size);
181
182 // Reset read pointer
183 file.Seek(0, SEEK_SET);
184
185 return ResultStatus::Success;
186}
187
121} // namespace Loader 188} // namespace Loader
diff --git a/src/core/loader/deconstructed_rom_directory.h b/src/core/loader/deconstructed_rom_directory.h
index 494220756..23295d911 100644
--- a/src/core/loader/deconstructed_rom_directory.h
+++ b/src/core/loader/deconstructed_rom_directory.h
@@ -20,22 +20,28 @@ namespace Loader {
20 */ 20 */
21class AppLoader_DeconstructedRomDirectory final : public AppLoader { 21class AppLoader_DeconstructedRomDirectory final : public AppLoader {
22public: 22public:
23 explicit AppLoader_DeconstructedRomDirectory(FileSys::VirtualFile main_file); 23 AppLoader_DeconstructedRomDirectory(FileUtil::IOFile&& file, std::string filepath);
24 24
25 /** 25 /**
26 * Returns the type of the file 26 * Returns the type of the file
27 * @param file std::shared_ptr<VfsFile> open file 27 * @param file FileUtil::IOFile open file
28 * @param filepath Path of the file that we are opening.
28 * @return FileType found, or FileType::Error if this loader doesn't know it 29 * @return FileType found, or FileType::Error if this loader doesn't know it
29 */ 30 */
30 static FileType IdentifyType(const FileSys::VirtualFile& file); 31 static FileType IdentifyType(FileUtil::IOFile& file, const std::string& filepath);
31 32
32 FileType GetFileType() override { 33 FileType GetFileType() override {
33 return IdentifyType(file); 34 return IdentifyType(file, filepath);
34 } 35 }
35 36
36 ResultStatus Load(Kernel::SharedPtr<Kernel::Process>& process) override; 37 ResultStatus Load(Kernel::SharedPtr<Kernel::Process>& process) override;
37 38
39 ResultStatus ReadRomFS(std::shared_ptr<FileUtil::IOFile>& romfs_file, u64& offset,
40 u64& size) override;
41
38private: 42private:
43 std::string filepath_romfs;
44 std::string filepath;
39 FileSys::ProgramMetadata metadata; 45 FileSys::ProgramMetadata metadata;
40}; 46};
41 47
diff --git a/src/core/loader/elf.cpp b/src/core/loader/elf.cpp
index 4bfd5f536..b69e5c6ef 100644
--- a/src/core/loader/elf.cpp
+++ b/src/core/loader/elf.cpp
@@ -365,17 +365,20 @@ SectionID ElfReader::GetSectionByName(const char* name, int firstSection) const
365 365
366namespace Loader { 366namespace Loader {
367 367
368AppLoader_ELF::AppLoader_ELF(FileSys::VirtualFile file) : AppLoader(std::move(file)) {} 368AppLoader_ELF::AppLoader_ELF(FileUtil::IOFile&& file, std::string filename)
369 : AppLoader(std::move(file)), filename(std::move(filename)) {}
369 370
370FileType AppLoader_ELF::IdentifyType(const FileSys::VirtualFile& file) { 371FileType AppLoader_ELF::IdentifyType(FileUtil::IOFile& file, const std::string&) {
371 static constexpr u16 ELF_MACHINE_ARM{0x28}; 372 static constexpr u16 ELF_MACHINE_ARM{0x28};
372 373
373 u32 magic = 0; 374 u32 magic = 0;
374 if (4 != file->ReadObject(&magic)) 375 file.Seek(0, SEEK_SET);
376 if (1 != file.ReadArray<u32>(&magic, 1))
375 return FileType::Error; 377 return FileType::Error;
376 378
377 u16 machine = 0; 379 u16 machine = 0;
378 if (2 != file->ReadObject(&machine, 18)) 380 file.Seek(18, SEEK_SET);
381 if (1 != file.ReadArray<u16>(&machine, 1))
379 return FileType::Error; 382 return FileType::Error;
380 383
381 if (Common::MakeMagic('\x7f', 'E', 'L', 'F') == magic && ELF_MACHINE_ARM == machine) 384 if (Common::MakeMagic('\x7f', 'E', 'L', 'F') == magic && ELF_MACHINE_ARM == machine)
@@ -388,13 +391,20 @@ ResultStatus AppLoader_ELF::Load(Kernel::SharedPtr<Kernel::Process>& process) {
388 if (is_loaded) 391 if (is_loaded)
389 return ResultStatus::ErrorAlreadyLoaded; 392 return ResultStatus::ErrorAlreadyLoaded;
390 393
391 std::vector<u8> buffer = file->ReadAllBytes(); 394 if (!file.IsOpen())
392 if (buffer.size() != file->GetSize()) 395 return ResultStatus::Error;
396
397 // Reset read pointer in case this file has been read before.
398 file.Seek(0, SEEK_SET);
399
400 size_t size = file.GetSize();
401 std::unique_ptr<u8[]> buffer(new u8[size]);
402 if (file.ReadBytes(&buffer[0], size) != size)
393 return ResultStatus::Error; 403 return ResultStatus::Error;
394 404
395 ElfReader elf_reader(&buffer[0]); 405 ElfReader elf_reader(&buffer[0]);
396 SharedPtr<CodeSet> codeset = elf_reader.LoadInto(Memory::PROCESS_IMAGE_VADDR); 406 SharedPtr<CodeSet> codeset = elf_reader.LoadInto(Memory::PROCESS_IMAGE_VADDR);
397 codeset->name = file->GetName(); 407 codeset->name = filename;
398 408
399 process->LoadModule(codeset, codeset->entrypoint); 409 process->LoadModule(codeset, codeset->entrypoint);
400 process->svc_access_mask.set(); 410 process->svc_access_mask.set();
diff --git a/src/core/loader/elf.h b/src/core/loader/elf.h
index b8fb982d0..ee741a789 100644
--- a/src/core/loader/elf.h
+++ b/src/core/loader/elf.h
@@ -16,20 +16,24 @@ namespace Loader {
16/// Loads an ELF/AXF file 16/// Loads an ELF/AXF file
17class AppLoader_ELF final : public AppLoader { 17class AppLoader_ELF final : public AppLoader {
18public: 18public:
19 explicit AppLoader_ELF(FileSys::VirtualFile file); 19 AppLoader_ELF(FileUtil::IOFile&& file, std::string filename);
20 20
21 /** 21 /**
22 * Returns the type of the file 22 * Returns the type of the file
23 * @param file std::shared_ptr<VfsFile> open file 23 * @param file FileUtil::IOFile open file
24 * @param filepath Path of the file that we are opening.
24 * @return FileType found, or FileType::Error if this loader doesn't know it 25 * @return FileType found, or FileType::Error if this loader doesn't know it
25 */ 26 */
26 static FileType IdentifyType(const FileSys::VirtualFile& file); 27 static FileType IdentifyType(FileUtil::IOFile& file, const std::string& filepath);
27 28
28 FileType GetFileType() override { 29 FileType GetFileType() override {
29 return IdentifyType(file); 30 return IdentifyType(file, filename);
30 } 31 }
31 32
32 ResultStatus Load(Kernel::SharedPtr<Kernel::Process>& process) override; 33 ResultStatus Load(Kernel::SharedPtr<Kernel::Process>& process) override;
34
35private:
36 std::string filename;
33}; 37};
34 38
35} // namespace Loader 39} // namespace Loader
diff --git a/src/core/loader/loader.cpp b/src/core/loader/loader.cpp
index 1574345a1..8831d8e83 100644
--- a/src/core/loader/loader.cpp
+++ b/src/core/loader/loader.cpp
@@ -6,7 +6,6 @@
6#include <string> 6#include <string>
7#include "common/logging/log.h" 7#include "common/logging/log.h"
8#include "common/string_util.h" 8#include "common/string_util.h"
9#include "core/file_sys/vfs_real.h"
10#include "core/hle/kernel/process.h" 9#include "core/hle/kernel/process.h"
11#include "core/loader/deconstructed_rom_directory.h" 10#include "core/loader/deconstructed_rom_directory.h"
12#include "core/loader/elf.h" 11#include "core/loader/elf.h"
@@ -22,11 +21,11 @@ const std::initializer_list<Kernel::AddressMapping> default_address_mappings = {
22 {0x1F000000, 0x600000, false}, // entire VRAM 21 {0x1F000000, 0x600000, false}, // entire VRAM
23}; 22};
24 23
25FileType IdentifyFile(FileSys::VirtualFile file) { 24FileType IdentifyFile(FileUtil::IOFile& file, const std::string& filepath) {
26 FileType type; 25 FileType type;
27 26
28#define CHECK_TYPE(loader) \ 27#define CHECK_TYPE(loader) \
29 type = AppLoader_##loader::IdentifyType(file); \ 28 type = AppLoader_##loader::IdentifyType(file, filepath); \
30 if (FileType::Error != type) \ 29 if (FileType::Error != type) \
31 return type; 30 return type;
32 31
@@ -42,22 +41,25 @@ FileType IdentifyFile(FileSys::VirtualFile file) {
42} 41}
43 42
44FileType IdentifyFile(const std::string& file_name) { 43FileType IdentifyFile(const std::string& file_name) {
45 return IdentifyFile(FileSys::VirtualFile(std::make_shared<FileSys::RealVfsFile>(file_name))); 44 FileUtil::IOFile file(file_name, "rb");
46} 45 if (!file.IsOpen()) {
46 LOG_ERROR(Loader, "Failed to load file {}", file_name);
47 return FileType::Unknown;
48 }
47 49
48FileType GuessFromFilename(const std::string& name) { 50 return IdentifyFile(file, file_name);
49 if (name == "main") 51}
50 return FileType::DeconstructedRomDirectory;
51 52
52 const std::string extension = Common::ToLower(FileUtil::GetExtensionFromFilename(name)); 53FileType GuessFromExtension(const std::string& extension_) {
54 std::string extension = Common::ToLower(extension_);
53 55
54 if (extension == "elf") 56 if (extension == ".elf")
55 return FileType::ELF; 57 return FileType::ELF;
56 if (extension == "nro") 58 else if (extension == ".nro")
57 return FileType::NRO; 59 return FileType::NRO;
58 if (extension == "nso") 60 else if (extension == ".nso")
59 return FileType::NSO; 61 return FileType::NSO;
60 if (extension == "nca") 62 else if (extension == ".nca")
61 return FileType::NCA; 63 return FileType::NCA;
62 64
63 return FileType::Unknown; 65 return FileType::Unknown;
@@ -91,47 +93,58 @@ const char* GetFileTypeString(FileType type) {
91 * @param filepath the file full path (with name) 93 * @param filepath the file full path (with name)
92 * @return std::unique_ptr<AppLoader> a pointer to a loader object; nullptr for unsupported type 94 * @return std::unique_ptr<AppLoader> a pointer to a loader object; nullptr for unsupported type
93 */ 95 */
94static std::unique_ptr<AppLoader> GetFileLoader(FileSys::VirtualFile file, FileType type) { 96static std::unique_ptr<AppLoader> GetFileLoader(FileUtil::IOFile&& file, FileType type,
97 const std::string& filename,
98 const std::string& filepath) {
95 switch (type) { 99 switch (type) {
96 100
97 // Standard ELF file format. 101 // Standard ELF file format.
98 case FileType::ELF: 102 case FileType::ELF:
99 return std::make_unique<AppLoader_ELF>(std::move(file)); 103 return std::make_unique<AppLoader_ELF>(std::move(file), filename);
100 104
101 // NX NSO file format. 105 // NX NSO file format.
102 case FileType::NSO: 106 case FileType::NSO:
103 return std::make_unique<AppLoader_NSO>(std::move(file)); 107 return std::make_unique<AppLoader_NSO>(std::move(file), filepath);
104 108
105 // NX NRO file format. 109 // NX NRO file format.
106 case FileType::NRO: 110 case FileType::NRO:
107 return std::make_unique<AppLoader_NRO>(std::move(file)); 111 return std::make_unique<AppLoader_NRO>(std::move(file), filepath);
108 112
109 // NX NCA file format. 113 // NX NCA file format.
110 case FileType::NCA: 114 case FileType::NCA:
111 return std::make_unique<AppLoader_NCA>(std::move(file)); 115 return std::make_unique<AppLoader_NCA>(std::move(file), filepath);
112 116
113 // NX deconstructed ROM directory. 117 // NX deconstructed ROM directory.
114 case FileType::DeconstructedRomDirectory: 118 case FileType::DeconstructedRomDirectory:
115 return std::make_unique<AppLoader_DeconstructedRomDirectory>(std::move(file)); 119 return std::make_unique<AppLoader_DeconstructedRomDirectory>(std::move(file), filepath);
116 120
117 default: 121 default:
118 return nullptr; 122 return nullptr;
119 } 123 }
120} 124}
121 125
122std::unique_ptr<AppLoader> GetLoader(FileSys::VirtualFile file) { 126std::unique_ptr<AppLoader> GetLoader(const std::string& filename) {
123 FileType type = IdentifyFile(file); 127 FileUtil::IOFile file(filename, "rb");
124 FileType filename_type = GuessFromFilename(file->GetName()); 128 if (!file.IsOpen()) {
129 LOG_ERROR(Loader, "Failed to load file {}", filename);
130 return nullptr;
131 }
132
133 std::string filename_filename, filename_extension;
134 Common::SplitPath(filename, nullptr, &filename_filename, &filename_extension);
135
136 FileType type = IdentifyFile(file, filename);
137 FileType filename_type = GuessFromExtension(filename_extension);
125 138
126 if (type != filename_type) { 139 if (type != filename_type) {
127 LOG_WARNING(Loader, "File {} has a different type than its extension.", file->GetName()); 140 LOG_WARNING(Loader, "File {} has a different type than its extension.", filename);
128 if (FileType::Unknown == type) 141 if (FileType::Unknown == type)
129 type = filename_type; 142 type = filename_type;
130 } 143 }
131 144
132 LOG_DEBUG(Loader, "Loading file {} as {}...", file->GetName(), GetFileTypeString(type)); 145 LOG_DEBUG(Loader, "Loading file {} as {}...", filename, GetFileTypeString(type));
133 146
134 return GetFileLoader(std::move(file), type); 147 return GetFileLoader(std::move(file), type, filename_filename, filename);
135} 148}
136 149
137} // namespace Loader 150} // namespace Loader
diff --git a/src/core/loader/loader.h b/src/core/loader/loader.h
index 1da9e8099..b76f7b13d 100644
--- a/src/core/loader/loader.h
+++ b/src/core/loader/loader.h
@@ -13,7 +13,6 @@
13#include <boost/optional.hpp> 13#include <boost/optional.hpp>
14#include "common/common_types.h" 14#include "common/common_types.h"
15#include "common/file_util.h" 15#include "common/file_util.h"
16#include "core/file_sys/vfs.h"
17#include "core/hle/kernel/kernel.h" 16#include "core/hle/kernel/kernel.h"
18 17
19namespace Kernel { 18namespace Kernel {
@@ -37,9 +36,10 @@ enum class FileType {
37/** 36/**
38 * Identifies the type of a bootable file based on the magic value in its header. 37 * Identifies the type of a bootable file based on the magic value in its header.
39 * @param file open file 38 * @param file open file
39 * @param filepath Path of the file that we are opening.
40 * @return FileType of file 40 * @return FileType of file
41 */ 41 */
42FileType IdentifyFile(FileSys::VirtualFile file); 42FileType IdentifyFile(FileUtil::IOFile& file, const std::string& filepath);
43 43
44/** 44/**
45 * Identifies the type of a bootable file based on the magic value in its header. 45 * Identifies the type of a bootable file based on the magic value in its header.
@@ -50,12 +50,12 @@ FileType IdentifyFile(FileSys::VirtualFile file);
50FileType IdentifyFile(const std::string& file_name); 50FileType IdentifyFile(const std::string& file_name);
51 51
52/** 52/**
53 * Guess the type of a bootable file from its name 53 * Guess the type of a bootable file from its extension
54 * @param name String name of bootable file 54 * @param extension String extension of bootable file
55 * @return FileType of file. Note: this will return FileType::Unknown if it is unable to determine 55 * @return FileType of file. Note: this will return FileType::Unknown if it is unable to determine
56 * a filetype, and will never return FileType::Error. 56 * a filetype, and will never return FileType::Error.
57 */ 57 */
58FileType GuessFromFilename(const std::string& name); 58FileType GuessFromExtension(const std::string& extension);
59 59
60/** 60/**
61 * Convert a FileType into a string which can be displayed to the user. 61 * Convert a FileType into a string which can be displayed to the user.
@@ -79,7 +79,7 @@ enum class ResultStatus {
79/// Interface for loading an application 79/// Interface for loading an application
80class AppLoader : NonCopyable { 80class AppLoader : NonCopyable {
81public: 81public:
82 AppLoader(FileSys::VirtualFile file) : file(std::move(file)) {} 82 AppLoader(FileUtil::IOFile&& file) : file(std::move(file)) {}
83 virtual ~AppLoader() {} 83 virtual ~AppLoader() {}
84 84
85 /** 85 /**
@@ -154,20 +154,26 @@ public:
154 /** 154 /**
155 * Get the RomFS of the application 155 * Get the RomFS of the application
156 * Since the RomFS can be huge, we return a file reference instead of copying to a buffer 156 * Since the RomFS can be huge, we return a file reference instead of copying to a buffer
157 * @param file The file containing the RomFS 157 * @param romfs_file The file containing the RomFS
158 * @param offset The offset the romfs begins on
159 * @param size The size of the romfs
158 * @return ResultStatus result of function 160 * @return ResultStatus result of function
159 */ 161 */
160 virtual ResultStatus ReadRomFS(FileSys::VirtualFile& dir) { 162 virtual ResultStatus ReadRomFS(std::shared_ptr<FileUtil::IOFile>& romfs_file, u64& offset,
163 u64& size) {
161 return ResultStatus::ErrorNotImplemented; 164 return ResultStatus::ErrorNotImplemented;
162 } 165 }
163 166
164 /** 167 /**
165 * Get the update RomFS of the application 168 * Get the update RomFS of the application
166 * Since the RomFS can be huge, we return a file reference instead of copying to a buffer 169 * Since the RomFS can be huge, we return a file reference instead of copying to a buffer
167 * @param file The file containing the RomFS 170 * @param romfs_file The file containing the RomFS
171 * @param offset The offset the romfs begins on
172 * @param size The size of the romfs
168 * @return ResultStatus result of function 173 * @return ResultStatus result of function
169 */ 174 */
170 virtual ResultStatus ReadUpdateRomFS(FileSys::VirtualFile& file) { 175 virtual ResultStatus ReadUpdateRomFS(std::shared_ptr<FileUtil::IOFile>& romfs_file, u64& offset,
176 u64& size) {
171 return ResultStatus::ErrorNotImplemented; 177 return ResultStatus::ErrorNotImplemented;
172 } 178 }
173 179
@@ -181,7 +187,7 @@ public:
181 } 187 }
182 188
183protected: 189protected:
184 FileSys::VirtualFile file; 190 FileUtil::IOFile file;
185 bool is_loaded = false; 191 bool is_loaded = false;
186}; 192};
187 193
@@ -196,6 +202,6 @@ extern const std::initializer_list<Kernel::AddressMapping> default_address_mappi
196 * @param filename String filename of bootable file 202 * @param filename String filename of bootable file
197 * @return best loader for this file 203 * @return best loader for this file
198 */ 204 */
199std::unique_ptr<AppLoader> GetLoader(FileSys::VirtualFile file); 205std::unique_ptr<AppLoader> GetLoader(const std::string& filename);
200 206
201} // namespace Loader 207} // namespace Loader
diff --git a/src/core/loader/nca.cpp b/src/core/loader/nca.cpp
index 874f42b91..da064f8e3 100644
--- a/src/core/loader/nca.cpp
+++ b/src/core/loader/nca.cpp
@@ -4,11 +4,13 @@
4 4
5#include <vector> 5#include <vector>
6 6
7#include "common/common_funcs.h"
7#include "common/file_util.h" 8#include "common/file_util.h"
8#include "common/logging/log.h" 9#include "common/logging/log.h"
10#include "common/swap.h"
9#include "core/core.h" 11#include "core/core.h"
10#include "core/file_sys/content_archive.h"
11#include "core/file_sys/program_metadata.h" 12#include "core/file_sys/program_metadata.h"
13#include "core/file_sys/romfs_factory.h"
12#include "core/hle/kernel/process.h" 14#include "core/hle/kernel/process.h"
13#include "core/hle/kernel/resource_limit.h" 15#include "core/hle/kernel/resource_limit.h"
14#include "core/hle/service/filesystem/filesystem.h" 16#include "core/hle/service/filesystem/filesystem.h"
@@ -18,15 +20,208 @@
18 20
19namespace Loader { 21namespace Loader {
20 22
21AppLoader_NCA::AppLoader_NCA(FileSys::VirtualFile file) : AppLoader(file) {} 23// Media offsets in headers are stored divided by 512. Mult. by this to get real offset.
24constexpr u64 MEDIA_OFFSET_MULTIPLIER = 0x200;
22 25
23FileType AppLoader_NCA::IdentifyType(const FileSys::VirtualFile& file) { 26constexpr u64 SECTION_HEADER_SIZE = 0x200;
24 // TODO(DarkLordZach): Assuming everything is decrypted. Add crypto support. 27constexpr u64 SECTION_HEADER_OFFSET = 0x400;
25 FileSys::NCAHeader header{}; 28
26 if (sizeof(FileSys::NCAHeader) != file->ReadObject(&header)) 29enum class NcaContentType : u8 { Program = 0, Meta = 1, Control = 2, Manual = 3, Data = 4 };
30
31enum class NcaSectionFilesystemType : u8 { PFS0 = 0x2, ROMFS = 0x3 };
32
33struct NcaSectionTableEntry {
34 u32_le media_offset;
35 u32_le media_end_offset;
36 INSERT_PADDING_BYTES(0x8);
37};
38static_assert(sizeof(NcaSectionTableEntry) == 0x10, "NcaSectionTableEntry has incorrect size.");
39
40struct NcaHeader {
41 std::array<u8, 0x100> rsa_signature_1;
42 std::array<u8, 0x100> rsa_signature_2;
43 u32_le magic;
44 u8 is_system;
45 NcaContentType content_type;
46 u8 crypto_type;
47 u8 key_index;
48 u64_le size;
49 u64_le title_id;
50 INSERT_PADDING_BYTES(0x4);
51 u32_le sdk_version;
52 u8 crypto_type_2;
53 INSERT_PADDING_BYTES(15);
54 std::array<u8, 0x10> rights_id;
55 std::array<NcaSectionTableEntry, 0x4> section_tables;
56 std::array<std::array<u8, 0x20>, 0x4> hash_tables;
57 std::array<std::array<u8, 0x10>, 0x4> key_area;
58 INSERT_PADDING_BYTES(0xC0);
59};
60static_assert(sizeof(NcaHeader) == 0x400, "NcaHeader has incorrect size.");
61
62struct NcaSectionHeaderBlock {
63 INSERT_PADDING_BYTES(3);
64 NcaSectionFilesystemType filesystem_type;
65 u8 crypto_type;
66 INSERT_PADDING_BYTES(3);
67};
68static_assert(sizeof(NcaSectionHeaderBlock) == 0x8, "NcaSectionHeaderBlock has incorrect size.");
69
70struct Pfs0Superblock {
71 NcaSectionHeaderBlock header_block;
72 std::array<u8, 0x20> hash;
73 u32_le size;
74 INSERT_PADDING_BYTES(4);
75 u64_le hash_table_offset;
76 u64_le hash_table_size;
77 u64_le pfs0_header_offset;
78 u64_le pfs0_size;
79 INSERT_PADDING_BYTES(432);
80};
81static_assert(sizeof(Pfs0Superblock) == 0x200, "Pfs0Superblock has incorrect size.");
82
83static bool IsValidNca(const NcaHeader& header) {
84 return header.magic == Common::MakeMagic('N', 'C', 'A', '2') ||
85 header.magic == Common::MakeMagic('N', 'C', 'A', '3');
86}
87
88// TODO(DarkLordZach): Add support for encrypted.
89class Nca final {
90 std::vector<FileSys::PartitionFilesystem> pfs;
91 std::vector<u64> pfs_offset;
92
93 u64 romfs_offset = 0;
94 u64 romfs_size = 0;
95
96 boost::optional<u8> exefs_id = boost::none;
97
98 FileUtil::IOFile file;
99 std::string path;
100
101 u64 GetExeFsFileOffset(const std::string& file_name) const;
102 u64 GetExeFsFileSize(const std::string& file_name) const;
103
104public:
105 ResultStatus Load(FileUtil::IOFile&& file, std::string path);
106
107 FileSys::PartitionFilesystem GetPfs(u8 id) const;
108
109 u64 GetRomFsOffset() const;
110 u64 GetRomFsSize() const;
111
112 std::vector<u8> GetExeFsFile(const std::string& file_name);
113};
114
115static bool IsPfsExeFs(const FileSys::PartitionFilesystem& pfs) {
116 // According to switchbrew, an exefs must only contain these two files:
117 return pfs.GetFileSize("main") > 0 && pfs.GetFileSize("main.npdm") > 0;
118}
119
120ResultStatus Nca::Load(FileUtil::IOFile&& in_file, std::string in_path) {
121 file = std::move(in_file);
122 path = in_path;
123 file.Seek(0, SEEK_SET);
124 std::array<u8, sizeof(NcaHeader)> header_array{};
125 if (sizeof(NcaHeader) != file.ReadBytes(header_array.data(), sizeof(NcaHeader)))
126 LOG_CRITICAL(Loader, "File reader errored out during header read.");
127
128 NcaHeader header{};
129 std::memcpy(&header, header_array.data(), sizeof(NcaHeader));
130 if (!IsValidNca(header))
131 return ResultStatus::ErrorInvalidFormat;
132
133 int number_sections =
134 std::count_if(std::begin(header.section_tables), std::end(header.section_tables),
135 [](NcaSectionTableEntry entry) { return entry.media_offset > 0; });
136
137 for (int i = 0; i < number_sections; ++i) {
138 // Seek to beginning of this section.
139 file.Seek(SECTION_HEADER_OFFSET + i * SECTION_HEADER_SIZE, SEEK_SET);
140 std::array<u8, sizeof(NcaSectionHeaderBlock)> array{};
141 if (sizeof(NcaSectionHeaderBlock) !=
142 file.ReadBytes(array.data(), sizeof(NcaSectionHeaderBlock)))
143 LOG_CRITICAL(Loader, "File reader errored out during header read.");
144
145 NcaSectionHeaderBlock block{};
146 std::memcpy(&block, array.data(), sizeof(NcaSectionHeaderBlock));
147
148 if (block.filesystem_type == NcaSectionFilesystemType::ROMFS) {
149 romfs_offset = header.section_tables[i].media_offset * MEDIA_OFFSET_MULTIPLIER;
150 romfs_size =
151 header.section_tables[i].media_end_offset * MEDIA_OFFSET_MULTIPLIER - romfs_offset;
152 } else if (block.filesystem_type == NcaSectionFilesystemType::PFS0) {
153 Pfs0Superblock sb{};
154 // Seek back to beginning of this section.
155 file.Seek(SECTION_HEADER_OFFSET + i * SECTION_HEADER_SIZE, SEEK_SET);
156 if (sizeof(Pfs0Superblock) != file.ReadBytes(&sb, sizeof(Pfs0Superblock)))
157 LOG_CRITICAL(Loader, "File reader errored out during header read.");
158
159 u64 offset = (static_cast<u64>(header.section_tables[i].media_offset) *
160 MEDIA_OFFSET_MULTIPLIER) +
161 sb.pfs0_header_offset;
162 FileSys::PartitionFilesystem npfs{};
163 ResultStatus status = npfs.Load(path, offset);
164
165 if (status == ResultStatus::Success) {
166 pfs.emplace_back(std::move(npfs));
167 pfs_offset.emplace_back(offset);
168 }
169 }
170 }
171
172 for (size_t i = 0; i < pfs.size(); ++i) {
173 if (IsPfsExeFs(pfs[i]))
174 exefs_id = i;
175 }
176
177 return ResultStatus::Success;
178}
179
180FileSys::PartitionFilesystem Nca::GetPfs(u8 id) const {
181 return pfs[id];
182}
183
184u64 Nca::GetExeFsFileOffset(const std::string& file_name) const {
185 if (exefs_id == boost::none)
186 return 0;
187 return pfs[*exefs_id].GetFileOffset(file_name) + pfs_offset[*exefs_id];
188}
189
190u64 Nca::GetExeFsFileSize(const std::string& file_name) const {
191 if (exefs_id == boost::none)
192 return 0;
193 return pfs[*exefs_id].GetFileSize(file_name);
194}
195
196u64 Nca::GetRomFsOffset() const {
197 return romfs_offset;
198}
199
200u64 Nca::GetRomFsSize() const {
201 return romfs_size;
202}
203
204std::vector<u8> Nca::GetExeFsFile(const std::string& file_name) {
205 std::vector<u8> out(GetExeFsFileSize(file_name));
206 file.Seek(GetExeFsFileOffset(file_name), SEEK_SET);
207 file.ReadBytes(out.data(), GetExeFsFileSize(file_name));
208 return out;
209}
210
211AppLoader_NCA::AppLoader_NCA(FileUtil::IOFile&& file, std::string filepath)
212 : AppLoader(std::move(file)), filepath(std::move(filepath)) {}
213
214FileType AppLoader_NCA::IdentifyType(FileUtil::IOFile& file, const std::string&) {
215 file.Seek(0, SEEK_SET);
216 std::array<u8, 0x400> header_enc_array{};
217 if (0x400 != file.ReadBytes(header_enc_array.data(), 0x400))
27 return FileType::Error; 218 return FileType::Error;
28 219
29 if (IsValidNCA(header) && header.content_type == FileSys::NCAContentType::Program) 220 // TODO(DarkLordZach): Assuming everything is decrypted. Add crypto support.
221 NcaHeader header{};
222 std::memcpy(&header, header_enc_array.data(), sizeof(NcaHeader));
223
224 if (IsValidNca(header) && header.content_type == NcaContentType::Program)
30 return FileType::NCA; 225 return FileType::NCA;
31 226
32 return FileType::Error; 227 return FileType::Error;
@@ -36,22 +231,17 @@ ResultStatus AppLoader_NCA::Load(Kernel::SharedPtr<Kernel::Process>& process) {
36 if (is_loaded) { 231 if (is_loaded) {
37 return ResultStatus::ErrorAlreadyLoaded; 232 return ResultStatus::ErrorAlreadyLoaded;
38 } 233 }
234 if (!file.IsOpen()) {
235 return ResultStatus::Error;
236 }
39 237
40 nca = std::make_unique<FileSys::NCA>(file); 238 nca = std::make_unique<Nca>();
41 ResultStatus result = nca->GetStatus(); 239 ResultStatus result = nca->Load(std::move(file), filepath);
42 if (result != ResultStatus::Success) { 240 if (result != ResultStatus::Success) {
43 return result; 241 return result;
44 } 242 }
45 243
46 if (nca->GetType() != FileSys::NCAContentType::Program) 244 result = metadata.Load(nca->GetExeFsFile("main.npdm"));
47 return ResultStatus::ErrorInvalidFormat;
48
49 auto exefs = nca->GetExeFS();
50
51 if (exefs == nullptr)
52 return ResultStatus::ErrorInvalidFormat;
53
54 result = metadata.Load(exefs->GetFile("main.npdm"));
55 if (result != ResultStatus::Success) { 245 if (result != ResultStatus::Success) {
56 return result; 246 return result;
57 } 247 }
@@ -66,8 +256,7 @@ ResultStatus AppLoader_NCA::Load(Kernel::SharedPtr<Kernel::Process>& process) {
66 for (const auto& module : {"rtld", "main", "subsdk0", "subsdk1", "subsdk2", "subsdk3", 256 for (const auto& module : {"rtld", "main", "subsdk0", "subsdk1", "subsdk2", "subsdk3",
67 "subsdk4", "subsdk5", "subsdk6", "subsdk7", "sdk"}) { 257 "subsdk4", "subsdk5", "subsdk6", "subsdk7", "sdk"}) {
68 const VAddr load_addr = next_load_addr; 258 const VAddr load_addr = next_load_addr;
69 259 next_load_addr = AppLoader_NSO::LoadModule(module, nca->GetExeFsFile(module), load_addr);
70 next_load_addr = AppLoader_NSO::LoadModule(exefs->GetFile(module), load_addr);
71 if (next_load_addr) { 260 if (next_load_addr) {
72 LOG_DEBUG(Loader, "loaded module {} @ 0x{:X}", module, load_addr); 261 LOG_DEBUG(Loader, "loaded module {} @ 0x{:X}", module, load_addr);
73 } else { 262 } else {
@@ -83,11 +272,28 @@ ResultStatus AppLoader_NCA::Load(Kernel::SharedPtr<Kernel::Process>& process) {
83 process->Run(Memory::PROCESS_IMAGE_VADDR, metadata.GetMainThreadPriority(), 272 process->Run(Memory::PROCESS_IMAGE_VADDR, metadata.GetMainThreadPriority(),
84 metadata.GetMainThreadStackSize()); 273 metadata.GetMainThreadStackSize());
85 274
275 if (nca->GetRomFsSize() > 0)
276 Service::FileSystem::RegisterFileSystem(std::make_unique<FileSys::RomFS_Factory>(*this),
277 Service::FileSystem::Type::RomFS);
278
86 is_loaded = true; 279 is_loaded = true;
280 return ResultStatus::Success;
281}
282
283ResultStatus AppLoader_NCA::ReadRomFS(std::shared_ptr<FileUtil::IOFile>& romfs_file, u64& offset,
284 u64& size) {
285 if (nca->GetRomFsSize() == 0) {
286 LOG_DEBUG(Loader, "No RomFS available");
287 return ResultStatus::ErrorNotUsed;
288 }
289
290 romfs_file = std::make_shared<FileUtil::IOFile>(filepath, "rb");
291
292 offset = nca->GetRomFsOffset();
293 size = nca->GetRomFsSize();
87 294
88 const auto romfs = nca->GetRomFS(); 295 LOG_DEBUG(Loader, "RomFS offset: 0x{:016X}", offset);
89 if (romfs != nullptr) 296 LOG_DEBUG(Loader, "RomFS size: 0x{:016X}", size);
90 Service::FileSystem::RegisterRomFS(romfs);
91 297
92 return ResultStatus::Success; 298 return ResultStatus::Success;
93} 299}
diff --git a/src/core/loader/nca.h b/src/core/loader/nca.h
index a5639f149..3b6c451d0 100644
--- a/src/core/loader/nca.h
+++ b/src/core/loader/nca.h
@@ -6,37 +6,44 @@
6 6
7#include <string> 7#include <string>
8#include "common/common_types.h" 8#include "common/common_types.h"
9#include "core/file_sys/content_archive.h" 9#include "core/file_sys/partition_filesystem.h"
10#include "core/file_sys/program_metadata.h" 10#include "core/file_sys/program_metadata.h"
11#include "core/hle/kernel/kernel.h" 11#include "core/hle/kernel/kernel.h"
12#include "core/loader/loader.h" 12#include "core/loader/loader.h"
13 13
14namespace Loader { 14namespace Loader {
15 15
16class Nca;
17
16/// Loads an NCA file 18/// Loads an NCA file
17class AppLoader_NCA final : public AppLoader { 19class AppLoader_NCA final : public AppLoader {
18public: 20public:
19 explicit AppLoader_NCA(FileSys::VirtualFile file); 21 AppLoader_NCA(FileUtil::IOFile&& file, std::string filepath);
20 22
21 /** 23 /**
22 * Returns the type of the file 24 * Returns the type of the file
23 * @param file std::shared_ptr<VfsFile> open file 25 * @param file FileUtil::IOFile open file
26 * @param filepath Path of the file that we are opening.
24 * @return FileType found, or FileType::Error if this loader doesn't know it 27 * @return FileType found, or FileType::Error if this loader doesn't know it
25 */ 28 */
26 static FileType IdentifyType(const FileSys::VirtualFile& file); 29 static FileType IdentifyType(FileUtil::IOFile& file, const std::string& filepath);
27 30
28 FileType GetFileType() override { 31 FileType GetFileType() override {
29 return IdentifyType(file); 32 return IdentifyType(file, filepath);
30 } 33 }
31 34
32 ResultStatus Load(Kernel::SharedPtr<Kernel::Process>& process) override; 35 ResultStatus Load(Kernel::SharedPtr<Kernel::Process>& process) override;
33 36
37 ResultStatus ReadRomFS(std::shared_ptr<FileUtil::IOFile>& romfs_file, u64& offset,
38 u64& size) override;
39
34 ~AppLoader_NCA(); 40 ~AppLoader_NCA();
35 41
36private: 42private:
43 std::string filepath;
37 FileSys::ProgramMetadata metadata; 44 FileSys::ProgramMetadata metadata;
38 45
39 std::unique_ptr<FileSys::NCA> nca; 46 std::unique_ptr<Nca> nca;
40}; 47};
41 48
42} // namespace Loader 49} // namespace Loader
diff --git a/src/core/loader/nro.cpp b/src/core/loader/nro.cpp
index 08b7aad7a..3853cfa1a 100644
--- a/src/core/loader/nro.cpp
+++ b/src/core/loader/nro.cpp
@@ -47,12 +47,14 @@ struct ModHeader {
47}; 47};
48static_assert(sizeof(ModHeader) == 0x1c, "ModHeader has incorrect size."); 48static_assert(sizeof(ModHeader) == 0x1c, "ModHeader has incorrect size.");
49 49
50AppLoader_NRO::AppLoader_NRO(FileSys::VirtualFile file) : AppLoader(file) {} 50AppLoader_NRO::AppLoader_NRO(FileUtil::IOFile&& file, std::string filepath)
51 : AppLoader(std::move(file)), filepath(std::move(filepath)) {}
51 52
52FileType AppLoader_NRO::IdentifyType(const FileSys::VirtualFile& file) { 53FileType AppLoader_NRO::IdentifyType(FileUtil::IOFile& file, const std::string&) {
53 // Read NSO header 54 // Read NSO header
54 NroHeader nro_header{}; 55 NroHeader nro_header{};
55 if (sizeof(NroHeader) != file->ReadObject(&nro_header)) { 56 file.Seek(0, SEEK_SET);
57 if (sizeof(NroHeader) != file.ReadBytes(&nro_header, sizeof(NroHeader))) {
56 return FileType::Error; 58 return FileType::Error;
57 } 59 }
58 if (nro_header.magic == Common::MakeMagic('N', 'R', 'O', '0')) { 60 if (nro_header.magic == Common::MakeMagic('N', 'R', 'O', '0')) {
@@ -65,10 +67,16 @@ static constexpr u32 PageAlignSize(u32 size) {
65 return (size + Memory::PAGE_MASK) & ~Memory::PAGE_MASK; 67 return (size + Memory::PAGE_MASK) & ~Memory::PAGE_MASK;
66} 68}
67 69
68bool AppLoader_NRO::LoadNro(FileSys::VirtualFile file, VAddr load_base) { 70bool AppLoader_NRO::LoadNro(const std::string& path, VAddr load_base) {
71 FileUtil::IOFile file(path, "rb");
72 if (!file.IsOpen()) {
73 return {};
74 }
75
69 // Read NSO header 76 // Read NSO header
70 NroHeader nro_header{}; 77 NroHeader nro_header{};
71 if (sizeof(NroHeader) != file->ReadObject(&nro_header)) { 78 file.Seek(0, SEEK_SET);
79 if (sizeof(NroHeader) != file.ReadBytes(&nro_header, sizeof(NroHeader))) {
72 return {}; 80 return {};
73 } 81 }
74 if (nro_header.magic != Common::MakeMagic('N', 'R', 'O', '0')) { 82 if (nro_header.magic != Common::MakeMagic('N', 'R', 'O', '0')) {
@@ -77,9 +85,10 @@ bool AppLoader_NRO::LoadNro(FileSys::VirtualFile file, VAddr load_base) {
77 85
78 // Build program image 86 // Build program image
79 Kernel::SharedPtr<Kernel::CodeSet> codeset = Kernel::CodeSet::Create(""); 87 Kernel::SharedPtr<Kernel::CodeSet> codeset = Kernel::CodeSet::Create("");
80 std::vector<u8> program_image = file->ReadBytes(PageAlignSize(nro_header.file_size)); 88 std::vector<u8> program_image;
81 if (program_image.size() != PageAlignSize(nro_header.file_size)) 89 program_image.resize(PageAlignSize(nro_header.file_size));
82 return {}; 90 file.Seek(0, SEEK_SET);
91 file.ReadBytes(program_image.data(), nro_header.file_size);
83 92
84 for (int i = 0; i < nro_header.segments.size(); ++i) { 93 for (int i = 0; i < nro_header.segments.size(); ++i) {
85 codeset->segments[i].addr = nro_header.segments[i].offset; 94 codeset->segments[i].addr = nro_header.segments[i].offset;
@@ -102,7 +111,7 @@ bool AppLoader_NRO::LoadNro(FileSys::VirtualFile file, VAddr load_base) {
102 program_image.resize(static_cast<u32>(program_image.size()) + bss_size); 111 program_image.resize(static_cast<u32>(program_image.size()) + bss_size);
103 112
104 // Load codeset for current process 113 // Load codeset for current process
105 codeset->name = file->GetName(); 114 codeset->name = path;
106 codeset->memory = std::make_shared<std::vector<u8>>(std::move(program_image)); 115 codeset->memory = std::make_shared<std::vector<u8>>(std::move(program_image));
107 Core::CurrentProcess()->LoadModule(codeset, load_base); 116 Core::CurrentProcess()->LoadModule(codeset, load_base);
108 117
@@ -113,11 +122,14 @@ ResultStatus AppLoader_NRO::Load(Kernel::SharedPtr<Kernel::Process>& process) {
113 if (is_loaded) { 122 if (is_loaded) {
114 return ResultStatus::ErrorAlreadyLoaded; 123 return ResultStatus::ErrorAlreadyLoaded;
115 } 124 }
125 if (!file.IsOpen()) {
126 return ResultStatus::Error;
127 }
116 128
117 // Load NRO 129 // Load NRO
118 static constexpr VAddr base_addr{Memory::PROCESS_IMAGE_VADDR}; 130 static constexpr VAddr base_addr{Memory::PROCESS_IMAGE_VADDR};
119 131
120 if (!LoadNro(file, base_addr)) { 132 if (!LoadNro(filepath, base_addr)) {
121 return ResultStatus::ErrorInvalidFormat; 133 return ResultStatus::ErrorInvalidFormat;
122 } 134 }
123 135
diff --git a/src/core/loader/nro.h b/src/core/loader/nro.h
index 2c03d06bb..599adb253 100644
--- a/src/core/loader/nro.h
+++ b/src/core/loader/nro.h
@@ -15,23 +15,26 @@ namespace Loader {
15/// Loads an NRO file 15/// Loads an NRO file
16class AppLoader_NRO final : public AppLoader, Linker { 16class AppLoader_NRO final : public AppLoader, Linker {
17public: 17public:
18 AppLoader_NRO(FileSys::VirtualFile file); 18 AppLoader_NRO(FileUtil::IOFile&& file, std::string filepath);
19 19
20 /** 20 /**
21 * Returns the type of the file 21 * Returns the type of the file
22 * @param file std::shared_ptr<VfsFile> open file 22 * @param file FileUtil::IOFile open file
23 * @param filepath Path of the file that we are opening.
23 * @return FileType found, or FileType::Error if this loader doesn't know it 24 * @return FileType found, or FileType::Error if this loader doesn't know it
24 */ 25 */
25 static FileType IdentifyType(const FileSys::VirtualFile& file); 26 static FileType IdentifyType(FileUtil::IOFile& file, const std::string& filepath);
26 27
27 FileType GetFileType() override { 28 FileType GetFileType() override {
28 return IdentifyType(file); 29 return IdentifyType(file, filepath);
29 } 30 }
30 31
31 ResultStatus Load(Kernel::SharedPtr<Kernel::Process>& process) override; 32 ResultStatus Load(Kernel::SharedPtr<Kernel::Process>& process) override;
32 33
33private: 34private:
34 bool LoadNro(FileSys::VirtualFile file, VAddr load_base); 35 bool LoadNro(const std::string& path, VAddr load_base);
36
37 std::string filepath;
35}; 38};
36 39
37} // namespace Loader 40} // namespace Loader
diff --git a/src/core/loader/nso.cpp b/src/core/loader/nso.cpp
index 2ed12a5ab..7f84e4b1b 100644
--- a/src/core/loader/nso.cpp
+++ b/src/core/loader/nso.cpp
@@ -37,7 +37,6 @@ struct NsoHeader {
37 std::array<u32_le, 3> segments_compressed_size; 37 std::array<u32_le, 3> segments_compressed_size;
38}; 38};
39static_assert(sizeof(NsoHeader) == 0x6c, "NsoHeader has incorrect size."); 39static_assert(sizeof(NsoHeader) == 0x6c, "NsoHeader has incorrect size.");
40static_assert(std::is_trivially_copyable_v<NsoHeader>, "NsoHeader isn't trivially copyable.");
41 40
42struct ModHeader { 41struct ModHeader {
43 u32_le magic; 42 u32_le magic;
@@ -50,11 +49,15 @@ struct ModHeader {
50}; 49};
51static_assert(sizeof(ModHeader) == 0x1c, "ModHeader has incorrect size."); 50static_assert(sizeof(ModHeader) == 0x1c, "ModHeader has incorrect size.");
52 51
53AppLoader_NSO::AppLoader_NSO(FileSys::VirtualFile file) : AppLoader(std::move(file)) {} 52AppLoader_NSO::AppLoader_NSO(FileUtil::IOFile&& file, std::string filepath)
53 : AppLoader(std::move(file)), filepath(std::move(filepath)) {}
54 54
55FileType AppLoader_NSO::IdentifyType(const FileSys::VirtualFile& file) { 55FileType AppLoader_NSO::IdentifyType(FileUtil::IOFile& file, const std::string&) {
56 u32 magic = 0; 56 u32 magic = 0;
57 file->ReadObject(&magic); 57 file.Seek(0, SEEK_SET);
58 if (1 != file.ReadArray<u32>(&magic, 1)) {
59 return FileType::Error;
60 }
58 61
59 if (Common::MakeMagic('N', 'S', 'O', '0') == magic) { 62 if (Common::MakeMagic('N', 'S', 'O', '0') == magic) {
60 return FileType::NSO; 63 return FileType::NSO;
@@ -95,27 +98,80 @@ static constexpr u32 PageAlignSize(u32 size) {
95 return (size + Memory::PAGE_MASK) & ~Memory::PAGE_MASK; 98 return (size + Memory::PAGE_MASK) & ~Memory::PAGE_MASK;
96} 99}
97 100
98VAddr AppLoader_NSO::LoadModule(FileSys::VirtualFile file, VAddr load_base) { 101VAddr AppLoader_NSO::LoadModule(const std::string& name, const std::vector<u8>& file_data,
99 if (file == nullptr) 102 VAddr load_base) {
103 if (file_data.size() < sizeof(NsoHeader))
100 return {}; 104 return {};
101 105
102 if (file->GetSize() < sizeof(NsoHeader)) 106 NsoHeader nso_header;
107 std::memcpy(&nso_header, file_data.data(), sizeof(NsoHeader));
108
109 if (nso_header.magic != Common::MakeMagic('N', 'S', 'O', '0'))
103 return {}; 110 return {};
104 111
105 NsoHeader nso_header{}; 112 // Build program image
106 if (sizeof(NsoHeader) != file->ReadObject(&nso_header)) 113 Kernel::SharedPtr<Kernel::CodeSet> codeset = Kernel::CodeSet::Create("");
114 std::vector<u8> program_image;
115 for (int i = 0; i < nso_header.segments.size(); ++i) {
116 std::vector<u8> compressed_data(nso_header.segments_compressed_size[i]);
117 for (int j = 0; j < nso_header.segments_compressed_size[i]; ++j)
118 compressed_data[j] = file_data[nso_header.segments[i].offset + j];
119 std::vector<u8> data = DecompressSegment(compressed_data, nso_header.segments[i]);
120 program_image.resize(nso_header.segments[i].location);
121 program_image.insert(program_image.end(), data.begin(), data.end());
122 codeset->segments[i].addr = nso_header.segments[i].location;
123 codeset->segments[i].offset = nso_header.segments[i].location;
124 codeset->segments[i].size = PageAlignSize(static_cast<u32>(data.size()));
125 }
126
127 // MOD header pointer is at .text offset + 4
128 u32 module_offset;
129 std::memcpy(&module_offset, program_image.data() + 4, sizeof(u32));
130
131 // Read MOD header
132 ModHeader mod_header{};
133 // Default .bss to size in segment header if MOD0 section doesn't exist
134 u32 bss_size{PageAlignSize(nso_header.segments[2].bss_size)};
135 std::memcpy(&mod_header, program_image.data() + module_offset, sizeof(ModHeader));
136 const bool has_mod_header{mod_header.magic == Common::MakeMagic('M', 'O', 'D', '0')};
137 if (has_mod_header) {
138 // Resize program image to include .bss section and page align each section
139 bss_size = PageAlignSize(mod_header.bss_end_offset - mod_header.bss_start_offset);
140 }
141 codeset->data.size += bss_size;
142 const u32 image_size{PageAlignSize(static_cast<u32>(program_image.size()) + bss_size)};
143 program_image.resize(image_size);
144
145 // Load codeset for current process
146 codeset->name = name;
147 codeset->memory = std::make_shared<std::vector<u8>>(std::move(program_image));
148 Core::CurrentProcess()->LoadModule(codeset, load_base);
149
150 return load_base + image_size;
151}
152
153VAddr AppLoader_NSO::LoadModule(const std::string& path, VAddr load_base) {
154 FileUtil::IOFile file(path, "rb");
155 if (!file.IsOpen()) {
107 return {}; 156 return {};
157 }
108 158
109 if (nso_header.magic != Common::MakeMagic('N', 'S', 'O', '0')) 159 // Read NSO header
160 NsoHeader nso_header{};
161 file.Seek(0, SEEK_SET);
162 if (sizeof(NsoHeader) != file.ReadBytes(&nso_header, sizeof(NsoHeader))) {
163 return {};
164 }
165 if (nso_header.magic != Common::MakeMagic('N', 'S', 'O', '0')) {
110 return {}; 166 return {};
167 }
111 168
112 // Build program image 169 // Build program image
113 Kernel::SharedPtr<Kernel::CodeSet> codeset = Kernel::CodeSet::Create(""); 170 Kernel::SharedPtr<Kernel::CodeSet> codeset = Kernel::CodeSet::Create("");
114 std::vector<u8> program_image; 171 std::vector<u8> program_image;
115 for (int i = 0; i < nso_header.segments.size(); ++i) { 172 for (int i = 0; i < nso_header.segments.size(); ++i) {
116 const std::vector<u8> compressed_data = 173 std::vector<u8> data =
117 file->ReadBytes(nso_header.segments_compressed_size[i], nso_header.segments[i].offset); 174 ReadSegment(file, nso_header.segments[i], nso_header.segments_compressed_size[i]);
118 std::vector<u8> data = DecompressSegment(compressed_data, nso_header.segments[i]);
119 program_image.resize(nso_header.segments[i].location); 175 program_image.resize(nso_header.segments[i].location);
120 program_image.insert(program_image.end(), data.begin(), data.end()); 176 program_image.insert(program_image.end(), data.begin(), data.end());
121 codeset->segments[i].addr = nso_header.segments[i].location; 177 codeset->segments[i].addr = nso_header.segments[i].location;
@@ -142,7 +198,7 @@ VAddr AppLoader_NSO::LoadModule(FileSys::VirtualFile file, VAddr load_base) {
142 program_image.resize(image_size); 198 program_image.resize(image_size);
143 199
144 // Load codeset for current process 200 // Load codeset for current process
145 codeset->name = file->GetName(); 201 codeset->name = path;
146 codeset->memory = std::make_shared<std::vector<u8>>(std::move(program_image)); 202 codeset->memory = std::make_shared<std::vector<u8>>(std::move(program_image));
147 Core::CurrentProcess()->LoadModule(codeset, load_base); 203 Core::CurrentProcess()->LoadModule(codeset, load_base);
148 204
@@ -153,10 +209,13 @@ ResultStatus AppLoader_NSO::Load(Kernel::SharedPtr<Kernel::Process>& process) {
153 if (is_loaded) { 209 if (is_loaded) {
154 return ResultStatus::ErrorAlreadyLoaded; 210 return ResultStatus::ErrorAlreadyLoaded;
155 } 211 }
212 if (!file.IsOpen()) {
213 return ResultStatus::Error;
214 }
156 215
157 // Load module 216 // Load module
158 LoadModule(file, Memory::PROCESS_IMAGE_VADDR); 217 LoadModule(filepath, Memory::PROCESS_IMAGE_VADDR);
159 LOG_DEBUG(Loader, "loaded module {} @ 0x{:X}", file->GetName(), Memory::PROCESS_IMAGE_VADDR); 218 LOG_DEBUG(Loader, "loaded module {} @ 0x{:X}", filepath, Memory::PROCESS_IMAGE_VADDR);
160 219
161 process->svc_access_mask.set(); 220 process->svc_access_mask.set();
162 process->address_mappings = default_address_mappings; 221 process->address_mappings = default_address_mappings;
diff --git a/src/core/loader/nso.h b/src/core/loader/nso.h
index 3f7567500..386f4d39a 100644
--- a/src/core/loader/nso.h
+++ b/src/core/loader/nso.h
@@ -15,22 +15,29 @@ namespace Loader {
15/// Loads an NSO file 15/// Loads an NSO file
16class AppLoader_NSO final : public AppLoader, Linker { 16class AppLoader_NSO final : public AppLoader, Linker {
17public: 17public:
18 explicit AppLoader_NSO(FileSys::VirtualFile file); 18 AppLoader_NSO(FileUtil::IOFile&& file, std::string filepath);
19 19
20 /** 20 /**
21 * Returns the type of the file 21 * Returns the type of the file
22 * @param file std::shared_ptr<VfsFile> open file 22 * @param file FileUtil::IOFile open file
23 * @param filepath Path of the file that we are opening.
23 * @return FileType found, or FileType::Error if this loader doesn't know it 24 * @return FileType found, or FileType::Error if this loader doesn't know it
24 */ 25 */
25 static FileType IdentifyType(const FileSys::VirtualFile& file); 26 static FileType IdentifyType(FileUtil::IOFile& file, const std::string& filepath);
26 27
27 FileType GetFileType() override { 28 FileType GetFileType() override {
28 return IdentifyType(file); 29 return IdentifyType(file, filepath);
29 } 30 }
30 31
31 static VAddr LoadModule(FileSys::VirtualFile file, VAddr load_base); 32 static VAddr LoadModule(const std::string& name, const std::vector<u8>& file_data,
33 VAddr load_base);
34
35 static VAddr LoadModule(const std::string& path, VAddr load_base);
32 36
33 ResultStatus Load(Kernel::SharedPtr<Kernel::Process>& process) override; 37 ResultStatus Load(Kernel::SharedPtr<Kernel::Process>& process) override;
38
39private:
40 std::string filepath;
34}; 41};
35 42
36} // namespace Loader 43} // namespace Loader