Debian Codegraph @

Source/Core/DiscIO/DirectoryBlob.cpp

raw symbols SCIP
1 // Copyright 2008 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include "DiscIO/DirectoryBlob.h"
5
6 #include <algorithm>
7 #include <cstring>
8 #include <map>
9 #include <memory>
10 #include <set>
11 #include <string>
12 #include <utility>
13 #include <variant>
14 #include <vector>
15
16 #include "Common/Align.h"
17 #include "Common/Assert.h"
18 #include "Common/CommonTypes.h"
19 #include "Common/DirectIOFile.h"
20 #include "Common/FileUtil.h"
21 #include "Common/Logging/Log.h"
22 #include "Common/StringUtil.h"
23 #include "Common/Swap.h"
24 #include "Core/IOS/ES/Formats.h"
25 #include "DiscIO/Blob.h"
26 #include "DiscIO/DiscUtils.h"
27 #include "DiscIO/VolumeDisc.h"
28 #include "DiscIO/VolumeWii.h"
29 #include "DiscIO/WiiEncryptionCache.h"
30
31 namespace DiscIO
32 {
33 // Reads as many bytes as the vector fits (or less, if the file is smaller).
34 // Returns the number of bytes read.
35 static size_t ReadFileToVector(const std::string& path, std::vector<u8>* vector);
36
37 static void PadToAddress(u64 start_address, u64* address, u64* length, u8** buffer);
38 static void Write32(u32 data, u32 offset, std::vector<u8>* buffer);
39
40 enum class PartitionType : u32
41 {
42 Game = 0,
43 Update = 1,
44 Channel = 2,
45 // There are more types used by Super Smash Bros. Brawl, but they don't have special names
46 };
47
48 // 0xFF is an arbitrarily picked value. Note that we can't use 0x00, because that means NTSC-J
49 constexpr u32 INVALID_REGION = 0xFF;
50
51 constexpr u32 PARTITION_DATA_OFFSET = 0x20000;
52
53 constexpr u8 ENTRY_SIZE = 0x0c;
54 constexpr u8 FILE_ENTRY = 0;
55 constexpr u8 DIRECTORY_ENTRY = 1;
56
57 DiscContent::DiscContent(u64 offset, u64 size, ContentSource source)
58 : m_offset(offset), m_size(size), m_content_source(std::move(source))
59 {
60 }
61
62 DiscContent::DiscContent(u64 offset) : m_offset(offset)
63 {
64 }
65
66 u64 DiscContent::GetOffset() const
67 {
68 return m_offset;
69 }
70
71 u64 DiscContent::GetEndOffset() const
72 {
73 return m_offset + m_size;
74 }
75
76 u64 DiscContent::GetSize() const
77 {
78 return m_size;
79 }
80
81 bool DiscContent::Read(u64* offset, u64* length, u8** buffer, DirectoryBlobReader* blob) const
82 {
83 if (m_size == 0)
84 return true;
85
86 DEBUG_ASSERT(*offset >= m_offset);
87 const u64 offset_in_content = *offset - m_offset;
88
89 if (offset_in_content < m_size)
90 {
91 const u64 bytes_to_read = std::min(m_size - offset_in_content, *length);
92
93 if (std::holds_alternative<ContentFile>(m_content_source))
94 {
95 const auto& content = std::get<ContentFile>(m_content_source);
96 File::DirectIOFile file(content.m_filename, File::AccessMode::Read);
97 if (!file.OffsetRead(content.m_offset + offset_in_content, *buffer, bytes_to_read))
98 {
99 return false;
100 }
101 }
102 else if (std::holds_alternative<ContentMemory>(m_content_source))
103 {
104 const auto& content = std::get<ContentMemory>(m_content_source);
105 std::copy_n(content->begin() + offset_in_content, bytes_to_read, *buffer);
106 }
107 else if (std::holds_alternative<ContentPartition>(m_content_source))
108 {
109 const auto& content = std::get<ContentPartition>(m_content_source);
110 const u64 decrypted_size = m_size * VolumeWii::BLOCK_DATA_SIZE / VolumeWii::BLOCK_TOTAL_SIZE;
111 if (!blob->EncryptPartitionData(content.m_offset + offset_in_content, bytes_to_read, *buffer,
112 content.m_partition_data_offset, decrypted_size))
113 {
114 return false;
115 }
116 }
117 else if (std::holds_alternative<ContentVolume>(m_content_source))
118 {
119 const auto& source = std::get<ContentVolume>(m_content_source);
120 if (!blob->GetWrappedVolume()->Read(source.m_offset + offset_in_content, bytes_to_read,
121 *buffer, source.m_partition))
122 {
123 return false;
124 }
125 }
126 else if (std::holds_alternative<ContentFixedByte>(m_content_source))
127 {
128 const ContentFixedByte& source = std::get<ContentFixedByte>(m_content_source);
129 std::fill_n(*buffer, bytes_to_read, source.m_byte);
130 }
131 else
132 {
133 PanicAlertFmt("DirectoryBlob: Invalid content source in DiscContent.");
134 return false;
135 }
136
137 *length -= bytes_to_read;
138 *buffer += bytes_to_read;
139 *offset += bytes_to_read;
140 }
141
142 return true;
143 }
144
145 void DiscContentContainer::Add(u64 offset, u64 size, ContentSource source)
146 {
147 if (size != 0)
148 m_contents.emplace(offset, size, std::move(source));
149 }
150
151 u64 DiscContentContainer::CheckSizeAndAdd(u64 offset, const std::string& path)
152 {
153 const u64 size = File::GetSize(path);
154 Add(offset, size, ContentFile{path, 0});
155 return size;
156 }
157
158 u64 DiscContentContainer::CheckSizeAndAdd(u64 offset, u64 max_size, const std::string& path)
159 {
160 const u64 size = std::min(File::GetSize(path), max_size);
161 Add(offset, size, ContentFile{path, 0});
162 return size;
163 }
164
165 bool DiscContentContainer::Read(u64 offset, u64 length, u8* buffer, DirectoryBlobReader* blob) const
166 {
167 // Determine which DiscContent the offset refers to
168 std::set<DiscContent>::const_iterator it = m_contents.upper_bound(DiscContent(offset));
169
170 while (it != m_contents.end() && length > 0)
171 {
172 // Zero fill to start of DiscContent data
173 PadToAddress(it->GetOffset(), &offset, &length, &buffer);
174
175 if (length == 0)
176 return true;
177
178 if (!it->Read(&offset, &length, &buffer, blob))
179 return false;
180
181 ++it;
182 DEBUG_ASSERT(it == m_contents.end() || it->GetOffset() >= offset);
183 }
184
185 // Zero fill if we went beyond the last DiscContent
186 std::fill_n(buffer, static_cast<size_t>(length), 0);
187
188 return true;
189 }
190
191 static std::optional<PartitionType> ParsePartitionDirectoryName(const std::string& name)
192 {
193 if (name.size() < 2)
194 return {};
195
196 if (!strcasecmp(name.c_str(), "DATA"))
197 return PartitionType::Game;
198 if (!strcasecmp(name.c_str(), "UPDATE"))
199 return PartitionType::Update;
200 if (!strcasecmp(name.c_str(), "CHANNEL"))
201 return PartitionType::Channel;
202
203 if (name[0] == 'P' || name[0] == 'p')
204 {
205 // e.g. "P-HA8E" (normally only used for Super Smash Bros. Brawl's VC partitions)
206 if (name[1] == '-' && name.size() == 6)
207 {
208 const u32 result = Common::swap32(reinterpret_cast<const u8*>(name.data() + 2));
209 return static_cast<PartitionType>(result);
210 }
211
212 // e.g. "P0"
213 if (std::all_of(name.cbegin() + 1, name.cend(), [](char c) { return c >= '0' && c <= '9'; }))
214 {
215 u32 result;
216 if (TryParse(name.substr(1), &result))
217 return static_cast<PartitionType>(result);
218 }
219 }
220
221 return {};
222 }
223
224 static bool IsDirectorySeparator(char c)
225 {
226 return c == '/'
227 #ifdef _WIN32
228 || c == '\\'
229 #endif
230 ;
231 }
232
233 static bool PathCharactersEqual(char a, char b)
234 {
235 return a == b || (IsDirectorySeparator(a) && IsDirectorySeparator(b));
236 }
237
238 static bool PathEndsWith(const std::string& path, const std::string_view suffix)
239 {
240 if (suffix.size() > path.size())
241 return false;
242
243 std::string::const_iterator path_iterator = path.cend() - suffix.size();
244 std::string_view::const_iterator suffix_iterator = suffix.cbegin();
245 while (path_iterator != path.cend())
246 {
247 if (!PathCharactersEqual(*path_iterator, *suffix_iterator))
248 return false;
249 path_iterator++;
250 suffix_iterator++;
251 }
252
253 return true;
254 }
255
256 static bool IsValidDirectoryBlob(const std::string& dol_path, std::string* partition_root,
257 std::string* true_root = nullptr)
258 {
259 if (!PathEndsWith(dol_path, "/sys/main.dol"))
260 return false;
261
262 static constexpr size_t chars_to_remove = std::string_view("sys/main.dol").size();
263 *partition_root = dol_path.substr(0, dol_path.size() - chars_to_remove);
264
265 if (File::GetSize(*partition_root + "sys/boot.bin") < 0x20)
266 return false;
267
268 #ifdef _WIN32
269 constexpr const char* dir_separator = "/\\";
270 #else
271 constexpr char dir_separator = '/';
272 #endif
273 if (true_root)
274 {
275 *true_root =
276 dol_path.substr(0, dol_path.find_last_of(dir_separator, partition_root->size() - 2) + 1);
277 }
278
279 return true;
280 }
281
282 static bool ExistsAndIsValidDirectoryBlob(const std::string& dol_path)
283 {
284 std::string partition_root;
285 return File::Exists(dol_path) && IsValidDirectoryBlob(dol_path, &partition_root);
286 }
287
288 static bool IsInFilesDirectory(const std::string& path)
289 {
290 size_t files_pos = std::string::npos;
291 while (true)
292 {
293 files_pos = path.rfind("files", files_pos);
294 if (files_pos == std::string::npos)
295 return false;
296
297 const size_t slash_before_pos = files_pos - 1;
298 const size_t slash_after_pos = files_pos + 5;
299 if ((files_pos == 0 || IsDirectorySeparator(path[slash_before_pos])) &&
300 (slash_after_pos == path.size() || (IsDirectorySeparator(path[slash_after_pos]))) &&
301 ExistsAndIsValidDirectoryBlob(path.substr(0, files_pos) + "sys/main.dol"))
302 {
303 return true;
304 }
305
306 --files_pos;
307 }
308 }
309
310 static bool IsMainDolForNonGamePartition(const std::string& path)
311 {
312 std::string partition_root, true_root;
313 if (!IsValidDirectoryBlob(path, &partition_root, &true_root))
314 return false; // This is not a /sys/main.dol
315
316 std::string partition_directory_name = partition_root.substr(true_root.size());
317 partition_directory_name.pop_back(); // Remove trailing slash
318 const std::optional<PartitionType> partition_type =
319 ParsePartitionDirectoryName(partition_directory_name);
320 if (!partition_type || *partition_type == PartitionType::Game)
321 return false; // volume_path is the game partition's /sys/main.dol
322
323 const File::FSTEntry true_root_entry = File::ScanDirectoryTree(true_root, false);
324 for (const File::FSTEntry& entry : true_root_entry.children)
325 {
326 if (entry.isDirectory &&
327 ParsePartitionDirectoryName(entry.virtualName) == PartitionType::Game &&
328 ExistsAndIsValidDirectoryBlob(entry.physicalName + "/sys/main.dol"))
329 {
330 return true; // volume_path is the /sys/main.dol for a non-game partition
331 }
332 }
333
334 return false; // volume_path is the game partition's /sys/main.dol
335 }
336
337 static bool IsBootBin(const std::string& path)
338 {
339 static constexpr std::string_view boot_bin = "/sys/boot.bin";
340 if (!PathEndsWith(path, boot_bin))
341 return false;
342
343 const std::string partition_root = path.substr(0, path.size() - boot_bin.size());
344 return File::Exists(partition_root + "/sys/main.dol");
345 }
346
347 static bool IsHeaderBin(const std::string& path)
348 {
349 static constexpr std::string_view header_bin = "/disc/header.bin";
350 if (!PathEndsWith(path, header_bin))
351 return false;
352
353 const std::string partition_root = path.substr(0, path.size() - header_bin.size());
354 return File::Exists(partition_root + "/sys/main.dol");
355 }
356
357 bool ShouldHideFromGameList(const std::string& volume_path)
358 {
359 return IsInFilesDirectory(volume_path) || IsMainDolForNonGamePartition(volume_path) ||
360 IsBootBin(volume_path) || IsHeaderBin(volume_path);
361 }
362
363 std::unique_ptr<DirectoryBlobReader> DirectoryBlobReader::Create(const std::string& dol_path)
364 {
365 std::string partition_root, true_root;
366 if (!IsValidDirectoryBlob(dol_path, &partition_root, &true_root))
367 return nullptr;
368
369 return std::unique_ptr<DirectoryBlobReader>(new DirectoryBlobReader(partition_root, true_root));
370 }
371
372 std::unique_ptr<DirectoryBlobReader> DirectoryBlobReader::Create(
373 std::unique_ptr<VolumeDisc> volume,
374 const std::function<void(std::vector<FSTBuilderNode>* fst_nodes)>& sys_callback,
375 const std::function<void(std::vector<FSTBuilderNode>* fst_nodes, FSTBuilderNode* dol_node)>&
376 fst_callback)
377 {
378 if (!volume)
379 return nullptr;
380
381 return std::unique_ptr<DirectoryBlobReader>(
382 new DirectoryBlobReader(std::move(volume), sys_callback, fst_callback));
383 }
384
385 DirectoryBlobReader::DirectoryBlobReader(const std::string& game_partition_root,
386 const std::string& true_root)
387 : m_encryption_cache(this)
388 {
389 DirectoryBlobPartition game_partition(game_partition_root, {});
390 m_is_wii = game_partition.IsWii();
391
392 if (!m_is_wii)
393 {
394 m_gamecube_pseudopartition = std::move(game_partition);
395 m_data_size = m_gamecube_pseudopartition.GetDataSize();
396 m_encrypted = false;
397 }
398 else
399 {
400 std::vector<u8> disc_header(DISCHEADER_SIZE);
401 game_partition.GetContents().Read(DISCHEADER_ADDRESS, DISCHEADER_SIZE, disc_header.data(),
402 this);
403 SetNonpartitionDiscHeaderFromFile(disc_header, game_partition_root);
404 SetWiiRegionDataFromFile(game_partition_root);
405
406 std::vector<PartitionWithType> partitions;
407 partitions.emplace_back(std::move(game_partition), PartitionType::Game);
408
409 std::string game_partition_directory_name = game_partition_root.substr(true_root.size());
410 game_partition_directory_name.pop_back(); // Remove trailing slash
411 if (ParsePartitionDirectoryName(game_partition_directory_name) == PartitionType::Game)
412 {
413 const File::FSTEntry true_root_entry = File::ScanDirectoryTree(true_root, false);
414 for (const File::FSTEntry& entry : true_root_entry.children)
415 {
416 if (entry.isDirectory)
417 {
418 const std::optional<PartitionType> type = ParsePartitionDirectoryName(entry.virtualName);
419 if (type && *type != PartitionType::Game)
420 {
421 partitions.emplace_back(DirectoryBlobPartition(entry.physicalName + "/", m_is_wii),
422 *type);
423 }
424 }
425 }
426 }
427
428 SetPartitions(std::move(partitions));
429 }
430 }
431
432 DirectoryBlobReader::DirectoryBlobReader(
433 std::unique_ptr<VolumeDisc> volume,
434 const std::function<void(std::vector<FSTBuilderNode>* fst_nodes)>& sys_callback,
435 const std::function<void(std::vector<FSTBuilderNode>* fst_nodes, FSTBuilderNode* dol_node)>&
436 fst_callback)
437 : m_encryption_cache(this), m_wrapped_volume(std::move(volume))
438 {
439 DirectoryBlobPartition game_partition(m_wrapped_volume.get(),
440 m_wrapped_volume->GetGamePartition(), std::nullopt,
441 sys_callback, fst_callback, this);
442 m_is_wii = game_partition.IsWii();
443
444 if (!m_is_wii)
445 {
446 m_gamecube_pseudopartition = std::move(game_partition);
447 m_data_size = m_gamecube_pseudopartition.GetDataSize();
448 m_encrypted = false;
449 }
450 else
451 {
452 std::vector<u8> header_bin(WII_NONPARTITION_DISCHEADER_SIZE);
453 if (!m_wrapped_volume->Read(WII_NONPARTITION_DISCHEADER_ADDRESS,
454 WII_NONPARTITION_DISCHEADER_SIZE, header_bin.data(),
455 PARTITION_NONE))
456 {
457 header_bin.clear();
458 }
459 std::vector<u8> disc_header(DISCHEADER_SIZE);
460 game_partition.GetContents().Read(DISCHEADER_ADDRESS, DISCHEADER_SIZE, disc_header.data(),
461 this);
462 SetNonpartitionDiscHeader(disc_header, std::move(header_bin));
463
464 std::vector<u8> wii_region_data(WII_REGION_DATA_SIZE);
465 if (!m_wrapped_volume->Read(WII_REGION_DATA_ADDRESS, WII_REGION_DATA_SIZE,
466 wii_region_data.data(), PARTITION_NONE))
467 {
468 wii_region_data.clear();
469 }
470 SetWiiRegionData(wii_region_data, "volume");
471
472 std::vector<PartitionWithType> partitions;
473 partitions.emplace_back(std::move(game_partition), PartitionType::Game);
474
475 for (Partition partition : m_wrapped_volume->GetPartitions())
476 {
477 if (partition == m_wrapped_volume->GetGamePartition())
478 continue;
479
480 auto type = m_wrapped_volume->GetPartitionType(partition);
481 if (type)
482 {
483 partitions.emplace_back(DirectoryBlobPartition(m_wrapped_volume.get(), partition, m_is_wii,
484 nullptr, nullptr, this),
485 static_cast<PartitionType>(*type));
486 }
487 }
488
489 SetPartitions(std::move(partitions));
490 }
491 }
492
493 DirectoryBlobReader::DirectoryBlobReader(const DirectoryBlobReader& rhs)
494 : m_gamecube_pseudopartition(rhs.m_gamecube_pseudopartition),
495 m_nonpartition_contents(rhs.m_nonpartition_contents), m_partitions(rhs.m_partitions),
496 m_encryption_cache(this), m_is_wii(rhs.m_is_wii), m_encrypted(rhs.m_encrypted),
497 m_data_size(rhs.m_data_size),
498 m_wrapped_volume(rhs.m_wrapped_volume ?
499 CreateDisc(rhs.m_wrapped_volume->GetBlobReader().CopyReader()) :
500 nullptr)
501 {
502 }
503
504 bool DirectoryBlobReader::Read(u64 offset, u64 length, u8* buffer)
505 {
506 if (offset + length > m_data_size)
507 return false;
508
509 return (m_is_wii ? m_nonpartition_contents : m_gamecube_pseudopartition.GetContents())
510 .Read(offset, length, buffer, this);
511 }
512
513 const DirectoryBlobPartition* DirectoryBlobReader::GetPartition(u64 offset, u64 size,
514 u64 partition_data_offset) const
515 {
516 const auto it = m_partitions.find(partition_data_offset);
517 if (it == m_partitions.end())
518 return nullptr;
519
520 if (offset + size > it->second.GetDataSize())
521 return nullptr;
522
523 return &it->second;
524 }
525
526 bool DirectoryBlobReader::SupportsReadWiiDecrypted(u64 offset, u64 size,
527 u64 partition_data_offset) const
528 {
529 return static_cast<bool>(GetPartition(offset, size, partition_data_offset));
530 }
531
532 bool DirectoryBlobReader::ReadWiiDecrypted(u64 offset, u64 size, u8* buffer,
533 u64 partition_data_offset)
534 {
535 const DirectoryBlobPartition* partition = GetPartition(offset, size, partition_data_offset);
536 if (!partition)
537 return false;
538
539 return partition->GetContents().Read(offset, size, buffer, this);
540 }
541
542 bool DirectoryBlobReader::EncryptPartitionData(u64 offset, u64 size, u8* buffer,
543 u64 partition_data_offset,
544 u64 partition_data_decrypted_size)
545 {
546 auto it = m_partitions.find(partition_data_offset);
547 if (it == m_partitions.end())
548 return false;
549
550 if (!m_encrypted)
551 return it->second.GetContents().Read(offset, size, buffer, this);
552
553 return m_encryption_cache.EncryptGroups(offset, size, buffer, partition_data_offset,
554 partition_data_decrypted_size, it->second.GetKey());
555 }
556
557 BlobType DirectoryBlobReader::GetBlobType() const
558 {
559 return BlobType::DIRECTORY;
560 }
561
562 std::unique_ptr<BlobReader> DirectoryBlobReader::CopyReader() const
563 {
564 return std::unique_ptr<DirectoryBlobReader>(new DirectoryBlobReader(*this));
565 }
566
567 u64 DirectoryBlobReader::GetRawSize() const
568 {
569 // Not implemented
570 return 0;
571 }
572
573 u64 DirectoryBlobReader::GetDataSize() const
574 {
575 return m_data_size;
576 }
577
578 void DirectoryBlobReader::SetNonpartitionDiscHeaderFromFile(std::span<const u8> partition_header,
579 const std::string& game_partition_root)
580 {
581 std::vector<u8> header_bin(WII_NONPARTITION_DISCHEADER_SIZE);
582 const size_t header_bin_bytes_read =
583 ReadFileToVector(game_partition_root + "disc/header.bin", &header_bin);
584 header_bin.resize(header_bin_bytes_read);
585 SetNonpartitionDiscHeader(partition_header, std::move(header_bin));
586 }
587
588 void DirectoryBlobReader::SetNonpartitionDiscHeader(std::span<const u8> partition_header,
589 std::vector<u8> header_bin)
590 {
591 const size_t header_bin_size = header_bin.size();
592 header_bin.resize(WII_NONPARTITION_DISCHEADER_SIZE);
593
594 // If header.bin is missing or smaller than expected, use the content of sys/boot.bin instead
595 if (header_bin_size < header_bin.size())
596 {
597 std::copy(partition_header.data() + header_bin_size,
598 partition_header.data() + header_bin.size(), header_bin.data() + header_bin_size);
599 }
600
601 // 0x60 and 0x61 are the only differences between the partition and non-partition headers
602 if (header_bin_size < 0x60)
603 header_bin[0x60] = 0;
604 if (header_bin_size < 0x61)
605 header_bin[0x61] = 0;
606
607 m_encrypted =
608 std::all_of(header_bin.data() + 0x60, header_bin.data() + 0x64, [](u8 x) { return x == 0; });
609
610 m_nonpartition_contents.Add(WII_NONPARTITION_DISCHEADER_ADDRESS, std::move(header_bin));
611 }
612
613 void DirectoryBlobReader::SetWiiRegionDataFromFile(const std::string& game_partition_root)
614 {
615 std::vector<u8> wii_region_data(WII_REGION_DATA_SIZE);
616 const std::string region_bin_path = game_partition_root + "disc/region.bin";
617 const size_t bytes_read = ReadFileToVector(region_bin_path, &wii_region_data);
618 wii_region_data.resize(bytes_read);
619 SetWiiRegionData(wii_region_data, region_bin_path);
620 }
621
622 void DirectoryBlobReader::SetWiiRegionData(std::span<const u8> wii_region_data,
623 const std::string& log_path)
624 {
625 std::vector<u8> region_data(0x10, 0x00);
626 region_data.resize(WII_REGION_DATA_SIZE, 0x80);
627 Write32(INVALID_REGION, 0, &region_data);
628
629 std::copy_n(wii_region_data.begin(),
630 std::min<size_t>(wii_region_data.size(), WII_REGION_DATA_SIZE), region_data.begin());
631
632 if (wii_region_data.size() < 0x4)
633 ERROR_LOG_FMT(DISCIO, "Couldn't read region from {}", log_path);
634 else if (wii_region_data.size() < 0x20)
635 ERROR_LOG_FMT(DISCIO, "Couldn't read age ratings from {}", log_path);
636
637 m_nonpartition_contents.Add(WII_REGION_DATA_ADDRESS, std::move(region_data));
638 }
639
640 void DirectoryBlobReader::SetPartitions(std::vector<PartitionWithType>&& partitions)
641 {
642 std::ranges::sort(partitions, [](const PartitionWithType& lhs, const PartitionWithType& rhs) {
643 if (lhs.type == rhs.type)
644 return lhs.partition.GetRootDirectory() < rhs.partition.GetRootDirectory();
645
646 // Ascending sort by partition type, except Update (1) comes before before Game (0)
647 return (lhs.type > PartitionType::Update || rhs.type > PartitionType::Update) ?
648 lhs.type < rhs.type :
649 lhs.type > rhs.type;
650 });
651
652 u32 subtable_1_size = 0;
653 while (subtable_1_size < partitions.size() && subtable_1_size < 3 &&
654 partitions[subtable_1_size].type <= PartitionType::Channel)
655 {
656 ++subtable_1_size;
657 }
658 const u32 subtable_2_size = static_cast<u32>(partitions.size() - subtable_1_size);
659
660 constexpr u32 PARTITION_TABLE_ADDRESS = 0x40000;
661 constexpr u32 PARTITION_SUBTABLE1_OFFSET = 0x20;
662 constexpr u32 PARTITION_SUBTABLE2_OFFSET = 0x40;
663 std::vector<u8> partition_table(PARTITION_SUBTABLE2_OFFSET + subtable_2_size * 8);
664
665 Write32(subtable_1_size, 0x0, &partition_table);
666 Write32((PARTITION_TABLE_ADDRESS + PARTITION_SUBTABLE1_OFFSET) >> 2, 0x4, &partition_table);
667 if (subtable_2_size != 0)
668 {
669 Write32(subtable_2_size, 0x8, &partition_table);
670 Write32((PARTITION_TABLE_ADDRESS + PARTITION_SUBTABLE2_OFFSET) >> 2, 0xC, &partition_table);
671 }
672
673 constexpr u64 STANDARD_UPDATE_PARTITION_ADDRESS = 0x50000;
674 constexpr u64 STANDARD_GAME_PARTITION_ADDRESS = 0xF800000;
675 u64 partition_address = STANDARD_UPDATE_PARTITION_ADDRESS;
676 u64 offset_in_table = PARTITION_SUBTABLE1_OFFSET;
677 for (size_t i = 0; i < partitions.size(); ++i)
678 {
679 if (i == subtable_1_size)
680 offset_in_table = PARTITION_SUBTABLE2_OFFSET;
681
682 if (partitions[i].type == PartitionType::Game)
683 partition_address = std::max(partition_address, STANDARD_GAME_PARTITION_ADDRESS);
684
685 Write32(static_cast<u32>(partition_address >> 2), offset_in_table, &partition_table);
686 offset_in_table += 4;
687 Write32(static_cast<u32>(partitions[i].type), offset_in_table, &partition_table);
688 offset_in_table += 4;
689
690 SetPartitionHeader(&partitions[i].partition, partition_address);
691
692 const u64 data_size =
693 Common::AlignUp(partitions[i].partition.GetDataSize(), VolumeWii::BLOCK_DATA_SIZE);
694 partitions[i].partition.SetDataSize(data_size);
695 const u64 encrypted_data_size =
696 (data_size / VolumeWii::BLOCK_DATA_SIZE) * VolumeWii::BLOCK_TOTAL_SIZE;
697 const u64 partition_data_offset = partition_address + PARTITION_DATA_OFFSET;
698 m_partitions.emplace(partition_data_offset, std::move(partitions[i].partition));
699 m_nonpartition_contents.Add(partition_data_offset, encrypted_data_size,
700 ContentPartition{0, partition_data_offset});
701 const u64 unaligned_next_partition_address = VolumeWii::OffsetInHashedPartitionToRawOffset(
702 data_size, Partition(partition_address), PARTITION_DATA_OFFSET);
703 partition_address = Common::AlignUp(unaligned_next_partition_address, 0x10000ull);
704 }
705 m_data_size = partition_address;
706
707 m_nonpartition_contents.Add(PARTITION_TABLE_ADDRESS, std::move(partition_table));
708 }
709
710 // This function sets the header that's shortly before the start of the encrypted
711 // area, not the header that's right at the beginning of the encrypted area
712 void DirectoryBlobReader::SetPartitionHeader(DirectoryBlobPartition* partition,
713 u64 partition_address)
714 {
715 constexpr u32 TMD_OFFSET = 0x2c0;
716 constexpr u32 H3_OFFSET = 0x4000;
717
718 const std::optional<Partition>& wrapped_partition = partition->GetWrappedPartition();
719 const std::string& partition_root = partition->GetRootDirectory();
720
721 u64 ticket_size;
722 if (wrapped_partition)
723 {
724 std::vector<u8> new_ticket = m_wrapped_volume->GetTicket(*wrapped_partition).GetBytes();
725 if (new_ticket.size() > WII_PARTITION_TICKET_SIZE)
726 new_ticket.resize(WII_PARTITION_TICKET_SIZE);
727 ticket_size = new_ticket.size();
728 m_nonpartition_contents.Add(partition_address + WII_PARTITION_TICKET_ADDRESS,
729 std::move(new_ticket));
730 }
731 else
732 {
733 ticket_size = m_nonpartition_contents.CheckSizeAndAdd(
734 partition_address + WII_PARTITION_TICKET_ADDRESS, WII_PARTITION_TICKET_SIZE,
735 partition_root + "ticket.bin");
736 }
737
738 u64 tmd_size;
739 if (wrapped_partition)
740 {
741 std::vector<u8> new_tmd = m_wrapped_volume->GetTMD(*wrapped_partition).GetBytes();
742 if (new_tmd.size() > IOS::ES::MAX_TMD_SIZE)
743 new_tmd.resize(IOS::ES::MAX_TMD_SIZE);
744 tmd_size = new_tmd.size();
745 m_nonpartition_contents.Add(partition_address + TMD_OFFSET, std::move(new_tmd));
746 }
747 else
748 {
749 tmd_size = m_nonpartition_contents.CheckSizeAndAdd(
750 partition_address + TMD_OFFSET, IOS::ES::MAX_TMD_SIZE, partition_root + "tmd.bin");
751 }
752
753 const u64 cert_offset = Common::AlignUp(TMD_OFFSET + tmd_size, 0x20ull);
754 const u64 max_cert_size = H3_OFFSET - cert_offset;
755
756 u64 cert_size;
757 if (wrapped_partition)
758 {
759 std::vector<u8> new_cert = m_wrapped_volume->GetCertificateChain(*wrapped_partition);
760 if (new_cert.size() > max_cert_size)
761 new_cert.resize(max_cert_size);
762 cert_size = new_cert.size();
763 m_nonpartition_contents.Add(partition_address + cert_offset, std::move(new_cert));
764 }
765 else
766 {
767 cert_size = m_nonpartition_contents.CheckSizeAndAdd(partition_address + cert_offset,
768 max_cert_size, partition_root + "cert.bin");
769 }
770
771 if (wrapped_partition)
772 {
773 if (m_wrapped_volume->HasWiiHashes())
774 {
775 const std::optional<u64> offset = m_wrapped_volume->ReadSwappedAndShifted(
776 wrapped_partition->offset + WII_PARTITION_H3_OFFSET_ADDRESS, PARTITION_NONE);
777 if (offset)
778 {
779 std::vector<u8> new_h3(WII_PARTITION_H3_SIZE);
780 if (m_wrapped_volume->Read(wrapped_partition->offset + *offset, new_h3.size(),
781 new_h3.data(), PARTITION_NONE))
782 {
783 m_nonpartition_contents.Add(partition_address + H3_OFFSET, std::move(new_h3));
784 }
785 }
786 }
787 }
788 else
789 {
790 m_nonpartition_contents.CheckSizeAndAdd(partition_address + H3_OFFSET, WII_PARTITION_H3_SIZE,
791 partition_root + "h3.bin");
792 }
793
794 constexpr u32 PARTITION_HEADER_SIZE = 0x1c;
795 const u64 data_size = Common::AlignUp(partition->GetDataSize(), 0x7c00) / 0x7c00 * 0x8000;
796 std::vector<u8> partition_header(PARTITION_HEADER_SIZE);
797 Write32(static_cast<u32>(tmd_size), 0x0, &partition_header);
798 Write32(TMD_OFFSET >> 2, 0x4, &partition_header);
799 Write32(static_cast<u32>(cert_size), 0x8, &partition_header);
800 Write32(static_cast<u32>(cert_offset >> 2), 0x0C, &partition_header);
801 Write32(H3_OFFSET >> 2, 0x10, &partition_header);
802 Write32(PARTITION_DATA_OFFSET >> 2, 0x14, &partition_header);
803 Write32(static_cast<u32>(data_size >> 2), 0x18, &partition_header);
804
805 m_nonpartition_contents.Add(partition_address + WII_PARTITION_TICKET_SIZE,
806 std::move(partition_header));
807
808 std::vector<u8> ticket_buffer(ticket_size);
809 m_nonpartition_contents.Read(partition_address + WII_PARTITION_TICKET_ADDRESS, ticket_size,
810 ticket_buffer.data(), this);
811 IOS::ES::TicketReader ticket(std::move(ticket_buffer));
812 if (ticket.IsValid())
813 partition->SetKey(ticket.GetTitleKey());
814 }
815
816 static void GenerateBuilderNodesFromFileSystem(const VolumeDisc& volume, const Partition& partition,
817 std::vector<FSTBuilderNode>* nodes,
818 const FileInfo& parent_info)
819 {
820 for (const FileInfo& file_info : parent_info)
821 {
822 if (file_info.IsDirectory())
823 {
824 std::vector<FSTBuilderNode> child_nodes;
825 GenerateBuilderNodesFromFileSystem(volume, partition, &child_nodes, file_info);
826 nodes->emplace_back(FSTBuilderNode{file_info.GetName(), file_info.GetTotalChildren(),
827 std::move(child_nodes)});
828 }
829 else
830 {
831 std::vector<BuilderContentSource> source;
832 source.emplace_back(BuilderContentSource{0, file_info.GetSize(),
833 ContentVolume{file_info.GetOffset(), partition}});
834 nodes->emplace_back(
835 FSTBuilderNode{file_info.GetName(), file_info.GetSize(), std::move(source)});
836 }
837 }
838 }
839
840 DirectoryBlobPartition::DirectoryBlobPartition(std::string root_directory,
841 std::optional<bool> is_wii)
842 : m_root_directory(std::move(root_directory))
843 {
844 std::vector<u8> disc_header(DISCHEADER_SIZE);
845 if (ReadFileToVector(m_root_directory + "sys/boot.bin", &disc_header) < 0x20)
846 ERROR_LOG_FMT(DISCIO, "{} doesn't exist or is too small", m_root_directory + "sys/boot.bin");
847
848 SetDiscType(is_wii, disc_header);
849 SetBI2FromFile(m_root_directory + "sys/bi2.bin");
850 const u64 dol_address = SetApploaderFromFile(m_root_directory + "sys/apploader.img");
851 const u64 fst_address =
852 SetDOLFromFile(m_root_directory + "sys/main.dol", dol_address, &disc_header);
853 BuildFSTFromFolder(m_root_directory + "files/", fst_address, &disc_header);
854
855 m_contents.Add(DISCHEADER_ADDRESS, disc_header);
856 }
857
858 static void FillSingleFileNode(FSTBuilderNode* node, std::vector<u8> data)
859 {
860 std::vector<BuilderContentSource> contents;
861 const size_t size = data.size();
862 contents.emplace_back(
863 BuilderContentSource{0, size, std::make_shared<std::vector<u8>>(std::move(data))});
864 node->m_size = size;
865 node->m_content = std::move(contents);
866 }
867
868 static FSTBuilderNode BuildSingleFileNode(std::string filename, std::vector<u8> data,
869 void* userdata)
870 {
871 FSTBuilderNode node{std::move(filename), 0, {}, userdata};
872 FillSingleFileNode(&node, std::move(data));
873 return node;
874 }
875
876 static std::vector<u8> ExtractNodeToVector(std::vector<FSTBuilderNode>* nodes, void* userdata,
877 DirectoryBlobReader* blob)
878 {
879 std::vector<u8> data;
880 const auto it = std::ranges::find(*nodes, userdata, &FSTBuilderNode::m_user_data);
881 if (it == nodes->end() || !it->IsFile())
882 return data;
883
884 DiscContentContainer tmp;
885 for (auto& content : it->GetFileContent())
886 tmp.Add(content.m_offset, content.m_size, std::move(content.m_source));
887 data.resize(it->m_size);
888 tmp.Read(0, it->m_size, data.data(), blob);
889 return data;
890 }
891
892 DirectoryBlobPartition::DirectoryBlobPartition(
893 VolumeDisc* volume, const Partition& partition, std::optional<bool> is_wii,
894 const std::function<void(std::vector<FSTBuilderNode>* fst_nodes)>& sys_callback,
895 const std::function<void(std::vector<FSTBuilderNode>* fst_nodes, FSTBuilderNode* dol_node)>&
896 fst_callback,
897 DirectoryBlobReader* blob)
898 : m_wrapped_partition(partition)
899 {
900 std::vector<FSTBuilderNode> sys_nodes;
901
902 std::vector<u8> disc_header(DISCHEADER_SIZE);
903 if (!volume->Read(DISCHEADER_ADDRESS, DISCHEADER_SIZE, disc_header.data(), partition))
904 disc_header.clear();
905 sys_nodes.emplace_back(BuildSingleFileNode("boot.bin", std::move(disc_header), &disc_header));
906
907 std::vector<u8> bi2(BI2_SIZE);
908 if (!volume->Read(BI2_ADDRESS, BI2_SIZE, bi2.data(), partition))
909 bi2.clear();
910 sys_nodes.emplace_back(BuildSingleFileNode("bi2.bin", std::move(bi2), &bi2));
911
912 std::vector<u8> apploader;
913 const auto apploader_size = GetApploaderSize(*volume, partition);
914 auto& apploader_node = sys_nodes.emplace_back(FSTBuilderNode{"apploader.img", 0, {}, &apploader});
915 if (apploader_size)
916 {
917 apploader.resize(*apploader_size);
918 if (!volume->Read(APPLOADER_ADDRESS, *apploader_size, apploader.data(), partition))
919 apploader.clear();
920 FillSingleFileNode(&apploader_node, std::move(apploader));
921 }
922
923 if (sys_callback)
924 sys_callback(&sys_nodes);
925
926 disc_header = ExtractNodeToVector(&sys_nodes, &disc_header, blob);
927 disc_header.resize(DISCHEADER_SIZE);
928 SetDiscType(is_wii, disc_header);
929 SetBI2(ExtractNodeToVector(&sys_nodes, &bi2, blob));
930 const u64 new_dol_address =
931 SetApploader(ExtractNodeToVector(&sys_nodes, &apploader, blob), "apploader");
932
933 FSTBuilderNode dol_node{"main.dol", 0, {}};
934 const auto dol_offset = GetBootDOLOffset(*volume, partition);
935 if (dol_offset)
936 {
937 const auto dol_size = GetBootDOLSize(*volume, partition, *dol_offset);
938 if (dol_size)
939 {
940 std::vector<BuilderContentSource> dol_contents;
941 dol_contents.emplace_back(
942 BuilderContentSource{0, *dol_size, ContentVolume{*dol_offset, partition}});
943 dol_node.m_size = *dol_size;
944 dol_node.m_content = std::move(dol_contents);
945 }
946 }
947
948 std::vector<FSTBuilderNode> nodes;
949
950 const FileSystem* fs = volume->GetFileSystem(partition);
951 if (fs && fs->IsValid())
952 GenerateBuilderNodesFromFileSystem(*volume, partition, &nodes, fs->GetRoot());
953
954 if (fst_callback)
955 fst_callback(&nodes, &dol_node);
956
957 const u64 new_fst_address = SetDOL(std::move(dol_node), new_dol_address, &disc_header);
958 BuildFST(std::move(nodes), new_fst_address, &disc_header);
959
960 m_contents.Add(DISCHEADER_ADDRESS, disc_header);
961 }
962
963 void DirectoryBlobPartition::SetDiscType(std::optional<bool> is_wii,
964 std::span<const u8> disc_header)
965 {
966 if (is_wii.has_value())
967 {
968 m_is_wii = *is_wii;
969 }
970 else
971 {
972 m_is_wii = Common::swap32(&disc_header[0x18]) == WII_DISC_MAGIC;
973 const bool is_gc = Common::swap32(&disc_header[0x1c]) == GAMECUBE_DISC_MAGIC;
974 if (m_is_wii == is_gc)
975 {
976 ERROR_LOG_FMT(DISCIO, "Couldn't detect disc type based on disc header; assuming {}",
977 m_is_wii ? "Wii" : "GameCube");
978 }
979 }
980
981 m_address_shift = m_is_wii ? 2 : 0;
982 }
983
984 void DirectoryBlobPartition::SetBI2FromFile(const std::string& bi2_path)
985 {
986 std::vector<u8> bi2(BI2_SIZE);
987
988 if (!m_is_wii)
989 Write32(INVALID_REGION, 0x18, &bi2);
990
991 const size_t bytes_read = ReadFileToVector(bi2_path, &bi2);
992 if (!m_is_wii && bytes_read < 0x1C)
993 ERROR_LOG_FMT(DISCIO, "Couldn't read region from {}", bi2_path);
994
995 m_contents.Add(BI2_ADDRESS, std::move(bi2));
996 }
997
998 void DirectoryBlobPartition::SetBI2(std::vector<u8> bi2)
999 {
1000 const size_t bi2_size = bi2.size();
1001 bi2.resize(BI2_SIZE);
1002
1003 if (!m_is_wii && bi2_size < 0x1C)
1004 Write32(INVALID_REGION, 0x18, &bi2);
1005
1006 m_contents.Add(BI2_ADDRESS, std::move(bi2));
1007 }
1008
1009 u64 DirectoryBlobPartition::SetApploaderFromFile(const std::string& path)
1010 {
1011 File::DirectIOFile file(path, File::AccessMode::Read);
1012 std::vector<u8> apploader(file.GetSize());
1013 file.Read(apploader);
1014 return SetApploader(std::move(apploader), path);
1015 }
1016
1017 u64 DirectoryBlobPartition::SetApploader(std::vector<u8> apploader, const std::string& log_path)
1018 {
1019 bool success = false;
1020
1021 if (apploader.size() < 0x20)
1022 {
1023 ERROR_LOG_FMT(DISCIO, "{} couldn't be accessed or is too small", log_path);
1024 }
1025 else
1026 {
1027 const size_t apploader_size =
1028 0x20 + Common::swap32(*(u32*)&apploader[0x14]) + Common::swap32(*(u32*)&apploader[0x18]);
1029 if (apploader_size != apploader.size())
1030 ERROR_LOG_FMT(DISCIO, "{} is the wrong size... Is it really an apploader?", log_path);
1031 else
1032 success = true;
1033 }
1034
1035 if (!success)
1036 {
1037 apploader.resize(0x20);
1038 // Make sure BS2 HLE doesn't try to run the apploader
1039 Write32(static_cast<u32>(-1), 0x10, &apploader);
1040 }
1041
1042 size_t apploader_size = apploader.size();
1043 m_contents.Add(APPLOADER_ADDRESS, std::move(apploader));
1044
1045 // Return DOL address, 32 byte aligned (plus 32 byte padding)
1046 return Common::AlignUp(APPLOADER_ADDRESS + apploader_size + 0x20, 0x20ull);
1047 }
1048
1049 u64 DirectoryBlobPartition::SetDOLFromFile(const std::string& path, u64 dol_address,
1050 std::vector<u8>* disc_header)
1051 {
1052 const u64 dol_size = m_contents.CheckSizeAndAdd(dol_address, path);
1053
1054 Write32(static_cast<u32>(dol_address >> m_address_shift), 0x0420, disc_header);
1055
1056 // Return FST address, 32 byte aligned (plus 32 byte padding)
1057 return Common::AlignUp(dol_address + dol_size + 0x20, 0x20ull);
1058 }
1059
1060 u64 DirectoryBlobPartition::SetDOL(FSTBuilderNode dol_node, u64 dol_address,
1061 std::vector<u8>* disc_header)
1062 {
1063 for (auto& content : dol_node.GetFileContent())
1064 m_contents.Add(dol_address + content.m_offset, content.m_size, std::move(content.m_source));
1065
1066 Write32(static_cast<u32>(dol_address >> m_address_shift), 0x0420, disc_header);
1067
1068 // Return FST address, 32 byte aligned (plus 32 byte padding)
1069 return Common::AlignUp(dol_address + dol_node.m_size + 0x20, 0x20ull);
1070 }
1071
1072 static std::vector<FSTBuilderNode> ConvertFSTEntriesToBuilderNodes(const File::FSTEntry& parent)
1073 {
1074 std::vector<FSTBuilderNode> nodes;
1075 nodes.reserve(parent.children.size());
1076 for (const File::FSTEntry& entry : parent.children)
1077 {
1078 std::variant<std::vector<BuilderContentSource>, std::vector<FSTBuilderNode>> content;
1079 if (entry.isDirectory)
1080 {
1081 content = ConvertFSTEntriesToBuilderNodes(entry);
1082 }
1083 else
1084 {
1085 content =
1086 std::vector<BuilderContentSource>{{0, entry.size, ContentFile{entry.physicalName, 0}}};
1087 }
1088
1089 nodes.emplace_back(FSTBuilderNode{entry.virtualName, entry.size, std::move(content)});
1090 }
1091 return nodes;
1092 }
1093
1094 void DirectoryBlobPartition::BuildFSTFromFolder(const std::string& fst_root_path, u64 fst_address,
1095 std::vector<u8>* disc_header)
1096 {
1097 auto nodes = ConvertFSTEntriesToBuilderNodes(File::ScanDirectoryTree(fst_root_path, true));
1098 BuildFST(std::move(nodes), fst_address, disc_header);
1099 }
1100
1101 static void ConvertUTF8NamesToSHIFTJIS(std::vector<FSTBuilderNode>* fst)
1102 {
1103 for (FSTBuilderNode& entry : *fst)
1104 {
1105 if (entry.IsFolder())
1106 ConvertUTF8NamesToSHIFTJIS(&entry.GetFolderContent());
1107 entry.m_filename = UTF8ToSHIFTJIS(entry.m_filename);
1108 }
1109 }
1110
1111 static u32 ComputeNameSize(std::span<const FSTBuilderNode> files)
1112 {
1113 u32 name_size = 0;
1114 for (const FSTBuilderNode& entry : files)
1115 {
1116 if (entry.IsFolder())
1117 name_size += ComputeNameSize(entry.GetFolderContent());
1118 name_size += static_cast<u32>(entry.m_filename.length() + 1);
1119 }
1120 return name_size;
1121 }
1122
1123 static size_t RecalculateFolderSizes(std::vector<FSTBuilderNode>* fst)
1124 {
1125 size_t size = 0;
1126 for (FSTBuilderNode& entry : *fst)
1127 {
1128 ++size;
1129 if (entry.IsFile())
1130 continue;
1131
1132 entry.m_size = RecalculateFolderSizes(&entry.GetFolderContent());
1133 size += entry.m_size;
1134 }
1135 return size;
1136 }
1137
1138 void DirectoryBlobPartition::BuildFST(std::vector<FSTBuilderNode> root_nodes, u64 fst_address,
1139 std::vector<u8>* disc_header)
1140 {
1141 ConvertUTF8NamesToSHIFTJIS(&root_nodes);
1142
1143 u32 name_table_size = Common::AlignUp(ComputeNameSize(root_nodes), 1ull << m_address_shift);
1144
1145 // 1 extra for the root entry
1146 u64 total_entries = RecalculateFolderSizes(&root_nodes) + 1;
1147
1148 const u64 name_table_offset = total_entries * ENTRY_SIZE;
1149 std::vector<u8> fst_data(name_table_offset + name_table_size);
1150
1151 // 32 KiB aligned start of data on disc
1152 u64 current_data_address = Common::AlignUp(fst_address + fst_data.size(), 0x8000ull);
1153
1154 u32 fst_offset = 0; // Offset within FST data
1155 u32 name_offset = 0; // Offset within name table
1156 u32 root_offset = 0; // Offset of root of FST
1157
1158 // write root entry
1159 WriteEntryData(&fst_data, &fst_offset, DIRECTORY_ENTRY, 0, 0, total_entries, m_address_shift);
1160
1161 WriteDirectory(&fst_data, &root_nodes, &fst_offset, &name_offset, &current_data_address,
1162 root_offset, name_table_offset);
1163
1164 // overflow check, compare the aligned name offset with the aligned name table size
1165 ASSERT(Common::AlignUp(name_offset, 1ull << m_address_shift) == name_table_size);
1166
1167 // write FST size and location
1168 Write32((u32)(fst_address >> m_address_shift), 0x0424, disc_header);
1169 Write32((u32)(fst_data.size() >> m_address_shift), 0x0428, disc_header);
1170 Write32((u32)(fst_data.size() >> m_address_shift), 0x042c, disc_header);
1171
1172 m_contents.Add(fst_address, std::move(fst_data));
1173
1174 m_data_size = current_data_address;
1175 }
1176
1177 void DirectoryBlobPartition::WriteEntryData(std::vector<u8>* fst_data, u32* entry_offset, u8 type,
1178 u32 name_offset, u64 data_offset, u64 length,
1179 u32 address_shift)
1180 {
1181 (*fst_data)[(*entry_offset)++] = type;
1182
1183 (*fst_data)[(*entry_offset)++] = (name_offset >> 16) & 0xff;
1184 (*fst_data)[(*entry_offset)++] = (name_offset >> 8) & 0xff;
1185 (*fst_data)[(*entry_offset)++] = (name_offset) & 0xff;
1186
1187 Write32((u32)(data_offset >> address_shift), *entry_offset, fst_data);
1188 *entry_offset += 4;
1189
1190 Write32((u32)length, *entry_offset, fst_data);
1191 *entry_offset += 4;
1192 }
1193
1194 void DirectoryBlobPartition::WriteEntryName(std::vector<u8>* fst_data, u32* name_offset,
1195 const std::string& name, u64 name_table_offset)
1196 {
1197 strncpy((char*)&(*fst_data)[*name_offset + name_table_offset], name.c_str(), name.length() + 1);
1198
1199 *name_offset += (u32)(name.length() + 1);
1200 }
1201
1202 void DirectoryBlobPartition::WriteDirectory(std::vector<u8>* fst_data,
1203 std::vector<FSTBuilderNode>* parent_entries,
1204 u32* fst_offset, u32* name_offset, u64* data_offset,
1205 u32 parent_entry_index, u64 name_table_offset)
1206 {
1207 std::vector<FSTBuilderNode>& sorted_entries = *parent_entries;
1208
1209 // Sort for determinism
1210 std::ranges::sort(sorted_entries, [](const FSTBuilderNode& one, const FSTBuilderNode& two) {
1211 std::string one_upper = one.m_filename;
1212 std::string two_upper = two.m_filename;
1213 Common::ToUpper(&one_upper);
1214 Common::ToUpper(&two_upper);
1215 return one_upper == two_upper ? one.m_filename < two.m_filename : one_upper < two_upper;
1216 });
1217
1218 for (FSTBuilderNode& entry : sorted_entries)
1219 {
1220 if (entry.IsFolder())
1221 {
1222 u32 entry_index = *fst_offset / ENTRY_SIZE;
1223 WriteEntryData(fst_data, fst_offset, DIRECTORY_ENTRY, *name_offset, parent_entry_index,
1224 entry_index + entry.m_size + 1, 0);
1225 WriteEntryName(fst_data, name_offset, entry.m_filename, name_table_offset);
1226
1227 auto& child_nodes = entry.GetFolderContent();
1228 WriteDirectory(fst_data, &child_nodes, fst_offset, name_offset, data_offset, entry_index,
1229 name_table_offset);
1230 }
1231 else
1232 {
1233 // put entry in FST
1234 WriteEntryData(fst_data, fst_offset, FILE_ENTRY, *name_offset, *data_offset, entry.m_size,
1235 m_address_shift);
1236 WriteEntryName(fst_data, name_offset, entry.m_filename, name_table_offset);
1237
1238 // write entry to virtual disc
1239 auto& contents = entry.GetFileContent();
1240 for (BuilderContentSource& content : contents)
1241 {
1242 m_contents.Add(*data_offset + content.m_offset, content.m_size,
1243 std::move(content.m_source));
1244 }
1245
1246 // 32 KiB aligned - many games are fine with less alignment, but not all
1247 *data_offset = Common::AlignUp(*data_offset + entry.m_size, 0x8000ull);
1248 }
1249 }
1250 }
1251
1252 static size_t ReadFileToVector(const std::string& path, std::vector<u8>* vector)
1253 {
1254 File::DirectIOFile file(path, File::AccessMode::Read);
1255 file.Read(vector->data(), std::min<u64>(file.GetSize(), vector->size()));
1256 return file.Tell();
1257 }
1258
1259 static void PadToAddress(u64 start_address, u64* address, u64* length, u8** buffer)
1260 {
1261 if (start_address > *address && *length > 0)
1262 {
1263 u64 padBytes = std::min(start_address - *address, *length);
1264 memset(*buffer, 0, (size_t)padBytes);
1265 *length -= padBytes;
1266 *buffer += padBytes;
1267 *address += padBytes;
1268 }
1269 }
1270
1271 static void Write32(u32 data, u32 offset, std::vector<u8>* buffer)
1272 {
1273 (*buffer)[offset++] = (data >> 24);
1274 (*buffer)[offset++] = (data >> 16) & 0xff;
1275 (*buffer)[offset++] = (data >> 8) & 0xff;
1276 (*buffer)[offset] = data & 0xff;
1277 }
1278 } // namespace DiscIO