Play your Steam library's Windows games on a jailbroken PS5.
C++
Read LZX cabinets in Windows Installer packages
Leonardo Lobato48fd336e47aa
diff --git a/cmake/HomebrewUI.cmake b/cmake/HomebrewUI.cmakeindex 6820634..4ea8d5f 100644--- a/cmake/HomebrewUI.cmake+++ b/cmake/HomebrewUI.cmake@@ -70,6 +70,7 @@ add_library(playden_steam_cm_codec STATIC"${CMAKE_SOURCE_DIR}/src/runtime/game_settings.cpp""${CMAKE_SOURCE_DIR}/src/runtime/install_script.cpp""${CMAKE_SOURCE_DIR}/src/runtime/msi_package.cpp"+ "${CMAKE_SOURCE_DIR}/src/runtime/lzx_decoder.cpp""${CMAKE_SOURCE_DIR}/src/runtime/burn_bundle.cpp""${CMAKE_SOURCE_DIR}/src/runtime/redist_install.cpp""${CMAKE_SOURCE_DIR}/src/runtime/game_probe.cpp")diff --git a/src/runtime/lzx_decoder.cpp b/src/runtime/lzx_decoder.cppnew file mode 100644index 0000000..6710364--- /dev/null+++ b/src/runtime/lzx_decoder.cpp@@ -0,0 +1,367 @@+// SPDX-License-Identifier: GPL-3.0-or-later+#include "runtime/lzx_decoder.h"++#include <algorithm>+#include <cstring>++namespace playden::runtime {+namespace {++constexpr unsigned kLiterals = 256;+constexpr unsigned kLengthSymbols = 249;+constexpr unsigned kAlignedSymbols = 8;+constexpr unsigned kPretreeSymbols = 20;+constexpr unsigned kMinMatch = 2;+constexpr unsigned kMaxCodeBits = 16;+constexpr std::size_t kFrameSize = 32768;++enum BlockType : unsigned { kVerbatim = 1, kAligned = 2, kUncompressed = 3 };++// Position slots: extra bits and base offset (the formatted offset before the 2 is taken off).+struct Slots {+ std::uint8_t extra[51];+ std::uint32_t base[51];+ Slots() {+ for (unsigned slot = 0, bits = 0; slot < 51; slot += 2) {+ extra[slot] = static_cast<std::uint8_t>(bits);+ if (slot + 1 < 51) extra[slot + 1] = static_cast<std::uint8_t>(bits);+ if (slot != 0 && bits < 17) ++bits;+ }+ base[0] = 0;+ for (unsigned slot = 0; slot + 1 < 51; ++slot) base[slot + 1] = base[slot] + (1u << extra[slot]);+ }+};+const Slots kSlots;++std::uint32_t Get32(const unsigned char* bytes) {+ return static_cast<std::uint32_t>(bytes[0]) | static_cast<std::uint32_t>(bytes[1]) << 8 |+ static_cast<std::uint32_t>(bytes[2]) << 16 | static_cast<std::uint32_t>(bytes[3]) << 24;+}++void Put32(unsigned char* bytes, std::uint32_t value) {+ for (int index = 0; index < 4; ++index) bytes[index] = static_cast<unsigned char>(value >> (index * 8));+}++} // namespace++// A canonical Huffman code as a full 16-bit lookup: entry = symbol << 8 | code length, 0 when no+// code starts with those bits (an empty code). A code must fill the table or be empty.+struct LzxDecoder::Tree {+ std::vector<std::uint32_t> table;+ Tree() : table(1u << kMaxCodeBits, 0) {}+ bool Build(const std::uint8_t* lengths, std::size_t count) {+ std::fill(table.begin(), table.end(), 0);+ std::uint32_t code = 0;+ std::size_t filled = 0;+ for (unsigned length = 1; length <= kMaxCodeBits; ++length) {+ for (std::size_t symbol = 0; symbol < count; ++symbol) {+ if (lengths[symbol] != length) continue;+ const std::uint32_t span = 1u << (kMaxCodeBits - length);+ const std::uint32_t first = code << (kMaxCodeBits - length);+ if (first + span > table.size()) return false; // over-subscribed+ std::fill(table.begin() + first, table.begin() + first + span, static_cast<std::uint32_t>(symbol) << 8 | length);+ ++code;+ filled += span;+ }+ code <<= 1;+ }+ return filled == 0 || filled == table.size(); // incomplete otherwise+ }+};++LzxDecoder::LzxDecoder(unsigned window_bits, std::vector<std::string_view> blocks) : blocks_(std::move(blocks)) {+ for (const auto& block : blocks_) {+ starts_.push_back(input_size_);+ input_size_ += block.size();+ }+ static constexpr unsigned kSlotsForBits[] = {30, 32, 34, 36, 38, 42, 50}; // window bits 15 to 21+ if (window_bits < 15 || window_bits > 21) {+ error_ = "unsupported LZX window size";+ return;+ }+ window_size_ = std::size_t{1} << window_bits;+ main_symbols_ = kLiterals + kSlotsForBits[window_bits - 15] * 8;+ window_ = std::make_unique<std::uint8_t[]>(window_size_);+ main_lengths_.assign(main_symbols_, 0);+ length_lengths_.assign(kLengthSymbols, 0);+ aligned_lengths_.assign(kAlignedSymbols, 0);+ pretree_ = std::make_unique<Tree>();+ main_ = std::make_unique<Tree>();+ length_ = std::make_unique<Tree>();+ aligned_ = std::make_unique<Tree>();+}++LzxDecoder::~LzxDecoder() = default;++bool LzxDecoder::Failed(const char* why) {+ if (!error_) error_ = why;+ return false;+}++// The stream's byte at `at` (below input_size_).+unsigned char LzxDecoder::ByteAt(std::size_t at) {+ if (at < starts_[block_] || at >= starts_[block_] + blocks_[block_].size())+ block_ = static_cast<std::size_t>(std::upper_bound(starts_.begin(), starts_.end(), at) - starts_.begin()) - 1;+ while (blocks_[block_].empty()) ++block_; // an empty block shares its start with the next one+ return static_cast<unsigned char>(blocks_[block_][at - starts_[block_]]);+}++// Copies the next `count` bytes of the stream, false when it ends first.+bool LzxDecoder::CopyInput(std::size_t count, unsigned char* out) {+ if (count > input_size_ - std::min(input_at_, input_size_)) return false;+ while (count > 0) {+ ByteAt(input_at_); // selects the block+ const auto offset = input_at_ - starts_[block_];+ const auto take = std::min(count, blocks_[block_].size() - offset);+ std::memcpy(out, blocks_[block_].data() + offset, take);+ out += take;+ input_at_ += take;+ count -= take;+ }+ return true;+}++// Keeps at least `count` bits (at most 32) in the buffer, a 16-bit word at a time.+void LzxDecoder::Ensure(unsigned count) {+ while (bits_ < count) {+ std::uint32_t word = 0;+ if (input_at_ + 2 <= input_size_) {+ word = ByteAt(input_at_) | static_cast<std::uint32_t>(ByteAt(input_at_ + 1)) << 8;+ input_at_ += 2;+ } else {+ padding_ += 2; // past the end: zeros a lookup may look at but no code may use (DecodeFrame)+ }+ bit_buffer_ |= static_cast<std::uint64_t>(word) << (48 - bits_);+ bits_ += 16;+ }+}++unsigned LzxDecoder::Bits(unsigned count) {+ if (count == 0) return 0;+ Ensure(count);+ const auto value = static_cast<unsigned>(bit_buffer_ >> (64 - count));+ bit_buffer_ <<= count;+ bits_ -= count;+ return value;+}++bool LzxDecoder::Symbol(const Tree& tree, unsigned* symbol) {+ Ensure(kMaxCodeBits);+ const auto entry = tree.table[static_cast<std::size_t>(bit_buffer_ >> (64 - kMaxCodeBits))];+ if (entry == 0) return Failed("damaged LZX data (no such code)");+ const unsigned length = entry & 0xff;+ bit_buffer_ <<= length;+ bits_ -= length;+ *symbol = entry >> 8;+ return true;+}++// Code lengths [first, last) as differences from the previous block's, through a pretree.+bool LzxDecoder::ReadLengths(Tree& pretree, std::vector<std::uint8_t>& lengths, std::size_t first, std::size_t last) {+ std::uint8_t pre[kPretreeSymbols];+ for (auto& length : pre) length = static_cast<std::uint8_t>(Bits(4));+ if (!pretree.Build(pre, kPretreeSymbols)) return Failed("damaged LZX data (pretree)");+ for (std::size_t at = first; at < last;) {+ unsigned code;+ if (!Symbol(pretree, &code)) return false;+ if (code == 17 || code == 18) {+ const std::size_t run = code == 17 ? Bits(4) + 4 : Bits(5) + 20;+ if (run > last - at) return Failed("damaged LZX data (lengths run past their tree)");+ std::fill(lengths.begin() + at, lengths.begin() + at + run, 0);+ at += run;+ } else if (code == 19) {+ const std::size_t run = Bits(1) + 4;+ if (run > last - at) return Failed("damaged LZX data (lengths run past their tree)");+ if (!Symbol(pretree, &code) || code > 16) return Failed("damaged LZX data (pretree)");+ const auto value = static_cast<std::uint8_t>((lengths[at] + 17 - code) % 17);+ std::fill(lengths.begin() + at, lengths.begin() + at + run, value);+ at += run;+ } else {+ lengths[at] = static_cast<std::uint8_t>((lengths[at] + 17 - code) % 17);+ ++at;+ }+ }+ return true;+}++bool LzxDecoder::ReadBlockHeader() {+ // An uncompressed block of odd length is followed by a byte that realigns the stream.+ if (block_type_ == kUncompressed && (block_length_ & 1)) {+ if (input_at_ >= input_size_) return Failed("damaged LZX data (input ends early)");+ ++input_at_;+ }+ block_type_ = Bits(3);+ const unsigned high = Bits(16), low = Bits(8);+ block_length_ = block_remaining_ = static_cast<std::size_t>(high) << 8 | low;+ switch (block_type_) {+ case kAligned:+ for (auto& length : aligned_lengths_) length = static_cast<std::uint8_t>(Bits(3));+ if (!aligned_->Build(aligned_lengths_.data(), kAlignedSymbols)) return Failed("damaged LZX data (aligned tree)");+ [[fallthrough]];+ case kVerbatim:+ if (!ReadLengths(*pretree_, main_lengths_, 0, kLiterals) ||+ !ReadLengths(*pretree_, main_lengths_, kLiterals, main_symbols_))+ return false;+ if (!main_->Build(main_lengths_.data(), main_symbols_)) return Failed("damaged LZX data (main tree)");+ if (!ReadLengths(*pretree_, length_lengths_, 0, kLengthSymbols)) return false;+ if (!length_->Build(length_lengths_.data(), kLengthSymbols)) return Failed("damaged LZX data (length tree)");+ return true;+ case kUncompressed: {+ // 1 to 16 bits of padding up to the next word, then the repeated offsets as bytes; words+ // already in the buffer go back to the input.+ if (bits_ == 0) Ensure(16);+ const unsigned drop = bits_ % 16 ? bits_ % 16 : 16;+ bit_buffer_ <<= drop;+ bits_ -= drop;+ input_at_ -= bits_ / 8;+ bit_buffer_ = 0;+ bits_ = 0;+ unsigned char stored[12];+ if (!CopyInput(sizeof(stored), stored)) return Failed("damaged LZX data (input ends early)");+ for (int index = 0; index < 3; ++index) repeated_[index] = Get32(stored + index * 4);+ return true;+ }+ default:+ return Failed("damaged LZX data (block type)");+ }+}++// Decodes up to *todo bytes of the current block into the window.+bool LzxDecoder::DecodeRun(std::size_t* todo) {+ std::size_t run = std::min(*todo, block_remaining_);+ if (block_type_ == kUncompressed) {+ if (!CopyInput(run, window_.get() + window_position_)) return Failed("damaged LZX data (input ends early)");+ window_position_ += run;+ decoded_ += run;+ block_remaining_ -= run;+ *todo -= run;+ return true;+ }+ std::size_t done = 0;+ while (done < run) {+ unsigned element;+ if (!Symbol(*main_, &element)) return false;+ if (element < kLiterals) {+ window_[window_position_++] = static_cast<std::uint8_t>(element);+ ++done;+ ++decoded_;+ continue;+ }+ element -= kLiterals;+ std::size_t length = element & 7;+ if (length == 7) {+ unsigned extra;+ if (!Symbol(*length_, &extra)) return false;+ length += extra;+ }+ length += kMinMatch;+ const unsigned slot = element >> 3;+ std::uint32_t offset;+ if (slot > 2) {+ const unsigned extra = kSlots.extra[slot];+ offset = kSlots.base[slot] - 2;+ if (block_type_ == kAligned && extra >= 3) {+ offset += Bits(extra - 3) << 3;+ unsigned aligned;+ if (!Symbol(*aligned_, &aligned)) return false;+ offset += aligned;+ } else {+ offset += Bits(extra);+ }+ repeated_[2] = repeated_[1];+ repeated_[1] = repeated_[0];+ repeated_[0] = offset;+ } else {+ offset = repeated_[slot];+ repeated_[slot] = repeated_[0];+ repeated_[0] = offset;+ }+ // A match stays inside its block, its frame and the window, and refers only to bytes decoded before.+ if (done + length > run) return Failed("damaged LZX data (match past its block or frame)");+ if (window_position_ + length > window_size_) return Failed("damaged LZX data (match past the window)");+ if (offset == 0 || offset > decoded_ || offset > window_size_) return Failed("damaged LZX data (match before the start)");+ std::size_t from = (window_position_ + window_size_ - offset) % window_size_;+ for (std::size_t index = 0; index < length; ++index) {+ window_[window_position_++] = window_[from];+ from = (from + 1) % window_size_;+ }+ done += length;+ decoded_ += length;+ }+ block_remaining_ -= done;+ *todo -= done;+ return true;+}++bool LzxDecoder::DecodeFrame(std::size_t size, unsigned char* out, std::string* reason) {+ const auto fail = [&]() {+ if (reason) *reason = error_ ? error_ : "damaged LZX data";+ return false;+ };+ if (error_) return fail();+ // Every frame but the last is a full one, so frames never straddle the window's end.+ if (size == 0 || size > kFrameSize || ended_) {+ Failed("damaged cabinet (LZX frame size)");+ return fail();+ }+ if (window_position_ == window_size_) window_position_ = 0;+ if (size > window_size_ - window_position_) {+ Failed("damaged cabinet (LZX frame size)");+ return fail();+ }+ ended_ = size < kFrameSize;+ const std::size_t frame_start = window_position_;+ if (!header_read_) {+ // The stream starts with the x86 translation flag and, when set, the file size it uses.+ std::uint32_t translation = 0;+ if (Bits(1)) {+ const unsigned high = Bits(16), low = Bits(16);+ translation = high << 16 | low;+ }+ translation_size_ = static_cast<std::int32_t>(translation);+ header_read_ = true;+ }+ for (std::size_t todo = size; todo > 0;) {+ if (block_remaining_ == 0 && !ReadBlockHeader()) return fail();+ const auto before = todo;+ if (!DecodeRun(&todo)) return fail();+ if (todo == before && block_remaining_ != 0) {+ Failed("damaged LZX data (no progress)");+ return fail();+ }+ }+ // Bits used, not just looked at, must all be real input.+ if ((input_at_ + padding_) * 8 - bits_ > input_size_ * 8) {+ Failed("damaged LZX data (input ends early)");+ return fail();+ }+ // Frames end on a 16-bit boundary of the input.+ if (bits_ % 16) {+ const unsigned drop = bits_ % 16;+ bit_buffer_ <<= drop;+ bits_ -= drop;+ }+ std::memcpy(out, window_.get() + frame_start, size);+ // Undo the encoder's E8 translation: absolute call targets back to relative ones, in the+ // first 1 GiB of output, for frames longer than 10 bytes.+ if (translation_size_ != 0 && size > 10 && output_ < (std::uint64_t{1} << 30)) {+ const auto position = static_cast<std::int64_t>(output_);+ for (std::size_t at = 0; at < size - 10;) {+ if (out[at] != 0xe8) {+ ++at;+ continue;+ }+ const auto current = position + static_cast<std::int64_t>(at);+ const auto absolute = static_cast<std::int32_t>(Get32(out + at + 1));+ if (absolute >= -current && absolute < translation_size_) {+ const std::int64_t relative = absolute >= 0 ? absolute - current : static_cast<std::int64_t>(absolute) + translation_size_;+ Put32(out + at + 1, static_cast<std::uint32_t>(relative));+ }+ at += 5;+ }+ }+ output_ += size;+ return true;+}++} // namespace playden::runtimediff --git a/src/runtime/lzx_decoder.h b/src/runtime/lzx_decoder.hnew file mode 100644index 0000000..e8c2f6b--- /dev/null+++ b/src/runtime/lzx_decoder.h@@ -0,0 +1,68 @@+// SPDX-License-Identifier: GPL-3.0-or-later+#pragma once++#include <cstddef>+#include <cstdint>+#include <memory>+#include <string>+#include <string_view>+#include <vector>++namespace playden::runtime {++// Microsoft's LZX compression as cabinets use it ([MS-CAB], the LZX folder type, and the LZX+// format it refers to): one decoder per folder, reading the folder's data blocks as one stream,+// in place (a cabinet can be tens of MiB, and the console's heap is small).+// Each data block decodes to one frame of up to 32 KiB that depends on the frames before it (the+// window, the repeated offsets and the Huffman code lengths carry over), and the encoder's x86+// call translation (E8) is undone on each frame.+class LzxDecoder {+ public:+ // window_bits: 15 to 21, from the folder's compression type ((type >> 8) & 0x1f). blocks: the+ // folder's data blocks' bytes, in order; they must outlive the decoder.+ LzxDecoder(unsigned window_bits, std::vector<std::string_view> blocks);+ ~LzxDecoder();+ LzxDecoder(const LzxDecoder&) = delete;+ LzxDecoder& operator=(const LzxDecoder&) = delete;++ // Decodes the next frame into exactly `size` bytes (1 to 32768; only the folder's last frame+ // may be shorter). false with a reason for damaged data; the decoder can't continue after that.+ bool DecodeFrame(std::size_t size, unsigned char* out, std::string* reason);++ private:+ struct Tree;+ bool ReadLengths(Tree& pretree, std::vector<std::uint8_t>& lengths, std::size_t first, std::size_t last);+ bool ReadBlockHeader();+ bool DecodeRun(std::size_t* todo);+ bool Symbol(const Tree& tree, unsigned* symbol);+ unsigned char ByteAt(std::size_t at);+ bool CopyInput(std::size_t count, unsigned char* out);+ void Ensure(unsigned count);+ unsigned Bits(unsigned count);+ bool Failed(const char* why);++ std::size_t window_size_ = 0;+ unsigned main_symbols_ = 0;+ std::unique_ptr<std::uint8_t[]> window_;+ std::size_t window_position_ = 0;+ std::uint64_t output_ = 0; // bytes of finished frames, for the E8 translation+ std::uint64_t decoded_ = 0; // bytes in the window so far, which a match may refer back to+ std::uint32_t repeated_[3] = {1, 1, 1};+ bool header_read_ = false;+ bool ended_ = false; // a short frame was decoded: it was the last+ std::int32_t translation_size_ = 0;+ unsigned block_type_ = 0;+ std::size_t block_length_ = 0, block_remaining_ = 0;+ // 16-bit little-endian words, read most significant bit first, across the blocks.+ std::vector<std::string_view> blocks_;+ std::vector<std::size_t> starts_; // each block's offset in the stream+ std::size_t input_size_ = 0, block_ = 0;+ std::size_t input_at_ = 0, padding_ = 0;+ std::uint64_t bit_buffer_ = 0;+ unsigned bits_ = 0;+ const char* error_ = nullptr;+ std::vector<std::uint8_t> main_lengths_, length_lengths_, aligned_lengths_;+ std::unique_ptr<Tree> pretree_, main_, length_, aligned_;+};++} // namespace playden::runtimediff --git a/src/runtime/msi_package.cpp b/src/runtime/msi_package.cppindex e7b7148..3eecf9c 100644--- a/src/runtime/msi_package.cpp+++ b/src/runtime/msi_package.cpp@@ -1,6 +1,7 @@#include "runtime/msi_package.h"#include "miniz.h"+#include "runtime/lzx_decoder.h"#include <algorithm>#include <cctype>@@ -56,6 +57,8 @@ class Compound {return nullptr;}bool Read(const CompoundEntry& entry, std::string* out) const;+ // The stream in place when its sectors follow one another, as a large stream's usually do.+ std::optional<std::string_view> View(const CompoundEntry& entry) const;private:bool Chain(const std::vector<std::uint32_t>& table, std::uint32_t start, std::uint64_t size, bool mini,@@ -118,6 +121,19 @@ bool Compound::Read(const CompoundEntry& entry, std::string* out) const {return Chain(entry.size < cutoff_ ? mini_fat_ : fat_, entry.start, entry.size, entry.size < cutoff_, out);}+std::optional<std::string_view> Compound::View(const CompoundEntry& entry) const {+ if (entry.size < cutoff_ || entry.size == 0 || entry.size > kMaxStreamBytes) return std::nullopt;+ const std::uint64_t sectors = (entry.size + sector_size_ - 1) / sector_size_;+ const std::uint64_t at = (static_cast<std::uint64_t>(entry.start) + 1) * sector_size_;+ if (at + entry.size > data_.size()) return std::nullopt;+ // Each sector is in the FAT, as Read requires, and each but the last links to the next.+ for (std::uint64_t index = 0; index < sectors; ++index) {+ const auto sector = entry.start + index;+ if (sector >= fat_.size() || (index + 1 < sectors && fat_[sector] != sector + 1)) return std::nullopt;+ }+ return data_.substr(static_cast<std::size_t>(at), static_cast<std::size_t>(entry.size));+}+bool Compound::Open(std::string_view data, std::string* reason) {const auto fail = [&](const char* why) {if (reason) *reason = why;@@ -960,6 +976,14 @@ bool ReadMsiPackage(std::string_view package, MsiInstallPlan* plan, std::string*return builder.Build(plan, reason);}+std::optional<std::string_view> ViewMsiStream(std::string_view package, const std::string& name) {+ Compound compound;+ std::string reason;+ if (!compound.Open(package, &reason)) return std::nullopt;+ const auto* entry = compound.Find(name);+ return entry ? compound.View(*entry) : std::nullopt;+}+std::optional<std::string> ReadMsiStream(std::string_view package, const std::string& name) {Compound compound;std::string reason, out;@@ -1032,7 +1056,7 @@ bool ExtractCabinet(std::string_view cabinet, const std::function<bool(const stdfor (std::size_t folder_index = 0; folder_index < folders.size(); ++folder_index) {const auto& folder = folders[folder_index];const auto kind = folder.compression & 0x0f;- if (kind != 0 && kind != 1) return fail(kind == 3 ? "LZX cabinets are not supported" : "Quantum cabinets are not supported");+ if (kind != 0 && kind != 1 && kind != 3) return fail("Quantum cabinets are not supported");std::vector<const Member*> wanted;for (const auto& member : members)if (member.folder == folder_index) wanted.push_back(&member);@@ -1078,7 +1102,31 @@ bool ExtractCabinet(std::string_view cabinet, const std::function<bool(const std}return true;};- for (std::size_t block = 0; block < folder.blocks; ++block) {+ if (kind == 3) {+ // LZX: the folder's blocks are one stream, read in place, each block one frame of it.+ std::vector<std::string_view> stream;+ std::vector<std::uint16_t> frames;+ for (std::size_t block = 0; block < folder.blocks; ++block) {+ if (block_at + 8 + data_reserve > cabinet.size()) return fail("damaged cabinet");+ const auto packed = U16(cabinet, block_at + 4);+ const auto unpacked = U16(cabinet, block_at + 6);+ const auto data_at = block_at + 8 + data_reserve;+ if (data_at + packed > cabinet.size() || unpacked > kWindow) return fail("damaged cabinet");+ stream.push_back(cabinet.substr(data_at, packed));+ frames.push_back(unpacked);+ block_at = data_at + packed;+ }+ LzxDecoder lzx((folder.compression >> 8) & 0x1f, std::move(stream));+ for (const auto unpacked : frames) {+ std::string why;+ if (!lzx.DecodeFrame(unpacked, buffer.get(), &why)) {+ if (reason) *reason = why;+ return false;+ }+ if (!deliver(buffer.get(), unpacked)) return fail("extraction stopped");+ }+ }+ for (std::size_t block = 0; kind != 3 && block < folder.blocks; ++block) {if (block_at + 8 + data_reserve > cabinet.size()) return fail("damaged cabinet");const auto packed = U16(cabinet, block_at + 4);const auto unpacked = U16(cabinet, block_at + 6);diff --git a/src/runtime/msi_package.h b/src/runtime/msi_package.hindex a0f2d9c..6a2a67f 100644--- a/src/runtime/msi_package.h+++ b/src/runtime/msi_package.h@@ -57,7 +57,11 @@ bool ReadMsiPackage(std::string_view package, MsiInstallPlan* plan, std::string*// One stream of the package by its decoded name ("media1.cab"); nullopt when missing.std::optional<std::string> ReadMsiStream(std::string_view package, const std::string& name);-// Extracts every file of a cabinet (MSZIP or stored folders; LZX and Quantum are refused),+// The same stream in place, without a copy, when its sectors follow one another in the package (a+// large cabinet's usually do); nullopt otherwise, and the caller reads it with ReadMsiStream.+std::optional<std::string_view> ViewMsiStream(std::string_view package, const std::string& name);++// Extracts every file of a cabinet (MSZIP, LZX or stored folders; Quantum is refused),// calling sink with each member's name and contents in cabinet order. Stops at the first sink// that returns false. Cabinets that continue into another one are refused.bool ExtractCabinet(std::string_view cabinet, const std::function<bool(const std::string&, std::string_view)>& sink,diff --git a/tests/msi_fixture.h b/tests/msi_fixture.hindex c071eda..116129c 100644--- a/tests/msi_fixture.h+++ b/tests/msi_fixture.h@@ -322,6 +322,140 @@ inline std::string StoredCabinet(const std::vector<std::pair<std::string, std::sreturn cabinet + files + data;}+// The members' CFFILE rows, all in folder 0, and their bytes in order.+inline void LzxMembers(const std::vector<std::pair<std::string, std::string>>& members, std::string* files,+ std::string* content) {+ for (const auto& [name, data] : members) {+ Put32(files, static_cast<std::uint32_t>(data.size()));+ Put32(files, static_cast<std::uint32_t>(content->size()));+ Put16(files, 0); // folder+ Put16(files, 0);+ Put16(files, 0);+ Put16(files, 0x20);+ *files += name;+ files->push_back('\0');+ *content += data;+ }+}++// LZX bits, most significant first, packed into 16-bit little-endian words.+struct LzxBits {+ std::vector<bool> bits;+ void Put(std::uint32_t value, unsigned count) {+ for (unsigned bit = count; bit-- > 0;) bits.push_back((value >> bit) & 1);+ }+ void Align() { Put(0, bits.size() % 16 ? 16 - bits.size() % 16 : 0); }+ std::string Words() const {+ std::string stream;+ for (std::size_t at = 0; at < bits.size(); at += 16) {+ unsigned word = 0;+ for (unsigned bit = 0; bit < 16; ++bit) word = word << 1 | (at + bit < bits.size() && bits[at + bit] ? 1 : 0);+ Put16(&stream, word);+ }+ return stream;+ }+};++// A cabinet with one LZX folder (64 KiB window) holding stream, its data blocks given as (packed, unpacked) sizes.+inline std::string LzxFolderCabinet(const std::string& files, std::size_t members, const std::string& stream,+ const std::vector<std::pair<std::size_t, std::size_t>>& blocks) {+ std::string data;+ std::size_t taken = 0;+ for (const auto& [packed, frame] : blocks) {+ Put32(&data, 0);+ Put16(&data, static_cast<unsigned>(packed));+ Put16(&data, static_cast<unsigned>(frame));+ data += stream.substr(taken, packed);+ taken += packed;+ }+ const std::uint32_t files_at = 36 + 8;+ const std::uint32_t data_at = files_at + static_cast<std::uint32_t>(files.size());+ std::string cabinet = "MSCF";+ Put32(&cabinet, 0);+ Put32(&cabinet, data_at + static_cast<std::uint32_t>(data.size()));+ Put32(&cabinet, 0);+ Put32(&cabinet, files_at);+ Put32(&cabinet, 0);+ cabinet.push_back(3);+ cabinet.push_back(1);+ Put16(&cabinet, 1); // folders+ Put16(&cabinet, static_cast<unsigned>(members));+ Put16(&cabinet, 0); // flags+ Put16(&cabinet, 0);+ Put16(&cabinet, 0);+ Put32(&cabinet, data_at);+ Put16(&cabinet, static_cast<unsigned>(blocks.size()));+ Put16(&cabinet, 3 | 16 << 8); // LZX, 2^16 window+ return cabinet + files + data;+}++// A cabinet with one LZX folder (64 KiB window) whose stream is a single uncompressed LZX block:+// the members' bytes follow the stream header, the block header, its padding and the repeated+// offsets, split into 32 KiB frames across data blocks. translation: the stream's x86 call+// translation size (0 for none); the bytes are stored as an encoder writes them. frames: other frame+// sizes, with the whole stream in the first data block.+inline std::string LzxCabinet(const std::vector<std::pair<std::string, std::string>>& members, std::uint32_t translation = 0,+ const std::vector<std::size_t>& frames = {}) {+ std::string files, content;+ LzxMembers(members, &files, &content);+ LzxBits bits;+ bits.Put(translation ? 1 : 0, 1);+ if (translation) {+ bits.Put(translation >> 16, 16);+ bits.Put(translation & 0xffff, 16);+ }+ bits.Put(3, 3); // uncompressed block+ bits.Put(static_cast<std::uint32_t>(content.size()) >> 8, 16);+ bits.Put(static_cast<std::uint32_t>(content.size()) & 0xff, 8);+ bits.Put(0, bits.bits.size() % 16 ? 16 - bits.bits.size() % 16 : 16); // 1 to 16 bits up to the next word+ std::string stream = bits.Words();+ for (int repeated = 0; repeated < 3; ++repeated) Put32(&stream, 1);+ const auto header = stream.size();+ stream += content;+ if (content.size() & 1) stream.push_back('\0');+ std::vector<std::pair<std::size_t, std::size_t>> blocks;+ if (!frames.empty()) {+ for (const auto frame : frames) blocks.emplace_back(blocks.empty() ? stream.size() : 0, frame);+ } else {+ for (std::size_t at = 0; at < content.size(); at += 32768) {+ const auto frame = std::min<std::size_t>(32768, content.size() - at);+ blocks.emplace_back((at == 0 ? header : 0) + frame + (at + frame == content.size() ? stream.size() - header - content.size() : 0),+ frame);+ }+ }+ return LzxFolderCabinet(files, members.size(), stream, blocks);+}++// A cabinet with one LZX folder whose stream is a single verbatim block of literals, in one frame: every byte value+// has an 8-bit code (the code is the byte), with no matches. cut: bytes taken off the stream's end (and its data+// block's packed size). missing_literal: a byte value left out of the main tree, which is then incomplete.+inline std::string LzxVerbatimCabinet(const std::string& name, const std::string& content, std::size_t cut = 0,+ int missing_literal = -1) {+ std::string files, all;+ LzxMembers({{name, content}}, &files, &all);+ LzxBits bits;+ bits.Put(0, 1); // no translation+ bits.Put(1, 3); // verbatim block+ bits.Put(static_cast<std::uint32_t>(content.size()) >> 8, 16);+ bits.Put(static_cast<std::uint32_t>(content.size()) & 0xff, 8);+ // Each tree's lengths go through a pretree whose codes are 0 (length unchanged from 0) and 1 (pretree symbol 9:+ // (0 - 8) mod 17, so length 8).+ const auto pretree = [&] {+ for (unsigned symbol = 0; symbol < 20; ++symbol) bits.Put(symbol == 0 || symbol == 9 ? 1 : 0, 4);+ };+ pretree();+ for (int literal = 0; literal < 256; ++literal) bits.Put(literal == missing_literal ? 0 : 1, 1);+ pretree();+ for (unsigned symbol = 256; symbol < 256 + 32 * 8; ++symbol) bits.Put(0, 1); // no matches+ pretree();+ for (unsigned symbol = 0; symbol < 249; ++symbol) bits.Put(0, 1); // an empty length tree+ for (const auto byte : content) bits.Put(static_cast<unsigned char>(byte), 8);+ bits.Align();+ auto stream = bits.Words();+ stream.resize(stream.size() - cut);+ return LzxFolderCabinet(files, 1, stream, {{stream.size(), content.size()}});+}+// A WiX Burn bundle: a small PE whose .wixburn section lists the UX container (file "0" is the manifest)// and one attached container. signed_form: the attached container follows an original signature, as in// Microsoft's bundles; otherwise it follows the UX container. with_section false: no .wixburn section.diff --git a/tests/runtime_redist_test.cpp b/tests/runtime_redist_test.cppindex ea7eeda..1e67450 100644--- a/tests/runtime_redist_test.cpp+++ b/tests/runtime_redist_test.cpp@@ -150,13 +150,64 @@ void TestCabinet() {CHECK(members["second"] == "0123456789"); // copied from the previous block's historyCHECK(members.count("empty") && members["empty"].empty());CHECK((order == std::vector<std::string>{"first", "second", "empty"}));- // LZX is refused by name; a sink that stops ends extraction.+ // LZX needs a window of 2^15 to 2^21 bytes, Quantum is refused by name; a sink that stops ends extraction.auto lzx = TwoBlockCabinet();lzx[36 + 6] = 3;CHECK(!ExtractCabinet(lzx, [](const std::string&, std::string_view) { return true; }, &reason));- CHECK(reason == "LZX cabinets are not supported");+ CHECK(reason == "unsupported LZX window size");+ auto quantum = TwoBlockCabinet();+ quantum[36 + 6] = 2;+ CHECK(!ExtractCabinet(quantum, [](const std::string&, std::string_view) { return true; }, &reason));+ CHECK(reason == "Quantum cabinets are not supported");CHECK(!ExtractCabinet(TwoBlockCabinet(), [](const std::string&, std::string_view) { return false; }, &reason));CHECK(!ExtractCabinet("MSCF", [](const std::string&, std::string_view) { return true; }, &reason));+ // LZX: an uncompressed block over two frames, an odd length, and the x86 call translation undone.+ std::string big(40001, '\0');+ for (std::size_t index = 0; index < big.size(); ++index) big[index] = static_cast<char>('a' + index % 23);+ members.clear();+ CHECK(ExtractCabinet(LzxCabinet({{"big", big}, {"small", "hello"}}), [&](const std::string& name, std::string_view data) {+ members[name] = std::string(data);+ return true;+ }, &reason));+ CHECK(members["big"] == big && members["small"] == "hello");+ // At output position 2 an encoder turned the call's relative target 98 into the absolute 100.+ std::string call = "ab\xe8";+ Put32(&call, 100);+ call += std::string(20, 'z');+ std::string expected = "ab\xe8";+ Put32(&expected, 98);+ expected += std::string(20, 'z');+ members.clear();+ CHECK(ExtractCabinet(LzxCabinet({{"call", call}}, 1000), [&](const std::string& name, std::string_view data) {+ members[name] = std::string(data);+ return true;+ }, &reason));+ CHECK(members["call"] == expected);+ // A stream cut short is damaged, not padded out.+ auto cut = LzxCabinet({{"big", big}});+ cut.resize(cut.size() - 2000);+ CHECK(!ExtractCabinet(cut, [](const std::string&, std::string_view) { return true; }, &reason));+ // Literals of a verbatim block decode. Ones that need bits past the stream's end don't, even when the data block+ // says the stream is that short, and nor does a main tree that leaves a code unused.+ const std::string text = "verbatim literals, eight bits each";+ members.clear();+ CHECK(ExtractCabinet(LzxVerbatimCabinet("text", text), [&](const std::string& name, std::string_view data) {+ members[name] = std::string(data);+ return true;+ }, &reason));+ CHECK(members["text"] == text);+ CHECK(!ExtractCabinet(LzxVerbatimCabinet("text", text, 2), [](const std::string&, std::string_view) { return true; }, &reason));+ CHECK(reason == "damaged LZX data (input ends early)");+ CHECK(!ExtractCabinet(LzxVerbatimCabinet("text", text, 0, 255), [](const std::string&, std::string_view) { return true; },+ &reason));+ CHECK(reason == "damaged LZX data (main tree)");+ // Only the last frame may be short: after a short one, a full frame would run past the window's end.+ const std::string frames(32769, 'q');+ CHECK(ExtractCabinet(LzxCabinet({{"frames", frames}}, 0, {32768, 1}), [](const std::string&, std::string_view) { return true; },+ &reason));+ CHECK(!ExtractCabinet(LzxCabinet({{"frames", frames}}, 0, {1, 32768}), [](const std::string&, std::string_view) { return true; },+ &reason));+ CHECK(reason == "damaged cabinet (LZX frame size)");// Members that overlap are refused: "second" moved to offset 5.auto overlapping = TwoBlockCabinet();const auto second = overlapping.find("second") - 16 + 4;