| 1 | // Copyright 2008 Dolphin Emulator Project |
| 2 | // SPDX-License-Identifier: GPL-2.0-or-later |
| 3 | |
| 4 | #include "DiscIO/CompressedBlob.h" |
| 5 | |
| 6 | #include <algorithm> |
| 7 | #include <cstring> |
| 8 | #include <expected> |
| 9 | #include <memory> |
| 10 | #include <string> |
| 11 | #include <utility> |
| 12 | #include <vector> |
| 13 | |
| 14 | #include <zlib.h> |
| 15 | |
| 16 | #ifdef _WIN32 |
| 17 | #include <windows.h> |
| 18 | #include <io.h> |
| 19 | #endif |
| 20 | |
| 21 | #include "Common/Assert.h" |
| 22 | #include "Common/BitUtils.h" |
| 23 | #include "Common/CommonTypes.h" |
| 24 | #include "Common/FileUtil.h" |
| 25 | #include "Common/Hash.h" |
| 26 | #include "Common/Logging/Log.h" |
| 27 | #include "Common/MsgHandler.h" |
| 28 | #include "DiscIO/Blob.h" |
| 29 | #include "DiscIO/MultithreadedCompressor.h" |
| 30 | #include "DiscIO/Volume.h" |
| 31 | |
| 32 | namespace DiscIO |
| 33 | { |
| 34 | static constexpr u64 uncompressed_flag = 1ULL << 63; |
| 35 | |
| 36 | bool IsGCZBlob(File::DirectIOFile& file); |
| 37 | |
| 38 | CompressedBlobReader::CompressedBlobReader(File::DirectIOFile file, std::string filename) |
| 39 | : m_file(std::move(file)), m_file_name(std::move(filename)) |
| 40 | { |
| 41 | m_valid = Initialize(); |
| 42 | } |
| 43 | |
| 44 | bool CompressedBlobReader::Initialize() |
| 45 | { |
| 46 | m_file_size = m_file.GetSize(); |
| 47 | m_file.Seek(0, File::SeekOrigin::Begin); |
| 48 | if (!m_file.Read(Common::AsWritableU8Span(m_header))) |
| 49 | return false; |
| 50 | |
| 51 | if (m_header.magic_cookie != GCZ_MAGIC) |
| 52 | return false; |
| 53 | |
| 54 | size_t block_pointers_size = m_header.num_blocks * sizeof(u64); |
| 55 | size_t hashes_size = m_header.num_blocks * sizeof(u32); |
| 56 | |
| 57 | size_t header_size = sizeof(CompressedBlobHeader) + block_pointers_size + hashes_size; |
| 58 | |
| 59 | // Basic sanity check for size before we start allocating |
| 60 | if (header_size > m_file_size) |
| 61 | { |
| 62 | ERROR_LOG_FMT(DISCIO, "Headers' size is larger than file size"); |
| 63 | return false; |
| 64 | } |
| 65 | |
| 66 | if ((header_size + m_header.compressed_data_size) > m_file_size) |
| 67 | { |
| 68 | ERROR_LOG_FMT(DISCIO, "Data size is larger than file size."); |
| 69 | return false; |
| 70 | } |
| 71 | |
| 72 | if (m_header.num_blocks == 0) |
| 73 | { |
| 74 | ERROR_LOG_FMT(DISCIO, "GCZ file has zero blocks"); |
| 75 | return false; |
| 76 | } |
| 77 | |
| 78 | // cache block pointers and hashes |
| 79 | m_block_pointers.resize(m_header.num_blocks); |
| 80 | if (!m_file.Read(Common::AsWritableU8Span(m_block_pointers))) |
| 81 | return false; |
| 82 | |
| 83 | m_hashes.resize(m_header.num_blocks); |
| 84 | if (!m_file.Read(Common::AsWritableU8Span(m_hashes))) |
| 85 | return false; |
| 86 | |
| 87 | m_data_offset = header_size; |
| 88 | |
| 89 | // A compressed block is never ever longer than a decompressed block, so just header.block_size |
| 90 | // should be fine. |
| 91 | // I still add some safety margin. |
| 92 | const u32 zlib_buffer_size = m_header.block_size + 64; |
| 93 | m_zlib_buffer.resize(zlib_buffer_size); |
| 94 | |
| 95 | SetSectorSize(m_header.block_size); |
| 96 | |
| 97 | return ValidateBlockPointers(); |
| 98 | } |
| 99 | |
| 100 | std::unique_ptr<CompressedBlobReader> CompressedBlobReader::Create(File::DirectIOFile file, |
| 101 | const std::string& filename) |
| 102 | { |
| 103 | if (IsGCZBlob(file)) |
| 104 | { |
| 105 | std::unique_ptr<CompressedBlobReader> reader( |
| 106 | new CompressedBlobReader(std::move(file), filename)); |
| 107 | |
| 108 | if (reader->m_valid) |
| 109 | return reader; |
| 110 | } |
| 111 | |
| 112 | return nullptr; |
| 113 | } |
| 114 | |
| 115 | CompressedBlobReader::~CompressedBlobReader() = default; |
| 116 | |
| 117 | std::unique_ptr<BlobReader> CompressedBlobReader::CopyReader() const |
| 118 | { |
| 119 | return Create(m_file, m_file_name); |
| 120 | } |
| 121 | |
| 122 | // IMPORTANT: Calling this function invalidates all earlier pointers gotten from this function. |
| 123 | u64 CompressedBlobReader::GetBlockCompressedSize(u64 block_num) const |
| 124 | { |
| 125 | u64 start = m_block_pointers[block_num] & ~uncompressed_flag; |
| 126 | if (block_num < m_header.num_blocks - 1) |
| 127 | return (m_block_pointers[block_num + 1] & ~uncompressed_flag) - start; |
| 128 | else if (block_num == m_header.num_blocks - 1) |
| 129 | return m_header.compressed_data_size - start; |
| 130 | else |
| 131 | ERROR_LOG_FMT(DISCIO, "{} - illegal block number {}", __func__, block_num); |
| 132 | return 0; |
| 133 | } |
| 134 | |
| 135 | bool CompressedBlobReader::GetBlock(u64 block_num, u8* out_ptr) |
| 136 | { |
| 137 | if (block_num >= m_header.num_blocks) |
| 138 | return false; |
| 139 | |
| 140 | bool uncompressed = false; |
| 141 | u64 read_size = GetBlockCompressedSize(block_num); |
| 142 | u64 offset = m_block_pointers[block_num] + m_data_offset; |
| 143 | |
| 144 | if (offset & uncompressed_flag) |
| 145 | { |
| 146 | if (read_size != m_header.block_size) |
| 147 | { |
| 148 | ERROR_LOG_FMT(DISCIO, "Uncompressed block with wrong size"); |
| 149 | return false; |
| 150 | } |
| 151 | uncompressed = true; |
| 152 | offset &= ~uncompressed_flag; |
| 153 | } |
| 154 | else |
| 155 | { |
| 156 | if (read_size > m_zlib_buffer.size()) |
| 157 | { |
| 158 | ERROR_LOG_FMT(DISCIO, "Compressed block is too large"); |
| 159 | return false; |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | if (!m_file.OffsetRead(offset, m_zlib_buffer.data(), read_size)) |
| 164 | { |
| 165 | ERROR_LOG_FMT(DISCIO, "The disc image \"{}\" is truncated, some of the data is missing.", |
| 166 | m_file_name); |
| 167 | return false; |
| 168 | } |
| 169 | |
| 170 | // First, check hash. |
| 171 | const u32 block_hash = Common::HashAdler32(m_zlib_buffer.data(), read_size); |
| 172 | if (block_hash != m_hashes[block_num]) |
| 173 | { |
| 174 | ERROR_LOG_FMT(DISCIO, |
| 175 | "The disc image \"{}\" is corrupt.\n" |
| 176 | "Hash of block {} is {:08x} instead of {:08x}.", |
| 177 | m_file_name, block_num, block_hash, m_hashes[block_num]); |
| 178 | } |
| 179 | |
| 180 | if (uncompressed) |
| 181 | { |
| 182 | std::copy_n(m_zlib_buffer.begin(), m_header.block_size, out_ptr); |
| 183 | } |
| 184 | else |
| 185 | { |
| 186 | z_stream z = {}; |
| 187 | z.next_in = m_zlib_buffer.data(); |
| 188 | z.avail_in = read_size; |
| 189 | if (z.avail_in > m_header.block_size) |
| 190 | { |
| 191 | ERROR_LOG_FMT(DISCIO, "Compressed block size is larger than uncompressed block size"); |
| 192 | } |
| 193 | z.next_out = out_ptr; |
| 194 | z.avail_out = m_header.block_size; |
| 195 | inflateInit(&z); |
| 196 | int status = inflate(&z, Z_FULL_FLUSH); |
| 197 | u32 uncomp_size = m_header.block_size - z.avail_out; |
| 198 | if (status != Z_STREAM_END) |
| 199 | { |
| 200 | // this seem to fire wrongly from time to time |
| 201 | // to be sure, don't use compressed isos :P |
| 202 | ERROR_LOG_FMT(DISCIO, "Failure reading block {} - out of data and not at end.", block_num); |
| 203 | } |
| 204 | inflateEnd(&z); |
| 205 | if (uncomp_size != m_header.block_size) |
| 206 | { |
| 207 | ERROR_LOG_FMT(DISCIO, "Wrong block size"); |
| 208 | return false; |
| 209 | } |
| 210 | } |
| 211 | return true; |
| 212 | } |
| 213 | |
| 214 | bool CompressedBlobReader::ValidateBlockPointers() const |
| 215 | { |
| 216 | size_t valid_pointers = 0; |
| 217 | |
| 218 | // Validate block pointers |
| 219 | for (u32 i = 0; i < m_header.num_blocks; ++i) |
| 220 | { |
| 221 | u64 next; |
| 222 | if (i + 1 < m_header.num_blocks) |
| 223 | next = m_block_pointers[i + 1] & ~uncompressed_flag; |
| 224 | else |
| 225 | next = m_header.compressed_data_size; |
| 226 | |
| 227 | if (next > m_header.compressed_data_size) |
| 228 | continue; |
| 229 | |
| 230 | u64 offset = m_block_pointers[i] & ~uncompressed_flag; |
| 231 | if (offset > m_header.compressed_data_size) |
| 232 | continue; |
| 233 | |
| 234 | bool uncompressed = m_block_pointers[i] & uncompressed_flag; |
| 235 | u64 size = next - offset; |
| 236 | |
| 237 | if (uncompressed && size != m_header.block_size) |
| 238 | continue; |
| 239 | |
| 240 | if (!uncompressed && size > m_zlib_buffer.size()) |
| 241 | continue; |
| 242 | |
| 243 | valid_pointers++; |
| 244 | } |
| 245 | |
| 246 | size_t invalid_pointers = m_header.num_blocks - valid_pointers; |
| 247 | |
| 248 | if (invalid_pointers > 0) |
| 249 | ERROR_LOG_FMT(DISCIO, "GCZ file has {} invalid block pointers", invalid_pointers); |
| 250 | |
| 251 | return invalid_pointers == 0; |
| 252 | } |
| 253 | |
| 254 | struct CompressThreadState |
| 255 | { |
| 256 | CompressThreadState() : z{} {} |
| 257 | ~CompressThreadState() { deflateEnd(&z); } |
| 258 | |
| 259 | // z_stream will stop working if it changes address, so this object must not be moved |
| 260 | CompressThreadState(const CompressThreadState&) = delete; |
| 261 | CompressThreadState(CompressThreadState&&) = delete; |
| 262 | CompressThreadState& operator=(const CompressThreadState&) = delete; |
| 263 | CompressThreadState& operator=(CompressThreadState&&) = delete; |
| 264 | |
| 265 | std::vector<u8> compressed_buffer; |
| 266 | z_stream z; |
| 267 | }; |
| 268 | |
| 269 | struct CompressParameters |
| 270 | { |
| 271 | std::vector<u8> data{}; |
| 272 | u32 block_number = 0; |
| 273 | u64 inpos = 0; |
| 274 | }; |
| 275 | |
| 276 | struct OutputParameters |
| 277 | { |
| 278 | std::vector<u8> data{}; |
| 279 | u32 block_number = 0; |
| 280 | bool compressed = false; |
| 281 | u64 inpos = 0; |
| 282 | }; |
| 283 | |
| 284 | static ConversionResultCode SetUpCompressThreadState(CompressThreadState* state) |
| 285 | { |
| 286 | return deflateInit(&state->z, 9) == Z_OK ? ConversionResultCode::Success : |
| 287 | ConversionResultCode::InternalError; |
| 288 | } |
| 289 | |
| 290 | static ConversionResult<OutputParameters> Compress(CompressThreadState* state, |
| 291 | CompressParameters parameters, int block_size, |
| 292 | std::vector<u32>* hashes, int* num_stored, |
| 293 | int* num_compressed) |
| 294 | { |
| 295 | state->compressed_buffer.resize(block_size); |
| 296 | |
| 297 | int retval = deflateReset(&state->z); |
| 298 | state->z.next_in = parameters.data.data(); |
| 299 | state->z.avail_in = block_size; |
| 300 | state->z.next_out = state->compressed_buffer.data(); |
| 301 | state->z.avail_out = block_size; |
| 302 | |
| 303 | if (retval != Z_OK) |
| 304 | { |
| 305 | ERROR_LOG_FMT(DISCIO, "Deflate failed"); |
| 306 | return std::unexpected{ConversionResultCode::InternalError}; |
| 307 | } |
| 308 | |
| 309 | const int status = deflate(&state->z, Z_FINISH); |
| 310 | |
| 311 | state->compressed_buffer.resize(block_size - state->z.avail_out); |
| 312 | |
| 313 | OutputParameters output_parameters; |
| 314 | if ((status != Z_STREAM_END) || (state->z.avail_out < 10)) |
| 315 | { |
| 316 | // let's store uncompressed |
| 317 | ++*num_stored; |
| 318 | output_parameters = OutputParameters{std::move(parameters.data), parameters.block_number, false, |
| 319 | parameters.inpos}; |
| 320 | } |
| 321 | else |
| 322 | { |
| 323 | // let's store compressed |
| 324 | ++*num_compressed; |
| 325 | output_parameters = OutputParameters{std::move(state->compressed_buffer), |
| 326 | parameters.block_number, true, parameters.inpos}; |
| 327 | } |
| 328 | |
| 329 | (*hashes)[parameters.block_number] = |
| 330 | Common::HashAdler32(output_parameters.data.data(), output_parameters.data.size()); |
| 331 | |
| 332 | return std::move(output_parameters); |
| 333 | } |
| 334 | |
| 335 | static ConversionResultCode Output(OutputParameters parameters, File::DirectIOFile* outfile, |
| 336 | u64* position, std::vector<u64>* offsets, int progress_monitor, |
| 337 | u32 num_blocks, const CompressCB& callback) |
| 338 | { |
| 339 | u64 offset = *position; |
| 340 | if (!parameters.compressed) |
| 341 | offset |= uncompressed_flag; |
| 342 | (*offsets)[parameters.block_number] = offset; |
| 343 | |
| 344 | *position += parameters.data.size(); |
| 345 | |
| 346 | if (!outfile->Write(parameters.data)) |
| 347 | return ConversionResultCode::WriteFailed; |
| 348 | |
| 349 | if (parameters.block_number % progress_monitor == 0) |
| 350 | { |
| 351 | const int ratio = |
| 352 | parameters.inpos == 0 ? 0 : static_cast<int>(100 * *position / parameters.inpos); |
| 353 | |
| 354 | const std::string text = Common::FmtFormatT("{0} of {1} blocks. Compression ratio {2}%", |
| 355 | parameters.block_number, num_blocks, ratio); |
| 356 | |
| 357 | const float completion = static_cast<float>(parameters.block_number) / num_blocks; |
| 358 | |
| 359 | if (!callback(text, completion)) |
| 360 | return ConversionResultCode::Canceled; |
| 361 | } |
| 362 | |
| 363 | return ConversionResultCode::Success; |
| 364 | } |
| 365 | |
| 366 | bool ConvertToGCZ(BlobReader* infile, const std::string& infile_path, |
| 367 | const std::string& outfile_path, u32 sub_type, int block_size, |
| 368 | const CompressCB& callback) |
| 369 | { |
| 370 | ASSERT(infile->GetDataSizeType() == DataSizeType::Accurate); |
| 371 | |
| 372 | File::DirectIOFile outfile(outfile_path, File::AccessMode::Write); |
| 373 | if (!outfile.IsOpen()) |
| 374 | { |
| 375 | PanicAlertFmtT( |
| 376 | "Failed to open the output file \"{0}\".\n" |
| 377 | "Check that you have permissions to write the target folder and that the media can " |
| 378 | "be written.", |
| 379 | outfile_path); |
| 380 | return false; |
| 381 | } |
| 382 | |
| 383 | callback(Common::GetStringT("Files opened, ready to compress."), 0); |
| 384 | |
| 385 | CompressedBlobHeader header; |
| 386 | header.magic_cookie = GCZ_MAGIC; |
| 387 | header.sub_type = sub_type; |
| 388 | header.block_size = block_size; |
| 389 | header.disc_size = infile->GetDataSize(); |
| 390 | |
| 391 | // round upwards! |
| 392 | header.num_blocks = (u32)((header.disc_size + (block_size - 1)) / block_size); |
| 393 | |
| 394 | std::vector<u64> offsets(header.num_blocks); |
| 395 | std::vector<u32> hashes(header.num_blocks); |
| 396 | |
| 397 | // seek past the header (we will write it at the end) |
| 398 | outfile.Seek(sizeof(CompressedBlobHeader), File::SeekOrigin::Current); |
| 399 | // seek past the offset and hash tables (we will write them at the end) |
| 400 | outfile.Seek((sizeof(u64) + sizeof(u32)) * header.num_blocks, File::SeekOrigin::Current); |
| 401 | |
| 402 | // Now we are ready to write compressed data! |
| 403 | u64 inpos = 0; |
| 404 | u64 position = 0; |
| 405 | int num_compressed = 0; |
| 406 | int num_stored = 0; |
| 407 | int progress_monitor = std::max<int>(1, header.num_blocks / 1000); |
| 408 | |
| 409 | const auto compress = [&](CompressThreadState* state, CompressParameters parameters) { |
| 410 | return Compress(state, std::move(parameters), block_size, &hashes, &num_stored, |
| 411 | &num_compressed); |
| 412 | }; |
| 413 | |
| 414 | const auto output = [&](OutputParameters parameters) { |
| 415 | return Output(std::move(parameters), &outfile, &position, &offsets, progress_monitor, |
| 416 | header.num_blocks, callback); |
| 417 | }; |
| 418 | |
| 419 | MultithreadedCompressor<CompressThreadState, CompressParameters, OutputParameters> compressor( |
| 420 | SetUpCompressThreadState, compress, output); |
| 421 | |
| 422 | std::vector<u8> in_buf(block_size); |
| 423 | for (u32 i = 0; i < header.num_blocks; i++) |
| 424 | { |
| 425 | if (compressor.GetStatus() != ConversionResultCode::Success) |
| 426 | break; |
| 427 | |
| 428 | const u64 bytes_to_read = std::min<u64>(block_size, header.disc_size - inpos); |
| 429 | |
| 430 | if (!infile->Read(inpos, bytes_to_read, in_buf.data())) |
| 431 | { |
| 432 | compressor.SetError(ConversionResultCode::ReadFailed); |
| 433 | break; |
| 434 | } |
| 435 | |
| 436 | std::fill(in_buf.begin() + bytes_to_read, in_buf.begin() + header.block_size, 0); |
| 437 | |
| 438 | inpos += block_size; |
| 439 | |
| 440 | compressor.CompressAndWrite(CompressParameters{in_buf, i, inpos}); |
| 441 | } |
| 442 | |
| 443 | compressor.Shutdown(); |
| 444 | |
| 445 | header.compressed_data_size = position; |
| 446 | |
| 447 | const ConversionResultCode result = compressor.GetStatus(); |
| 448 | |
| 449 | if (result != ConversionResultCode::Success) |
| 450 | { |
| 451 | // Remove the incomplete output file. |
| 452 | outfile.Close(); |
| 453 | File::Delete(outfile_path); |
| 454 | } |
| 455 | else |
| 456 | { |
| 457 | // Okay, go back and fill in headers |
| 458 | outfile.Seek(0, File::SeekOrigin::Begin); |
| 459 | outfile.Write(Common::AsU8Span(header)); |
| 460 | outfile.Write(Common::AsU8Span(offsets)); |
| 461 | outfile.Write(Common::AsU8Span(hashes)); |
| 462 | |
| 463 | callback(Common::GetStringT("Done compressing disc image."), 1.0f); |
| 464 | } |
| 465 | |
| 466 | if (result == ConversionResultCode::ReadFailed) |
| 467 | PanicAlertFmtT("Failed to read from the input file \"{0}\".", infile_path); |
| 468 | |
| 469 | if (result == ConversionResultCode::WriteFailed) |
| 470 | { |
| 471 | PanicAlertFmtT("Failed to write the output file \"{0}\".\n" |
| 472 | "Check that you have enough space available on the target drive.", |
| 473 | outfile_path); |
| 474 | } |
| 475 | |
| 476 | return result == ConversionResultCode::Success; |
| 477 | } |
| 478 | |
| 479 | bool IsGCZBlob(File::DirectIOFile& file) |
| 480 | { |
| 481 | CompressedBlobHeader header; |
| 482 | return file.OffsetRead(0, Common::AsWritableU8Span(header)) && header.magic_cookie == GCZ_MAGIC; |
| 483 | } |
| 484 | |
| 485 | } // namespace DiscIO |