WIABlob.cpp 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087
  1. // Copyright 2018 Dolphin Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include "DiscIO/WIABlob.h"
  4. #include <algorithm>
  5. #include <array>
  6. #include <cstring>
  7. #include <limits>
  8. #include <map>
  9. #include <memory>
  10. #include <mutex>
  11. #include <optional>
  12. #include <type_traits>
  13. #include <utility>
  14. #include <fmt/format.h>
  15. #include <zstd.h>
  16. #include "Common/Align.h"
  17. #include "Common/Assert.h"
  18. #include "Common/CommonTypes.h"
  19. #include "Common/Crypto/SHA1.h"
  20. #include "Common/FileUtil.h"
  21. #include "Common/IOFile.h"
  22. #include "Common/Logging/Log.h"
  23. #include "Common/MsgHandler.h"
  24. #include "Common/ScopeGuard.h"
  25. #include "Common/Swap.h"
  26. #include "DiscIO/Blob.h"
  27. #include "DiscIO/DiscUtils.h"
  28. #include "DiscIO/Filesystem.h"
  29. #include "DiscIO/LaggedFibonacciGenerator.h"
  30. #include "DiscIO/MultithreadedCompressor.h"
  31. #include "DiscIO/Volume.h"
  32. #include "DiscIO/VolumeWii.h"
  33. #include "DiscIO/WIACompression.h"
  34. #include "DiscIO/WiiEncryptionCache.h"
  35. namespace DiscIO
  36. {
  37. static void PushBack(std::vector<u8>* vector, const u8* begin, const u8* end)
  38. {
  39. const size_t offset_in_vector = vector->size();
  40. vector->resize(offset_in_vector + (end - begin));
  41. std::copy(begin, end, vector->data() + offset_in_vector);
  42. }
  43. template <typename T>
  44. static void PushBack(std::vector<u8>* vector, const T& x)
  45. {
  46. static_assert(std::is_trivially_copyable_v<T>);
  47. const u8* x_ptr = reinterpret_cast<const u8*>(&x);
  48. PushBack(vector, x_ptr, x_ptr + sizeof(T));
  49. }
  50. std::pair<int, int> GetAllowedCompressionLevels(WIARVZCompressionType compression_type, bool gui)
  51. {
  52. switch (compression_type)
  53. {
  54. case WIARVZCompressionType::Bzip2:
  55. case WIARVZCompressionType::LZMA:
  56. case WIARVZCompressionType::LZMA2:
  57. return {1, 9};
  58. case WIARVZCompressionType::Zstd:
  59. // The actual minimum level can be gotten by calling ZSTD_minCLevel(). However, returning that
  60. // would make the UI rather weird, because it is a negative number with very large magnitude.
  61. // Note: Level 0 is a special number which means "default level" (level 3 as of this writing).
  62. if (gui)
  63. return {1, ZSTD_maxCLevel()};
  64. else
  65. return {ZSTD_minCLevel(), ZSTD_maxCLevel()};
  66. default:
  67. return {0, -1};
  68. }
  69. }
  70. template <bool RVZ>
  71. WIARVZFileReader<RVZ>::WIARVZFileReader(File::IOFile file, const std::string& path)
  72. : m_file(std::move(file)), m_path(path), m_encryption_cache(this)
  73. {
  74. m_valid = Initialize(path);
  75. }
  76. template <bool RVZ>
  77. WIARVZFileReader<RVZ>::~WIARVZFileReader() = default;
  78. template <bool RVZ>
  79. bool WIARVZFileReader<RVZ>::Initialize(const std::string& path)
  80. {
  81. if (!m_file.Seek(0, File::SeekOrigin::Begin) || !m_file.ReadArray(&m_header_1, 1))
  82. return false;
  83. if ((!RVZ && m_header_1.magic != WIA_MAGIC) || (RVZ && m_header_1.magic != RVZ_MAGIC))
  84. return false;
  85. const u32 version = RVZ ? RVZ_VERSION : WIA_VERSION;
  86. const u32 version_read_compatible =
  87. RVZ ? RVZ_VERSION_READ_COMPATIBLE : WIA_VERSION_READ_COMPATIBLE;
  88. const u32 file_version = Common::swap32(m_header_1.version);
  89. const u32 file_version_compatible = Common::swap32(m_header_1.version_compatible);
  90. if (version < file_version_compatible || version_read_compatible > file_version)
  91. {
  92. ERROR_LOG_FMT(DISCIO, "Unsupported version {} in {}", VersionToString(file_version), path);
  93. return false;
  94. }
  95. const auto header_1_actual_hash = Common::SHA1::CalculateDigest(
  96. reinterpret_cast<const u8*>(&m_header_1), sizeof(m_header_1) - Common::SHA1::DIGEST_LEN);
  97. if (m_header_1.header_1_hash != header_1_actual_hash)
  98. return false;
  99. if (Common::swap64(m_header_1.wia_file_size) != m_file.GetSize())
  100. {
  101. ERROR_LOG_FMT(DISCIO, "File size is incorrect for {}", path);
  102. return false;
  103. }
  104. const u32 header_2_size = Common::swap32(m_header_1.header_2_size);
  105. const u32 header_2_min_size = sizeof(WIAHeader2) - sizeof(WIAHeader2::compressor_data);
  106. if (header_2_size < header_2_min_size)
  107. return false;
  108. std::vector<u8> header_2(header_2_size);
  109. if (!m_file.ReadBytes(header_2.data(), header_2.size()))
  110. return false;
  111. const auto header_2_actual_hash = Common::SHA1::CalculateDigest(header_2);
  112. if (m_header_1.header_2_hash != header_2_actual_hash)
  113. return false;
  114. std::memcpy(&m_header_2, header_2.data(), std::min(header_2.size(), sizeof(WIAHeader2)));
  115. if (m_header_2.compressor_data_size > sizeof(WIAHeader2::compressor_data) ||
  116. header_2_size < header_2_min_size + m_header_2.compressor_data_size)
  117. {
  118. return false;
  119. }
  120. const u32 chunk_size = Common::swap32(m_header_2.chunk_size);
  121. const auto is_power_of_two = [](u32 x) { return (x & (x - 1)) == 0; };
  122. if ((!RVZ || chunk_size < VolumeWii::BLOCK_TOTAL_SIZE || !is_power_of_two(chunk_size)) &&
  123. chunk_size % VolumeWii::GROUP_TOTAL_SIZE != 0)
  124. {
  125. return false;
  126. }
  127. const u32 compression_type = Common::swap32(m_header_2.compression_type);
  128. m_compression_type = static_cast<WIARVZCompressionType>(compression_type);
  129. if (m_compression_type > (RVZ ? WIARVZCompressionType::Zstd : WIARVZCompressionType::LZMA2) ||
  130. (RVZ && m_compression_type == WIARVZCompressionType::Purge))
  131. {
  132. ERROR_LOG_FMT(DISCIO, "Unsupported compression type {} in {}", compression_type, path);
  133. return false;
  134. }
  135. const size_t number_of_partition_entries = Common::swap32(m_header_2.number_of_partition_entries);
  136. const size_t partition_entry_size = Common::swap32(m_header_2.partition_entry_size);
  137. std::vector<u8> partition_entries(partition_entry_size * number_of_partition_entries);
  138. if (!m_file.Seek(Common::swap64(m_header_2.partition_entries_offset), File::SeekOrigin::Begin))
  139. return false;
  140. if (!m_file.ReadBytes(partition_entries.data(), partition_entries.size()))
  141. return false;
  142. const auto partition_entries_actual_hash = Common::SHA1::CalculateDigest(partition_entries);
  143. if (m_header_2.partition_entries_hash != partition_entries_actual_hash)
  144. return false;
  145. const size_t copy_length = std::min(partition_entry_size, sizeof(PartitionEntry));
  146. const size_t memset_length = sizeof(PartitionEntry) - copy_length;
  147. u8* ptr = partition_entries.data();
  148. m_partition_entries.resize(number_of_partition_entries);
  149. for (size_t i = 0; i < number_of_partition_entries; ++i, ptr += partition_entry_size)
  150. {
  151. std::memcpy(&m_partition_entries[i], ptr, copy_length);
  152. std::memset(reinterpret_cast<u8*>(&m_partition_entries[i]) + copy_length, 0, memset_length);
  153. }
  154. for (size_t i = 0; i < m_partition_entries.size(); ++i)
  155. {
  156. const std::array<PartitionDataEntry, 2>& entries = m_partition_entries[i].data_entries;
  157. size_t non_empty_entries = 0;
  158. for (size_t j = 0; j < entries.size(); ++j)
  159. {
  160. const u32 number_of_sectors = Common::swap32(entries[j].number_of_sectors);
  161. if (number_of_sectors != 0)
  162. {
  163. ++non_empty_entries;
  164. const u32 last_sector = Common::swap32(entries[j].first_sector) + number_of_sectors;
  165. m_data_entries.emplace(last_sector * VolumeWii::BLOCK_TOTAL_SIZE, DataEntry(i, j));
  166. }
  167. }
  168. if (non_empty_entries > 1)
  169. {
  170. if (Common::swap32(entries[0].first_sector) > Common::swap32(entries[1].first_sector))
  171. return false;
  172. }
  173. }
  174. const u32 number_of_raw_data_entries = Common::swap32(m_header_2.number_of_raw_data_entries);
  175. m_raw_data_entries.resize(number_of_raw_data_entries);
  176. Chunk& raw_data_entries =
  177. ReadCompressedData(Common::swap64(m_header_2.raw_data_entries_offset),
  178. Common::swap32(m_header_2.raw_data_entries_size),
  179. number_of_raw_data_entries * sizeof(RawDataEntry), m_compression_type);
  180. if (!raw_data_entries.ReadAll(&m_raw_data_entries))
  181. return false;
  182. for (size_t i = 0; i < m_raw_data_entries.size(); ++i)
  183. {
  184. const RawDataEntry& entry = m_raw_data_entries[i];
  185. const u64 data_size = Common::swap64(entry.data_size);
  186. if (data_size != 0)
  187. m_data_entries.emplace(Common::swap64(entry.data_offset) + data_size, DataEntry(i));
  188. }
  189. const u32 number_of_group_entries = Common::swap32(m_header_2.number_of_group_entries);
  190. m_group_entries.resize(number_of_group_entries);
  191. Chunk& group_entries =
  192. ReadCompressedData(Common::swap64(m_header_2.group_entries_offset),
  193. Common::swap32(m_header_2.group_entries_size),
  194. number_of_group_entries * sizeof(GroupEntry), m_compression_type);
  195. if (!group_entries.ReadAll(&m_group_entries))
  196. return false;
  197. if (HasDataOverlap())
  198. return false;
  199. return true;
  200. }
  201. template <bool RVZ>
  202. bool WIARVZFileReader<RVZ>::HasDataOverlap() const
  203. {
  204. for (size_t i = 0; i < m_partition_entries.size(); ++i)
  205. {
  206. const std::array<PartitionDataEntry, 2>& entries = m_partition_entries[i].data_entries;
  207. for (size_t j = 0; j < entries.size(); ++j)
  208. {
  209. if (Common::swap32(entries[j].number_of_sectors) == 0)
  210. continue;
  211. const u64 data_offset = Common::swap32(entries[j].first_sector) * VolumeWii::BLOCK_TOTAL_SIZE;
  212. const auto it = m_data_entries.upper_bound(data_offset);
  213. if (it == m_data_entries.end())
  214. return true; // Not an overlap, but an error nonetheless
  215. if (!it->second.is_partition || it->second.index != i || it->second.partition_data_index != j)
  216. return true; // Overlap
  217. }
  218. }
  219. for (size_t i = 0; i < m_raw_data_entries.size(); ++i)
  220. {
  221. if (Common::swap64(m_raw_data_entries[i].data_size) == 0)
  222. continue;
  223. const u64 data_offset = Common::swap64(m_raw_data_entries[i].data_offset);
  224. const auto it = m_data_entries.upper_bound(data_offset);
  225. if (it == m_data_entries.end())
  226. return true; // Not an overlap, but an error nonetheless
  227. if (it->second.is_partition || it->second.index != i)
  228. return true; // Overlap
  229. }
  230. return false;
  231. }
  232. template <bool RVZ>
  233. std::unique_ptr<WIARVZFileReader<RVZ>> WIARVZFileReader<RVZ>::Create(File::IOFile file,
  234. const std::string& path)
  235. {
  236. std::unique_ptr<WIARVZFileReader> blob(new WIARVZFileReader(std::move(file), path));
  237. return blob->m_valid ? std::move(blob) : nullptr;
  238. }
  239. template <bool RVZ>
  240. BlobType WIARVZFileReader<RVZ>::GetBlobType() const
  241. {
  242. return RVZ ? BlobType::RVZ : BlobType::WIA;
  243. }
  244. template <bool RVZ>
  245. std::unique_ptr<BlobReader> WIARVZFileReader<RVZ>::CopyReader() const
  246. {
  247. return Create(m_file.Duplicate("rb"), m_path);
  248. }
  249. template <bool RVZ>
  250. std::string WIARVZFileReader<RVZ>::GetCompressionMethod() const
  251. {
  252. switch (m_compression_type)
  253. {
  254. case WIARVZCompressionType::Purge:
  255. return "Purge";
  256. case WIARVZCompressionType::Bzip2:
  257. return "bzip2";
  258. case WIARVZCompressionType::LZMA:
  259. return "LZMA";
  260. case WIARVZCompressionType::LZMA2:
  261. return "LZMA2";
  262. case WIARVZCompressionType::Zstd:
  263. return "Zstandard";
  264. default:
  265. return {};
  266. }
  267. }
  268. template <bool RVZ>
  269. bool WIARVZFileReader<RVZ>::Read(u64 offset, u64 size, u8* out_ptr)
  270. {
  271. if (offset + size > Common::swap64(m_header_1.iso_file_size))
  272. return false;
  273. if (offset < sizeof(WIAHeader2::disc_header))
  274. {
  275. const u64 bytes_to_read = std::min(sizeof(WIAHeader2::disc_header) - offset, size);
  276. std::memcpy(out_ptr, m_header_2.disc_header.data() + offset, bytes_to_read);
  277. offset += bytes_to_read;
  278. size -= bytes_to_read;
  279. out_ptr += bytes_to_read;
  280. }
  281. const u32 chunk_size = Common::swap32(m_header_2.chunk_size);
  282. while (size > 0)
  283. {
  284. const auto it = m_data_entries.upper_bound(offset);
  285. if (it == m_data_entries.end())
  286. return false;
  287. const DataEntry& data = it->second;
  288. if (data.is_partition)
  289. {
  290. const PartitionEntry& partition = m_partition_entries[it->second.index];
  291. const u32 partition_first_sector = Common::swap32(partition.data_entries[0].first_sector);
  292. const u64 partition_data_offset = partition_first_sector * VolumeWii::BLOCK_TOTAL_SIZE;
  293. const u32 second_number_of_sectors =
  294. Common::swap32(partition.data_entries[1].number_of_sectors);
  295. const u32 partition_total_sectors =
  296. second_number_of_sectors ? Common::swap32(partition.data_entries[1].first_sector) -
  297. partition_first_sector + second_number_of_sectors :
  298. Common::swap32(partition.data_entries[0].number_of_sectors);
  299. for (const PartitionDataEntry& partition_data : partition.data_entries)
  300. {
  301. if (size == 0)
  302. return true;
  303. const u32 first_sector = Common::swap32(partition_data.first_sector);
  304. const u32 number_of_sectors = Common::swap32(partition_data.number_of_sectors);
  305. const u64 data_offset = first_sector * VolumeWii::BLOCK_TOTAL_SIZE;
  306. const u64 data_size = number_of_sectors * VolumeWii::BLOCK_TOTAL_SIZE;
  307. if (data_size == 0)
  308. continue;
  309. if (data_offset + data_size <= offset)
  310. continue;
  311. if (offset < data_offset)
  312. return false;
  313. const u64 bytes_to_read = std::min(data_size - (offset - data_offset), size);
  314. m_exception_list.clear();
  315. m_write_to_exception_list = true;
  316. m_exception_list_last_group_index = std::numeric_limits<u64>::max();
  317. Common::ScopeGuard guard([this] { m_write_to_exception_list = false; });
  318. bool hash_exception_error = false;
  319. if (!m_encryption_cache.EncryptGroups(
  320. offset - partition_data_offset, bytes_to_read, out_ptr, partition_data_offset,
  321. partition_total_sectors * VolumeWii::BLOCK_DATA_SIZE, partition.partition_key,
  322. [this, &hash_exception_error](
  323. VolumeWii::HashBlock hash_blocks[VolumeWii::BLOCKS_PER_GROUP], u64 offset_) {
  324. // EncryptGroups calls ReadWiiDecrypted, which calls ReadFromGroups,
  325. // which populates m_exception_list when m_write_to_exception_list == true
  326. if (!ApplyHashExceptions(m_exception_list, hash_blocks))
  327. hash_exception_error = true;
  328. }))
  329. {
  330. return false;
  331. }
  332. if (hash_exception_error)
  333. return false;
  334. offset += bytes_to_read;
  335. size -= bytes_to_read;
  336. out_ptr += bytes_to_read;
  337. }
  338. }
  339. else
  340. {
  341. const RawDataEntry& raw_data = m_raw_data_entries[data.index];
  342. if (!ReadFromGroups(&offset, &size, &out_ptr, chunk_size, VolumeWii::BLOCK_TOTAL_SIZE,
  343. Common::swap64(raw_data.data_offset), Common::swap64(raw_data.data_size),
  344. Common::swap32(raw_data.group_index),
  345. Common::swap32(raw_data.number_of_groups), 0))
  346. {
  347. return false;
  348. }
  349. }
  350. }
  351. return true;
  352. }
  353. template <bool RVZ>
  354. const typename WIARVZFileReader<RVZ>::PartitionEntry*
  355. WIARVZFileReader<RVZ>::GetPartition(u64 partition_data_offset, u32* partition_first_sector) const
  356. {
  357. const auto it = m_data_entries.upper_bound(partition_data_offset);
  358. if (it == m_data_entries.end() || !it->second.is_partition)
  359. return nullptr;
  360. const PartitionEntry* partition = &m_partition_entries[it->second.index];
  361. *partition_first_sector = Common::swap32(partition->data_entries[0].first_sector);
  362. if (partition_data_offset != *partition_first_sector * VolumeWii::BLOCK_TOTAL_SIZE)
  363. return nullptr;
  364. return partition;
  365. }
  366. template <bool RVZ>
  367. bool WIARVZFileReader<RVZ>::SupportsReadWiiDecrypted(u64 offset, u64 size,
  368. u64 partition_data_offset) const
  369. {
  370. u32 partition_first_sector;
  371. const PartitionEntry* partition = GetPartition(partition_data_offset, &partition_first_sector);
  372. if (!partition)
  373. return false;
  374. for (const PartitionDataEntry& data : partition->data_entries)
  375. {
  376. const u32 start_sector = Common::swap32(data.first_sector) - partition_first_sector;
  377. const u32 end_sector = start_sector + Common::swap32(data.number_of_sectors);
  378. if (offset + size <= end_sector * VolumeWii::BLOCK_DATA_SIZE)
  379. return true;
  380. }
  381. return false;
  382. }
  383. template <bool RVZ>
  384. bool WIARVZFileReader<RVZ>::ReadWiiDecrypted(u64 offset, u64 size, u8* out_ptr,
  385. u64 partition_data_offset)
  386. {
  387. u32 partition_first_sector;
  388. const PartitionEntry* partition = GetPartition(partition_data_offset, &partition_first_sector);
  389. if (!partition)
  390. return false;
  391. const u64 chunk_size = Common::swap32(m_header_2.chunk_size) * VolumeWii::BLOCK_DATA_SIZE /
  392. VolumeWii::BLOCK_TOTAL_SIZE;
  393. for (const PartitionDataEntry& data : partition->data_entries)
  394. {
  395. if (size == 0)
  396. return true;
  397. const u64 data_offset =
  398. (Common::swap32(data.first_sector) - partition_first_sector) * VolumeWii::BLOCK_DATA_SIZE;
  399. const u64 data_size = Common::swap32(data.number_of_sectors) * VolumeWii::BLOCK_DATA_SIZE;
  400. if (!ReadFromGroups(
  401. &offset, &size, &out_ptr, chunk_size, VolumeWii::BLOCK_DATA_SIZE, data_offset,
  402. data_size, Common::swap32(data.group_index), Common::swap32(data.number_of_groups),
  403. std::max<u32>(1, static_cast<u32>(chunk_size / VolumeWii::GROUP_DATA_SIZE))))
  404. {
  405. return false;
  406. }
  407. }
  408. return size == 0;
  409. }
  410. template <bool RVZ>
  411. bool WIARVZFileReader<RVZ>::ReadFromGroups(u64* offset, u64* size, u8** out_ptr, u64 chunk_size,
  412. u32 sector_size, u64 data_offset, u64 data_size,
  413. u32 group_index, u32 number_of_groups,
  414. u32 exception_lists)
  415. {
  416. if (data_offset + data_size <= *offset)
  417. return true;
  418. if (*offset < data_offset)
  419. return false;
  420. const u64 skipped_data = data_offset % sector_size;
  421. data_offset -= skipped_data;
  422. data_size += skipped_data;
  423. const u64 start_group_index = (*offset - data_offset) / chunk_size;
  424. for (u64 i = start_group_index; i < number_of_groups && (*size) > 0; ++i)
  425. {
  426. const u64 total_group_index = group_index + i;
  427. if (total_group_index >= m_group_entries.size())
  428. return false;
  429. const GroupEntry group = m_group_entries[total_group_index];
  430. const u64 group_offset_in_data = i * chunk_size;
  431. const u64 offset_in_group = *offset - group_offset_in_data - data_offset;
  432. chunk_size = std::min(chunk_size, data_size - group_offset_in_data);
  433. const u64 bytes_to_read = std::min(chunk_size - offset_in_group, *size);
  434. u32 group_data_size = Common::swap32(group.data_size);
  435. WIARVZCompressionType compression_type = m_compression_type;
  436. u32 rvz_packed_size = 0;
  437. if constexpr (RVZ)
  438. {
  439. if ((group_data_size & 0x80000000) == 0)
  440. compression_type = WIARVZCompressionType::None;
  441. group_data_size &= 0x7FFFFFFF;
  442. rvz_packed_size = Common::swap32(group.rvz_packed_size);
  443. }
  444. if (group_data_size == 0)
  445. {
  446. std::memset(*out_ptr, 0, bytes_to_read);
  447. }
  448. else
  449. {
  450. const u64 group_offset_in_file = static_cast<u64>(Common::swap32(group.data_offset)) << 2;
  451. Chunk& chunk =
  452. ReadCompressedData(group_offset_in_file, group_data_size, chunk_size, compression_type,
  453. exception_lists, rvz_packed_size, group_offset_in_data);
  454. if (!chunk.Read(offset_in_group, bytes_to_read, *out_ptr))
  455. {
  456. m_cached_chunk_offset = std::numeric_limits<u64>::max(); // Invalidate the cache
  457. return false;
  458. }
  459. if (m_write_to_exception_list && m_exception_list_last_group_index != total_group_index)
  460. {
  461. const u64 exception_list_index = offset_in_group / VolumeWii::GROUP_DATA_SIZE;
  462. const u16 additional_offset =
  463. static_cast<u16>(group_offset_in_data % VolumeWii::GROUP_DATA_SIZE /
  464. VolumeWii::BLOCK_DATA_SIZE * VolumeWii::BLOCK_HEADER_SIZE);
  465. chunk.GetHashExceptions(&m_exception_list, exception_list_index, additional_offset);
  466. m_exception_list_last_group_index = total_group_index;
  467. }
  468. }
  469. *offset += bytes_to_read;
  470. *size -= bytes_to_read;
  471. *out_ptr += bytes_to_read;
  472. }
  473. return true;
  474. }
  475. template <bool RVZ>
  476. typename WIARVZFileReader<RVZ>::Chunk&
  477. WIARVZFileReader<RVZ>::ReadCompressedData(u64 offset_in_file, u64 compressed_size,
  478. u64 decompressed_size,
  479. WIARVZCompressionType compression_type,
  480. u32 exception_lists, u32 rvz_packed_size, u64 data_offset)
  481. {
  482. if (offset_in_file == m_cached_chunk_offset)
  483. return m_cached_chunk;
  484. std::unique_ptr<Decompressor> decompressor;
  485. switch (compression_type)
  486. {
  487. case WIARVZCompressionType::None:
  488. decompressor = std::make_unique<NoneDecompressor>();
  489. break;
  490. case WIARVZCompressionType::Purge:
  491. decompressor = std::make_unique<PurgeDecompressor>(rvz_packed_size == 0 ? decompressed_size :
  492. rvz_packed_size);
  493. break;
  494. case WIARVZCompressionType::Bzip2:
  495. decompressor = std::make_unique<Bzip2Decompressor>();
  496. break;
  497. case WIARVZCompressionType::LZMA:
  498. decompressor = std::make_unique<LZMADecompressor>(false, m_header_2.compressor_data,
  499. m_header_2.compressor_data_size);
  500. break;
  501. case WIARVZCompressionType::LZMA2:
  502. decompressor = std::make_unique<LZMADecompressor>(true, m_header_2.compressor_data,
  503. m_header_2.compressor_data_size);
  504. break;
  505. case WIARVZCompressionType::Zstd:
  506. decompressor = std::make_unique<ZstdDecompressor>();
  507. break;
  508. }
  509. const bool compressed_exception_lists = compression_type > WIARVZCompressionType::Purge;
  510. m_cached_chunk =
  511. Chunk(&m_file, offset_in_file, compressed_size, decompressed_size, exception_lists,
  512. compressed_exception_lists, rvz_packed_size, data_offset, std::move(decompressor));
  513. m_cached_chunk_offset = offset_in_file;
  514. return m_cached_chunk;
  515. }
  516. template <bool RVZ>
  517. std::string WIARVZFileReader<RVZ>::VersionToString(u32 version)
  518. {
  519. const u8 a = version >> 24;
  520. const u8 b = (version >> 16) & 0xff;
  521. const u8 c = (version >> 8) & 0xff;
  522. const u8 d = version & 0xff;
  523. if (d == 0 || d == 0xff)
  524. return fmt::format("{}.{:02x}.{:02x}", a, b, c);
  525. else
  526. return fmt::format("{}.{:02x}.{:02x}.beta{}", a, b, c, d);
  527. }
  528. template <bool RVZ>
  529. WIARVZFileReader<RVZ>::Chunk::Chunk() = default;
  530. template <bool RVZ>
  531. WIARVZFileReader<RVZ>::Chunk::Chunk(File::IOFile* file, u64 offset_in_file, u64 compressed_size,
  532. u64 decompressed_size, u32 exception_lists,
  533. bool compressed_exception_lists, u32 rvz_packed_size,
  534. u64 data_offset, std::unique_ptr<Decompressor> decompressor)
  535. : m_decompressor(std::move(decompressor)), m_file(file), m_offset_in_file(offset_in_file),
  536. m_exception_lists(exception_lists), m_compressed_exception_lists(compressed_exception_lists),
  537. m_rvz_packed_size(rvz_packed_size), m_data_offset(data_offset)
  538. {
  539. constexpr size_t MAX_SIZE_PER_EXCEPTION_LIST =
  540. Common::AlignUp(VolumeWii::BLOCK_HEADER_SIZE, Common::SHA1::DIGEST_LEN) /
  541. Common::SHA1::DIGEST_LEN * VolumeWii::BLOCKS_PER_GROUP * sizeof(HashExceptionEntry) +
  542. sizeof(u16);
  543. m_out_bytes_allocated_for_exceptions =
  544. m_compressed_exception_lists ? MAX_SIZE_PER_EXCEPTION_LIST * m_exception_lists : 0;
  545. m_in.data.resize(compressed_size);
  546. m_out.data.resize(decompressed_size + m_out_bytes_allocated_for_exceptions);
  547. }
  548. template <bool RVZ>
  549. bool WIARVZFileReader<RVZ>::Chunk::Read(u64 offset, u64 size, u8* out_ptr)
  550. {
  551. if (!m_decompressor || !m_file ||
  552. offset + size > m_out.data.size() - m_out_bytes_allocated_for_exceptions)
  553. {
  554. return false;
  555. }
  556. while (offset + size > GetOutBytesWrittenExcludingExceptions())
  557. {
  558. u64 bytes_to_read;
  559. if (offset + size == m_out.data.size())
  560. {
  561. // Read all the remaining data.
  562. bytes_to_read = m_in.data.size() - m_in.bytes_written;
  563. }
  564. else
  565. {
  566. // Pick a suitable amount of compressed data to read. We have to ensure that bytes_to_read
  567. // is larger than 0 and smaller than or equal to the number of bytes available to read,
  568. // but the rest is a bit arbitrary and could be changed.
  569. // The compressed data is probably not much bigger than the decompressed data.
  570. // Add a few bytes for possible compression overhead and for any hash exceptions.
  571. bytes_to_read = offset + size - GetOutBytesWrittenExcludingExceptions() + 0x100;
  572. // Align the access in an attempt to gain speed. But we don't actually know the
  573. // block size of the underlying storage device, so we just use the Wii block size.
  574. bytes_to_read =
  575. Common::AlignUp(bytes_to_read + m_offset_in_file, VolumeWii::BLOCK_TOTAL_SIZE) -
  576. m_offset_in_file;
  577. // Ensure we don't read too much.
  578. bytes_to_read = std::min<u64>(m_in.data.size() - m_in.bytes_written, bytes_to_read);
  579. }
  580. if (bytes_to_read == 0)
  581. {
  582. // Compressed size is larger than expected or decompressed size is smaller than expected
  583. return false;
  584. }
  585. if (!m_file->Seek(m_offset_in_file, File::SeekOrigin::Begin))
  586. return false;
  587. if (!m_file->ReadBytes(m_in.data.data() + m_in.bytes_written, bytes_to_read))
  588. return false;
  589. m_offset_in_file += bytes_to_read;
  590. m_in.bytes_written += bytes_to_read;
  591. if (m_exception_lists > 0 && !m_compressed_exception_lists)
  592. {
  593. if (!HandleExceptions(m_in.data.data(), m_in.data.size(), m_in.bytes_written,
  594. &m_in_bytes_used_for_exceptions, true))
  595. {
  596. return false;
  597. }
  598. m_in_bytes_read = m_in_bytes_used_for_exceptions;
  599. }
  600. if (m_exception_lists == 0 || m_compressed_exception_lists)
  601. {
  602. if (!Decompress())
  603. return false;
  604. }
  605. if (m_exception_lists > 0 && m_compressed_exception_lists)
  606. {
  607. if (!HandleExceptions(m_out.data.data(), m_out_bytes_allocated_for_exceptions,
  608. m_out.bytes_written, &m_out_bytes_used_for_exceptions, false))
  609. {
  610. return false;
  611. }
  612. if (m_rvz_packed_size != 0 && m_exception_lists == 0)
  613. {
  614. if (!Decompress())
  615. return false;
  616. }
  617. }
  618. if (m_exception_lists == 0)
  619. {
  620. const size_t expected_out_bytes = m_out.data.size() - m_out_bytes_allocated_for_exceptions +
  621. m_out_bytes_used_for_exceptions;
  622. if (m_out.bytes_written > expected_out_bytes)
  623. return false; // Decompressed size is larger than expected
  624. // The reason why we need the m_in.bytes_written == m_in.data.size() check as part of
  625. // this conditional is because (for example) zstd can finish writing all data to m_out
  626. // before becoming done if we've given it all input data except the checksum at the end.
  627. if (m_out.bytes_written == expected_out_bytes && !m_decompressor->Done() &&
  628. m_in.bytes_written == m_in.data.size())
  629. {
  630. return false; // Decompressed size is larger than expected
  631. }
  632. if (m_decompressor->Done() && m_in_bytes_read != m_in.data.size())
  633. return false; // Compressed size is smaller than expected
  634. }
  635. }
  636. std::memcpy(out_ptr, m_out.data.data() + offset + m_out_bytes_used_for_exceptions, size);
  637. return true;
  638. }
  639. template <bool RVZ>
  640. bool WIARVZFileReader<RVZ>::Chunk::Decompress()
  641. {
  642. if (m_rvz_packed_size != 0 && m_exception_lists == 0)
  643. {
  644. const size_t bytes_to_move = m_out.bytes_written - m_out_bytes_used_for_exceptions;
  645. DecompressionBuffer in{std::vector<u8>(bytes_to_move), bytes_to_move};
  646. // Copying to a null pointer is undefined behaviour, so only copy when we
  647. // actually have data to copy.
  648. if (bytes_to_move > 0)
  649. {
  650. std::memcpy(in.data.data(), m_out.data.data() + m_out_bytes_used_for_exceptions,
  651. bytes_to_move);
  652. }
  653. m_out.bytes_written = m_out_bytes_used_for_exceptions;
  654. m_decompressor = std::make_unique<RVZPackDecompressor>(std::move(m_decompressor), std::move(in),
  655. m_data_offset, m_rvz_packed_size);
  656. m_rvz_packed_size = 0;
  657. }
  658. return m_decompressor->Decompress(m_in, &m_out, &m_in_bytes_read);
  659. }
  660. template <bool RVZ>
  661. bool WIARVZFileReader<RVZ>::Chunk::HandleExceptions(const u8* data, size_t bytes_allocated,
  662. size_t bytes_written, size_t* bytes_used,
  663. bool align)
  664. {
  665. while (m_exception_lists > 0)
  666. {
  667. if (sizeof(u16) + *bytes_used > bytes_allocated)
  668. {
  669. ERROR_LOG_FMT(DISCIO, "More hash exceptions than expected");
  670. return false;
  671. }
  672. if (sizeof(u16) + *bytes_used > bytes_written)
  673. return true;
  674. const u16 exceptions = Common::swap16(data + *bytes_used);
  675. size_t exception_list_size = exceptions * sizeof(HashExceptionEntry) + sizeof(u16);
  676. if (align && m_exception_lists == 1)
  677. exception_list_size = Common::AlignUp(*bytes_used + exception_list_size, 4) - *bytes_used;
  678. if (exception_list_size + *bytes_used > bytes_allocated)
  679. {
  680. ERROR_LOG_FMT(DISCIO, "More hash exceptions than expected");
  681. return false;
  682. }
  683. if (exception_list_size + *bytes_used > bytes_written)
  684. return true;
  685. *bytes_used += exception_list_size;
  686. --m_exception_lists;
  687. }
  688. return true;
  689. }
  690. template <bool RVZ>
  691. void WIARVZFileReader<RVZ>::Chunk::GetHashExceptions(
  692. std::vector<HashExceptionEntry>* exception_list, u64 exception_list_index,
  693. u16 additional_offset) const
  694. {
  695. ASSERT(m_exception_lists == 0);
  696. const u8* data_start = m_compressed_exception_lists ? m_out.data.data() : m_in.data.data();
  697. const u8* data = data_start;
  698. for (u64 i = exception_list_index; i > 0; --i)
  699. data += Common::swap16(data) * sizeof(HashExceptionEntry) + sizeof(u16);
  700. const u16 exceptions = Common::swap16(data);
  701. data += sizeof(u16);
  702. for (size_t i = 0; i < exceptions; ++i)
  703. {
  704. std::memcpy(&exception_list->emplace_back(), data, sizeof(HashExceptionEntry));
  705. data += sizeof(HashExceptionEntry);
  706. u16& offset = exception_list->back().offset;
  707. offset = Common::swap16(Common::swap16(offset) + additional_offset);
  708. }
  709. ASSERT(data <= data_start + (m_compressed_exception_lists ? m_out_bytes_used_for_exceptions :
  710. m_in_bytes_used_for_exceptions));
  711. }
  712. template <bool RVZ>
  713. size_t WIARVZFileReader<RVZ>::Chunk::GetOutBytesWrittenExcludingExceptions() const
  714. {
  715. return m_exception_lists == 0 ? m_out.bytes_written - m_out_bytes_used_for_exceptions : 0;
  716. }
  717. template <bool RVZ>
  718. bool WIARVZFileReader<RVZ>::ApplyHashExceptions(
  719. const std::vector<HashExceptionEntry>& exception_list,
  720. VolumeWii::HashBlock hash_blocks[VolumeWii::BLOCKS_PER_GROUP])
  721. {
  722. for (const HashExceptionEntry& exception : exception_list)
  723. {
  724. const u16 offset = Common::swap16(exception.offset);
  725. const size_t block_index = offset / VolumeWii::BLOCK_HEADER_SIZE;
  726. if (block_index > VolumeWii::BLOCKS_PER_GROUP)
  727. return false;
  728. const size_t offset_in_block = offset % VolumeWii::BLOCK_HEADER_SIZE;
  729. if (offset_in_block + Common::SHA1::DIGEST_LEN > VolumeWii::BLOCK_HEADER_SIZE)
  730. return false;
  731. std::memcpy(reinterpret_cast<u8*>(&hash_blocks[block_index]) + offset_in_block, &exception.hash,
  732. Common::SHA1::DIGEST_LEN);
  733. }
  734. return true;
  735. }
  736. template <bool RVZ>
  737. bool WIARVZFileReader<RVZ>::PadTo4(File::IOFile* file, u64* bytes_written)
  738. {
  739. constexpr u32 ZEROES = 0;
  740. const u64 bytes_to_write = Common::AlignUp(*bytes_written, 4) - *bytes_written;
  741. if (bytes_to_write == 0)
  742. return true;
  743. *bytes_written += bytes_to_write;
  744. return file->WriteBytes(&ZEROES, bytes_to_write);
  745. }
  746. template <bool RVZ>
  747. void WIARVZFileReader<RVZ>::AddRawDataEntry(u64 offset, u64 size, int chunk_size, u32* total_groups,
  748. std::vector<RawDataEntry>* raw_data_entries,
  749. std::vector<DataEntry>* data_entries)
  750. {
  751. constexpr size_t SKIP_SIZE = sizeof(WIAHeader2::disc_header);
  752. const u64 skip = offset < SKIP_SIZE ? std::min(SKIP_SIZE - offset, size) : 0;
  753. offset += skip;
  754. size -= skip;
  755. if (size == 0)
  756. return;
  757. const u32 group_index = *total_groups;
  758. const u32 groups = static_cast<u32>(Common::AlignUp(size, chunk_size) / chunk_size);
  759. *total_groups += groups;
  760. data_entries->emplace_back(raw_data_entries->size());
  761. raw_data_entries->emplace_back(RawDataEntry{Common::swap64(offset), Common::swap64(size),
  762. Common::swap32(group_index), Common::swap32(groups)});
  763. }
  764. template <bool RVZ>
  765. typename WIARVZFileReader<RVZ>::PartitionDataEntry WIARVZFileReader<RVZ>::CreatePartitionDataEntry(
  766. u64 offset, u64 size, u32 index, int chunk_size, u32* total_groups,
  767. const std::vector<PartitionEntry>& partition_entries, std::vector<DataEntry>* data_entries)
  768. {
  769. const u32 group_index = *total_groups;
  770. const u64 rounded_size = Common::AlignDown(size, VolumeWii::BLOCK_TOTAL_SIZE);
  771. const u32 groups = static_cast<u32>(Common::AlignUp(rounded_size, chunk_size) / chunk_size);
  772. *total_groups += groups;
  773. data_entries->emplace_back(partition_entries.size(), index);
  774. return PartitionDataEntry{Common::swap32(offset / VolumeWii::BLOCK_TOTAL_SIZE),
  775. Common::swap32(size / VolumeWii::BLOCK_TOTAL_SIZE),
  776. Common::swap32(group_index), Common::swap32(groups)};
  777. }
  778. template <bool RVZ>
  779. ConversionResultCode WIARVZFileReader<RVZ>::SetUpDataEntriesForWriting(
  780. const VolumeDisc* volume, int chunk_size, u64 iso_size, u32* total_groups,
  781. std::vector<PartitionEntry>* partition_entries, std::vector<RawDataEntry>* raw_data_entries,
  782. std::vector<DataEntry>* data_entries, std::vector<const FileSystem*>* partition_file_systems)
  783. {
  784. std::vector<Partition> partitions;
  785. if (volume && volume->HasWiiHashes() && volume->HasWiiEncryption())
  786. partitions = volume->GetPartitions();
  787. std::ranges::sort(partitions, {}, &Partition::offset);
  788. *total_groups = 0;
  789. u64 last_partition_end_offset = 0;
  790. const auto add_raw_data_entry = [&](u64 offset, u64 size) {
  791. return AddRawDataEntry(offset, size, chunk_size, total_groups, raw_data_entries, data_entries);
  792. };
  793. const auto create_partition_data_entry = [&](u64 offset, u64 size, u32 index) {
  794. return CreatePartitionDataEntry(offset, size, index, chunk_size, total_groups,
  795. *partition_entries, data_entries);
  796. };
  797. for (const Partition& partition : partitions)
  798. {
  799. // If a partition is odd in some way that prevents us from encoding it as a partition,
  800. // we encode it as raw data instead by skipping the current loop iteration.
  801. // Partitions can always be encoded as raw data, but it is less space efficient.
  802. if (partition.offset < last_partition_end_offset)
  803. {
  804. WARN_LOG_FMT(DISCIO, "Overlapping partitions at {:x}", partition.offset);
  805. continue;
  806. }
  807. if (volume->ReadSwapped<u32>(partition.offset, PARTITION_NONE) != 0x10001U)
  808. {
  809. // This looks more like garbage data than an actual partition.
  810. // The values of data_offset and data_size will very likely also be garbage.
  811. // Some WBFS writing programs scrub the SSBB Masterpiece partitions without
  812. // removing them from the partition table, causing this problem.
  813. WARN_LOG_FMT(DISCIO, "Invalid partition at {:x}", partition.offset);
  814. continue;
  815. }
  816. std::optional<u64> data_offset =
  817. volume->ReadSwappedAndShifted(partition.offset + 0x2b8, PARTITION_NONE);
  818. std::optional<u64> data_size =
  819. volume->ReadSwappedAndShifted(partition.offset + 0x2bc, PARTITION_NONE);
  820. if (!data_offset || !data_size)
  821. return ConversionResultCode::ReadFailed;
  822. const u64 data_start = partition.offset + *data_offset;
  823. const u64 data_end = data_start + *data_size;
  824. if (data_start % VolumeWii::BLOCK_TOTAL_SIZE != 0)
  825. {
  826. WARN_LOG_FMT(DISCIO, "Misaligned partition at {:x}", partition.offset);
  827. continue;
  828. }
  829. if (*data_size < VolumeWii::BLOCK_TOTAL_SIZE)
  830. {
  831. WARN_LOG_FMT(DISCIO, "Very small partition at {:x}", partition.offset);
  832. continue;
  833. }
  834. if (data_end > iso_size)
  835. {
  836. WARN_LOG_FMT(DISCIO, "Too large partition at {:x}", partition.offset);
  837. *data_size = iso_size - *data_offset - partition.offset;
  838. }
  839. const std::optional<u64> fst_offset = GetFSTOffset(*volume, partition);
  840. const std::optional<u64> fst_size = GetFSTSize(*volume, partition);
  841. if (!fst_offset || !fst_size)
  842. return ConversionResultCode::ReadFailed;
  843. const IOS::ES::TicketReader& ticket = volume->GetTicket(partition);
  844. if (!ticket.IsValid())
  845. return ConversionResultCode::ReadFailed;
  846. add_raw_data_entry(last_partition_end_offset, partition.offset - last_partition_end_offset);
  847. add_raw_data_entry(partition.offset, *data_offset);
  848. const u64 fst_end = volume->PartitionOffsetToRawOffset(*fst_offset + *fst_size, partition);
  849. const u64 split_point = std::min(
  850. data_end, Common::AlignUp(fst_end - data_start, VolumeWii::GROUP_TOTAL_SIZE) + data_start);
  851. PartitionEntry partition_entry;
  852. partition_entry.partition_key = ticket.GetTitleKey();
  853. partition_entry.data_entries[0] =
  854. create_partition_data_entry(data_start, split_point - data_start, 0);
  855. partition_entry.data_entries[1] =
  856. create_partition_data_entry(split_point, data_end - split_point, 1);
  857. // Note: We can't simply set last_partition_end_offset to data_end,
  858. // because construct_partition_data_entry may have rounded it
  859. last_partition_end_offset =
  860. (Common::swap32(partition_entry.data_entries[1].first_sector) +
  861. Common::swap32(partition_entry.data_entries[1].number_of_sectors)) *
  862. VolumeWii::BLOCK_TOTAL_SIZE;
  863. partition_entries->emplace_back(std::move(partition_entry));
  864. partition_file_systems->emplace_back(volume->GetFileSystem(partition));
  865. }
  866. add_raw_data_entry(last_partition_end_offset, iso_size - last_partition_end_offset);
  867. return ConversionResultCode::Success;
  868. }
  869. template <bool RVZ>
  870. std::optional<std::vector<u8>> WIARVZFileReader<RVZ>::Compress(Compressor* compressor,
  871. const u8* data, size_t size)
  872. {
  873. if (compressor)
  874. {
  875. if (!compressor->Start(size) || !compressor->Compress(data, size) || !compressor->End())
  876. return std::nullopt;
  877. data = compressor->GetData();
  878. size = compressor->GetSize();
  879. }
  880. return std::vector<u8>(data, data + size);
  881. }
  882. template <bool RVZ>
  883. void WIARVZFileReader<RVZ>::SetUpCompressor(std::unique_ptr<Compressor>* compressor,
  884. WIARVZCompressionType compression_type,
  885. int compression_level, WIAHeader2* header_2)
  886. {
  887. switch (compression_type)
  888. {
  889. case WIARVZCompressionType::None:
  890. *compressor = nullptr;
  891. break;
  892. case WIARVZCompressionType::Purge:
  893. *compressor = std::make_unique<PurgeCompressor>();
  894. break;
  895. case WIARVZCompressionType::Bzip2:
  896. *compressor = std::make_unique<Bzip2Compressor>(compression_level);
  897. break;
  898. case WIARVZCompressionType::LZMA:
  899. case WIARVZCompressionType::LZMA2:
  900. {
  901. u8* compressor_data = nullptr;
  902. u8* compressor_data_size = nullptr;
  903. if (header_2)
  904. {
  905. compressor_data = header_2->compressor_data;
  906. compressor_data_size = &header_2->compressor_data_size;
  907. }
  908. const bool lzma2 = compression_type == WIARVZCompressionType::LZMA2;
  909. *compressor = std::make_unique<LZMACompressor>(lzma2, compression_level, compressor_data,
  910. compressor_data_size);
  911. break;
  912. }
  913. case WIARVZCompressionType::Zstd:
  914. *compressor = std::make_unique<ZstdCompressor>(compression_level);
  915. break;
  916. }
  917. }
  918. template <bool RVZ>
  919. bool WIARVZFileReader<RVZ>::TryReuse(std::map<ReuseID, GroupEntry>* reusable_groups,
  920. std::mutex* reusable_groups_mutex,
  921. OutputParametersEntry* entry)
  922. {
  923. if (entry->reused_group)
  924. return true;
  925. if (!entry->reuse_id)
  926. return false;
  927. std::lock_guard guard(*reusable_groups_mutex);
  928. const auto it = reusable_groups->find(*entry->reuse_id);
  929. if (it == reusable_groups->end())
  930. return false;
  931. entry->reused_group = it->second;
  932. return true;
  933. }
  934. static bool AllAre(const std::vector<u8>& data, u8 x)
  935. {
  936. return std::ranges::all_of(data, [x](u8 y) { return x == y; });
  937. }
  938. static bool AllAre(const u8* begin, const u8* end, u8 x)
  939. {
  940. return std::all_of(begin, end, [x](u8 y) { return x == y; });
  941. }
  942. static bool AllZero(const std::vector<u8>& data)
  943. {
  944. return AllAre(data, 0);
  945. }
  946. static bool AllSame(const std::vector<u8>& data)
  947. {
  948. return AllAre(data, data.front());
  949. }
  950. static bool AllSame(const u8* begin, const u8* end)
  951. {
  952. return AllAre(begin, end, *begin);
  953. }
  954. template <typename OutputParametersEntry>
  955. static void RVZPack(const u8* in, OutputParametersEntry* out, u64 bytes_per_chunk, size_t chunks,
  956. u64 total_size, u64 data_offset, bool multipart, bool allow_junk_reuse,
  957. bool compression, const FileSystem* file_system)
  958. {
  959. using Seed = std::array<u32, LaggedFibonacciGenerator::SEED_SIZE>;
  960. struct JunkInfo
  961. {
  962. size_t start_offset;
  963. Seed seed;
  964. };
  965. constexpr size_t SEED_SIZE = LaggedFibonacciGenerator::SEED_SIZE * sizeof(u32);
  966. // Maps end_offset -> (start_offset, seed)
  967. std::map<size_t, JunkInfo> junk_info;
  968. size_t position = 0;
  969. while (position < total_size)
  970. {
  971. // Skip the 0 to 32 zero bytes that typically come after a file
  972. size_t zeroes = 0;
  973. while (position + zeroes < total_size && in[position + zeroes] == 0)
  974. ++zeroes;
  975. // If there are very many zero bytes (perhaps the PRNG junk data has been scrubbed?)
  976. // and we aren't using compression, it makes sense to encode the zero bytes as junk.
  977. // If we are using compression, the compressor will likely encode zeroes better than we can
  978. if (!compression && zeroes > SEED_SIZE)
  979. junk_info.emplace(position + zeroes, JunkInfo{position, {}});
  980. position += zeroes;
  981. data_offset += zeroes;
  982. const size_t bytes_to_read =
  983. std::min(Common::AlignUp(data_offset + 1, VolumeWii::BLOCK_TOTAL_SIZE) - data_offset,
  984. total_size - position);
  985. const size_t data_offset_mod = static_cast<size_t>(data_offset % VolumeWii::BLOCK_TOTAL_SIZE);
  986. Seed seed;
  987. const size_t bytes_reconstructed = LaggedFibonacciGenerator::GetSeed(
  988. in + position, bytes_to_read, data_offset_mod, seed.data());
  989. if (bytes_reconstructed > 0)
  990. junk_info.emplace(position + bytes_reconstructed, JunkInfo{position, seed});
  991. if (file_system)
  992. {
  993. const std::unique_ptr<DiscIO::FileInfo> file_info =
  994. file_system->FindFileInfo(data_offset + bytes_reconstructed);
  995. // If we're at a file and there's more space in this block after the file,
  996. // continue after the file instead of skipping to the next block
  997. if (file_info)
  998. {
  999. const u64 file_end_offset = file_info->GetOffset() + file_info->GetSize();
  1000. if (file_end_offset < data_offset + bytes_to_read)
  1001. {
  1002. position += file_end_offset - data_offset;
  1003. data_offset = file_end_offset;
  1004. continue;
  1005. }
  1006. }
  1007. }
  1008. position += bytes_to_read;
  1009. data_offset += bytes_to_read;
  1010. }
  1011. for (size_t i = 0; i < chunks; ++i)
  1012. {
  1013. OutputParametersEntry& entry = out[i];
  1014. if (entry.reused_group)
  1015. continue;
  1016. u64 current_offset = i * bytes_per_chunk;
  1017. const u64 end_offset = std::min(current_offset + bytes_per_chunk, total_size);
  1018. const bool store_junk_efficiently = allow_junk_reuse || !entry.reuse_id;
  1019. // TODO: It would be possible to support skipping RVZ packing even when the chunk size is larger
  1020. // than 2 MiB (multipart == true), but it would be more effort than it's worth since Dolphin's
  1021. // converter doesn't expose chunk sizes larger than 2 MiB to the user anyway
  1022. bool first_loop_iteration = !multipart;
  1023. while (current_offset < end_offset)
  1024. {
  1025. u64 next_junk_start = end_offset;
  1026. u64 next_junk_end = end_offset;
  1027. Seed* seed = nullptr;
  1028. if (store_junk_efficiently && end_offset - current_offset > SEED_SIZE)
  1029. {
  1030. const auto next_junk_it = junk_info.upper_bound(current_offset + SEED_SIZE);
  1031. if (next_junk_it != junk_info.end() &&
  1032. next_junk_it->second.start_offset + SEED_SIZE < end_offset)
  1033. {
  1034. next_junk_start = std::max<u64>(current_offset, next_junk_it->second.start_offset);
  1035. next_junk_end = std::min<u64>(end_offset, next_junk_it->first);
  1036. seed = &next_junk_it->second.seed;
  1037. }
  1038. }
  1039. if (first_loop_iteration)
  1040. {
  1041. if (next_junk_start == end_offset)
  1042. {
  1043. // Storing this chunk with RVZ packing would be inefficient, so store it without
  1044. PushBack(&entry.main_data, in + current_offset, in + end_offset);
  1045. break;
  1046. }
  1047. first_loop_iteration = false;
  1048. }
  1049. const u64 non_junk_bytes = next_junk_start - current_offset;
  1050. if (non_junk_bytes > 0)
  1051. {
  1052. const u8* ptr = in + current_offset;
  1053. PushBack(&entry.main_data, Common::swap32(static_cast<u32>(non_junk_bytes)));
  1054. PushBack(&entry.main_data, ptr, ptr + non_junk_bytes);
  1055. current_offset += non_junk_bytes;
  1056. entry.rvz_packed_size += sizeof(u32) + non_junk_bytes;
  1057. }
  1058. const u64 junk_bytes = next_junk_end - current_offset;
  1059. if (junk_bytes > 0)
  1060. {
  1061. PushBack(&entry.main_data, Common::swap32(static_cast<u32>(junk_bytes) | 0x80000000));
  1062. PushBack(&entry.main_data, *seed);
  1063. current_offset += junk_bytes;
  1064. entry.rvz_packed_size += sizeof(u32) + SEED_SIZE;
  1065. }
  1066. }
  1067. }
  1068. }
  1069. template <typename OutputParametersEntry>
  1070. static void RVZPack(const u8* in, OutputParametersEntry* out, u64 size, u64 data_offset,
  1071. bool allow_junk_reuse, bool compression, const FileSystem* file_system)
  1072. {
  1073. RVZPack(in, out, size, 1, size, data_offset, false, allow_junk_reuse, compression, file_system);
  1074. }
  1075. template <bool RVZ>
  1076. ConversionResult<typename WIARVZFileReader<RVZ>::OutputParameters>
  1077. WIARVZFileReader<RVZ>::ProcessAndCompress(CompressThreadState* state, CompressParameters parameters,
  1078. const std::vector<PartitionEntry>& partition_entries,
  1079. const std::vector<DataEntry>& data_entries,
  1080. const FileSystem* file_system,
  1081. std::map<ReuseID, GroupEntry>* reusable_groups,
  1082. std::mutex* reusable_groups_mutex,
  1083. u64 chunks_per_wii_group, u64 exception_lists_per_chunk,
  1084. bool compressed_exception_lists, bool compression)
  1085. {
  1086. std::vector<OutputParametersEntry> output_entries;
  1087. if (!parameters.data_entry->is_partition)
  1088. {
  1089. OutputParametersEntry& entry = output_entries.emplace_back();
  1090. std::vector<u8>& data = parameters.data;
  1091. if (AllSame(data))
  1092. entry.reuse_id = ReuseID{WiiKey{}, data.size(), false, data.front()};
  1093. if constexpr (RVZ)
  1094. {
  1095. RVZPack(data.data(), output_entries.data(), data.size(), parameters.data_offset, true,
  1096. compression, file_system);
  1097. }
  1098. else
  1099. {
  1100. entry.main_data = std::move(data);
  1101. }
  1102. }
  1103. else
  1104. {
  1105. const PartitionEntry& partition_entry = partition_entries[parameters.data_entry->index];
  1106. auto aes_context = Common::AES::CreateContextDecrypt(partition_entry.partition_key.data());
  1107. const u64 groups = Common::AlignUp(parameters.data.size(), VolumeWii::GROUP_TOTAL_SIZE) /
  1108. VolumeWii::GROUP_TOTAL_SIZE;
  1109. ASSERT(parameters.data.size() % VolumeWii::BLOCK_TOTAL_SIZE == 0);
  1110. const u64 blocks = parameters.data.size() / VolumeWii::BLOCK_TOTAL_SIZE;
  1111. const u64 blocks_per_chunk = chunks_per_wii_group == 1 ?
  1112. exception_lists_per_chunk * VolumeWii::BLOCKS_PER_GROUP :
  1113. VolumeWii::BLOCKS_PER_GROUP / chunks_per_wii_group;
  1114. const u64 chunks = Common::AlignUp(blocks, blocks_per_chunk) / blocks_per_chunk;
  1115. const u64 in_data_per_chunk = blocks_per_chunk * VolumeWii::BLOCK_TOTAL_SIZE;
  1116. const u64 out_data_per_chunk = blocks_per_chunk * VolumeWii::BLOCK_DATA_SIZE;
  1117. const size_t first_chunk = output_entries.size();
  1118. const auto create_reuse_id = [&partition_entry, blocks,
  1119. blocks_per_chunk](u8 value, bool encrypted, u64 block) {
  1120. const u64 size = std::min(blocks - block, blocks_per_chunk) * VolumeWii::BLOCK_DATA_SIZE;
  1121. return ReuseID{partition_entry.partition_key, size, encrypted, value};
  1122. };
  1123. const u8* parameters_data_end = parameters.data.data() + parameters.data.size();
  1124. for (u64 i = 0; i < chunks; ++i)
  1125. {
  1126. const u64 block_index = i * blocks_per_chunk;
  1127. OutputParametersEntry& entry = output_entries.emplace_back();
  1128. std::optional<ReuseID>& reuse_id = entry.reuse_id;
  1129. // Set this chunk as reusable if the encrypted data is AllSame
  1130. const u8* data = parameters.data.data() + block_index * VolumeWii::BLOCK_TOTAL_SIZE;
  1131. if (AllSame(data, std::min(parameters_data_end, data + in_data_per_chunk)))
  1132. reuse_id = create_reuse_id(parameters.data.front(), true, i * blocks_per_chunk);
  1133. TryReuse(reusable_groups, reusable_groups_mutex, &entry);
  1134. if (!entry.reused_group && reuse_id)
  1135. {
  1136. const auto it = std::ranges::find(output_entries.begin(), output_entries.begin() + i,
  1137. reuse_id, &OutputParametersEntry::reuse_id);
  1138. if (it != output_entries.begin() + i)
  1139. entry.reused_group = it->reused_group;
  1140. }
  1141. }
  1142. if (!std::ranges::all_of(output_entries,
  1143. [](const auto& entry) { return entry.reused_group.has_value(); }))
  1144. {
  1145. const u64 number_of_exception_lists =
  1146. chunks_per_wii_group == 1 ? exception_lists_per_chunk : chunks;
  1147. std::vector<std::vector<HashExceptionEntry>> exception_lists(number_of_exception_lists);
  1148. for (u64 i = 0; i < groups; ++i)
  1149. {
  1150. const u64 offset_of_group = i * VolumeWii::GROUP_TOTAL_SIZE;
  1151. const u64 write_offset_of_group = i * VolumeWii::GROUP_DATA_SIZE;
  1152. const u64 blocks_in_this_group =
  1153. std::min<u64>(VolumeWii::BLOCKS_PER_GROUP, blocks - i * VolumeWii::BLOCKS_PER_GROUP);
  1154. for (u32 j = 0; j < VolumeWii::BLOCKS_PER_GROUP; ++j)
  1155. {
  1156. if (j < blocks_in_this_group)
  1157. {
  1158. const u64 offset_of_block = offset_of_group + j * VolumeWii::BLOCK_TOTAL_SIZE;
  1159. VolumeWii::DecryptBlockData(parameters.data.data() + offset_of_block,
  1160. state->decryption_buffer[j].data(), aes_context.get());
  1161. }
  1162. else
  1163. {
  1164. state->decryption_buffer[j].fill(0);
  1165. }
  1166. }
  1167. VolumeWii::HashGroup(state->decryption_buffer.data(), state->hash_buffer.data());
  1168. for (u64 j = 0; j < blocks_in_this_group; ++j)
  1169. {
  1170. const u64 chunk_index = j / blocks_per_chunk;
  1171. const u64 block_index_in_chunk = j % blocks_per_chunk;
  1172. if (output_entries[chunk_index].reused_group)
  1173. continue;
  1174. const u64 exception_list_index = chunks_per_wii_group == 1 ? i : chunk_index;
  1175. const u64 offset_of_block = offset_of_group + j * VolumeWii::BLOCK_TOTAL_SIZE;
  1176. const u64 hash_offset_of_block = block_index_in_chunk * VolumeWii::BLOCK_HEADER_SIZE;
  1177. VolumeWii::HashBlock hashes;
  1178. VolumeWii::DecryptBlockHashes(parameters.data.data() + offset_of_block, &hashes,
  1179. aes_context.get());
  1180. const auto compare_hash = [&](size_t offset_in_block) {
  1181. ASSERT(offset_in_block + Common::SHA1::DIGEST_LEN <= VolumeWii::BLOCK_HEADER_SIZE);
  1182. const u8* desired_hash = reinterpret_cast<u8*>(&hashes) + offset_in_block;
  1183. const u8* computed_hash =
  1184. reinterpret_cast<u8*>(&state->hash_buffer[j]) + offset_in_block;
  1185. // We want to store a hash exception either if there is a hash mismatch, or if this
  1186. // chunk might get reused in a context where it is paired up (within a 2 MiB Wii group)
  1187. // with chunks that are different from the chunks it currently is paired up with, since
  1188. // that affects the recalculated hashes. Chunks which have been marked as reusable at
  1189. // this point normally have zero matching hashes anyway, so this shouldn't waste space.
  1190. if ((chunks_per_wii_group != 1 && output_entries[chunk_index].reuse_id) ||
  1191. !std::equal(desired_hash, desired_hash + Common::SHA1::DIGEST_LEN, computed_hash))
  1192. {
  1193. const u64 hash_offset = hash_offset_of_block + offset_in_block;
  1194. ASSERT(hash_offset <= std::numeric_limits<u16>::max());
  1195. HashExceptionEntry& exception = exception_lists[exception_list_index].emplace_back();
  1196. exception.offset = static_cast<u16>(Common::swap16(hash_offset));
  1197. std::memcpy(exception.hash.data(), desired_hash, Common::SHA1::DIGEST_LEN);
  1198. }
  1199. };
  1200. const auto compare_hashes = [&compare_hash](size_t offset, size_t size) {
  1201. for (size_t l = 0; l < size; l += Common::SHA1::DIGEST_LEN)
  1202. // The std::min is to ensure that we don't go beyond the end of HashBlock with
  1203. // padding_2, which is 32 bytes long (not divisible by SHA1::DIGEST_LEN, which is 20).
  1204. compare_hash(offset + std::min(l, size - Common::SHA1::DIGEST_LEN));
  1205. };
  1206. using HashBlock = VolumeWii::HashBlock;
  1207. compare_hashes(offsetof(HashBlock, h0), sizeof(HashBlock::h0));
  1208. compare_hashes(offsetof(HashBlock, padding_0), sizeof(HashBlock::padding_0));
  1209. compare_hashes(offsetof(HashBlock, h1), sizeof(HashBlock::h1));
  1210. compare_hashes(offsetof(HashBlock, padding_1), sizeof(HashBlock::padding_1));
  1211. compare_hashes(offsetof(HashBlock, h2), sizeof(HashBlock::h2));
  1212. compare_hashes(offsetof(HashBlock, padding_2), sizeof(HashBlock::padding_2));
  1213. }
  1214. static_assert(std::is_trivially_copyable_v<
  1215. typename decltype(CompressThreadState::decryption_buffer)::value_type>);
  1216. if constexpr (RVZ)
  1217. {
  1218. // We must not store junk efficiently for chunks that may get reused at a position
  1219. // which has a different value of data_offset % VolumeWii::BLOCK_TOTAL_SIZE
  1220. const bool allow_junk_reuse = chunks_per_wii_group == 1;
  1221. const u64 bytes_per_chunk = std::min(out_data_per_chunk, VolumeWii::GROUP_DATA_SIZE);
  1222. const u64 total_size = blocks_in_this_group * VolumeWii::BLOCK_DATA_SIZE;
  1223. const u64 data_offset = parameters.data_offset + write_offset_of_group;
  1224. RVZPack(state->decryption_buffer[0].data(), output_entries.data() + first_chunk,
  1225. bytes_per_chunk, chunks, total_size, data_offset, groups > 1, allow_junk_reuse,
  1226. compression, file_system);
  1227. }
  1228. else
  1229. {
  1230. const u8* in_ptr = state->decryption_buffer[0].data();
  1231. for (u64 j = 0; j < chunks; ++j)
  1232. {
  1233. OutputParametersEntry& entry = output_entries[first_chunk + j];
  1234. if (!entry.reused_group)
  1235. {
  1236. const u64 bytes_left = (blocks - j * blocks_per_chunk) * VolumeWii::BLOCK_DATA_SIZE;
  1237. const u64 bytes_to_write_total = std::min(out_data_per_chunk, bytes_left);
  1238. if (i == 0)
  1239. entry.main_data.resize(bytes_to_write_total);
  1240. const u64 bytes_to_write = std::min(bytes_to_write_total, VolumeWii::GROUP_DATA_SIZE);
  1241. std::memcpy(entry.main_data.data() + write_offset_of_group, in_ptr, bytes_to_write);
  1242. // Set this chunk as reusable if the decrypted data is AllSame.
  1243. // There is also a requirement that it lacks exceptions, but this is checked later
  1244. if (i == 0 && !entry.reuse_id)
  1245. {
  1246. if (AllSame(in_ptr, in_ptr + bytes_to_write))
  1247. entry.reuse_id = create_reuse_id(*in_ptr, false, j * blocks_per_chunk);
  1248. }
  1249. else
  1250. {
  1251. if (entry.reuse_id && !entry.reuse_id->encrypted &&
  1252. (!AllSame(in_ptr, in_ptr + bytes_to_write) || entry.reuse_id->value != *in_ptr))
  1253. {
  1254. entry.reuse_id.reset();
  1255. }
  1256. }
  1257. }
  1258. in_ptr += out_data_per_chunk;
  1259. }
  1260. }
  1261. }
  1262. for (size_t i = 0; i < exception_lists.size(); ++i)
  1263. {
  1264. OutputParametersEntry& entry = output_entries[chunks_per_wii_group == 1 ? 0 : i];
  1265. if (entry.reused_group)
  1266. continue;
  1267. const std::vector<HashExceptionEntry>& in = exception_lists[i];
  1268. std::vector<u8>& out = entry.exception_lists;
  1269. const u16 exceptions = Common::swap16(static_cast<u16>(in.size()));
  1270. PushBack(&out, exceptions);
  1271. for (const HashExceptionEntry& exception : in)
  1272. PushBack(&out, exception);
  1273. }
  1274. for (u64 i = 0; i < output_entries.size(); ++i)
  1275. {
  1276. OutputParametersEntry& entry = output_entries[i];
  1277. // If this chunk was set as reusable because the decrypted data is AllSame,
  1278. // but it has exceptions, unmark it as reusable
  1279. if (entry.reuse_id && !entry.reuse_id->encrypted && !AllZero(entry.exception_lists))
  1280. entry.reuse_id.reset();
  1281. }
  1282. }
  1283. }
  1284. for (OutputParametersEntry& entry : output_entries)
  1285. {
  1286. TryReuse(reusable_groups, reusable_groups_mutex, &entry);
  1287. if (entry.reused_group)
  1288. continue;
  1289. // Special case - a compressed size of zero is treated by WIA as meaning the data is all zeroes
  1290. if (entry.reuse_id && !entry.reuse_id->encrypted && entry.reuse_id->value == 0)
  1291. {
  1292. entry.exception_lists.clear();
  1293. entry.main_data.clear();
  1294. if constexpr (RVZ)
  1295. {
  1296. entry.rvz_packed_size = 0;
  1297. entry.compressed = false;
  1298. }
  1299. continue;
  1300. }
  1301. const auto pad_exception_lists = [&entry]() {
  1302. while (entry.exception_lists.size() % 4 != 0)
  1303. entry.exception_lists.push_back(0);
  1304. };
  1305. if (state->compressor)
  1306. {
  1307. if (!state->compressor->Start(entry.exception_lists.size() + entry.main_data.size()))
  1308. return ConversionResultCode::InternalError;
  1309. }
  1310. if (!entry.exception_lists.empty())
  1311. {
  1312. if (compressed_exception_lists && state->compressor)
  1313. {
  1314. if (!state->compressor->Compress(entry.exception_lists.data(),
  1315. entry.exception_lists.size()))
  1316. {
  1317. return ConversionResultCode::InternalError;
  1318. }
  1319. }
  1320. else
  1321. {
  1322. if (!compressed_exception_lists)
  1323. pad_exception_lists();
  1324. if (state->compressor)
  1325. {
  1326. if (!state->compressor->AddPrecedingDataOnlyForPurgeHashing(entry.exception_lists.data(),
  1327. entry.exception_lists.size()))
  1328. {
  1329. return ConversionResultCode::InternalError;
  1330. }
  1331. }
  1332. }
  1333. }
  1334. if (state->compressor)
  1335. {
  1336. if (!state->compressor->Compress(entry.main_data.data(), entry.main_data.size()))
  1337. return ConversionResultCode::InternalError;
  1338. if (!state->compressor->End())
  1339. return ConversionResultCode::InternalError;
  1340. }
  1341. bool compressed = !!state->compressor;
  1342. if constexpr (RVZ)
  1343. {
  1344. size_t uncompressed_size = entry.main_data.size();
  1345. if (compressed_exception_lists)
  1346. uncompressed_size += Common::AlignUp(entry.exception_lists.size(), 4);
  1347. compressed = state->compressor && state->compressor->GetSize() < uncompressed_size;
  1348. entry.compressed = compressed;
  1349. if (!compressed)
  1350. pad_exception_lists();
  1351. }
  1352. if (compressed)
  1353. {
  1354. const u8* data = state->compressor->GetData();
  1355. const size_t size = state->compressor->GetSize();
  1356. entry.main_data.resize(size);
  1357. std::copy_n(data, size, entry.main_data.data());
  1358. if (compressed_exception_lists)
  1359. entry.exception_lists.clear();
  1360. }
  1361. }
  1362. return OutputParameters{std::move(output_entries), parameters.bytes_read, parameters.group_index};
  1363. }
  1364. template <bool RVZ>
  1365. ConversionResultCode WIARVZFileReader<RVZ>::Output(std::vector<OutputParametersEntry>* entries,
  1366. File::IOFile* outfile,
  1367. std::map<ReuseID, GroupEntry>* reusable_groups,
  1368. std::mutex* reusable_groups_mutex,
  1369. GroupEntry* group_entry, u64* bytes_written)
  1370. {
  1371. for (OutputParametersEntry& entry : *entries)
  1372. {
  1373. TryReuse(reusable_groups, reusable_groups_mutex, &entry);
  1374. if (entry.reused_group)
  1375. {
  1376. *group_entry = *entry.reused_group;
  1377. ++group_entry;
  1378. continue;
  1379. }
  1380. if (*bytes_written >> 2 > std::numeric_limits<u32>::max())
  1381. return ConversionResultCode::InternalError;
  1382. ASSERT((*bytes_written & 3) == 0);
  1383. group_entry->data_offset = Common::swap32(static_cast<u32>(*bytes_written >> 2));
  1384. u32 data_size = static_cast<u32>(entry.exception_lists.size() + entry.main_data.size());
  1385. if constexpr (RVZ)
  1386. {
  1387. data_size = (data_size & 0x7FFFFFFF) | (static_cast<u32>(entry.compressed) << 31);
  1388. group_entry->rvz_packed_size = Common::swap32(static_cast<u32>(entry.rvz_packed_size));
  1389. }
  1390. group_entry->data_size = Common::swap32(data_size);
  1391. if (!outfile->WriteArray(entry.exception_lists.data(), entry.exception_lists.size()))
  1392. return ConversionResultCode::WriteFailed;
  1393. if (!outfile->WriteArray(entry.main_data.data(), entry.main_data.size()))
  1394. return ConversionResultCode::WriteFailed;
  1395. *bytes_written += entry.exception_lists.size() + entry.main_data.size();
  1396. if (entry.reuse_id)
  1397. {
  1398. std::lock_guard guard(*reusable_groups_mutex);
  1399. reusable_groups->emplace(*entry.reuse_id, *group_entry);
  1400. }
  1401. if (!PadTo4(outfile, bytes_written))
  1402. return ConversionResultCode::WriteFailed;
  1403. ++group_entry;
  1404. }
  1405. return ConversionResultCode::Success;
  1406. }
  1407. template <bool RVZ>
  1408. ConversionResultCode WIARVZFileReader<RVZ>::RunCallback(size_t groups_written, u64 bytes_read,
  1409. u64 bytes_written, u32 total_groups,
  1410. u64 iso_size, const CompressCB& callback)
  1411. {
  1412. int ratio = 0;
  1413. if (bytes_read != 0)
  1414. ratio = static_cast<int>(100 * bytes_written / bytes_read);
  1415. const std::string text = Common::FmtFormatT("{0} of {1} blocks. Compression ratio {2}%",
  1416. groups_written, total_groups, ratio);
  1417. const float completion = static_cast<float>(bytes_read) / iso_size;
  1418. return callback(text, completion) ? ConversionResultCode::Success :
  1419. ConversionResultCode::Canceled;
  1420. }
  1421. template <bool RVZ>
  1422. bool WIARVZFileReader<RVZ>::WriteHeader(File::IOFile* file, const u8* data, size_t size,
  1423. u64 upper_bound, u64* bytes_written, u64* offset_out)
  1424. {
  1425. // The first part of the check is to prevent this from running more than once. If *bytes_written
  1426. // is past the upper bound, we are already at the end of the file, so we don't need to do anything
  1427. if (*bytes_written <= upper_bound && *bytes_written + size > upper_bound)
  1428. {
  1429. WARN_LOG_FMT(DISCIO,
  1430. "Headers did not fit in the allocated space. Writing to end of file instead");
  1431. if (!file->Seek(0, File::SeekOrigin::End))
  1432. return false;
  1433. *bytes_written = file->Tell();
  1434. }
  1435. *offset_out = *bytes_written;
  1436. if (!file->WriteArray(data, size))
  1437. return false;
  1438. *bytes_written += size;
  1439. return PadTo4(file, bytes_written);
  1440. }
  1441. template <bool RVZ>
  1442. ConversionResultCode
  1443. WIARVZFileReader<RVZ>::Convert(BlobReader* infile, const VolumeDisc* infile_volume,
  1444. File::IOFile* outfile, WIARVZCompressionType compression_type,
  1445. int compression_level, int chunk_size, CompressCB callback)
  1446. {
  1447. ASSERT(infile->GetDataSizeType() == DataSizeType::Accurate);
  1448. ASSERT(chunk_size > 0);
  1449. const u64 iso_size = infile->GetDataSize();
  1450. const u64 chunks_per_wii_group = std::max<u64>(1, VolumeWii::GROUP_TOTAL_SIZE / chunk_size);
  1451. const u64 exception_lists_per_chunk = std::max<u64>(1, chunk_size / VolumeWii::GROUP_TOTAL_SIZE);
  1452. const bool compressed_exception_lists = compression_type > WIARVZCompressionType::Purge;
  1453. u64 bytes_read = 0;
  1454. u64 bytes_written = 0;
  1455. size_t groups_processed = 0;
  1456. WIAHeader1 header_1{};
  1457. WIAHeader2 header_2{};
  1458. std::vector<PartitionEntry> partition_entries;
  1459. std::vector<RawDataEntry> raw_data_entries;
  1460. std::vector<GroupEntry> group_entries;
  1461. u32 total_groups;
  1462. std::vector<DataEntry> data_entries;
  1463. const FileSystem* non_partition_file_system =
  1464. infile_volume ? infile_volume->GetFileSystem(PARTITION_NONE) : nullptr;
  1465. std::vector<const FileSystem*> partition_file_systems;
  1466. const ConversionResultCode set_up_data_entries_result = SetUpDataEntriesForWriting(
  1467. infile_volume, chunk_size, iso_size, &total_groups, &partition_entries, &raw_data_entries,
  1468. &data_entries, &partition_file_systems);
  1469. if (set_up_data_entries_result != ConversionResultCode::Success)
  1470. return set_up_data_entries_result;
  1471. group_entries.resize(total_groups);
  1472. const size_t partition_entries_size = partition_entries.size() * sizeof(PartitionEntry);
  1473. const size_t raw_data_entries_size = raw_data_entries.size() * sizeof(RawDataEntry);
  1474. const size_t group_entries_size = group_entries.size() * sizeof(GroupEntry);
  1475. // An estimate for how much space will be taken up by headers.
  1476. // We will reserve this much space at the beginning of the file, and if the headers don't
  1477. // fit in that space, we will need to write them at the end of the file instead.
  1478. const u64 headers_size_upper_bound = [&] {
  1479. // 0x100 is added to account for compression overhead (in particular for Purge).
  1480. u64 upper_bound = sizeof(WIAHeader1) + sizeof(WIAHeader2) + partition_entries_size +
  1481. raw_data_entries_size + 0x100;
  1482. // Compared to WIA, RVZ adds an extra member to the GroupEntry struct. This added data usually
  1483. // compresses well, so we'll assume the compression ratio for RVZ GroupEntries is 9 / 16 or
  1484. // better. This constant is somehwat arbitrarily chosen, but no games were found that get a
  1485. // worse compression ratio than that. There are some games that get a worse ratio than 1 / 2,
  1486. // such as Metroid: Other M (PAL) with the default settings.
  1487. if (RVZ && compression_type > WIARVZCompressionType::Purge)
  1488. upper_bound += static_cast<u64>(group_entries_size) * 9 / 16;
  1489. else
  1490. upper_bound += group_entries_size;
  1491. // This alignment is also somewhat arbitrary.
  1492. return Common::AlignUp(upper_bound, VolumeWii::BLOCK_TOTAL_SIZE);
  1493. }();
  1494. std::vector<u8> buffer;
  1495. buffer.resize(headers_size_upper_bound);
  1496. outfile->WriteBytes(buffer.data(), buffer.size());
  1497. bytes_written = headers_size_upper_bound;
  1498. if (!infile->Read(0, header_2.disc_header.size(), header_2.disc_header.data()))
  1499. return ConversionResultCode::ReadFailed;
  1500. // We intentionally do not increment bytes_read here, since these bytes will be read again
  1501. std::map<ReuseID, GroupEntry> reusable_groups;
  1502. std::mutex reusable_groups_mutex;
  1503. const auto set_up_compress_thread_state = [&](CompressThreadState* state) {
  1504. SetUpCompressor(&state->compressor, compression_type, compression_level, nullptr);
  1505. return ConversionResultCode::Success;
  1506. };
  1507. const auto process_and_compress = [&](CompressThreadState* state, CompressParameters parameters) {
  1508. const DataEntry& data_entry = *parameters.data_entry;
  1509. const FileSystem* file_system = data_entry.is_partition ?
  1510. partition_file_systems[data_entry.index] :
  1511. non_partition_file_system;
  1512. const bool compression = compression_type != WIARVZCompressionType::None;
  1513. return ProcessAndCompress(state, std::move(parameters), partition_entries, data_entries,
  1514. file_system, &reusable_groups, &reusable_groups_mutex,
  1515. chunks_per_wii_group, exception_lists_per_chunk,
  1516. compressed_exception_lists, compression);
  1517. };
  1518. const auto output = [&](OutputParameters parameters) {
  1519. const ConversionResultCode result =
  1520. Output(&parameters.entries, outfile, &reusable_groups, &reusable_groups_mutex,
  1521. &group_entries[parameters.group_index], &bytes_written);
  1522. if (result != ConversionResultCode::Success)
  1523. return result;
  1524. return RunCallback(parameters.group_index + parameters.entries.size(), parameters.bytes_read,
  1525. bytes_written, total_groups, iso_size, callback);
  1526. };
  1527. MultithreadedCompressor<CompressThreadState, CompressParameters, OutputParameters> mt_compressor(
  1528. set_up_compress_thread_state, process_and_compress, output);
  1529. for (const DataEntry& data_entry : data_entries)
  1530. {
  1531. u32 first_group;
  1532. u32 last_group;
  1533. u64 data_offset;
  1534. u64 data_size;
  1535. u64 data_offset_in_partition;
  1536. if (data_entry.is_partition)
  1537. {
  1538. const PartitionEntry& partition_entry = partition_entries[data_entry.index];
  1539. const PartitionDataEntry& partition_data_entry =
  1540. partition_entry.data_entries[data_entry.partition_data_index];
  1541. first_group = Common::swap32(partition_data_entry.group_index);
  1542. last_group = first_group + Common::swap32(partition_data_entry.number_of_groups);
  1543. const u32 first_sector = Common::swap32(partition_data_entry.first_sector);
  1544. data_offset = first_sector * VolumeWii::BLOCK_TOTAL_SIZE;
  1545. data_size =
  1546. Common::swap32(partition_data_entry.number_of_sectors) * VolumeWii::BLOCK_TOTAL_SIZE;
  1547. const u32 block_in_partition =
  1548. first_sector - Common::swap32(partition_entry.data_entries[0].first_sector);
  1549. data_offset_in_partition = block_in_partition * VolumeWii::BLOCK_DATA_SIZE;
  1550. }
  1551. else
  1552. {
  1553. const RawDataEntry& raw_data_entry = raw_data_entries[data_entry.index];
  1554. first_group = Common::swap32(raw_data_entry.group_index);
  1555. last_group = first_group + Common::swap32(raw_data_entry.number_of_groups);
  1556. data_offset = Common::swap64(raw_data_entry.data_offset);
  1557. data_size = Common::swap64(raw_data_entry.data_size);
  1558. const u64 skipped_data = data_offset % VolumeWii::BLOCK_TOTAL_SIZE;
  1559. data_offset -= skipped_data;
  1560. data_size += skipped_data;
  1561. data_offset_in_partition = data_offset;
  1562. }
  1563. ASSERT(groups_processed == first_group);
  1564. ASSERT(bytes_read == data_offset);
  1565. while (groups_processed < last_group)
  1566. {
  1567. const ConversionResultCode status = mt_compressor.GetStatus();
  1568. if (status != ConversionResultCode::Success)
  1569. return status;
  1570. u64 bytes_to_read = chunk_size;
  1571. if (data_entry.is_partition)
  1572. bytes_to_read = std::max<u64>(bytes_to_read, VolumeWii::GROUP_TOTAL_SIZE);
  1573. bytes_to_read = std::min<u64>(bytes_to_read, data_offset + data_size - bytes_read);
  1574. buffer.resize(bytes_to_read);
  1575. if (!infile->Read(bytes_read, bytes_to_read, buffer.data()))
  1576. return ConversionResultCode::ReadFailed;
  1577. bytes_read += bytes_to_read;
  1578. mt_compressor.CompressAndWrite(CompressParameters{
  1579. buffer, &data_entry, data_offset_in_partition, bytes_read, groups_processed});
  1580. data_offset += bytes_to_read;
  1581. data_size -= bytes_to_read;
  1582. if (data_entry.is_partition)
  1583. {
  1584. data_offset_in_partition +=
  1585. bytes_to_read / VolumeWii::BLOCK_TOTAL_SIZE * VolumeWii::BLOCK_DATA_SIZE;
  1586. }
  1587. else
  1588. {
  1589. data_offset_in_partition += bytes_to_read;
  1590. }
  1591. groups_processed += Common::AlignUp(bytes_to_read, chunk_size) / chunk_size;
  1592. }
  1593. ASSERT(data_size == 0);
  1594. }
  1595. ASSERT(groups_processed == total_groups);
  1596. ASSERT(bytes_read == iso_size);
  1597. mt_compressor.Shutdown();
  1598. const ConversionResultCode status = mt_compressor.GetStatus();
  1599. if (status != ConversionResultCode::Success)
  1600. return status;
  1601. std::unique_ptr<Compressor> compressor;
  1602. SetUpCompressor(&compressor, compression_type, compression_level, &header_2);
  1603. const std::optional<std::vector<u8>> compressed_raw_data_entries = Compress(
  1604. compressor.get(), reinterpret_cast<u8*>(raw_data_entries.data()), raw_data_entries_size);
  1605. if (!compressed_raw_data_entries)
  1606. return ConversionResultCode::InternalError;
  1607. const std::optional<std::vector<u8>> compressed_group_entries =
  1608. Compress(compressor.get(), reinterpret_cast<u8*>(group_entries.data()), group_entries_size);
  1609. if (!compressed_group_entries)
  1610. return ConversionResultCode::InternalError;
  1611. bytes_written = sizeof(WIAHeader1) + sizeof(WIAHeader2);
  1612. if (!outfile->Seek(sizeof(WIAHeader1) + sizeof(WIAHeader2), File::SeekOrigin::Begin))
  1613. return ConversionResultCode::WriteFailed;
  1614. u64 partition_entries_offset;
  1615. if (!WriteHeader(outfile, reinterpret_cast<u8*>(partition_entries.data()), partition_entries_size,
  1616. headers_size_upper_bound, &bytes_written, &partition_entries_offset))
  1617. {
  1618. return ConversionResultCode::WriteFailed;
  1619. }
  1620. u64 raw_data_entries_offset;
  1621. if (!WriteHeader(outfile, compressed_raw_data_entries->data(),
  1622. compressed_raw_data_entries->size(), headers_size_upper_bound, &bytes_written,
  1623. &raw_data_entries_offset))
  1624. {
  1625. return ConversionResultCode::WriteFailed;
  1626. }
  1627. u64 group_entries_offset;
  1628. if (!WriteHeader(outfile, compressed_group_entries->data(), compressed_group_entries->size(),
  1629. headers_size_upper_bound, &bytes_written, &group_entries_offset))
  1630. {
  1631. return ConversionResultCode::WriteFailed;
  1632. }
  1633. u32 disc_type = 0;
  1634. if (infile_volume)
  1635. {
  1636. if (infile_volume->GetVolumeType() == Platform::GameCubeDisc)
  1637. disc_type = 1;
  1638. else if (infile_volume->GetVolumeType() == Platform::WiiDisc)
  1639. disc_type = 2;
  1640. }
  1641. header_2.disc_type = Common::swap32(disc_type);
  1642. header_2.compression_type = Common::swap32(static_cast<u32>(compression_type));
  1643. header_2.compression_level =
  1644. static_cast<s32>(Common::swap32(static_cast<u32>(compression_level)));
  1645. header_2.chunk_size = Common::swap32(static_cast<u32>(chunk_size));
  1646. header_2.number_of_partition_entries = Common::swap32(static_cast<u32>(partition_entries.size()));
  1647. header_2.partition_entry_size = Common::swap32(sizeof(PartitionEntry));
  1648. header_2.partition_entries_offset = Common::swap64(partition_entries_offset);
  1649. header_2.partition_entries_hash = Common::SHA1::CalculateDigest(partition_entries);
  1650. header_2.number_of_raw_data_entries = Common::swap32(static_cast<u32>(raw_data_entries.size()));
  1651. header_2.raw_data_entries_offset = Common::swap64(raw_data_entries_offset);
  1652. header_2.raw_data_entries_size =
  1653. Common::swap32(static_cast<u32>(compressed_raw_data_entries->size()));
  1654. header_2.number_of_group_entries = Common::swap32(static_cast<u32>(group_entries.size()));
  1655. header_2.group_entries_offset = Common::swap64(group_entries_offset);
  1656. header_2.group_entries_size = Common::swap32(static_cast<u32>(compressed_group_entries->size()));
  1657. header_1.magic = RVZ ? RVZ_MAGIC : WIA_MAGIC;
  1658. header_1.version = Common::swap32(RVZ ? RVZ_VERSION : WIA_VERSION);
  1659. header_1.version_compatible =
  1660. Common::swap32(RVZ ? RVZ_VERSION_WRITE_COMPATIBLE : WIA_VERSION_WRITE_COMPATIBLE);
  1661. header_1.header_2_size = Common::swap32(sizeof(WIAHeader2));
  1662. header_1.header_2_hash =
  1663. Common::SHA1::CalculateDigest(reinterpret_cast<const u8*>(&header_2), sizeof(header_2));
  1664. header_1.iso_file_size = Common::swap64(infile->GetDataSize());
  1665. header_1.wia_file_size = Common::swap64(outfile->GetSize());
  1666. header_1.header_1_hash = Common::SHA1::CalculateDigest(reinterpret_cast<const u8*>(&header_1),
  1667. offsetof(WIAHeader1, header_1_hash));
  1668. if (!outfile->Seek(0, File::SeekOrigin::Begin))
  1669. return ConversionResultCode::WriteFailed;
  1670. if (!outfile->WriteArray(&header_1, 1))
  1671. return ConversionResultCode::WriteFailed;
  1672. if (!outfile->WriteArray(&header_2, 1))
  1673. return ConversionResultCode::WriteFailed;
  1674. return ConversionResultCode::Success;
  1675. }
  1676. bool ConvertToWIAOrRVZ(BlobReader* infile, const std::string& infile_path,
  1677. const std::string& outfile_path, bool rvz,
  1678. WIARVZCompressionType compression_type, int compression_level,
  1679. int chunk_size, const CompressCB& callback)
  1680. {
  1681. File::IOFile outfile(outfile_path, "wb");
  1682. if (!outfile)
  1683. {
  1684. PanicAlertFmtT(
  1685. "Failed to open the output file \"{0}\".\n"
  1686. "Check that you have permissions to write the target folder and that the media can "
  1687. "be written.",
  1688. outfile_path);
  1689. return false;
  1690. }
  1691. std::unique_ptr<VolumeDisc> infile_volume = CreateDisc(infile_path);
  1692. const auto convert = rvz ? RVZFileReader::Convert : WIAFileReader::Convert;
  1693. const ConversionResultCode result =
  1694. convert(infile, infile_volume.get(), &outfile, compression_type, compression_level,
  1695. chunk_size, callback);
  1696. if (result == ConversionResultCode::ReadFailed)
  1697. PanicAlertFmtT("Failed to read from the input file \"{0}\".", infile_path);
  1698. if (result == ConversionResultCode::WriteFailed)
  1699. {
  1700. PanicAlertFmtT("Failed to write the output file \"{0}\".\n"
  1701. "Check that you have enough space available on the target drive.",
  1702. outfile_path);
  1703. }
  1704. if (result != ConversionResultCode::Success)
  1705. {
  1706. // Remove the incomplete output file
  1707. outfile.Close();
  1708. File::Delete(outfile_path);
  1709. }
  1710. return result == ConversionResultCode::Success;
  1711. }
  1712. template class WIARVZFileReader<false>;
  1713. template class WIARVZFileReader<true>;
  1714. } // namespace DiscIO