1 // Copyright 2014 Citra Emulator Project
2 // Licensed under GPLv2 or any later version
3 // Refer to the license.txt file included.
4 
5 #include <algorithm>
6 #include <cinttypes>
7 #include <memory>
8 #include <utility>
9 #include <vector>
10 #include "bad_word_list.app.romfs.h"
11 #include "common/archives.h"
12 #include "common/common_types.h"
13 #include "common/file_util.h"
14 #include "common/logging/log.h"
15 #include "common/string_util.h"
16 #include "common/swap.h"
17 #include "core/core.h"
18 #include "core/file_sys/archive_ncch.h"
19 #include "core/file_sys/errors.h"
20 #include "core/file_sys/ivfc_archive.h"
21 #include "core/file_sys/ncch_container.h"
22 #include "core/hle/service/am/am.h"
23 #include "core/hle/service/fs/archive.h"
24 #include "core/loader/loader.h"
25 #include "country_list.app.romfs.h"
26 #include "mii.app.romfs.h"
27 #include "shared_font.app.romfs.h"
28 
29 ////////////////////////////////////////////////////////////////////////////////////////////////////
30 // FileSys namespace
31 
32 SERIALIZE_EXPORT_IMPL(FileSys::NCCHArchive)
33 SERIALIZE_EXPORT_IMPL(FileSys::NCCHFile)
34 SERIALIZE_EXPORT_IMPL(FileSys::ArchiveFactory_NCCH)
35 
36 namespace FileSys {
37 
38 struct NCCHArchivePath {
39     u64_le tid;
40     u32_le media_type;
41     u32_le unknown;
42 };
43 static_assert(sizeof(NCCHArchivePath) == 0x10, "NCCHArchivePath has wrong size!");
44 
45 struct NCCHFilePath {
46     enum_le<NCCHFileOpenType> open_type;
47     u32_le content_index;
48     enum_le<NCCHFilePathType> filepath_type;
49     std::array<char, 8> exefs_filepath;
50 };
51 static_assert(sizeof(NCCHFilePath) == 0x14, "NCCHFilePath has wrong size!");
52 
MakeNCCHArchivePath(u64 tid,Service::FS::MediaType media_type)53 Path MakeNCCHArchivePath(u64 tid, Service::FS::MediaType media_type) {
54     NCCHArchivePath path;
55     path.tid = static_cast<u64_le>(tid);
56     path.media_type = static_cast<u32_le>(media_type);
57     path.unknown = 0;
58     std::vector<u8> archive(sizeof(path));
59     std::memcpy(archive.data(), &path, sizeof(path));
60     return FileSys::Path(std::move(archive));
61 }
62 
MakeNCCHFilePath(NCCHFileOpenType open_type,u32 content_index,NCCHFilePathType filepath_type,std::array<char,8> & exefs_filepath)63 Path MakeNCCHFilePath(NCCHFileOpenType open_type, u32 content_index, NCCHFilePathType filepath_type,
64                       std::array<char, 8>& exefs_filepath) {
65     NCCHFilePath path;
66     path.open_type = open_type;
67     path.content_index = static_cast<u32_le>(content_index);
68     path.filepath_type = filepath_type;
69     path.exefs_filepath = exefs_filepath;
70     std::vector<u8> file(sizeof(path));
71     std::memcpy(file.data(), &path, sizeof(path));
72     return FileSys::Path(std::move(file));
73 }
74 
OpenFile(const Path & path,const Mode & mode) const75 ResultVal<std::unique_ptr<FileBackend>> NCCHArchive::OpenFile(const Path& path,
76                                                               const Mode& mode) const {
77     if (path.GetType() != LowPathType::Binary) {
78         LOG_ERROR(Service_FS, "Path need to be Binary");
79         return ERROR_INVALID_PATH;
80     }
81 
82     std::vector<u8> binary = path.AsBinary();
83     if (binary.size() != sizeof(NCCHFilePath)) {
84         LOG_ERROR(Service_FS, "Wrong path size {}", binary.size());
85         return ERROR_INVALID_PATH;
86     }
87 
88     NCCHFilePath openfile_path;
89     std::memcpy(&openfile_path, binary.data(), sizeof(NCCHFilePath));
90 
91     std::string file_path =
92         Service::AM::GetTitleContentPath(media_type, title_id, openfile_path.content_index);
93     auto ncch_container = NCCHContainer(file_path, 0, openfile_path.content_index);
94 
95     Loader::ResultStatus result;
96     std::unique_ptr<FileBackend> file;
97 
98     // NCCH RomFS
99     if (openfile_path.filepath_type == NCCHFilePathType::RomFS) {
100         std::shared_ptr<RomFSReader> romfs_file;
101 
102         result = ncch_container.ReadRomFS(romfs_file);
103         std::unique_ptr<DelayGenerator> delay_generator = std::make_unique<RomFSDelayGenerator>();
104         file = std::make_unique<IVFCFile>(std::move(romfs_file), std::move(delay_generator));
105     } else if (openfile_path.filepath_type == NCCHFilePathType::Code ||
106                openfile_path.filepath_type == NCCHFilePathType::ExeFS) {
107         std::vector<u8> buffer;
108 
109         // Load NCCH .code or icon/banner/logo
110         result = ncch_container.LoadSectionExeFS(openfile_path.exefs_filepath.data(), buffer);
111         std::unique_ptr<DelayGenerator> delay_generator = std::make_unique<ExeFSDelayGenerator>();
112         file = std::make_unique<NCCHFile>(std::move(buffer), std::move(delay_generator));
113     } else {
114         LOG_ERROR(Service_FS, "Unknown NCCH archive type {}!", openfile_path.filepath_type);
115         result = Loader::ResultStatus::Error;
116     }
117 
118     if (result != Loader::ResultStatus::Success) {
119         // High Title ID of the archive: The category (https://3dbrew.org/wiki/Title_list).
120         constexpr u32 shared_data_archive = 0x0004009B;
121         constexpr u32 system_data_archive = 0x000400DB;
122 
123         // Low Title IDs.
124         constexpr u32 mii_data = 0x00010202;
125         constexpr u32 region_manifest = 0x00010402;
126         constexpr u32 ng_word_list = 0x00010302;
127         constexpr u32 shared_font = 0x00014002;
128 
129         u32 high = static_cast<u32>(title_id >> 32);
130         u32 low = static_cast<u32>(title_id & 0xFFFFFFFF);
131 
132         LOG_DEBUG(Service_FS, "Full Path: {}. Category: 0x{:X}. Path: 0x{:X}.", path.DebugStr(),
133                   high, low);
134 
135         std::vector<u8> archive_data;
136         if (high == shared_data_archive) {
137             if (low == mii_data) {
138                 LOG_WARNING(Service_FS,
139                             "Mii data file missing. Loading open source replacement from memory");
140                 archive_data = std::vector<u8>(std::begin(MII_DATA), std::end(MII_DATA));
141             } else if (low == region_manifest) {
142                 LOG_WARNING(
143                     Service_FS,
144                     "Country list file missing. Loading open source replacement from memory");
145                 archive_data =
146                     std::vector<u8>(std::begin(COUNTRY_LIST_DATA), std::end(COUNTRY_LIST_DATA));
147             } else if (low == shared_font) {
148                 LOG_WARNING(
149                     Service_FS,
150                     "Shared Font file missing. Loading open source replacement from memory");
151                 archive_data =
152                     std::vector<u8>(std::begin(SHARED_FONT_DATA), std::end(SHARED_FONT_DATA));
153             }
154         } else if (high == system_data_archive) {
155             if (low == ng_word_list) {
156                 LOG_WARNING(
157                     Service_FS,
158                     "Bad Word List file missing. Loading open source replacement from memory");
159                 archive_data =
160                     std::vector<u8>(std::begin(BAD_WORD_LIST_DATA), std::end(BAD_WORD_LIST_DATA));
161             }
162         }
163 
164         if (!archive_data.empty()) {
165             u64 romfs_offset = 0;
166             u64 romfs_size = archive_data.size();
167             std::unique_ptr<DelayGenerator> delay_generator =
168                 std::make_unique<RomFSDelayGenerator>();
169             file = std::make_unique<IVFCFileInMemory>(std::move(archive_data), romfs_offset,
170                                                       romfs_size, std::move(delay_generator));
171             return MakeResult<std::unique_ptr<FileBackend>>(std::move(file));
172         }
173         return ERROR_NOT_FOUND;
174     }
175 
176     return MakeResult<std::unique_ptr<FileBackend>>(std::move(file));
177 }
178 
DeleteFile(const Path & path) const179 ResultCode NCCHArchive::DeleteFile(const Path& path) const {
180     LOG_CRITICAL(Service_FS, "Attempted to delete a file from an NCCH archive ({}).", GetName());
181     // TODO(Subv): Verify error code
182     return ResultCode(ErrorDescription::NoData, ErrorModule::FS, ErrorSummary::Canceled,
183                       ErrorLevel::Status);
184 }
185 
RenameFile(const Path & src_path,const Path & dest_path) const186 ResultCode NCCHArchive::RenameFile(const Path& src_path, const Path& dest_path) const {
187     LOG_CRITICAL(Service_FS, "Attempted to rename a file within an NCCH archive ({}).", GetName());
188     // TODO(wwylele): Use correct error code
189     return ResultCode(-1);
190 }
191 
DeleteDirectory(const Path & path) const192 ResultCode NCCHArchive::DeleteDirectory(const Path& path) const {
193     LOG_CRITICAL(Service_FS, "Attempted to delete a directory from an NCCH archive ({}).",
194                  GetName());
195     // TODO(wwylele): Use correct error code
196     return ResultCode(-1);
197 }
198 
DeleteDirectoryRecursively(const Path & path) const199 ResultCode NCCHArchive::DeleteDirectoryRecursively(const Path& path) const {
200     LOG_CRITICAL(Service_FS, "Attempted to delete a directory from an NCCH archive ({}).",
201                  GetName());
202     // TODO(wwylele): Use correct error code
203     return ResultCode(-1);
204 }
205 
CreateFile(const Path & path,u64 size) const206 ResultCode NCCHArchive::CreateFile(const Path& path, u64 size) const {
207     LOG_CRITICAL(Service_FS, "Attempted to create a file in an NCCH archive ({}).", GetName());
208     // TODO: Verify error code
209     return ResultCode(ErrorDescription::NotAuthorized, ErrorModule::FS, ErrorSummary::NotSupported,
210                       ErrorLevel::Permanent);
211 }
212 
CreateDirectory(const Path & path) const213 ResultCode NCCHArchive::CreateDirectory(const Path& path) const {
214     LOG_CRITICAL(Service_FS, "Attempted to create a directory in an NCCH archive ({}).", GetName());
215     // TODO(wwylele): Use correct error code
216     return ResultCode(-1);
217 }
218 
RenameDirectory(const Path & src_path,const Path & dest_path) const219 ResultCode NCCHArchive::RenameDirectory(const Path& src_path, const Path& dest_path) const {
220     LOG_CRITICAL(Service_FS, "Attempted to rename a file within an NCCH archive ({}).", GetName());
221     // TODO(wwylele): Use correct error code
222     return ResultCode(-1);
223 }
224 
OpenDirectory(const Path & path) const225 ResultVal<std::unique_ptr<DirectoryBackend>> NCCHArchive::OpenDirectory(const Path& path) const {
226     LOG_CRITICAL(Service_FS, "Attempted to open a directory within an NCCH archive ({}).",
227                  GetName().c_str());
228     // TODO(shinyquagsire23): Use correct error code
229     return ResultCode(-1);
230 }
231 
GetFreeBytes() const232 u64 NCCHArchive::GetFreeBytes() const {
233     LOG_WARNING(Service_FS, "Attempted to get the free space in an NCCH archive");
234     return 0;
235 }
236 
237 ////////////////////////////////////////////////////////////////////////////////////////////////////
238 
NCCHFile(std::vector<u8> buffer,std::unique_ptr<DelayGenerator> delay_generator_)239 NCCHFile::NCCHFile(std::vector<u8> buffer, std::unique_ptr<DelayGenerator> delay_generator_)
240     : file_buffer(std::move(buffer)) {
241     delay_generator = std::move(delay_generator_);
242 }
243 
Read(const u64 offset,const std::size_t length,u8 * buffer) const244 ResultVal<std::size_t> NCCHFile::Read(const u64 offset, const std::size_t length,
245                                       u8* buffer) const {
246     LOG_TRACE(Service_FS, "called offset={}, length={}", offset, length);
247 
248     std::size_t available_size = static_cast<std::size_t>(file_buffer.size() - offset);
249     std::size_t copy_size = std::min(length, available_size);
250     memcpy(buffer, file_buffer.data() + offset, copy_size);
251 
252     return MakeResult<std::size_t>(copy_size);
253 }
254 
Write(const u64 offset,const std::size_t length,const bool flush,const u8 * buffer)255 ResultVal<std::size_t> NCCHFile::Write(const u64 offset, const std::size_t length, const bool flush,
256                                        const u8* buffer) {
257     LOG_ERROR(Service_FS, "Attempted to write to NCCH file");
258     // TODO(shinyquagsire23): Find error code
259     return MakeResult<std::size_t>(0);
260 }
261 
GetSize() const262 u64 NCCHFile::GetSize() const {
263     return file_buffer.size();
264 }
265 
SetSize(const u64 size) const266 bool NCCHFile::SetSize(const u64 size) const {
267     LOG_ERROR(Service_FS, "Attempted to set the size of an NCCH file");
268     return false;
269 }
270 
271 ////////////////////////////////////////////////////////////////////////////////////////////////////
272 
ArchiveFactory_NCCH()273 ArchiveFactory_NCCH::ArchiveFactory_NCCH() {}
274 
Open(const Path & path,u64 program_id)275 ResultVal<std::unique_ptr<ArchiveBackend>> ArchiveFactory_NCCH::Open(const Path& path,
276                                                                      u64 program_id) {
277     if (path.GetType() != LowPathType::Binary) {
278         LOG_ERROR(Service_FS, "Path need to be Binary");
279         return ERROR_INVALID_PATH;
280     }
281 
282     std::vector<u8> binary = path.AsBinary();
283     if (binary.size() != sizeof(NCCHArchivePath)) {
284         LOG_ERROR(Service_FS, "Wrong path size {}", binary.size());
285         return ERROR_INVALID_PATH;
286     }
287 
288     NCCHArchivePath open_path;
289     std::memcpy(&open_path, binary.data(), sizeof(NCCHArchivePath));
290 
291     auto archive = std::make_unique<NCCHArchive>(
292         open_path.tid, static_cast<Service::FS::MediaType>(open_path.media_type & 0xFF));
293     return MakeResult<std::unique_ptr<ArchiveBackend>>(std::move(archive));
294 }
295 
Format(const Path & path,const FileSys::ArchiveFormatInfo & format_info,u64 program_id)296 ResultCode ArchiveFactory_NCCH::Format(const Path& path,
297                                        const FileSys::ArchiveFormatInfo& format_info,
298                                        u64 program_id) {
299     LOG_ERROR(Service_FS, "Attempted to format a NCCH archive.");
300     // TODO: Verify error code
301     return ResultCode(ErrorDescription::NotAuthorized, ErrorModule::FS, ErrorSummary::NotSupported,
302                       ErrorLevel::Permanent);
303 }
304 
GetFormatInfo(const Path & path,u64 program_id) const305 ResultVal<ArchiveFormatInfo> ArchiveFactory_NCCH::GetFormatInfo(const Path& path,
306                                                                 u64 program_id) const {
307     // TODO(Subv): Implement
308     LOG_ERROR(Service_FS, "Unimplemented GetFormatInfo archive {}", GetName());
309     return ResultCode(-1);
310 }
311 
312 } // namespace FileSys
313