Debian Codegraph @

Source/Core/DiscIO/VolumeVerifier.cpp

raw symbols SCIP
1 // Copyright 2019 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include "DiscIO/VolumeVerifier.h"
5
6 #include <algorithm>
7 #include <future>
8 #include <memory>
9 #include <optional>
10 #include <string>
11 #include <string_view>
12
13 #include <mbedtls/md5.h>
14 #include <mz.h>
15 #include <mz_strm.h>
16 #include <mz_zip.h>
17 #include <mz_zip_rw.h>
18 #include <pugixml.hpp>
19
20 #include "Common/Align.h"
21 #include "Common/Assert.h"
22 #include "Common/CPUDetect.h"
23 #include "Common/CommonPaths.h"
24 #include "Common/CommonTypes.h"
25 #include "Common/Contains.h"
26 #include "Common/Crypto/SHA1.h"
27 #include "Common/FileUtil.h"
28 #include "Common/Hash.h"
29 #include "Common/HttpRequest.h"
30 #include "Common/IOFile.h"
31 #include "Common/Logging/Log.h"
32 #include "Common/MinizipUtil.h"
33 #include "Common/MsgHandler.h"
34 #include "Common/ScopeGuard.h"
35 #include "Common/StringUtil.h"
36 #include "Common/Swap.h"
37 #include "Common/Version.h"
38 #include "Core/IOS/Device.h"
39 #include "Core/IOS/ES/ES.h"
40 #include "Core/IOS/ES/Formats.h"
41 #include "Core/IOS/IOS.h"
42 #include "Core/IOS/IOSC.h"
43 #include "DiscIO/Blob.h"
44 #include "DiscIO/DiscScrubber.h"
45 #include "DiscIO/DiscUtils.h"
46 #include "DiscIO/Enums.h"
47 #include "DiscIO/Filesystem.h"
48 #include "DiscIO/Volume.h"
49 #include "DiscIO/VolumeWii.h"
50
51 namespace DiscIO
52 {
53 RedumpVerifier::DownloadState RedumpVerifier::m_gc_download_state;
54 RedumpVerifier::DownloadState RedumpVerifier::m_wii_download_state;
55
56 void RedumpVerifier::Start(const Volume& volume)
57 {
58 if (!volume.IsDatelDisc())
59 {
60 m_game_id = volume.GetGameID();
61 if (m_game_id.size() > 4)
62 m_game_id = m_game_id.substr(0, 4);
63 }
64
65 m_revision = volume.GetRevision().value_or(0);
66 m_disc_number = volume.GetDiscNumber().value_or(0);
67 m_size = volume.GetDataSize();
68
69 const Platform platform = volume.GetVolumeType();
70
71 m_future = std::async(std::launch::async, [this, platform]() -> std::vector<PotentialMatch> {
72 std::string system;
73 DownloadState* download_state;
74 switch (platform)
75 {
76 case Platform::GameCubeDisc:
77 system = "gc";
78 download_state = &m_gc_download_state;
79 break;
80
81 case Platform::WiiDisc:
82 system = "wii";
83 download_state = &m_wii_download_state;
84 break;
85
86 default:
87 m_result.status = Status::Error;
88 return {};
89 }
90
91 {
92 std::lock_guard lk(download_state->mutex);
93 download_state->status = DownloadDatfile(system, download_state->status);
94 }
95
96 switch (download_state->status)
97 {
98 case DownloadStatus::FailButOldCacheAvailable:
99 ERROR_LOG_FMT(DISCIO, "Failed to fetch data from Redump.info, using old cached data instead");
100 [[fallthrough]];
101 case DownloadStatus::Success:
102 return ScanDatfile(ReadDatfile(system), system);
103
104 case DownloadStatus::Fail:
105 default:
106 m_result = {Status::Error, Common::GetStringT("Failed to connect to Redump.info")};
107 return {};
108 }
109 });
110 }
111
112 static std::string GetPathForSystem(const std::string& system)
113 {
114 return File::GetUserPath(D_REDUMPCACHE_IDX) + DIR_SEP + system + ".zip";
115 }
116
117 RedumpVerifier::DownloadStatus RedumpVerifier::DownloadDatfile(const std::string& system,
118 DownloadStatus old_status)
119 {
120 if (old_status == DownloadStatus::Success)
121 return old_status;
122
123 Common::HttpRequest request;
124
125 const std::optional<std::vector<u8>> result =
126 request.Get("https://redump.info/datfile/" + system + "/serial,version",
127 {{"User-Agent", Common::GetEmulatorName()}});
128
129 const std::string output_path = GetPathForSystem(system);
130
131 if (!result)
132 {
133 return File::Exists(output_path) ? DownloadStatus::FailButOldCacheAvailable :
134 DownloadStatus::Fail;
135 }
136
137 if (result->size() > 1 && (*result)[0] == '<' && (*result)[1] == '!')
138 {
139 // This is an HTML page, not a zip file like we want
140 return File::Exists(output_path) ? DownloadStatus::FailButOldCacheAvailable :
141 DownloadStatus::Fail;
142 }
143
144 File::CreateFullPath(output_path);
145 if (!File::IOFile(output_path, "wb").WriteBytes(result->data(), result->size()))
146 ERROR_LOG_FMT(DISCIO, "Failed to write downloaded datfile to {}", output_path);
147 return DownloadStatus::Success;
148 }
149
150 std::vector<u8> RedumpVerifier::ReadDatfile(const std::string& system)
151 {
152 void* zip_reader = mz_zip_reader_create();
153 if (!zip_reader)
154 return {};
155
156 Common::ScopeGuard file_guard{[&] { mz_zip_reader_delete(&zip_reader); }};
157
158 if (mz_zip_reader_open_file(zip_reader, GetPathForSystem(system).c_str()) != MZ_OK)
159 return {};
160
161 // Check that the zip file contains exactly one file
162 if (mz_zip_reader_goto_first_entry(zip_reader) != MZ_OK)
163 return {};
164 if (mz_zip_reader_goto_next_entry(zip_reader) != MZ_END_OF_LIST)
165 return {};
166
167 // Read the file
168 if (mz_zip_reader_goto_first_entry(zip_reader) != MZ_OK)
169 return {};
170 mz_zip_file* file_info;
171 mz_zip_reader_entry_get_info(zip_reader, &file_info);
172 std::vector<u8> data(file_info->uncompressed_size);
173 if (!Common::ReadFileFromZip(zip_reader, data.data(), file_info->uncompressed_size))
174 return {};
175
176 return data;
177 }
178
179 static u8 ParseHexDigit(char c)
180 {
181 if (c < '0')
182 return 0; // Error
183
184 if (c >= 'a')
185 c -= 'a' - 'A';
186 if (c >= 'A')
187 c -= 'A' - ('9' + 1);
188 c -= '0';
189
190 if (c >= 0x10)
191 return 0; // Error
192
193 return c;
194 }
195
196 static std::vector<u8> ParseHash(const char* str)
197 {
198 std::vector<u8> hash;
199 while (str[0] && str[1])
200 {
201 hash.push_back(static_cast<u8>(ParseHexDigit(str[0]) * 0x10 + ParseHexDigit(str[1])));
202 str += 2;
203 }
204 return hash;
205 }
206
207 std::vector<RedumpVerifier::PotentialMatch> RedumpVerifier::ScanDatfile(std::span<const u8> data,
208 const std::string& system)
209 {
210 pugi::xml_document doc;
211 if (!doc.load_buffer(data.data(), data.size()))
212 {
213 m_result = {Status::Error, Common::GetStringT("Failed to parse Redump.info data")};
214 return {};
215 }
216
217 std::vector<PotentialMatch> potential_matches;
218 bool serials_exist = false;
219 bool versions_exist = false;
220 const pugi::xml_node datafile = doc.child("datafile");
221 for (const pugi::xml_node game : datafile.children("game"))
222 {
223 std::string version_string = game.child("version").text().as_string();
224 if (!version_string.empty())
225 versions_exist = true;
226
227 // Strip out prefix (e.g. "v1.02" -> "02", "Rev 2" -> "2")
228 const size_t last_non_numeric = version_string.find_last_not_of("0123456789");
229 if (last_non_numeric != std::string::npos)
230 version_string = version_string.substr(last_non_numeric + 1);
231
232 const int version = version_string.empty() ? 0 : std::stoi(version_string);
233
234 const std::string serials = game.child("serial").text().as_string();
235 if (!serials.empty())
236 serials_exist = true;
237
238 // The revisions for Korean GameCube games whose four-char game IDs end in E are numbered from
239 // 0x30 in ring codes and in disc headers, but Redump switched to numbering them from 0 in 2019.
240 if (version % 0x30 != m_revision % 0x30)
241 continue;
242
243 if (serials.empty() || serials.starts_with("DS"))
244 {
245 // GC Datel discs have no serials in Redump, Wii Datel discs have serials like "DS000101"
246 if (!m_game_id.empty())
247 continue; // Non-empty m_game_id means we're verifying a non-Datel disc
248 }
249 else
250 {
251 bool serial_match_found = false;
252
253 // If a disc has multiple possible serials, they are delimited with ", ". We want to loop
254 // through all the serials until we find a match, because even though they normally only
255 // differ in the region code at the end (which we don't care about), there is an edge case
256 // disc with the game ID "G96P" and the serial "DL-DOL-D96P-EUR, DL-DOL-G96P-EUR".
257 for (const std::string& serial_str : SplitString(serials, ','))
258 {
259 const std::string_view serial = StripWhitespace(serial_str);
260
261 // Skip the prefix, normally either "DL-DOL-" or "RVL-" (depending on the console),
262 // but there are some exceptions like the "RVLE-SBSE-USA-B0" serial.
263 const size_t first_dash = serial.find_first_of('-', 3);
264 const size_t game_id_start =
265 first_dash == std::string::npos ? std::string::npos : first_dash + 1;
266
267 if (game_id_start == std::string::npos || serial.size() < game_id_start + 4)
268 {
269 ERROR_LOG_FMT(DISCIO, "Invalid serial in redump datfile: {}", serial_str);
270 continue;
271 }
272
273 const std::string_view game_id = serial.substr(game_id_start, 4);
274 if (game_id != m_game_id)
275 continue;
276
277 u8 disc_number = 0;
278 if (serial.size() > game_id_start + 5 && serial[game_id_start + 5] >= '0' &&
279 serial[game_id_start + 5] <= '9')
280 {
281 disc_number = serial[game_id_start + 5] - '0';
282 }
283 if (disc_number != m_disc_number)
284 continue;
285
286 serial_match_found = true;
287 break;
288 }
289 if (!serial_match_found)
290 continue;
291 }
292
293 PotentialMatch& potential_match = potential_matches.emplace_back();
294 const pugi::xml_node rom = game.child("rom");
295 potential_match.size = rom.attribute("size").as_ullong();
296 potential_match.hashes.crc32 = ParseHash(rom.attribute("crc").value());
297 potential_match.hashes.md5 = ParseHash(rom.attribute("md5").value());
298 potential_match.hashes.sha1 = ParseHash(rom.attribute("sha1").value());
299 }
300
301 if (!serials_exist || !versions_exist)
302 {
303 // If we reach this, the user has most likely downloaded a datfile manually,
304 // so show a panic alert rather than just using ERROR_LOG
305
306 // i18n: "Serial" refers to serial numbers, e.g. RVL-RSBE-USA
307 PanicAlertFmtT(
308 "Serial and/or version data is missing from {0}\n"
309 "Please append \"{1}\" (without the quotes) to the datfile URL when downloading\n"
310 "Example: {2}",
311 GetPathForSystem(system), "serial,version", "http://redump.info/datfile/gc/serial,version");
312 m_result = {Status::Error, Common::GetStringT("Failed to parse Redump.info data")};
313 return {};
314 }
315
316 return potential_matches;
317 }
318
319 static bool HashesMatch(const std::vector<u8>& calculated, const std::vector<u8>& expected)
320 {
321 return calculated.empty() || calculated == expected;
322 }
323
324 RedumpVerifier::Result RedumpVerifier::Finish(const Hashes<std::vector<u8>>& hashes)
325 {
326 if (m_result.status == Status::Error)
327 return m_result;
328
329 if (hashes.crc32.empty() && hashes.md5.empty() && hashes.sha1.empty())
330 return m_result;
331
332 const std::vector<PotentialMatch> potential_matches = m_future.get();
333 for (PotentialMatch p : potential_matches)
334 {
335 if (HashesMatch(hashes.crc32, p.hashes.crc32) && HashesMatch(hashes.md5, p.hashes.md5) &&
336 HashesMatch(hashes.sha1, p.hashes.sha1) && m_size == p.size)
337 {
338 return {Status::GoodDump, Common::GetStringT("Good dump")};
339 }
340 }
341
342 // We only return bad dump if there's a disc that we know this dump should match but that doesn't
343 // match. For disc without IDs (i.e. Datel discs), we don't have a good way of knowing whether we
344 // have a bad dump or just a dump that isn't in Redump, so we always pick unknown instead of bad
345 // dump for those to be on the safe side. (Besides, it's possible to dump a Datel disc correctly
346 // and have it not match Redump if you don't use the same replacement value for bad sectors.)
347 if (!potential_matches.empty() && !m_game_id.empty())
348 return {Status::BadDump, Common::GetStringT("Bad dump")};
349
350 return {Status::Unknown, Common::GetStringT("Unknown disc")};
351 }
352
353 constexpr u64 DEFAULT_READ_SIZE = 0x20000; // Arbitrary value
354
355 VolumeVerifier::VolumeVerifier(const Volume& volume, bool redump_verification,
356 Hashes<bool> hashes_to_calculate)
357 : m_volume(volume), m_redump_verification(redump_verification),
358 m_hashes_to_calculate(hashes_to_calculate),
359 m_calculating_any_hash(hashes_to_calculate.crc32 || hashes_to_calculate.md5 ||
360 hashes_to_calculate.sha1),
361 m_max_progress(volume.GetDataSize()), m_data_size_type(volume.GetDataSizeType())
362 {
363 if (!m_calculating_any_hash)
364 m_redump_verification = false;
365 }
366
367 VolumeVerifier::~VolumeVerifier()
368 {
369 WaitForAsyncOperations();
370 }
371
372 Hashes<bool> VolumeVerifier::GetDefaultHashesToCalculate()
373 {
374 Hashes<bool> hashes_to_calculate{.crc32 = true, .md5 = true, .sha1 = true};
375 // If the system can compute certain hashes faster than others, only default-enable the fast ones.
376 const bool sha1_hw_accel = Common::SHA1::CreateContext()->HwAccelerated();
377 // For crc32, we assume zlib-ng will be fast if cpu supports crc32
378 const bool crc32_hw_accel = cpu_info.bCRC32;
379 if (crc32_hw_accel || sha1_hw_accel)
380 {
381 hashes_to_calculate.crc32 = crc32_hw_accel;
382 // md5 has no accelerated implementation at the moment, always default to off
383 hashes_to_calculate.md5 = false;
384 // Always enable SHA1, to avoid situation where only crc32 is computed
385 hashes_to_calculate.sha1 = true;
386 }
387 return hashes_to_calculate;
388 }
389
390 void VolumeVerifier::Start()
391 {
392 ASSERT(!m_started);
393 m_started = true;
394
395 if (m_redump_verification)
396 m_redump_verifier.Start(m_volume);
397
398 m_is_tgc = m_volume.GetBlobType() == BlobType::TGC;
399 m_is_datel = m_volume.IsDatelDisc();
400 m_is_triforce = m_volume.GetVolumeType() == Platform::Triforce;
401 m_is_not_retail = (m_volume.GetVolumeType() == Platform::WiiDisc && !m_volume.HasWiiHashes()) ||
402 IsDebugSigned();
403
404 const std::vector<Partition> partitions = CheckPartitions();
405
406 if (IsDisc(m_volume.GetVolumeType()))
407 m_biggest_referenced_offset = GetBiggestReferencedOffset(m_volume, partitions);
408
409 CheckMisc();
410
411 SetUpHashing();
412 }
413
414 std::vector<Partition> VolumeVerifier::CheckPartitions()
415 {
416 if (m_volume.GetVolumeType() == Platform::WiiWAD)
417 return {};
418
419 const std::vector<Partition> partitions = m_volume.GetPartitions();
420 if (partitions.empty())
421 {
422 if (!m_volume.GetFileSystem(m_volume.GetGamePartition()))
423 {
424 AddProblem(Severity::High,
425 Common::GetStringT("The filesystem is invalid or could not be read."));
426 return {};
427 }
428 return {m_volume.GetGamePartition()};
429 }
430
431 std::optional<u32> partitions_in_first_table = m_volume.ReadSwapped<u32>(0x40000, PARTITION_NONE);
432 if (partitions_in_first_table && *partitions_in_first_table > 8)
433 {
434 // Not sure if 8 actually is the limit, but there certainly aren't any discs
435 // released that have as many partitions as 8 in the first partition table.
436 // The only game that has that many partitions in total is Super Smash Bros. Brawl,
437 // and that game places all partitions other than UPDATE and DATA in the second table.
438 AddProblem(Severity::Low,
439 Common::GetStringT("There are too many partitions in the first partition table."));
440 }
441
442 std::vector<u32> types;
443 for (const Partition& partition : partitions)
444 {
445 const std::optional<u32> type = m_volume.GetPartitionType(partition);
446 if (type)
447 types.emplace_back(*type);
448 }
449
450 if (!Common::Contains(types, PARTITION_UPDATE))
451 AddProblem(Severity::Low, Common::GetStringT("The update partition is missing."));
452
453 const bool has_data_partition = Common::Contains(types, PARTITION_DATA);
454 if (!m_is_datel && !has_data_partition)
455 AddProblem(Severity::High, Common::GetStringT("The data partition is missing."));
456
457 const bool has_channel_partition = Common::Contains(types, PARTITION_CHANNEL);
458 if (ShouldHaveChannelPartition() && !has_channel_partition)
459 AddProblem(Severity::Medium, Common::GetStringT("The channel partition is missing."));
460
461 const bool has_install_partition = Common::Contains(types, PARTITION_INSTALL);
462 if (ShouldHaveInstallPartition() && !has_install_partition)
463 AddProblem(Severity::High, Common::GetStringT("The install partition is missing."));
464
465 if (ShouldHaveMasterpiecePartitions() &&
466 types.cend() == std::ranges::find_if(types, [](u32 type) { return type >= 0xFF; }))
467 {
468 // i18n: This string is referring to a game mode in Super Smash Bros. Brawl called Masterpieces
469 // where you play demos of NES/SNES/N64 games. Official translations:
470 // 名作トライアル (Japanese), Masterpieces (English), Meisterstücke (German), Chefs-d'œuvre
471 // (French), Clásicos (Spanish), Capolavori (Italian), 클래식 게임 체험판 (Korean).
472 // If your language is not one of the languages above, consider leaving the string untranslated
473 // so that people will recognize it as the name of the game mode.
474 AddProblem(Severity::Medium, Common::GetStringT("The Masterpiece partitions are missing."));
475 }
476
477 for (const Partition& partition : partitions)
478 {
479 if (m_volume.GetPartitionType(partition) == PARTITION_UPDATE && partition.offset != 0x50000)
480 {
481 AddProblem(Severity::Low,
482 Common::GetStringT("The update partition is not at its normal position."));
483 }
484
485 const u64 normal_data_offset = m_volume.HasWiiHashes() ? 0xF800000 : 0x838000;
486 if (m_volume.GetPartitionType(partition) == PARTITION_DATA &&
487 partition.offset != normal_data_offset && !has_channel_partition && !has_install_partition)
488 {
489 AddProblem(Severity::Low,
490 Common::GetStringT(
491 "The data partition is not at its normal position. This will affect the "
492 "emulated loading times. You will be unable to share input recordings and use "
493 "NetPlay with anyone who is using a good dump."));
494 }
495 }
496
497 std::vector<Partition> valid_partitions;
498 for (const Partition& partition : partitions)
499 {
500 if (CheckPartition(partition))
501 valid_partitions.push_back(partition);
502 }
503
504 return valid_partitions;
505 }
506
507 bool VolumeVerifier::CheckPartition(const Partition& partition)
508 {
509 std::optional<u32> type = m_volume.GetPartitionType(partition);
510 if (!type)
511 {
512 // Not sure if this can happen in practice
513 AddProblem(Severity::Medium, Common::GetStringT("The type of a partition could not be read."));
514 return false;
515 }
516
517 Severity severity = Severity::Medium;
518 if (*type == PARTITION_DATA || *type == PARTITION_INSTALL)
519 severity = Severity::High;
520 else if (*type == PARTITION_UPDATE)
521 severity = Severity::Low;
522
523 const std::string name = GetPartitionName(type);
524
525 if (partition.offset % VolumeWii::BLOCK_TOTAL_SIZE != 0 ||
526 m_volume.PartitionOffsetToRawOffset(0, partition) % VolumeWii::BLOCK_TOTAL_SIZE != 0)
527 {
528 AddProblem(Severity::Medium,
529 Common::FmtFormatT("The {0} partition is not properly aligned.", name));
530 }
531
532 bool invalid_header = false;
533 bool blank_contents = false;
534 std::vector<u8> disc_header(0x80);
535 if (!m_volume.Read(0, disc_header.size(), disc_header.data(), partition))
536 {
537 invalid_header = true;
538 }
539 else if (Common::swap32(disc_header.data() + 0x18) != WII_DISC_MAGIC)
540 {
541 for (size_t i = 0; i < disc_header.size(); i += 4)
542 {
543 if (Common::swap32(disc_header.data() + i) != i)
544 {
545 invalid_header = true;
546 break;
547 }
548 }
549
550 // The loop above ends without setting invalid_header for discs that legitimately lack
551 // updates. No such discs have been released to end users. Most such discs are debug signed,
552 // but there is apparently at least one that is retail signed, the Movie-Ch Install Disc.
553 if (!invalid_header)
554 blank_contents = true;
555 }
556 if (invalid_header)
557 {
558 // This can happen when certain programs that create WBFS files scrub the entirety of
559 // the Masterpiece partitions in Super Smash Bros. Brawl without removing them from
560 // the partition table. https://bugs.dolphin-emu.org/issues/8733
561 AddProblem(severity,
562 Common::FmtFormatT("The {0} partition does not seem to contain valid data.", name));
563 return false;
564 }
565
566 if (!m_is_datel)
567 {
568 const auto console_type =
569 IsDebugSigned() ? IOS::HLE::IOSC::ConsoleType::RVT : IOS::HLE::IOSC::ConsoleType::Retail;
570 IOS::HLE::Kernel ios(console_type);
571 auto& es = ios.GetESCore();
572 const std::vector<u8>& cert_chain = m_volume.GetCertificateChain(partition);
573
574 if (IOS::HLE::IPC_SUCCESS !=
575 es.VerifyContainer(IOS::HLE::ESCore::VerifyContainerType::Ticket,
576 IOS::HLE::ESCore::VerifyMode::DoNotUpdateCertStore,
577 m_volume.GetTicket(partition), cert_chain) ||
578 IOS::HLE::IPC_SUCCESS !=
579 es.VerifyContainer(IOS::HLE::ESCore::VerifyContainerType::TMD,
580 IOS::HLE::ESCore::VerifyMode::DoNotUpdateCertStore,
581 m_volume.GetTMD(partition), cert_chain))
582 {
583 AddProblem(Severity::Low,
584 Common::FmtFormatT("The {0} partition is not correctly signed.", name));
585 }
586 }
587
588 if (m_volume.HasWiiHashes() && !m_volume.CheckH3TableIntegrity(partition))
589 {
590 AddProblem(Severity::Low,
591 Common::FmtFormatT("The H3 hash table for the {0} partition is not correct.", name));
592 }
593
594 // Prepare for hash verification in the Process step
595 if (m_volume.HasWiiHashes())
596 {
597 const u64 data_size =
598 m_volume.ReadSwappedAndShifted(partition.offset + 0x2bc, PARTITION_NONE).value_or(0);
599 const size_t blocks = static_cast<size_t>(data_size / VolumeWii::BLOCK_TOTAL_SIZE);
600
601 if (data_size % VolumeWii::BLOCK_TOTAL_SIZE != 0)
602 {
603 std::string text = Common::FmtFormatT(
604 "The data size for the {0} partition is not evenly divisible by the block size.", name);
605 AddProblem(Severity::Low, std::move(text));
606 }
607
608 u64 offset = m_volume.PartitionOffsetToRawOffset(0, partition);
609 for (size_t block_index = 0; block_index < blocks;
610 block_index += VolumeWii::BLOCKS_PER_GROUP, offset += VolumeWii::GROUP_TOTAL_SIZE)
611 {
612 m_groups.emplace_back(
613 GroupToVerify{partition, offset, block_index,
614 std::min(block_index + VolumeWii::BLOCKS_PER_GROUP, blocks)});
615 }
616
617 m_block_errors.emplace(partition, 0);
618 }
619
620 if (blank_contents)
621 return false;
622
623 const FileSystem* filesystem = m_volume.GetFileSystem(partition);
624 if (!filesystem)
625 {
626 if (m_is_datel)
627 {
628 // Datel's Wii Freeloader has an invalid FST in its only partition
629 return true;
630 }
631
632 AddProblem(severity,
633 Common::FmtFormatT("The {0} partition does not have a valid file system.", name));
634 return false;
635 }
636
637 if (type == PARTITION_UPDATE)
638 {
639 const IOS::ES::TMDReader& tmd = m_volume.GetTMD(m_volume.GetGamePartition());
640 if (tmd.IsValid())
641 {
642 const u64 ios_ver = tmd.GetIOSId() & 0xFF;
643 bool has_correct_ios = false;
644
645 if (ios_ver == 9)
646 {
647 // IOS9 is the only IOS which can be assumed to exist in a working state on any Wii
648 // regardless of what updates have been installed. At least Mario Party 8
649 // (RM8E01, revision 2) uses IOS9 without having it in its update partition.
650 has_correct_ios = true;
651 }
652 else
653 {
654 std::unique_ptr<FileInfo> file_info = filesystem->FindFileInfo("_sys");
655 if (file_info)
656 {
657 const std::string ios_ver_str = std::to_string(ios_ver);
658 const std::string correct_ios =
659 IsDebugSigned() ? ("firmware.64." + ios_ver_str + ".") : ("ios" + ios_ver_str + "-");
660 for (const FileInfo& f : *file_info)
661 {
662 std::string file_name = f.GetName();
663 Common::ToLower(&file_name);
664 if (file_name.starts_with(correct_ios))
665 {
666 has_correct_ios = true;
667 break;
668 }
669 }
670 }
671 }
672
673 if (!has_correct_ios)
674 {
675 // This is reached for hacked dumps where the update partition has been replaced with
676 // a very old update partition so that no updates will be installed.
677 AddProblem(Severity::Low,
678 Common::GetStringT(
679 "The update partition does not contain the IOS used by this title."));
680 }
681 }
682 }
683
684 const IOS::ES::TicketReader& ticket = m_volume.GetTicket(partition);
685 if (!ticket.IsValid())
686 {
687 AddProblem(severity,
688 // i18n: "Ticket" here is a kind of digital authorization to use a certain title
689 // (e.g. a game)
690 Common::FmtFormatT("The {0} partition does not have a valid ticket.", name));
691 }
692
693 const IOS::ES::TMDReader& tmd = m_volume.GetTMD(partition);
694 if (!tmd.IsValid())
695 {
696 AddProblem(severity, Common::FmtFormatT("The {0} partition does not have a valid TMD.", name));
697 }
698
699 return true;
700 }
701
702 std::string VolumeVerifier::GetPartitionName(std::optional<u32> type) const
703 {
704 if (!type)
705 return "???";
706
707 std::string name = NameForPartitionType(*type, false);
708 if (ShouldHaveMasterpiecePartitions() && *type > 0xFF)
709 {
710 // i18n: This string is referring to a game mode in Super Smash Bros. Brawl called Masterpieces
711 // where you play demos of NES/SNES/N64 games. This string is referring to a specific such demo
712 // rather than the game mode as a whole, so please use the singular form. Official translations:
713 // 名作トライアル (Japanese), Masterpieces (English), Meisterstücke (German), Chefs-d'œuvre
714 // (French), Clásicos (Spanish), Capolavori (Italian), 클래식 게임 체험판 (Korean).
715 // If your language is not one of the languages above, consider leaving the string untranslated
716 // so that people will recognize it as the name of the game mode.
717 return Common::FmtFormatT("{0} (Masterpiece)", name);
718 }
719 return name;
720 }
721
722 bool VolumeVerifier::IsDebugSigned() const
723 {
724 const IOS::ES::TicketReader& ticket = m_volume.GetTicket(m_volume.GetGamePartition());
725 return ticket.IsValid() ? ticket.GetConsoleType() == IOS::HLE::IOSC::ConsoleType::RVT : false;
726 }
727
728 bool VolumeVerifier::ShouldHaveChannelPartition() const
729 {
730 static constexpr std::array<std::string_view, 18> channel_discs = {
731 "RFNE01", "RFNJ01", "RFNK01", "RFNP01", "RFNW01", "RFPE01", "RFPJ01", "RFPK01", "RFPP01",
732 "RFPW01", "RGWE41", "RGWJ41", "RGWP41", "RGWX41", "RMCE01", "RMCJ01", "RMCK01", "RMCP01",
733 };
734 static_assert(std::ranges::is_sorted(channel_discs));
735
736 return std::ranges::binary_search(channel_discs, m_volume.GetGameID());
737 }
738
739 bool VolumeVerifier::ShouldHaveInstallPartition() const
740 {
741 static constexpr std::array<std::string_view, 4> dragon_quest_x = {"S4MJGD", "S4SJGD", "S6TJGD",
742 "SDQJGD"};
743 const std::string& game_id = m_volume.GetGameID();
744 return std::ranges::any_of(dragon_quest_x,
745 [&game_id](std::string_view x) { return x == game_id; });
746 }
747
748 bool VolumeVerifier::ShouldHaveMasterpiecePartitions() const
749 {
750 static constexpr std::array<std::string_view, 4> ssbb = {"RSBE01", "RSBJ01", "RSBK01", "RSBP01"};
751 const std::string& game_id = m_volume.GetGameID();
752 return std::ranges::any_of(ssbb, [&game_id](std::string_view x) { return x == game_id; });
753 }
754
755 bool VolumeVerifier::ShouldBeDualLayer() const
756 {
757 // The Japanese versions of Xenoblade and The Last Story are single-layer
758 // (unlike the other versions) and must not be added to this list.
759 static constexpr std::array<std::string_view, 33> dual_layer_discs = {
760 "R3ME01", "R3MP01", "R3OE01", "R3OJ01", "R3OP01", "RSBE01", "RSBJ01", "RSBK01", "RSBP01",
761 "RXMJ8P", "S59E01", "S59JC8", "S59P01", "S5QJC8", "SAKENS", "SAKPNS", "SK8V52", "SK8X52",
762 "SLSEXJ", "SLSP01", "SQIE4Q", "SQIP4Q", "SQIY4Q", "SR5E41", "SR5P41", "SUOE41", "SUOP41",
763 "SVXX52", "SVXY52", "SX4E01", "SX4P01", "SZ3EGT", "SZ3PGT",
764 };
765 static_assert(std::ranges::is_sorted(dual_layer_discs));
766
767 return std::ranges::binary_search(dual_layer_discs, m_volume.GetGameID());
768 }
769
770 void VolumeVerifier::CheckVolumeSize()
771 {
772 u64 volume_size = m_volume.GetDataSize();
773 const bool is_disc = IsDisc(m_volume.GetVolumeType());
774 const bool should_be_dual_layer = is_disc && ShouldBeDualLayer();
775 bool volume_size_roughly_known = m_data_size_type != DataSizeType::UpperBound;
776
777 if (should_be_dual_layer && m_biggest_referenced_offset <= SL_DVD_R_SIZE)
778 {
779 AddProblem(Severity::Medium,
780 Common::GetStringT(
781 "This game has been hacked to fit on a single-layer DVD. Some content such as "
782 "pre-rendered videos, extra languages or entire game modes will be broken. "
783 "This problem generally only exists in illegal copies of games."));
784 }
785
786 if (m_data_size_type != DataSizeType::Accurate)
787 {
788 AddProblem(Severity::Low,
789 Common::GetStringT("The format that the disc image is saved in does not "
790 "store the size of the disc image."));
791
792 if (!volume_size_roughly_known && m_volume.HasWiiHashes())
793 {
794 volume_size = m_biggest_verified_offset;
795 volume_size_roughly_known = true;
796 }
797 }
798
799 if (m_content_index != m_content_offsets.size() || m_group_index != m_groups.size() ||
800 (!m_is_datel && volume_size_roughly_known && m_biggest_referenced_offset > volume_size))
801 {
802 const bool second_layer_missing = is_disc && volume_size_roughly_known &&
803 volume_size >= SL_DVD_SIZE && volume_size <= SL_DVD_R_SIZE;
804 std::string text =
805 second_layer_missing ?
806 Common::GetStringT("This disc image is too small and lacks some data. The problem is "
807 "most likely that this is a dual-layer disc that has been dumped "
808 "as a single-layer disc.") :
809 Common::GetStringT("This disc image is too small and lacks some data. If your "
810 "dumping program saved the disc image as several parts, you need "
811 "to merge them into one file.");
812 AddProblem(Severity::High, std::move(text));
813 return;
814 }
815
816 // The reason why this condition is checking for m_data_size_type != UpperBound instead of
817 // m_data_size_type == Accurate is because we want to show the warning about input recordings and
818 // NetPlay for NFS disc images (which are the only disc images that have it set to LowerBound).
819 if (is_disc && m_data_size_type != DataSizeType::UpperBound && !m_is_tgc)
820 {
821 const Platform platform = m_volume.GetVolumeType();
822 const bool should_be_gc_size = platform == Platform::GameCubeDisc || m_is_datel;
823
824 const bool valid_gamecube = volume_size == MINI_DVD_SIZE;
825 const bool valid_retail_wii = volume_size == SL_DVD_SIZE || volume_size == DL_DVD_SIZE;
826 const bool valid_debug_wii = volume_size == SL_DVD_R_SIZE || volume_size == DL_DVD_R_SIZE;
827
828 const bool debug = IsDebugSigned();
829 if ((should_be_gc_size && !valid_gamecube) ||
830 (!should_be_gc_size && (debug ? !valid_debug_wii : !valid_retail_wii)))
831 {
832 if (debug && valid_retail_wii)
833 {
834 AddProblem(
835 Severity::Low,
836 Common::GetStringT("This debug disc image has the size of a retail disc image."));
837 }
838 else
839 {
840 u64 normal_size;
841 if (should_be_gc_size)
842 normal_size = MINI_DVD_SIZE;
843 else if (!should_be_dual_layer)
844 normal_size = SL_DVD_SIZE;
845 else
846 normal_size = DL_DVD_SIZE;
847
848 if (volume_size < normal_size)
849 {
850 AddProblem(
851 Severity::Low,
852 Common::GetStringT(
853 "This disc image has an unusual size. This will likely make the emulated "
854 "loading times longer. You will likely be unable to share input recordings "
855 "and use NetPlay with anyone who is using a good dump."));
856 }
857 else
858 {
859 AddProblem(Severity::Low, Common::GetStringT("This disc image has an unusual size."));
860 }
861 }
862 }
863 }
864 }
865
866 void VolumeVerifier::CheckMisc()
867 {
868 const std::string game_id_unencrypted = m_volume.GetGameID(PARTITION_NONE);
869 const std::string game_id_encrypted = m_volume.GetGameID(m_volume.GetGamePartition());
870
871 if (game_id_unencrypted != game_id_encrypted)
872 {
873 bool inconsistent_game_id = true;
874 if (game_id_encrypted == "RELSAB")
875 {
876 if (game_id_unencrypted.starts_with("410"))
877 {
878 // This is the Wii Backup Disc (aka "pinkfish" disc),
879 // which legitimately has an inconsistent game ID.
880 inconsistent_game_id = false;
881 }
882 else if (game_id_unencrypted.starts_with("010"))
883 {
884 // Hacked version of the Wii Backup Disc (aka "pinkfish" disc).
885 std::string proper_game_id = game_id_unencrypted;
886 proper_game_id[0] = '4';
887 AddProblem(Severity::Low, Common::FmtFormatT("The game ID is {0} but should be {1}.",
888 game_id_unencrypted, proper_game_id));
889 inconsistent_game_id = false;
890 }
891 }
892
893 if (inconsistent_game_id)
894 {
895 AddProblem(Severity::Low, Common::GetStringT("The game ID is inconsistent."));
896 }
897 }
898
899 const Region region = m_volume.GetRegion();
900
901 constexpr std::string_view GAMECUBE_PLACEHOLDER_ID = "RELSAB";
902 constexpr std::string_view WII_PLACEHOLDER_ID = "RABAZZ";
903
904 if (game_id_encrypted.size() < 4)
905 {
906 AddProblem(Severity::Low, Common::GetStringT("The game ID is unusually short."));
907 }
908 else if (!m_is_datel && game_id_encrypted != GAMECUBE_PLACEHOLDER_ID &&
909 game_id_encrypted != WII_PLACEHOLDER_ID)
910 {
911 char country_code;
912 if (IsDisc(m_volume.GetVolumeType()))
913 country_code = game_id_encrypted[3];
914 else
915 country_code = static_cast<char>(m_volume.GetTitleID().value_or(0) & 0xff);
916
917 const Platform platform = m_volume.GetVolumeType();
918 const std::optional<u16> revision = m_volume.GetRevision();
919
920 if (CountryCodeToRegion(country_code, platform, region, revision) != region)
921 {
922 AddProblem(Severity::Medium,
923 Common::GetStringT(
924 "The region code does not match the game ID. If this is because the "
925 "region code has been modified, the game might run at the wrong speed, "
926 "graphical elements might be offset, or the game might not run at all."));
927 }
928 }
929
930 const IOS::ES::TMDReader& tmd = m_volume.GetTMD(m_volume.GetGamePartition());
931 if (tmd.IsValid())
932 {
933 const u64 ios_id = tmd.GetIOSId() & 0xFF;
934
935 // List of launch day Korean IOSes obtained from https://hackmii.com/2008/09/korean-wii/.
936 // More IOSes were released later that were used in Korean games, but they're all over 40.
937 // Also, old IOSes like IOS36 did eventually get released for Korean Wiis as part of system
938 // updates, but there are likely no Korean games using them since those IOSes were old by then.
939 if (region == Region::NTSC_K && ios_id < 40 && ios_id != 4 && ios_id != 9 && ios_id != 21 &&
940 ios_id != 37)
941 {
942 // This is intended to catch Korean games (usually but not always pirated) that have the IOS
943 // slot set to 36 as a side effect of having to fakesign after changing the common key slot to
944 // 0. (IOS36 was the last IOS with the Trucha bug.) https://bugs.dolphin-emu.org/issues/10319
945 AddProblem(
946 Severity::High,
947 // i18n: You may want to leave the term "ERROR #002" untranslated,
948 // since the emulated software always displays it in English.
949 Common::GetStringT("This Korean title is set to use an IOS that typically isn't used on "
950 "Korean consoles. This is likely to lead to ERROR #002."));
951 }
952
953 if (ios_id >= 0x80)
954 {
955 // This is intended to catch the same kind of fakesigned Korean games,
956 // but this time with the IOS slot set to cIOS instead of IOS36.
957 AddProblem(Severity::High, Common::GetStringT("This title is set to use an invalid IOS."));
958 }
959 }
960
961 m_ticket = m_volume.GetTicket(m_volume.GetGamePartition());
962 if (m_ticket.IsValid())
963 {
964 const u8 specified_common_key_index = m_ticket.GetCommonKeyIndex();
965
966 // Wii discs only use common key 0 (regular) and common key 1 (Korean), not common key 2 (vWii).
967 if (m_volume.GetVolumeType() == Platform::WiiDisc && specified_common_key_index > 1)
968 {
969 AddProblem(Severity::High,
970 // i18n: This is "common" as in "shared", not the opposite of "uncommon"
971 Common::GetStringT("This title is set to use an invalid common key."));
972 }
973
974 if (m_volume.GetVolumeType() == Platform::WiiWAD)
975 {
976 m_ticket = m_volume.GetTicketWithFixedCommonKey();
977 const u8 fixed_common_key_index = m_ticket.GetCommonKeyIndex();
978 if (specified_common_key_index != fixed_common_key_index)
979 {
980 // Many fakesigned WADs have the common key index set to a (random?) bogus value.
981 // For WADs, Dolphin will detect this and use the correct key, making this low severity.
982 AddProblem(Severity::Low,
983 // i18n: This is "common" as in "shared", not the opposite of "uncommon"
984 Common::FmtFormatT("The specified common key index is {0} but should be {1}.",
985 specified_common_key_index, fixed_common_key_index));
986 }
987 }
988 }
989
990 if (m_volume.GetVolumeType() == Platform::WiiWAD)
991 {
992 IOS::HLE::Kernel ios(m_ticket.GetConsoleType());
993 auto& es = ios.GetESCore();
994 const std::vector<u8>& cert_chain = m_volume.GetCertificateChain(PARTITION_NONE);
995
996 if (!m_ticket.IsValid())
997 {
998 // i18n: "Ticket" here is a kind of digital authorization to use a certain title (e.g. a game)
999 AddProblem(Severity::High, Common::GetStringT("The ticket is invalid."));
1000 }
1001 else if (IOS::HLE::IPC_SUCCESS !=
1002 es.VerifyContainer(IOS::HLE::ESCore::VerifyContainerType::Ticket,
1003 IOS::HLE::ESCore::VerifyMode::DoNotUpdateCertStore, m_ticket,
1004 cert_chain))
1005 {
1006 // i18n: "Ticket" here is a kind of digital authorization to use a certain title (e.g. a game)
1007 AddProblem(Severity::Low, Common::GetStringT("The ticket is not correctly signed."));
1008 }
1009
1010 if (!tmd.IsValid())
1011 {
1012 AddProblem(Severity::High, Common::GetStringT("The TMD is invalid."));
1013 }
1014 else if (IOS::HLE::IPC_SUCCESS !=
1015 es.VerifyContainer(IOS::HLE::ESCore::VerifyContainerType::TMD,
1016 IOS::HLE::ESCore::VerifyMode::DoNotUpdateCertStore, tmd,
1017 cert_chain))
1018 {
1019 AddProblem(
1020 Severity::Medium,
1021 Common::GetStringT("The TMD is not correctly signed. If you move or copy this title to "
1022 "the SD Card, the Wii System Menu will not launch it anymore and will "
1023 "also refuse to copy or move it back to the NAND."));
1024 }
1025 }
1026
1027 if (m_volume.IsNKit())
1028 {
1029 AddProblem(
1030 Severity::Low,
1031 Common::GetStringT("This disc image is in the NKit format. It is not a good dump in its "
1032 "current form, but it might become a good dump if converted back. "
1033 "The CRC32 of this file might match the CRC32 of a good dump even "
1034 "though the files are not identical."));
1035 }
1036
1037 if (IsDisc(m_volume.GetVolumeType()) && game_id_unencrypted.starts_with("R8P"))
1038 CheckSuperPaperMario();
1039 }
1040
1041 void VolumeVerifier::CheckSuperPaperMario()
1042 {
1043 // When Super Paper Mario (any region/revision) reads setup/aa1_01.dat when starting a new game,
1044 // it also reads a few extra bytes so that the read length is divisible by 0x20. If these extra
1045 // bytes are zeroes like in good dumps, the game works correctly, but otherwise it can freeze
1046 // (depending on the exact values of the extra bytes). https://bugs.dolphin-emu.org/issues/11900
1047
1048 const Partition partition = m_volume.GetGamePartition();
1049 const FileSystem* fs = m_volume.GetFileSystem(partition);
1050 if (!fs)
1051 return;
1052
1053 std::unique_ptr<FileInfo> file_info = fs->FindFileInfo("setup/aa1_01.dat");
1054 if (!file_info)
1055 return;
1056
1057 const u64 offset = file_info->GetOffset() + file_info->GetSize();
1058 const u64 length = Common::AlignUp(offset, 0x20) - offset;
1059 std::vector<u8> data(length);
1060 if (!m_volume.Read(offset, length, data.data(), partition))
1061 return;
1062
1063 if (std::ranges::any_of(data, [](u8 x) { return x != 0; }))
1064 {
1065 AddProblem(Severity::High,
1066 Common::GetStringT("Some padding data that should be zero is not zero. "
1067 "This can make the game freeze at certain points."));
1068 }
1069 }
1070
1071 void VolumeVerifier::SetUpHashing()
1072 {
1073 if (m_volume.GetVolumeType() == Platform::WiiWAD)
1074 {
1075 m_content_offsets = m_volume.GetContentOffsets();
1076 }
1077 else if (m_volume.GetVolumeType() == Platform::WiiDisc)
1078 {
1079 // Set up a DiscScrubber for checking whether blocks with errors are unused
1080 m_scrubber.SetupScrub(m_volume);
1081 }
1082
1083 std::ranges::sort(m_groups, {}, &GroupToVerify::offset);
1084
1085 if (m_hashes_to_calculate.crc32)
1086 m_crc32_context = Common::StartCRC32();
1087
1088 if (m_hashes_to_calculate.md5)
1089 {
1090 mbedtls_md5_init(&m_md5_context);
1091 mbedtls_md5_starts_ret(&m_md5_context);
1092 }
1093
1094 if (m_hashes_to_calculate.sha1)
1095 {
1096 m_sha1_context = Common::SHA1::CreateContext();
1097 }
1098 }
1099
1100 void VolumeVerifier::WaitForAsyncOperations() const
1101 {
1102 if (m_crc32_future.valid())
1103 m_crc32_future.wait();
1104 if (m_md5_future.valid())
1105 m_md5_future.wait();
1106 if (m_sha1_future.valid())
1107 m_sha1_future.wait();
1108 if (m_content_future.valid())
1109 m_content_future.wait();
1110 if (m_group_future.valid())
1111 m_group_future.wait();
1112 }
1113
1114 bool VolumeVerifier::ReadChunkAndWaitForAsyncOperations(u64 bytes_to_read)
1115 {
1116 std::vector<u8> data(bytes_to_read);
1117
1118 const u64 bytes_to_copy = std::min(m_excess_bytes, bytes_to_read);
1119 if (bytes_to_copy > 0)
1120 std::memcpy(data.data(), m_data.data() + m_data.size() - m_excess_bytes, bytes_to_copy);
1121 bytes_to_read -= bytes_to_copy;
1122
1123 if (bytes_to_read > 0)
1124 {
1125 if (!m_volume.Read(m_progress + bytes_to_copy, bytes_to_read, data.data() + bytes_to_copy,
1126 PARTITION_NONE))
1127 {
1128 return false;
1129 }
1130 }
1131
1132 WaitForAsyncOperations();
1133 m_data = std::move(data);
1134 return true;
1135 }
1136
1137 void VolumeVerifier::Process()
1138 {
1139 ASSERT(m_started);
1140 ASSERT(!m_done);
1141
1142 if (m_progress >= m_max_progress)
1143 return;
1144
1145 IOS::ES::Content content{};
1146 bool content_read = false;
1147 bool group_read = false;
1148 u64 bytes_to_read = DEFAULT_READ_SIZE;
1149 u64 excess_bytes = 0;
1150 if (m_content_index < m_content_offsets.size() &&
1151 m_content_offsets[m_content_index] == m_progress)
1152 {
1153 m_volume.GetTMD(PARTITION_NONE).GetContent(m_content_index, &content);
1154 bytes_to_read = Common::AlignUp(content.size, 0x40);
1155 content_read = true;
1156
1157 const u16 next_content_index = m_content_index + 1;
1158 if (next_content_index < m_content_offsets.size() &&
1159 m_content_offsets[next_content_index] < m_progress + bytes_to_read)
1160 {
1161 excess_bytes = m_progress + bytes_to_read - m_content_offsets[next_content_index];
1162 }
1163 }
1164 else if (m_content_index < m_content_offsets.size() &&
1165 m_content_offsets[m_content_index] > m_progress)
1166 {
1167 bytes_to_read = std::min(bytes_to_read, m_content_offsets[m_content_index] - m_progress);
1168 }
1169 else if (m_group_index < m_groups.size() && m_groups[m_group_index].offset == m_progress)
1170 {
1171 const size_t blocks =
1172 m_groups[m_group_index].block_index_end - m_groups[m_group_index].block_index_start;
1173 bytes_to_read = VolumeWii::BLOCK_TOTAL_SIZE * blocks;
1174 group_read = true;
1175
1176 if (m_group_index + 1 < m_groups.size() &&
1177 m_groups[m_group_index + 1].offset < m_progress + bytes_to_read)
1178 {
1179 excess_bytes = m_progress + bytes_to_read - m_groups[m_group_index + 1].offset;
1180 }
1181 }
1182 else if (m_group_index < m_groups.size() && m_groups[m_group_index].offset > m_progress)
1183 {
1184 bytes_to_read = std::min(bytes_to_read, m_groups[m_group_index].offset - m_progress);
1185 }
1186
1187 if (m_progress + bytes_to_read > m_max_progress)
1188 {
1189 const u64 bytes_over_max = m_progress + bytes_to_read - m_max_progress;
1190
1191 if (m_data_size_type == DataSizeType::LowerBound)
1192 {
1193 // Disc images in NFS format can have the last referenced block be past m_max_progress.
1194 // For NFS, reading beyond m_max_progress doesn't return an error, so let's read beyond it.
1195 excess_bytes = std::max(excess_bytes, bytes_over_max);
1196 }
1197 else
1198 {
1199 // Don't read beyond the end of the disc.
1200 bytes_to_read -= bytes_over_max;
1201 excess_bytes -= std::min(excess_bytes, bytes_over_max);
1202 content_read = false;
1203 group_read = false;
1204 }
1205 }
1206
1207 const bool is_data_needed = m_calculating_any_hash || content_read || group_read;
1208 const bool read_failed = is_data_needed && !ReadChunkAndWaitForAsyncOperations(bytes_to_read);
1209
1210 if (read_failed)
1211 {
1212 ERROR_LOG_FMT(DISCIO, "Read failed at {:#x} to {:#x}", m_progress, m_progress + bytes_to_read);
1213
1214 m_read_errors_occurred = true;
1215 m_calculating_any_hash = false;
1216 }
1217
1218 m_excess_bytes = excess_bytes;
1219 const u64 byte_increment = bytes_to_read - excess_bytes;
1220
1221 if (m_calculating_any_hash)
1222 {
1223 if (m_hashes_to_calculate.crc32)
1224 {
1225 m_crc32_future = std::async(std::launch::async, [this, byte_increment] {
1226 m_crc32_context = Common::UpdateCRC32(m_crc32_context, m_data.data(),
1227 static_cast<size_t>(byte_increment));
1228 });
1229 }
1230
1231 if (m_hashes_to_calculate.md5)
1232 {
1233 m_md5_future = std::async(std::launch::async, [this, byte_increment] {
1234 mbedtls_md5_update_ret(&m_md5_context, m_data.data(), byte_increment);
1235 });
1236 }
1237
1238 if (m_hashes_to_calculate.sha1)
1239 {
1240 m_sha1_future = std::async(std::launch::async, [this, byte_increment] {
1241 m_sha1_context->Update(m_data.data(), byte_increment);
1242 });
1243 }
1244 }
1245
1246 if (content_read)
1247 {
1248 m_content_future = std::async(std::launch::async, [this, read_failed, content] {
1249 if (read_failed || !m_volume.CheckContentIntegrity(content, m_data, m_ticket))
1250 {
1251 AddProblem(Severity::High, Common::FmtFormatT("Content {0:08x} is corrupt.", content.id));
1252 }
1253 });
1254
1255 m_content_index++;
1256 }
1257
1258 if (group_read)
1259 {
1260 m_group_future = std::async(std::launch::async, [this, read_failed,
1261 group_index = m_group_index] {
1262 const GroupToVerify& group = m_groups[group_index];
1263 u64 offset_in_group = 0;
1264 for (u64 block_index = group.block_index_start; block_index < group.block_index_end;
1265 ++block_index, offset_in_group += VolumeWii::BLOCK_TOTAL_SIZE)
1266 {
1267 const u64 block_offset = group.offset + offset_in_group;
1268
1269 if (!read_failed && m_volume.CheckBlockIntegrity(
1270 block_index, m_data.data() + offset_in_group, group.partition))
1271 {
1272 m_biggest_verified_offset =
1273 std::max(m_biggest_verified_offset, block_offset + VolumeWii::BLOCK_TOTAL_SIZE);
1274 }
1275 else
1276 {
1277 if (m_scrubber.CanBlockBeScrubbed(block_offset))
1278 {
1279 WARN_LOG_FMT(DISCIO, "Integrity check failed for unused block at {:#x}", block_offset);
1280 m_unused_block_errors[group.partition]++;
1281 }
1282 else
1283 {
1284 WARN_LOG_FMT(DISCIO, "Integrity check failed for block at {:#x}", block_offset);
1285 m_block_errors[group.partition]++;
1286 }
1287 }
1288 }
1289 });
1290
1291 m_group_index++;
1292 }
1293
1294 m_progress += byte_increment;
1295 }
1296
1297 u64 VolumeVerifier::GetBytesProcessed() const
1298 {
1299 return m_progress;
1300 }
1301
1302 u64 VolumeVerifier::GetTotalBytes() const
1303 {
1304 return m_max_progress;
1305 }
1306
1307 void VolumeVerifier::Finish()
1308 {
1309 if (m_done)
1310 return;
1311 m_done = true;
1312
1313 WaitForAsyncOperations();
1314
1315 if (m_calculating_any_hash)
1316 {
1317 if (m_hashes_to_calculate.crc32)
1318 {
1319 m_result.hashes.crc32 = std::vector<u8>(4);
1320 const u32 crc32_be = Common::swap32(m_crc32_context);
1321 std::memcpy(m_result.hashes.crc32.data(), &crc32_be, 4);
1322 }
1323
1324 if (m_hashes_to_calculate.md5)
1325 {
1326 m_result.hashes.md5 = std::vector<u8>(16);
1327 mbedtls_md5_finish_ret(&m_md5_context, m_result.hashes.md5.data());
1328 }
1329
1330 if (m_hashes_to_calculate.sha1)
1331 {
1332 const auto digest = m_sha1_context->Finish();
1333 m_result.hashes.sha1 = std::vector<u8>(digest.begin(), digest.end());
1334 }
1335 }
1336
1337 if (m_read_errors_occurred)
1338 AddProblem(Severity::Medium, Common::GetStringT("Some of the data could not be read."));
1339
1340 CheckVolumeSize();
1341
1342 for (auto [partition, blocks] : m_block_errors)
1343 {
1344 if (blocks > 0)
1345 {
1346 const std::string name = GetPartitionName(m_volume.GetPartitionType(partition));
1347 AddProblem(Severity::Medium,
1348 Common::FmtFormatT("Errors were found in {0} blocks in the {1} partition.", blocks,
1349 name));
1350 }
1351 }
1352
1353 for (auto [partition, blocks] : m_unused_block_errors)
1354 {
1355 if (blocks > 0)
1356 {
1357 const std::string name = GetPartitionName(m_volume.GetPartitionType(partition));
1358 AddProblem(Severity::Low,
1359 Common::FmtFormatT("Errors were found in {0} unused blocks in the {1} partition.",
1360 blocks, name));
1361 }
1362 }
1363
1364 // Show the most serious problems at the top
1365 std::ranges::stable_sort(m_result.problems, std::ranges::greater{}, &Problem::severity);
1366 const Severity highest_severity =
1367 m_result.problems.empty() ? Severity::None : m_result.problems[0].severity;
1368
1369 if (m_redump_verification)
1370 m_result.redump = m_redump_verifier.Finish(m_result.hashes);
1371
1372 if (m_result.redump.status == RedumpVerifier::Status::GoodDump ||
1373 (m_volume.GetVolumeType() == Platform::WiiWAD && !m_is_not_retail &&
1374 m_result.problems.empty()))
1375 {
1376 if (m_result.problems.empty())
1377 {
1378 m_result.summary_text = Common::GetStringT("This is a good dump.");
1379 }
1380 else
1381 {
1382 m_result.summary_text =
1383 Common::GetStringT("This is a good dump according to Redump.info, but Dolphin has found "
1384 "problems. This might be a bug in Dolphin.");
1385 }
1386 return;
1387 }
1388
1389 if (m_is_datel)
1390 {
1391 m_result.summary_text = Common::GetStringT("Dolphin is unable to verify unlicensed discs.");
1392 return;
1393 }
1394
1395 if (m_is_tgc)
1396 {
1397 m_result.summary_text =
1398 Common::GetStringT("Dolphin is unable to verify typical TGC files properly, "
1399 "since they are not dumps of actual discs.");
1400 return;
1401 }
1402
1403 if (m_is_triforce)
1404 {
1405 m_result.summary_text =
1406 Common::GetStringT("Dolphin is currently unable to verify Triforce games.");
1407 return;
1408 }
1409
1410 if (m_result.redump.status == RedumpVerifier::Status::BadDump &&
1411 highest_severity <= Severity::Low)
1412 {
1413 if (m_volume.GetBlobType() == BlobType::NFS)
1414 {
1415 m_result.summary_text =
1416 Common::GetStringT("Compared to the Wii disc release of the game, this is a bad dump. "
1417 "Despite this, it's possible that this is a good dump compared to the "
1418 "Wii U eShop release of the game. Dolphin can't verify this.");
1419 }
1420 else
1421 {
1422 m_result.summary_text = Common::GetStringT(
1423 "This is a bad dump. This doesn't necessarily mean that the game won't run correctly.");
1424 }
1425 }
1426 else
1427 {
1428 if (m_result.redump.status == RedumpVerifier::Status::BadDump)
1429 {
1430 m_result.summary_text = Common::GetStringT("This is a bad dump.") + "\n\n";
1431 }
1432
1433 switch (highest_severity)
1434 {
1435 case Severity::None:
1436 if (IsWii(m_volume.GetVolumeType()) && !m_is_not_retail)
1437 {
1438 m_result.summary_text = Common::GetStringT(
1439 "No problems were found. This does not guarantee that this is a good dump, "
1440 "but since Wii titles contain a lot of verification data, it does mean that "
1441 "there most likely are no problems that will affect emulation.");
1442 }
1443 else
1444 {
1445 m_result.summary_text = Common::GetStringT("No problems were found.");
1446 }
1447 break;
1448 case Severity::Low:
1449 if (m_volume.GetBlobType() == BlobType::NFS)
1450 {
1451 m_result.summary_text = Common::GetStringT(
1452 "Compared to the Wii disc release of the game, problems of low severity were found. "
1453 "Despite this, it's possible that this is a good dump compared to the Wii U eShop "
1454 "release of the game. Dolphin can't verify this.");
1455 }
1456 else
1457 {
1458 m_result.summary_text =
1459 Common::GetStringT("Problems with low severity were found. They will most "
1460 "likely not prevent the game from running.");
1461 }
1462 break;
1463 case Severity::Medium:
1464 m_result.summary_text +=
1465 Common::GetStringT("Problems with medium severity were found. The whole game "
1466 "or certain parts of the game might not work correctly.");
1467 break;
1468 case Severity::High:
1469 m_result.summary_text += Common::GetStringT(
1470 "Problems with high severity were found. The game will most likely not work at all.");
1471 break;
1472 }
1473 }
1474
1475 if (m_volume.GetVolumeType() == Platform::GameCubeDisc)
1476 {
1477 m_result.summary_text +=
1478 Common::GetStringT("\n\nBecause GameCube disc images contain little verification data, "
1479 "there may be problems that Dolphin is unable to detect.");
1480 }
1481 else if (m_is_not_retail)
1482 {
1483 m_result.summary_text +=
1484 Common::GetStringT("\n\nBecause this title is not for retail Wii consoles, "
1485 "Dolphin cannot ensure that it hasn't been tampered with, even if "
1486 "signatures appear valid.");
1487 }
1488 }
1489
1490 const VolumeVerifier::Result& VolumeVerifier::GetResult() const
1491 {
1492 return m_result;
1493 }
1494
1495 void VolumeVerifier::AddProblem(Severity severity, std::string text)
1496 {
1497 m_result.problems.emplace_back(Problem{severity, std::move(text)});
1498 }
1499
1500 } // namespace DiscIO