Skip to content

Play your Steam library's Windows games on a jailbroken PS5.

C++

Install games' Windows Installer redistributables

Leonardo Lobatoaaa9ffa0769a
diff --git a/cmake/HomebrewUI.cmake b/cmake/HomebrewUI.cmake
index 19debaf..3845e90 100644
--- a/cmake/HomebrewUI.cmake
+++ b/cmake/HomebrewUI.cmake
@@ -69,12 +69,14 @@ add_library(playden_steam_cm_codec STATIC
"${CMAKE_SOURCE_DIR}/src/runtime/prospero_profile.cpp"
"${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/redist_install.cpp"
"${CMAKE_SOURCE_DIR}/src/runtime/game_probe.cpp")
target_include_directories(playden_steam_cm_codec PUBLIC "${CMAKE_SOURCE_DIR}/src")
target_include_directories(playden_steam_cm_codec PRIVATE "${PLAYDEN_STB_IMAGE_INCLUDE_DIR}")
target_compile_features(playden_steam_cm_codec PUBLIC cxx_std_17)
target_link_libraries(playden_steam_cm_codec PUBLIC playden_game_paths playden_steam_protocol playden_managed_directory
- playden_runtime_steamworks)
+ playden_runtime_steamworks playden_runtime_artifact_hash playden_miniz)
if(PLAYDEN_PLATFORM_PS5)
target_compile_options(playden_steam_cm_codec PRIVATE -fno-exceptions -fno-rtti)
endif()
@@ -514,6 +516,10 @@ if(BUILD_TESTING)
add_test(NAME prospero_profile COMMAND prospero_profile_test "${CMAKE_SOURCE_DIR}/fixtures/prospero-win-profiles")
add_test(NAME game_settings COMMAND game_settings_test "${CMAKE_SOURCE_DIR}")
add_test(NAME game_probe COMMAND game_probe_test)
+ add_executable(runtime_redist_test tests/runtime_redist_test.cpp)
+ target_link_libraries(runtime_redist_test PRIVATE playden_steam_cm_codec)
+ target_compile_features(runtime_redist_test PRIVATE cxx_std_20)
+ add_test(NAME runtime_redist COMMAND runtime_redist_test)
add_executable(runtime_steamworks_test tests/runtime_steamworks_test.cpp)
target_link_libraries(runtime_steamworks_test PRIVATE playden_runtime_steamworks)
add_test(NAME runtime_steamworks COMMAND runtime_steamworks_test "${CMAKE_SOURCE_DIR}/runtime/steamworks")
diff --git a/src/homebrew/runtime_host.cpp b/src/homebrew/runtime_host.cpp
index 52d391d..ca2a0da 100644
--- a/src/homebrew/runtime_host.cpp
+++ b/src/homebrew/runtime_host.cpp
@@ -9,6 +9,7 @@
#include "runtime/settings_publication_journal.h"
#include "runtime/dotnet_heap.h"
#include "runtime/install_script.h"
+#include "runtime/redist_install.h"
#include "runtime/settings_publication_owner.h"
#include "runtime/session_storage.h"
#include "runtime/steam_stub.h"
@@ -508,6 +509,16 @@ std::string RuntimeHost::ApplySteamworks(Composition& c, const rt::RuntimeInstal
(script.ok ? std::string() : " failed=" + script.message));
}
if (!script.ok) return "The game's install script could not be applied: " + script.message + ".";
+ // The redistributables those scripts run (PhysX and the like): packages Playden can install
+ // go into the bottle once; a package that fails is logged and the game still starts.
+ const auto redist = rt::InstallRedistributables(root.string(), *install_dir,
+ (HostPath(record.data_root) / "library/prefixes/game").string(),
+ config_.unix_time());
+ for (const auto& outcome : redist.outcomes)
+ if (outcome.result != "already" && outcome.result != "covered")
+ Log("redist app=" + std::to_string(record.app_id) + " script=" + outcome.script + " name=" + outcome.name +
+ " result=" + outcome.result + " detail=" + outcome.detail +
+ (outcome.files ? " files=" + std::to_string(outcome.files) : std::string()));
}
// Registry values the recipe carries (docs/community-recipes.md), written the way an install script's are.
if (!recipe->registry.empty()) {
diff --git a/src/runtime/install_script.cpp b/src/runtime/install_script.cpp
index 0c3754a..cd702c2 100644
--- a/src/runtime/install_script.cpp
+++ b/src/runtime/install_script.cpp
@@ -158,6 +158,44 @@ bool ParseInstallScript(std::string_view text, const std::string& install_dir, I
return true;
}
+bool ParseRunProcess(std::string_view text, const std::string& install_dir, std::vector<RedistEntry>* entries,
+ std::string* reason) {
+ const auto fail = [&](const char* why) {
+ if (reason) *reason = why;
+ return false;
+ };
+ auto utf8 = ScriptText(text);
+ while (!utf8.empty() && utf8.back() == '\0') utf8.pop_back();
+ const auto root = steam::ParseVdf(utf8);
+ if (!root) return fail("not a valid install script");
+ const steam::VdfNode* script = root->children.size() == 1 && root->children.front().second.is_dict
+ ? &root->children.front().second
+ : &*root;
+ const auto* run = script->Find("Run Process");
+ if (!run) return true;
+ for (const auto& [name, node] : run->children) {
+ if (!node.is_dict) continue;
+ RedistEntry entry;
+ entry.name = name;
+ bool usable = Ascii(name);
+ for (const auto& [field, value] : node.children) {
+ if (value.is_dict) continue;
+ const auto key = Lower(field);
+ std::string* target = key == "process 1" ? &entry.process : key == "command 1" ? &entry.command
+ : key == "hasrunkey" ? &entry.has_run_key : nullptr;
+ if (!target) continue;
+ if (!Substitute(value.value, install_dir, target) || !Ascii(*target)) usable = false;
+ }
+ if (usable && !entry.process.empty()) entries->push_back(std::move(entry));
+ }
+ return true;
+}
+
+bool ReadInstallScript(const std::string& path, std::string* text) {
+ text->clear();
+ return ReadScript(path, text);
+}
+
InstallScriptResult ApplyInstallScripts(const std::string& game_root, const std::string& install_dir,
const std::string& prefix_dir, std::int64_t unix_time) {
InstallScriptResult result;
diff --git a/src/runtime/install_script.h b/src/runtime/install_script.h
index d8382ec..07eb646 100644
--- a/src/runtime/install_script.h
+++ b/src/runtime/install_script.h
@@ -41,4 +41,20 @@ struct InstallScriptResult {
InstallScriptResult ApplyInstallScripts(const std::string& game_root, const std::string& install_dir,
const std::string& prefix_dir, std::int64_t unix_time);
+// A redistributable an install script runs on the game's first start ("Run Process" entry).
+struct RedistEntry {
+ std::string name; // the entry's name ("PhysX")
+ std::string process; // "process 1", %INSTALLDIR% replaced
+ std::string command; // "command 1", %INSTALLDIR% replaced
+ std::string has_run_key; // "HasRunKey", e.g. HKEY_LOCAL_MACHINE\Software\Valve\Steam\Apps\696180
+};
+
+// The Run Process entries of one install script (only the first process of each); entries
+// naming another %TOKEN% or non-ASCII text are left out.
+bool ParseRunProcess(std::string_view text, const std::string& install_dir, std::vector<RedistEntry>* entries,
+ std::string* reason);
+
+// Reads an install script file (at most 1 MiB, no symlink).
+bool ReadInstallScript(const std::string& path, std::string* text);
+
} // namespace playden::runtime
diff --git a/src/runtime/msi_package.cpp b/src/runtime/msi_package.cpp
new file mode 100644
index 0000000..6954632
--- /dev/null
+++ b/src/runtime/msi_package.cpp
@@ -0,0 +1,1054 @@
+#include "runtime/msi_package.h"
+
+#include "miniz.h"
+
+#include <algorithm>
+#include <cctype>
+#include <cerrno>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <memory>
+#include <set>
+
+namespace playden::runtime {
+namespace {
+
+constexpr std::uint32_t kEndOfChain = 0xfffffffe;
+constexpr std::uint32_t kFreeSector = 0xffffffff;
+constexpr std::size_t kMaxStreamBytes = 512u * 1024u * 1024u;
+
+std::uint16_t U16(std::string_view data, std::size_t at) {
+ return static_cast<std::uint16_t>(static_cast<unsigned char>(data[at]) | (static_cast<unsigned char>(data[at + 1]) << 8));
+}
+
+std::uint32_t U32(std::string_view data, std::size_t at) {
+ return static_cast<std::uint32_t>(U16(data, at)) | (static_cast<std::uint32_t>(U16(data, at + 2)) << 16);
+}
+
+std::string Lower(std::string_view text) {
+ std::string out(text);
+ std::transform(out.begin(), out.end(), out.begin(),
+ [](unsigned char value) { return static_cast<char>(value >= 'A' && value <= 'Z' ? value + 32 : value); });
+ return out;
+}
+
+bool Ascii(std::string_view text) {
+ return std::all_of(text.begin(), text.end(), [](unsigned char value) { return value >= 0x20 && value < 0x7f; });
+}
+
+// ---------------------------------------------------------------------------------------------
+// Compound file (the container an .msi is): sectors chained through a FAT, small streams in a
+// mini stream chained through the mini FAT, and a directory of 128-byte entries.
+
+struct CompoundEntry {
+ std::string name; // decoded MSI stream name ("!File", "media1.cab")
+ std::uint32_t start = 0;
+ std::uint64_t size = 0;
+};
+
+class Compound {
+ public:
+ bool Open(std::string_view data, std::string* reason);
+ const CompoundEntry* Find(const std::string& name) const {
+ for (const auto& entry : entries_)
+ if (entry.name == name) return &entry;
+ return nullptr;
+ }
+ bool Read(const CompoundEntry& entry, std::string* out) const;
+
+ private:
+ bool Chain(const std::vector<std::uint32_t>& table, std::uint32_t start, std::uint64_t size, bool mini,
+ std::string* out) const;
+ std::string_view data_;
+ std::uint32_t sector_size_ = 512;
+ std::uint32_t cutoff_ = 4096;
+ std::vector<std::uint32_t> fat_, mini_fat_;
+ std::string mini_stream_;
+ std::vector<CompoundEntry> entries_;
+};
+
+// MSI packs stream names: characters 0x3800-0x47ff hold two name characters, 0x4800-0x483f one,
+// and 0x4840 marks a table stream ("!").
+std::string DecodeStreamName(const std::vector<std::uint16_t>& units) {
+ static constexpr char kAlphabet[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz._";
+ std::string out;
+ for (const auto unit : units) {
+ if (unit >= 0x3800 && unit < 0x4800) {
+ out += kAlphabet[(unit - 0x3800) & 0x3f];
+ out += kAlphabet[((unit - 0x3800) >> 6) & 0x3f];
+ } else if (unit >= 0x4800 && unit < 0x4840) {
+ out += kAlphabet[unit - 0x4800];
+ } else if (unit == 0x4840) {
+ out += '!';
+ } else if (unit < 0x80) {
+ out += static_cast<char>(unit);
+ } else {
+ out += '?';
+ }
+ }
+ return out;
+}
+
+bool Compound::Chain(const std::vector<std::uint32_t>& table, std::uint32_t start, std::uint64_t size, bool mini,
+ std::string* out) const {
+ out->clear();
+ if (size > kMaxStreamBytes) return false;
+ const std::uint32_t unit = mini ? 64 : sector_size_;
+ out->reserve(static_cast<std::size_t>(size));
+ std::uint32_t sector = start;
+ for (std::size_t steps = 0; out->size() < size; ++steps) {
+ if (sector == kEndOfChain || sector >= table.size() || steps > table.size()) return false;
+ const std::size_t take = static_cast<std::size_t>(std::min<std::uint64_t>(unit, size - out->size()));
+ if (mini) {
+ const std::size_t at = static_cast<std::size_t>(sector) * 64;
+ if (at + take > mini_stream_.size()) return false;
+ out->append(mini_stream_, at, take);
+ } else {
+ const std::uint64_t at = (static_cast<std::uint64_t>(sector) + 1) * sector_size_;
+ if (at + take > data_.size()) return false;
+ out->append(data_.substr(static_cast<std::size_t>(at), take));
+ }
+ sector = table[sector];
+ }
+ return true;
+}
+
+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);
+}
+
+bool Compound::Open(std::string_view data, std::string* reason) {
+ const auto fail = [&](const char* why) {
+ if (reason) *reason = why;
+ return false;
+ };
+ static constexpr unsigned char kSignature[] = {0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1};
+ if (data.size() < 512 || std::memcmp(data.data(), kSignature, sizeof(kSignature)) != 0)
+ return fail("not a Windows Installer package");
+ data_ = data;
+ const auto shift = U16(data, 0x1e);
+ if (shift != 9 && shift != 12) return fail("unsupported package sector size");
+ sector_size_ = 1u << shift;
+ if (U16(data, 0x20) != 6) return fail("unsupported package mini sector size");
+ cutoff_ = U32(data, 0x38);
+ const auto fat_sectors = U32(data, 0x2c);
+ const std::uint32_t total_sectors = static_cast<std::uint32_t>(data.size() / sector_size_);
+ if (fat_sectors > total_sectors) return fail("damaged package");
+ // The FAT's own sectors: 109 in the header, the rest in a chain of DIFAT sectors.
+ std::vector<std::uint32_t> fat_list;
+ for (std::size_t index = 0; index < 109 && fat_list.size() < fat_sectors; ++index)
+ fat_list.push_back(U32(data, 0x4c + index * 4));
+ std::uint32_t difat = U32(data, 0x44);
+ for (std::uint32_t steps = 0; fat_list.size() < fat_sectors; ++steps) {
+ if (difat == kEndOfChain || difat == kFreeSector || steps > total_sectors) return fail("damaged package");
+ const std::uint64_t at = (static_cast<std::uint64_t>(difat) + 1) * sector_size_;
+ if (at + sector_size_ > data.size()) return fail("damaged package");
+ for (std::size_t index = 0; index + 1 < sector_size_ / 4 && fat_list.size() < fat_sectors; ++index)
+ fat_list.push_back(U32(data, static_cast<std::size_t>(at) + index * 4));
+ difat = U32(data, static_cast<std::size_t>(at) + sector_size_ - 4);
+ }
+ fat_.clear();
+ for (const auto sector : fat_list) {
+ const std::uint64_t at = (static_cast<std::uint64_t>(sector) + 1) * sector_size_;
+ if (at + sector_size_ > data.size()) return fail("damaged package");
+ for (std::size_t index = 0; index < sector_size_ / 4; ++index)
+ fat_.push_back(U32(data, static_cast<std::size_t>(at) + index * 4));
+ }
+ // Chains of unknown length (directory, mini FAT) are read sector by sector until their end.
+ const auto whole_chain = [&](std::uint32_t start, std::string* out) {
+ out->clear();
+ for (std::uint32_t sector = start, steps = 0; sector != kEndOfChain; ++steps) {
+ if (sector >= fat_.size() || steps > fat_.size()) return false;
+ const std::uint64_t at = (static_cast<std::uint64_t>(sector) + 1) * sector_size_;
+ if (at + sector_size_ > data.size()) return false;
+ out->append(data.substr(static_cast<std::size_t>(at), sector_size_));
+ sector = fat_[sector];
+ }
+ return true;
+ };
+ std::string directory, mini_fat;
+ if (!whole_chain(U32(data, 0x30), &directory) || directory.size() < 128) return fail("damaged package directory");
+ const auto mini_fat_start = U32(data, 0x3c);
+ if (mini_fat_start != kEndOfChain && !whole_chain(mini_fat_start, &mini_fat)) return fail("damaged package");
+ mini_fat_.clear();
+ for (std::size_t at = 0; at + 4 <= mini_fat.size(); at += 4) mini_fat_.push_back(U32(mini_fat, at));
+ entries_.clear();
+ for (std::size_t at = 0; at + 128 <= directory.size(); at += 128) {
+ const auto type = static_cast<unsigned char>(directory[at + 0x42]);
+ const auto name_bytes = std::min<std::uint16_t>(U16(directory, at + 0x40), 64);
+ std::vector<std::uint16_t> units;
+ for (std::size_t index = 0; index + 1 < name_bytes; index += 2) {
+ const auto unit = U16(directory, at + index);
+ if (unit == 0) break;
+ units.push_back(unit);
+ }
+ CompoundEntry entry;
+ entry.name = DecodeStreamName(units);
+ entry.start = U32(directory, at + 0x74);
+ entry.size = U32(directory, at + 0x78);
+ if (sector_size_ == 4096) entry.size |= static_cast<std::uint64_t>(U32(directory, at + 0x7c)) << 32;
+ if (type == 5) { // the root entry holds the mini stream
+ if (entry.size && !Chain(fat_, entry.start, entry.size, false, &mini_stream_))
+ return fail("damaged package mini stream");
+ } else if (type == 2) {
+ entries_.push_back(std::move(entry));
+ }
+ }
+ return true;
+}
+
+// ---------------------------------------------------------------------------------------------
+// The installer database: a string pool and column-major tables described by _Columns.
+
+struct Cell {
+ bool null = true;
+ std::string text; // strings
+ long long number = 0; // integers
+};
+
+struct Table {
+ std::vector<std::string> columns;
+ std::vector<std::vector<Cell>> rows;
+ int Column(const char* name) const {
+ for (std::size_t index = 0; index < columns.size(); ++index)
+ if (columns[index] == name) return static_cast<int>(index);
+ return -1;
+ }
+};
+
+struct ColumnInfo {
+ int number = 0;
+ std::string name;
+ unsigned type = 0;
+};
+
+constexpr unsigned kTypeString = 0x0800;
+constexpr unsigned kTypeValid = 0x0100;
+constexpr unsigned kTypeNullable = 0x1000;
+constexpr unsigned kTypeTemporary = 0x4000;
+
+class Database {
+ public:
+ bool Open(std::string_view package, std::string* reason);
+ bool ReadTable(const std::string& name, Table* table) const;
+ const Compound& compound() const { return compound_; }
+
+ private:
+ const std::string& String(std::uint32_t id) const {
+ static const std::string empty;
+ return id < strings_.size() ? strings_[id] : empty;
+ }
+ bool ReadColumns(const std::string& stream, const std::vector<ColumnInfo>& columns, Table* table) const;
+ Compound compound_;
+ std::vector<std::string> strings_;
+ std::size_t string_bytes_ = 2;
+ std::map<std::string, std::vector<ColumnInfo>> columns_;
+};
+
+bool Database::Open(std::string_view package, std::string* reason) {
+ const auto fail = [&](const char* why) {
+ if (reason) *reason = why;
+ return false;
+ };
+ if (!compound_.Open(package, reason)) return false;
+ const auto* pool_entry = compound_.Find("!_StringPool");
+ const auto* data_entry = compound_.Find("!_StringData");
+ std::string pool, data;
+ if (!pool_entry || !data_entry || !compound_.Read(*pool_entry, &pool) || !compound_.Read(*data_entry, &data) ||
+ pool.size() < 4)
+ return fail("the package has no string pool");
+ // The first entry is the code page, its top bit saying string ids take three bytes.
+ string_bytes_ = (U32(pool, 0) & 0x80000000u) ? 3 : 2;
+ strings_.assign(1, std::string());
+ std::size_t offset = 0;
+ for (std::size_t at = 4; at + 4 <= pool.size();) {
+ std::size_t length = U16(pool, at);
+ const auto references = U16(pool, at + 2);
+ if (length == 0 && references != 0) {
+ // A string over 64 KiB: this entry's count is the high word, the next entry the length.
+ if (at + 8 > pool.size()) return fail("damaged string pool");
+ length = (static_cast<std::size_t>(U16(pool, at + 6)) << 16) | U16(pool, at + 4);
+ at += 8;
+ } else {
+ at += 4;
+ }
+ if (offset + length > data.size()) return fail("damaged string pool");
+ strings_.push_back(data.substr(offset, length));
+ offset += length;
+ }
+ const auto* columns_entry = compound_.Find("!_Columns");
+ std::string columns;
+ if (!columns_entry || !compound_.Read(*columns_entry, &columns)) return fail("the package has no column list");
+ const std::size_t row = string_bytes_ * 2 + 4;
+ const std::size_t count = columns.size() / row;
+ const auto string_at = [&](std::size_t at) {
+ return string_bytes_ == 3 ? static_cast<std::uint32_t>(U16(columns, at)) | (static_cast<unsigned char>(columns[at + 2]) << 16)
+ : static_cast<std::uint32_t>(U16(columns, at));
+ };
+ for (std::size_t index = 0; index < count; ++index) {
+ const auto table = String(string_at(index * string_bytes_));
+ ColumnInfo info;
+ info.number = static_cast<int>(U16(columns, count * string_bytes_ + index * 2) ^ 0x8000u);
+ info.name = String(string_at(count * (string_bytes_ + 2) + index * string_bytes_));
+ info.type = U16(columns, count * (string_bytes_ * 2 + 2) + index * 2) ^ 0x8000u;
+ columns_[table].push_back(std::move(info));
+ }
+ for (auto& [name, list] : columns_)
+ std::sort(list.begin(), list.end(), [](const ColumnInfo& a, const ColumnInfo& b) { return a.number < b.number; });
+ return true;
+}
+
+bool Database::ReadColumns(const std::string& stream, const std::vector<ColumnInfo>& columns, Table* table) const {
+ std::vector<std::size_t> widths;
+ std::vector<const ColumnInfo*> stored;
+ for (const auto& column : columns) {
+ if (column.type & kTypeTemporary) continue;
+ const bool binary = (column.type & ~kTypeNullable) == (kTypeString | kTypeValid);
+ widths.push_back(binary ? 2 : (column.type & kTypeString) ? string_bytes_ : (column.type & 0xff) <= 2 ? 2 : 4);
+ stored.push_back(&column);
+ }
+ std::size_t row_bytes = 0;
+ for (const auto width : widths) row_bytes += width;
+ if (row_bytes == 0) return false;
+ const std::size_t count = stream.size() / row_bytes;
+ table->columns.clear();
+ for (const auto* column : stored) table->columns.push_back(column->name);
+ table->rows.assign(count, std::vector<Cell>(stored.size()));
+ std::size_t at = 0;
+ for (std::size_t column = 0; column < stored.size(); ++column) {
+ const bool binary = (stored[column]->type & ~kTypeNullable) == (kTypeString | kTypeValid);
+ const bool text = (stored[column]->type & kTypeString) && !binary;
+ for (std::size_t index = 0; index < count; ++index, at += widths[column]) {
+ auto& cell = table->rows[index][column];
+ if (text) {
+ const std::uint32_t id = widths[column] == 3
+ ? static_cast<std::uint32_t>(U16(stream, at)) | (static_cast<unsigned char>(stream[at + 2]) << 16)
+ : U16(stream, at);
+ cell.null = id == 0;
+ cell.text = String(id);
+ } else if (widths[column] == 2) {
+ const auto raw = U16(stream, at);
+ cell.null = raw == 0;
+ cell.number = static_cast<long long>(raw) - 0x8000;
+ } else {
+ const auto raw = U32(stream, at);
+ cell.null = raw == 0;
+ cell.number = static_cast<long long>(raw) - 0x80000000ll;
+ }
+ }
+ }
+ return true;
+}
+
+bool Database::ReadTable(const std::string& name, Table* table) const {
+ table->columns.clear();
+ table->rows.clear();
+ const auto columns = columns_.find(name);
+ if (columns == columns_.end()) return true; // the package doesn't have it
+ const auto* entry = compound_.Find("!" + name);
+ if (!entry) {
+ for (const auto& column : columns->second) table->columns.push_back(column.name);
+ return true; // an empty table has no stream
+ }
+ std::string stream;
+ return compound_.Read(*entry, &stream) && ReadColumns(stream, columns->second, table);
+}
+
+const Cell& At(const Table& table, const std::vector<Cell>& row, const char* column) {
+ static const Cell null_cell;
+ const int index = table.Column(column);
+ return index < 0 ? null_cell : row[static_cast<std::size_t>(index)];
+}
+
+// "short|long" names keep the long part; "target:source" names keep the target.
+std::string LongName(std::string text) {
+ if (const auto colon = text.find(':'); colon != std::string::npos) text.resize(colon);
+ if (const auto bar = text.find('|'); bar != std::string::npos) text.erase(0, bar + 1);
+ return text;
+}
+
+// ---------------------------------------------------------------------------------------------
+// Conditions.
+
+class ConditionParser {
+ public:
+ ConditionParser(std::string_view text, const std::map<std::string, std::string>& properties)
+ : text_(text), properties_(properties) {}
+ std::optional<bool> Parse() {
+ bool value = false;
+ if (!Implication(&value)) return std::nullopt;
+ Space();
+ if (at_ != text_.size()) return std::nullopt;
+ return value;
+ }
+
+ private:
+ void Space() {
+ while (at_ < text_.size() && (text_[at_] == ' ' || text_[at_] == '\t' || text_[at_] == '\r' || text_[at_] == '\n')) ++at_;
+ }
+ bool Keyword(const char* word) {
+ Space();
+ const std::size_t length = std::strlen(word);
+ if (at_ + length > text_.size() || Lower(text_.substr(at_, length)) != Lower(word)) return false;
+ const std::size_t end = at_ + length;
+ if (end < text_.size() && (std::isalnum(static_cast<unsigned char>(text_[end])) || text_[end] == '_' || text_[end] == '.'))
+ return false;
+ at_ = end;
+ return true;
+ }
+ bool Implication(bool* value) {
+ if (!Equivalence(value)) return false;
+ while (Keyword("IMP")) {
+ bool right = false;
+ if (!Equivalence(&right)) return false;
+ *value = !*value || right;
+ }
+ return true;
+ }
+ bool Equivalence(bool* value) {
+ if (!Exclusive(value)) return false;
+ while (Keyword("EQV")) {
+ bool right = false;
+ if (!Exclusive(&right)) return false;
+ *value = *value == right;
+ }
+ return true;
+ }
+ bool Exclusive(bool* value) {
+ if (!Disjunction(value)) return false;
+ while (Keyword("XOR")) {
+ bool right = false;
+ if (!Disjunction(&right)) return false;
+ *value = *value != right;
+ }
+ return true;
+ }
+ bool Disjunction(bool* value) {
+ if (!Conjunction(value)) return false;
+ while (Keyword("OR")) {
+ bool right = false;
+ if (!Conjunction(&right)) return false;
+ *value = *value || right;
+ }
+ return true;
+ }
+ bool Conjunction(bool* value) {
+ if (!Negation(value)) return false;
+ while (Keyword("AND")) {
+ bool right = false;
+ if (!Negation(&right)) return false;
+ *value = *value && right;
+ }
+ return true;
+ }
+ bool Negation(bool* value) {
+ if (Keyword("NOT")) {
+ if (!Negation(value)) return false;
+ *value = !*value;
+ return true;
+ }
+ return Comparison(value);
+ }
+ struct Operand {
+ std::string text;
+ bool integer = false;
+ long long number = 0;
+ };
+ static Operand Classify(std::string text, bool literal_string) {
+ Operand operand;
+ operand.text = std::move(text);
+ if (!literal_string && !operand.text.empty()) {
+ char* end = nullptr;
+ errno = 0;
+ const auto number = std::strtoll(operand.text.c_str(), &end, 10);
+ if (!errno && end && !*end) {
+ operand.integer = true;
+ operand.number = number;
+ }
+ }
+ return operand;
+ }
+ bool Value(Operand* operand) {
+ Space();
+ if (at_ >= text_.size()) return false;
+ const char first = text_[at_];
+ if (first == '"') {
+ const auto end = text_.find('"', at_ + 1);
+ if (end == std::string_view::npos) return false;
+ *operand = Classify(std::string(text_.substr(at_ + 1, end - at_ - 1)), true);
+ at_ = end + 1;
+ return true;
+ }
+ if (first == '-' || std::isdigit(static_cast<unsigned char>(first))) {
+ std::size_t end = at_ + 1;
+ while (end < text_.size() && std::isdigit(static_cast<unsigned char>(text_[end]))) ++end;
+ *operand = Classify(std::string(text_.substr(at_, end - at_)), false);
+ at_ = end;
+ return !operand->text.empty() && operand->text != "-";
+ }
+ // Environment variables and component or feature states are not known: empty.
+ bool state = false;
+ if (first == '%' || first == '$' || first == '&' || first == '?' || first == '!') {
+ state = true;
+ ++at_;
+ }
+ std::size_t end = at_;
+ while (end < text_.size() &&
+ (std::isalnum(static_cast<unsigned char>(text_[end])) || text_[end] == '_' || text_[end] == '.'))
+ ++end;
+ if (end == at_) return false;
+ const std::string name(text_.substr(at_, end - at_));
+ at_ = end;
+ const auto found = properties_.find(name);
+ *operand = Classify(state || found == properties_.end() ? std::string() : found->second, false);
+ return true;
+ }
+ static bool Truth(const Operand& operand) { return operand.integer ? operand.number != 0 : !operand.text.empty(); }
+ bool Comparison(bool* value) {
+ Space();
+ if (at_ < text_.size() && text_[at_] == '(') {
+ ++at_;
+ if (!Implication(value)) return false;
+ Space();
+ if (at_ >= text_.size() || text_[at_] != ')') return false;
+ ++at_;
+ return true;
+ }
+ Operand left;
+ if (!Value(&left)) return false;
+ Space();
+ static constexpr const char* kOperators[] = {"<>", "><", "<<", ">>", "<=", ">=", "=", "<", ">"};
+ bool fold = false;
+ std::size_t probe = at_;
+ if (probe < text_.size() && text_[probe] == '~') {
+ fold = true;
+ ++probe;
+ }
+ std::string op;
+ for (const auto* candidate : kOperators) {
+ const std::size_t length = std::strlen(candidate);
+ if (text_.substr(probe, length) == candidate) {
+ op = candidate;
+ break;
+ }
+ }
+ if (op.empty()) {
+ if (fold) return false;
+ *value = Truth(left);
+ return true;
+ }
+ at_ = probe + op.size();
+ Operand right;
+ if (!Value(&right)) return false;
+ if (left.integer && right.integer) {
+ const auto a = left.number, b = right.number;
+ *value = op == "=" ? a == b : op == "<>" ? a != b : op == "<" ? a < b : op == ">" ? a > b
+ : op == "<=" ? a <= b : op == ">=" ? a >= b : op == "><" ? (a & b) != 0
+ : op == "<<" ? ((a >> 16) & 0xffff) == b : ((a & 0xffff) == b);
+ return true;
+ }
+ const auto a = fold ? Lower(left.text) : left.text, b = fold ? Lower(right.text) : right.text;
+ *value = op == "=" ? a == b : op == "<>" ? a != b : op == "<" ? a < b : op == ">" ? a > b
+ : op == "<=" ? a <= b : op == ">=" ? a >= b : op == "><" ? a.find(b) != std::string::npos
+ : op == "<<" ? a.rfind(b, 0) == 0 : (a.size() >= b.size() && a.compare(a.size() - b.size(), b.size(), b) == 0);
+ return true;
+ }
+ std::string_view text_;
+ const std::map<std::string, std::string>& properties_;
+ std::size_t at_ = 0;
+};
+
+// ---------------------------------------------------------------------------------------------
+// Values written into the bottle.
+
+std::string WineString(std::string_view text) {
+ std::string out = "\"";
+ for (const char value : text) {
+ if (value == '\\' || value == '"') out += '\\';
+ out += value;
+ }
+ return out + "\"";
+}
+
+std::string WindowsPath(const std::string& relative) {
+ std::string out = "C:\\" + relative;
+ std::replace(out.begin(), out.end(), '/', '\\');
+ return out;
+}
+
+// The bottle folders a package's standard directories stand for (64-bit Windows, all users).
+// nullopt for per-user folders, which this installer leaves alone.
+std::optional<std::string> StandardFolder(const std::string& name) {
+ static const std::map<std::string, std::string> kFolders = {
+ {"TARGETDIR", ""},
+ {"ProgramFilesFolder", "Program Files (x86)"},
+ {"ProgramFiles64Folder", "Program Files"},
+ {"CommonFilesFolder", "Program Files (x86)/Common Files"},
+ {"CommonFiles64Folder", "Program Files/Common Files"},
+ {"SystemFolder", "windows/syswow64"},
+ {"System64Folder", "windows/system32"},
+ {"System16Folder", "windows/system"},
+ {"WindowsFolder", "windows"},
+ {"WindowsVolume", ""},
+ {"CommonAppDataFolder", "ProgramData"},
+ {"FontsFolder", "windows/Fonts"},
+ };
+ const auto found = kFolders.find(name);
+ if (found != kFolders.end()) return found->second;
+ return std::nullopt;
+}
+
+bool PerUserFolder(const std::string& name) {
+ static const std::set<std::string> kFolders = {
+ "AppDataFolder", "LocalAppDataFolder", "PersonalFolder", "DesktopFolder", "ProgramMenuFolder",
+ "StartMenuFolder", "StartupFolder", "SendToFolder", "TemplateFolder", "FavoritesFolder", "NetHoodFolder",
+ "PrintHoodFolder", "RecentFolder", "MyPicturesFolder", "AdminToolsFolder", "TempFolder"};
+ return kFolders.count(name) != 0;
+}
+
+class PlanBuilder {
+ public:
+ explicit PlanBuilder(const Database& database) : database_(database) {}
+ bool Build(MsiInstallPlan* plan, std::string* reason);
+
+ private:
+ std::optional<std::string> Directory(const std::string& key, int depth = 0);
+ std::string Format(std::string_view text, bool* multi = nullptr) const;
+ void AddRegistry(MsiInstallPlan* plan, bool machine, const std::string& key, const std::string& name,
+ const std::string& data, bool default_value);
+ const Database& database_;
+ std::map<std::string, std::string> properties_;
+ std::map<std::string, std::pair<std::string, std::string>> directory_rows_; // key → parent, name
+ std::map<std::string, std::optional<std::string>> directories_; // resolved, relative to drive_c
+ std::map<std::string, std::string> file_paths_; // File key → Windows path
+ std::map<std::string, std::string> component_paths_; // Component → Windows folder
+ std::map<std::string, std::size_t> registry_index_;
+};
+
+std::optional<std::string> PlanBuilder::Directory(const std::string& key, int depth) {
+ if (const auto found = directories_.find(key); found != directories_.end()) return found->second;
+ std::optional<std::string> result;
+ const auto row = directory_rows_.find(key);
+ if (const auto standard = StandardFolder(key)) {
+ result = standard;
+ } else if (PerUserFolder(key) || row == directory_rows_.end() || depth > 64) {
+ result = std::nullopt;
+ } else {
+ const auto& [parent, name] = row->second;
+ if (parent.empty() || parent == key) {
+ result = std::string(); // another root: the system drive, like TARGETDIR
+ } else if (const auto base = Directory(parent, depth + 1)) {
+ const auto component = LongName(name);
+ result = component == "." || component.empty() ? *base : (base->empty() ? component : *base + "/" + component);
+ }
+ }
+ directories_[key] = result;
+ return result;
+}
+
+// Formatted text: [Property], [#File], [!File], [$Component], [\x] and [~]; environment
+// variables ([%NAME]) are empty. multi is set when [~] appears.
+std::string PlanBuilder::Format(std::string_view text, bool* multi) const {
+ std::string out;
+ for (std::size_t at = 0; at < text.size();) {
+ if (text[at] != '[') {
+ out += text[at++];
+ continue;
+ }
+ const auto end = text.find(']', at + 1);
+ if (end == std::string_view::npos) {
+ out += text.substr(at);
+ break;
+ }
+ const std::string token(text.substr(at + 1, end - at - 1));
+ at = end + 1;
+ if (token == "~") {
+ if (multi) *multi = true;
+ out += '\0';
+ } else if (token.size() == 2 && token[0] == '\\') {
+ out += token[1];
+ } else if (!token.empty() && (token[0] == '#' || token[0] == '!')) {
+ if (const auto found = file_paths_.find(token.substr(1)); found != file_paths_.end()) out += found->second;
+ } else if (!token.empty() && token[0] == '$') {
+ if (const auto found = component_paths_.find(token.substr(1)); found != component_paths_.end()) out += found->second;
+ } else if (!token.empty() && token[0] == '%') {
+ // Environment variables are not known.
+ } else if (const auto found = properties_.find(token); found != properties_.end()) {
+ out += found->second;
+ }
+ }
+ return out;
+}
+
+void PlanBuilder::AddRegistry(MsiInstallPlan* plan, bool machine, const std::string& key, const std::string& name,
+ const std::string& data, bool default_value) {
+ auto& list = machine ? plan->machine : plan->user;
+ const auto identity = std::string(machine ? "m:" : "u:") + Lower(key) + "\n" + (default_value ? "@" : Lower(name));
+ if (const auto found = registry_index_.find(identity); found != registry_index_.end()) {
+ list[found->second].data = data; // a later row wins, as when the installer writes both
+ return;
+ }
+ registry_index_[identity] = list.size();
+ RegistryValue value;
+ value.key = key;
+ value.name = default_value ? std::string() : name;
+ value.data = data;
+ value.default_value = default_value;
+ list.push_back(std::move(value));
+}
+
+bool PlanBuilder::Build(MsiInstallPlan* plan, std::string* reason) {
+ const auto fail = [&](const char* why) {
+ if (reason) *reason = why;
+ return false;
+ };
+ *plan = MsiInstallPlan{};
+ Table property, directory, component, feature, feature_components, condition, file, media, registry, environment,
+ custom_action;
+ for (const auto& [name, table] : std::initializer_list<std::pair<const char*, Table*>>{
+ {"Property", &property}, {"Directory", &directory}, {"Component", &component}, {"Feature", &feature},
+ {"FeatureComponents", &feature_components}, {"Condition", &condition}, {"File", &file}, {"Media", &media},
+ {"Registry", &registry}, {"Environment", &environment}, {"CustomAction", &custom_action}})
+ if (!database_.ReadTable(name, table)) return fail("a package table could not be read");
+ plan->custom_actions = custom_action.rows.size();
+
+ // A quiet, per-machine install on 64-bit Windows 7.
+ properties_ = {{"VersionNT", "601"}, {"VersionNT64", "601"}, {"WindowsBuild", "7601"}, {"ServicePackLevel", "1"},
+ {"Intel", "6"}, {"Msix64", "6"}, {"Privileged", "1"}, {"AdminUser", "1"}, {"INSTALLLEVEL", "1"},
+ {"UILevel", "2"}};
+ for (const auto& row : property.rows) {
+ const auto& name = At(property, row, "Property");
+ if (!name.null) properties_[name.text] = At(property, row, "Value").text;
+ }
+ properties_["ALLUSERS"] = "1";
+ plan->product_code = properties_["ProductCode"];
+ plan->product_name = properties_["ProductName"];
+ plan->product_version = properties_["ProductVersion"];
+
+ for (const auto& row : directory.rows)
+ directory_rows_[At(directory, row, "Directory").text] = {At(directory, row, "Directory_Parent").text,
+ At(directory, row, "DefaultDir").text};
+ for (const auto& [key, unused] : directory_rows_) {
+ (void)unused;
+ if (const auto path = Directory(key)) properties_[key] = WindowsPath(*path) + (path->empty() ? "" : "\\");
+ }
+
+ // Features at a level from 1 to INSTALLLEVEL, after their Condition rows, under selected parents.
+ const long long install_level = std::strtoll(properties_["INSTALLLEVEL"].c_str(), nullptr, 10);
+ std::map<std::string, std::pair<std::string, long long>> features; // name → parent, level
+ for (const auto& row : feature.rows)
+ features[At(feature, row, "Feature").text] = {At(feature, row, "Feature_Parent").text, At(feature, row, "Level").number};
+ for (const auto& row : condition.rows) {
+ const auto found = features.find(At(condition, row, "Feature_").text);
+ if (found == features.end()) continue;
+ if (EvaluateMsiCondition(At(condition, row, "Condition").text, properties_).value_or(false))
+ found->second.second = At(condition, row, "Level").number;
+ }
+ std::set<std::string> selected_features;
+ for (const auto& [name, info] : features) {
+ bool selected = true;
+ std::string current = name;
+ for (int depth = 0; selected && !current.empty() && depth < 64; ++depth) {
+ const auto found = features.find(current);
+ if (found == features.end()) break;
+ const auto level = found->second.second;
+ selected = level >= 1 && level <= install_level;
+ current = found->second.first == current ? std::string() : found->second.first;
+ }
+ if (selected) selected_features.insert(name);
+ }
+ std::set<std::string> selected_components;
+ for (const auto& row : feature_components.rows)
+ if (selected_features.count(At(feature_components, row, "Feature_").text))
+ selected_components.insert(At(feature_components, row, "Component_").text);
+ std::map<std::string, std::pair<std::string, bool>> components; // name → directory key, 64-bit
+ for (const auto& row : component.rows) {
+ const auto& name = At(component, row, "Component").text;
+ const auto& when = At(component, row, "Condition");
+ if (!selected_components.count(name)) continue;
+ // A condition this reader can't parse doesn't keep the component out.
+ if (!when.null && !when.text.empty() && !EvaluateMsiCondition(when.text, properties_).value_or(true)) continue;
+ components[name] = {At(component, row, "Directory_").text, (At(component, row, "Attributes").number & 0x100) != 0};
+ if (const auto path = Directory(At(component, row, "Directory_").text))
+ component_paths_[name] = WindowsPath(*path) + (path->empty() ? "" : "\\");
+ }
+
+ // Files, each from the cabinet of the first Media row whose last sequence reaches it.
+ std::vector<std::pair<long long, std::string>> media_rows;
+ for (const auto& row : media.rows)
+ media_rows.emplace_back(At(media, row, "LastSequence").number, At(media, row, "Cabinet").text);
+ std::sort(media_rows.begin(), media_rows.end());
+ std::map<std::string, std::size_t> cabinet_index;
+ for (const auto& row : file.rows) {
+ const auto& key = At(file, row, "File").text;
+ const auto owner = components.find(At(file, row, "Component_").text);
+ const auto name = LongName(At(file, row, "FileName").text);
+ if (owner == components.end()) continue;
+ const auto folder = Directory(owner->second.first);
+ if (folder) file_paths_[key] = WindowsPath(folder->empty() ? name : *folder + "/" + name);
+ const auto sequence = At(file, row, "Sequence").number;
+ const auto attributes = At(file, row, "Attributes").number;
+ const auto disk = std::find_if(media_rows.begin(), media_rows.end(),
+ [&](const auto& media_row) { return media_row.first >= sequence; });
+ if (!folder || name.empty() || name.find('/') != std::string::npos || name.find('\\') != std::string::npos ||
+ disk == media_rows.end() || disk->second.empty() || (attributes & 0x2000)) {
+ ++plan->skipped_files;
+ continue;
+ }
+ const bool embedded = disk->second[0] == '#';
+ const auto cabinet_name = embedded ? disk->second.substr(1) : disk->second;
+ auto found = cabinet_index.find(disk->second);
+ if (found == cabinet_index.end()) {
+ found = cabinet_index.emplace(disk->second, plan->cabinets.size()).first;
+ plan->cabinets.push_back({cabinet_name, embedded});
+ }
+ MsiFile entry;
+ entry.target = folder->empty() ? name : *folder + "/" + name;
+ entry.member = key;
+ entry.cabinet = found->second;
+ entry.size = static_cast<std::uint32_t>(At(file, row, "FileSize").number);
+ plan->files.push_back(std::move(entry));
+ }
+
+ // Registry rows of the selected components.
+ for (const auto& row : registry.rows) {
+ const auto owner = components.find(At(registry, row, "Component_").text);
+ if (owner == components.end()) continue;
+ const bool wide = owner->second.second;
+ const auto root = At(registry, row, "Root").number;
+ const auto& raw_name = At(registry, row, "Name");
+ const auto& raw_value = At(registry, row, "Value");
+ if (raw_value.null && (raw_name.null || raw_name.text == "+" || raw_name.text == "-" || raw_name.text == "*"))
+ continue; // only creates or removes the key
+ auto key = Format(At(registry, row, "Key").text);
+ const auto name = raw_name.null ? std::string() : Format(raw_name.text);
+ std::string data;
+ const auto& value = raw_value.text;
+ bool multi = false;
+ if (value.rfind("#x", 0) == 0 || value.rfind("#X", 0) == 0) {
+ ++plan->skipped_registry;
+ continue;
+ } else if (value.rfind("#%", 0) == 0) {
+ data = "str(2):" + WineString(Format(value.substr(2), &multi));
+ } else if (value.rfind("##", 0) == 0) {
+ data = WineString("#" + Format(value.substr(2), &multi));
+ } else if (value.rfind("#", 0) == 0) {
+ const auto number = Format(value.substr(1), &multi);
+ char* end = nullptr;
+ errno = 0;
+ const auto parsed = std::strtoll(number.c_str(), &end, 10);
+ if (number.empty() || errno || *end || parsed < -2147483648ll || parsed > 0xffffffffll) {
+ ++plan->skipped_registry;
+ continue;
+ }
+ char text[24];
+ std::snprintf(text, sizeof(text), "dword:%08x", static_cast<unsigned>(static_cast<std::uint32_t>(parsed)));
+ data = text;
+ } else {
+ data = WineString(Format(value, &multi));
+ }
+ if (multi || !Ascii(key) || !Ascii(name) || !Ascii(data) || key.empty()) {
+ ++plan->skipped_registry;
+ continue;
+ }
+ bool machine = true;
+ if (root == 1) {
+ machine = false;
+ } else if (root == 0) {
+ key = std::string(wide ? "Software\\Classes\\" : "Software\\Classes\\Wow6432Node\\") + key;
+ } else if (root == 2 || root == -1) {
+ const auto lower = Lower(key);
+ if (!wide && lower.rfind("software\\", 0) == 0 && lower.rfind("software\\wow6432node\\", 0) != 0 &&
+ lower.rfind("software\\classes\\", 0) != 0)
+ key = "Software\\Wow6432Node\\" + key.substr(9);
+ } else {
+ ++plan->skipped_registry;
+ continue;
+ }
+ AddRegistry(plan, machine, key, name, data, raw_name.null || name.empty());
+ }
+
+ // Environment rows: folders the package adds to the machine-wide PATH. Other variables, and
+ // values that replace PATH instead of extending it, are left alone.
+ for (const auto& row : environment.rows) {
+ if (!components.count(At(environment, row, "Component_").text)) continue;
+ auto name = At(environment, row, "Name").text;
+ bool system = false, remove = false;
+ while (!name.empty() && std::strchr("=+-!*", name[0])) {
+ system = system || name[0] == '*';
+ remove = remove || name[0] == '!';
+ name.erase(0, 1);
+ }
+ const auto& value = At(environment, row, "Value").text;
+ const bool append = value.rfind("[~];", 0) == 0;
+ const bool prepend = value.size() >= 4 && value.compare(value.size() - 4, 4, ";[~]") == 0;
+ if (!system || remove || Lower(name) != "path" || (!append && !prepend)) {
+ ++plan->skipped_registry;
+ continue;
+ }
+ const auto entry = Format(append ? value.substr(4) : value.substr(0, value.size() - 4));
+ if (entry.empty() || !Ascii(entry) || entry.find(';') != std::string::npos) {
+ ++plan->skipped_registry;
+ continue;
+ }
+ (append ? plan->path_append : plan->path_prepend).push_back(entry);
+ }
+ return true;
+}
+
+} // namespace
+
+bool ReadMsiPackage(std::string_view package, MsiInstallPlan* plan, std::string* reason) {
+ Database database;
+ if (!database.Open(package, reason)) return false;
+ PlanBuilder builder(database);
+ return builder.Build(plan, reason);
+}
+
+std::optional<std::string> ReadMsiStream(std::string_view package, const std::string& name) {
+ Compound compound;
+ std::string reason, out;
+ if (!compound.Open(package, &reason)) return std::nullopt;
+ const auto* entry = compound.Find(name);
+ if (!entry || !compound.Read(*entry, &out)) return std::nullopt;
+ return out;
+}
+
+std::optional<bool> EvaluateMsiCondition(std::string_view condition, const std::map<std::string, std::string>& properties) {
+ std::size_t first = 0;
+ while (first < condition.size() && (condition[first] == ' ' || condition[first] == '\t')) ++first;
+ if (first == condition.size()) return true;
+ return ConditionParser(condition, properties).Parse();
+}
+
+bool ExtractCabinet(std::string_view cabinet, const std::function<bool(const std::string&, std::string_view)>& sink,
+ std::string* reason) {
+ const auto fail = [&](const char* why) {
+ if (reason) *reason = why;
+ return false;
+ };
+ if (cabinet.size() < 36 || cabinet.substr(0, 4) != "MSCF") return fail("not a cabinet");
+ const auto files_offset = U32(cabinet, 16);
+ const auto folder_count = U16(cabinet, 26);
+ const auto file_count = U16(cabinet, 28);
+ const auto flags = U16(cabinet, 30);
+ if (flags & 0x3) return fail("cabinets that continue into another one are not supported");
+ std::size_t at = 36;
+ std::size_t folder_reserve = 0, data_reserve = 0;
+ if (flags & 0x4) {
+ if (at + 4 > cabinet.size()) return fail("damaged cabinet");
+ const auto header_reserve = U16(cabinet, at);
+ folder_reserve = static_cast<unsigned char>(cabinet[at + 2]);
+ data_reserve = static_cast<unsigned char>(cabinet[at + 3]);
+ at += 4 + header_reserve;
+ }
+ struct Folder {
+ std::uint32_t data_offset;
+ std::uint16_t blocks;
+ std::uint16_t compression;
+ };
+ std::vector<Folder> folders;
+ for (std::size_t index = 0; index < folder_count; ++index, at += 8 + folder_reserve) {
+ if (at + 8 > cabinet.size()) return fail("damaged cabinet");
+ folders.push_back({U32(cabinet, at), U16(cabinet, at + 4), U16(cabinet, at + 6)});
+ }
+ struct Member {
+ std::string name;
+ std::uint32_t size, offset;
+ std::uint16_t folder;
+ };
+ std::vector<Member> members;
+ at = files_offset;
+ for (std::size_t index = 0; index < file_count; ++index) {
+ if (at + 16 > cabinet.size()) return fail("damaged cabinet");
+ Member member{{}, U32(cabinet, at), U32(cabinet, at + 4), U16(cabinet, at + 8)};
+ const auto end = cabinet.find('\0', at + 16);
+ if (end == std::string_view::npos) return fail("damaged cabinet");
+ member.name = std::string(cabinet.substr(at + 16, end - at - 16));
+ at = end + 1;
+ if (member.folder >= folders.size()) return fail("cabinets that continue into another one are not supported");
+ members.push_back(std::move(member));
+ }
+ // Each folder is one stream; MSZIP blocks are deflate streams that may refer back into the
+ // previous block's 32 KiB, so that history stays in front of each block's output.
+ constexpr std::size_t kWindow = 32768;
+ auto buffer = std::make_unique<unsigned char[]>(kWindow * 2 + 6144);
+ auto decompressor = std::make_unique<tinfl_decompressor>();
+ for (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");
+ std::vector<const Member*> wanted;
+ for (const auto& member : members)
+ if (member.folder == folder_index) wanted.push_back(&member);
+ std::sort(wanted.begin(), wanted.end(), [](const Member* a, const Member* b) { return a->offset < b->offset; });
+ std::size_t next = 0;
+ std::string current; // the member being collected
+ std::uint64_t position = 0; // bytes of the folder produced so far
+ std::size_t history = 0;
+ std::size_t block_at = folder.data_offset;
+ const auto deliver = [&](const unsigned char* bytes, std::size_t length) {
+ for (std::size_t used = 0; used < length;) {
+ while (next < wanted.size() && wanted[next]->size == 0 && wanted[next]->offset <= position) {
+ if (!sink(wanted[next]->name, std::string_view())) return false;
+ ++next;
+ }
+ if (next >= wanted.size()) return true;
+ const auto* member = wanted[next];
+ if (position + (length - used) <= member->offset) {
+ position += length - used;
+ return true;
+ }
+ if (position < member->offset) {
+ const auto skip = static_cast<std::size_t>(member->offset - position);
+ used += skip;
+ position += skip;
+ }
+ const auto want = static_cast<std::size_t>(member->size - current.size());
+ const auto take = std::min(want, length - used);
+ current.append(reinterpret_cast<const char*>(bytes + used), take);
+ used += take;
+ position += take;
+ if (current.size() == member->size) {
+ if (!sink(member->name, current)) return false;
+ current.clear();
+ ++next;
+ }
+ }
+ return true;
+ };
+ 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");
+ const auto* input = reinterpret_cast<const unsigned char*>(cabinet.data() + data_at);
+ unsigned char* output = buffer.get() + history;
+ if (kind == 0) {
+ if (packed != unpacked) return fail("damaged cabinet");
+ std::memcpy(output, input, unpacked);
+ } else {
+ if (packed < 2 || input[0] != 'C' || input[1] != 'K') return fail("damaged MSZIP block");
+ tinfl_init(decompressor.get());
+ std::size_t in_size = packed - 2u, out_size = unpacked;
+ const auto status = tinfl_decompress(decompressor.get(), input + 2, &in_size, buffer.get(), output, &out_size,
+ TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF);
+ if (status != TINFL_STATUS_DONE || out_size != unpacked) return fail("damaged MSZIP block");
+ }
+ if (!deliver(output, unpacked)) return fail("extraction stopped");
+ const auto total = history + unpacked;
+ history = std::min(total, kWindow);
+ std::memmove(buffer.get(), buffer.get() + total - history, history);
+ block_at = data_at + packed;
+ }
+ // Empty members at the folder's end.
+ for (; next < wanted.size() && wanted[next]->size == 0 && wanted[next]->offset <= position; ++next)
+ if (!sink(wanted[next]->name, std::string_view())) return fail("extraction stopped");
+ if (next < wanted.size()) return fail("damaged cabinet: files run past their folder");
+ }
+ return true;
+}
+
+} // namespace playden::runtime
diff --git a/src/runtime/msi_package.h b/src/runtime/msi_package.h
new file mode 100644
index 0000000..252c4f5
--- /dev/null
+++ b/src/runtime/msi_package.h
@@ -0,0 +1,69 @@
+#pragma once
+
+#include "runtime/game_settings.h"
+
+#include <cstdint>
+#include <functional>
+#include <map>
+#include <optional>
+#include <string>
+#include <string_view>
+#include <vector>
+
+namespace playden::runtime {
+
+// A Windows Installer package (.msi) read the way `msiexec /i <package> /quiet` would install it
+// for all users on 64-bit Windows 7, without running anything: the console can't start the
+// installer, so Playden copies the package's files and writes its registry and PATH values into
+// the bottle itself (runtime/redist_install.h). Custom actions, UI, patches and self-registration
+// are not run. Paths are relative to the bottle's drive_c with '/' separators.
+
+// One file the package installs, taken from cabinet `cabinet` by its member name (File.File).
+struct MsiFile {
+ std::string target; // e.g. "Program Files (x86)/NVIDIA Corporation/PhysX/Common/PhysXLoader.dll"
+ std::string member; // the cabinet member name
+ std::size_t cabinet = 0; // index into MsiInstallPlan::cabinets
+ std::uint32_t size = 0;
+};
+
+// A cabinet holding files: a stream in the package ("#name" in the Media table) or a file
+// beside it.
+struct MsiCabinet {
+ std::string name;
+ bool embedded = false;
+};
+
+struct MsiInstallPlan {
+ std::string product_code;
+ std::string product_name;
+ std::string product_version;
+ std::vector<MsiCabinet> cabinets;
+ std::vector<MsiFile> files;
+ std::vector<RegistryValue> machine; // system.reg (HKEY_LOCAL_MACHINE)
+ std::vector<RegistryValue> user; // user.reg (HKEY_CURRENT_USER)
+ // Folders (Windows paths) the package adds to the machine-wide PATH.
+ std::vector<std::string> path_prepend;
+ std::vector<std::string> path_append;
+ std::size_t skipped_files = 0; // under a folder this reader doesn't place, or uncompressed
+ std::size_t skipped_registry = 0; // binary or multi-string values, HKEY_USERS
+ std::size_t custom_actions = 0; // not run
+};
+
+// Reads a package. false with a reason for a file that is not a readable package; a package
+// whose files sit uncompressed beside it is read, with those files counted in skipped_files.
+bool ReadMsiPackage(std::string_view package, MsiInstallPlan* plan, std::string* reason);
+
+// 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),
+// 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,
+ std::string* reason);
+
+// Evaluates a Windows Installer condition ("VersionNT64", "NOT Installed AND (A = 1)") against
+// properties; missing properties are empty. nullopt when the text can't be parsed.
+std::optional<bool> EvaluateMsiCondition(std::string_view condition, const std::map<std::string, std::string>& properties);
+
+} // namespace playden::runtime
diff --git a/src/runtime/redist_install.cpp b/src/runtime/redist_install.cpp
new file mode 100644
index 0000000..55d6025
--- /dev/null
+++ b/src/runtime/redist_install.cpp
@@ -0,0 +1,441 @@
+#include "runtime/redist_install.h"
+
+#include "platform/managed_directory.h"
+#include "runtime/artifact_hash.h"
+#include "runtime/game_settings.h"
+#include "runtime/msi_package.h"
+
+#include <algorithm>
+#include <cerrno>
+#include <chrono>
+#include <fcntl.h>
+#include <filesystem>
+#include <map>
+#include <set>
+#include <unistd.h>
+
+namespace playden::runtime {
+namespace {
+
+using platform::DirectoryPolicy;
+using platform::ManagedDirectory;
+
+constexpr std::size_t kMaxPackageBytes = 256u * 1024u * 1024u;
+constexpr std::size_t kMaxScripts = 32;
+constexpr int kMaxDepth = 4;
+constexpr const char* kStateFile = ".playden-redist";
+constexpr const char* kEnvironmentKey = "System\\CurrentControlSet\\Control\\Session Manager\\Environment";
+
+std::string Lower(std::string_view text) {
+ std::string out(text);
+ std::transform(out.begin(), out.end(), out.begin(),
+ [](unsigned char value) { return static_cast<char>(value >= 'A' && value <= 'Z' ? value + 32 : value); });
+ return out;
+}
+
+bool ReadFile(const std::filesystem::path& path, std::size_t maximum, std::string* text) {
+ text->clear();
+ const int file = ::open(path.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
+ if (file < 0) return false;
+ bool ok = true;
+ // Large packages: read straight into the string, not through a stack buffer (small worker stacks).
+ for (std::size_t chunk = 1u << 20;;) {
+ const auto size = text->size();
+ text->resize(size + chunk);
+ const auto count = ::read(file, &(*text)[size], chunk);
+ if (count < 0 && errno == EINTR) {
+ text->resize(size);
+ continue;
+ }
+ if (count < 0) { ok = false; text->resize(size); break; }
+ text->resize(size + static_cast<std::size_t>(count));
+ if (count == 0) break;
+ if (text->size() > maximum) { ok = false; break; }
+ }
+ ::close(file);
+ return ok;
+}
+
+// Folders where Steam games keep their redistributables, looked into below the game's top level.
+bool RedistFolder(const std::string& name) {
+ static const std::set<std::string> kNames = {
+ "_commonredist", "commonredist", "redist", "redists", "_redist", "redistributables", "redistributable",
+ "support", "__installer", "_installer", "installer", "installers", "prerequisites", "prereqs", "physx",
+ "directx", "vcredist", "dotnet"};
+ return kNames.count(Lower(name)) != 0;
+}
+
+bool ScriptName(const std::string& name) {
+ const auto lower = Lower(name);
+ return lower.rfind("installscript", 0) == 0 && lower.size() > 4 && lower.compare(lower.size() - 4, 4, ".vdf") == 0;
+}
+
+void FindScripts(const std::filesystem::path& folder, const std::string& relative, int depth,
+ std::vector<std::string>* scripts) {
+ std::error_code error;
+ std::vector<std::pair<std::string, bool>> children;
+ for (std::filesystem::directory_iterator it(folder, error), end; !error && it != end; it.increment(error)) {
+ std::error_code type_error;
+ if (it->is_symlink(type_error)) continue;
+ children.emplace_back(it->path().filename().string(), it->is_directory(type_error));
+ }
+ std::sort(children.begin(), children.end());
+ for (const auto& [name, directory] : children) {
+ if (scripts->size() >= kMaxScripts) return;
+ const auto path = relative.empty() ? name : relative + "/" + name;
+ if (!directory && ScriptName(name) && depth > 0) scripts->push_back(path);
+ else if (directory && depth < kMaxDepth && (depth > 0 || RedistFolder(name)))
+ FindScripts(folder / name, path, depth + 1, scripts);
+ }
+}
+
+// Splits a command line into arguments (double quotes group, as Windows does for msiexec).
+std::vector<std::string> Arguments(std::string_view command) {
+ std::vector<std::string> out;
+ std::string current;
+ bool quoted = false, any = false;
+ for (const char value : command) {
+ if (value == '"') {
+ quoted = !quoted;
+ any = true;
+ } else if ((value == ' ' || value == '\t') && !quoted) {
+ if (any) out.push_back(current);
+ current.clear();
+ any = false;
+ } else {
+ current += value;
+ any = true;
+ }
+ }
+ if (any) out.push_back(current);
+ return out;
+}
+
+std::string FileName(std::string path) {
+ std::replace(path.begin(), path.end(), '/', '\\');
+ const auto slash = path.rfind('\\');
+ return Lower(slash == std::string::npos ? path : path.substr(slash + 1));
+}
+
+// A Windows path inside the game folder, relative to it with '/' separators.
+bool InsideGame(const std::string& windows_path, const std::string& install_dir, std::string* relative) {
+ auto base = install_dir;
+ while (!base.empty() && base.back() == '\\') base.pop_back();
+ if (windows_path.size() <= base.size() + 1 || Lower(windows_path.substr(0, base.size())) != Lower(base) ||
+ windows_path[base.size()] != '\\')
+ return false;
+ auto rest = windows_path.substr(base.size() + 1);
+ std::replace(rest.begin(), rest.end(), '\\', '/');
+ if (rest.empty() || rest.find("..") != std::string::npos) return false;
+ *relative = rest;
+ return true;
+}
+
+// Opens (creating when asked) a folder below root, matching existing names without regard to
+// case as Windows does, so a package's "Program Files (x86)" lands in the bottle's own.
+std::optional<ManagedDirectory> OpenPath(const std::filesystem::path& root, const std::string& relative, bool create) {
+ auto directory = ManagedDirectory::Open(root, DirectoryPolicy::kApprovedTree);
+ if (!directory) return std::nullopt;
+ for (std::size_t start = 0; start < relative.size();) {
+ const auto slash = relative.find('/', start);
+ auto name = relative.substr(start, slash == std::string::npos ? std::string::npos : slash - start);
+ start = slash == std::string::npos ? relative.size() : slash + 1;
+ if (name.empty()) continue;
+ std::error_code error;
+ for (std::filesystem::directory_iterator it(directory->path(), error), end; !error && it != end; it.increment(error)) {
+ const auto existing = it->path().filename().string();
+ if (Lower(existing) == Lower(name)) {
+ name = existing;
+ break;
+ }
+ }
+ auto next = directory->OpenChild(name, DirectoryPolicy::kApprovedTree, create);
+ if (!next) return std::nullopt;
+ directory = std::move(next);
+ }
+ return directory;
+}
+
+bool WriteFileAt(const ManagedDirectory& directory, const std::string& name, std::string_view data) {
+ struct stat existing {};
+ std::string target = name;
+ if (!directory.InspectChild(name, &existing)) {
+ if (errno != ENOENT) return false;
+ // Reuse a differently cased file of the same name rather than adding a second one.
+ std::error_code error;
+ for (std::filesystem::directory_iterator it(directory.path(), error), end; !error && it != end; it.increment(error))
+ if (Lower(it->path().filename().string()) == Lower(name)) target = it->path().filename().string();
+ } else if (!S_ISREG(existing.st_mode)) {
+ return false;
+ }
+ const auto temporary = target + ".playden-tmp-" + std::to_string(static_cast<long long>(::getpid())) + "-" +
+ std::to_string(static_cast<long long>(std::chrono::steady_clock::now().time_since_epoch().count()));
+ const int file = directory.CreateExclusiveFile(temporary, 0644);
+ if (file < 0) return false;
+ std::size_t written = 0;
+ while (written < data.size()) {
+ const auto count = ::write(file, data.data() + written, data.size() - written);
+ if (count < 0 && errno == EINTR) continue;
+ if (count <= 0) break;
+ written += static_cast<std::size_t>(count);
+ }
+ const bool closed = ::close(file) == 0;
+ if (written != data.size() || !closed || !directory.RenameChild(temporary, directory, target, true)) {
+ directory.RemoveRegularFile(temporary);
+ return false;
+ }
+ return true;
+}
+
+// The machine PATH as system.reg holds it (REG_EXPAND_SZ, Wine's text form), or Wine's default.
+std::string MachinePath(const std::filesystem::path& prefix) {
+ static const std::string kDefault =
+ "%SystemRoot%\\system32;%SystemRoot%;%SystemRoot%\\system32\\wbem;%SystemRoot%\\system32\\WindowsPowershell\\v1.0";
+ std::string text;
+ if (!ReadFile(prefix / "system.reg", 64u * 1024u * 1024u, &text)) return kDefault;
+ const auto header = Lower("[System\\\\CurrentControlSet\\\\Control\\\\Session Manager\\\\Environment]");
+ const auto lower = Lower(text);
+ auto at = lower.find(header);
+ if (at == std::string::npos) return kDefault;
+ const auto section_end = lower.find("\n[", at + 1);
+ at = lower.find("\n\"path\"=", at);
+ if (at == std::string::npos || (section_end != std::string::npos && at > section_end)) return kDefault;
+ at = text.find('=', at) + 1;
+ if (text.compare(at, 7, "str(2):") == 0) at += 7;
+ if (at >= text.size() || text[at] != '"') return kDefault;
+ std::string value;
+ for (++at; at < text.size() && text[at] != '"' && text[at] != '\n'; ++at) {
+ if (text[at] == '\\' && at + 1 < text.size()) ++at;
+ value += text[at];
+ }
+ return value;
+}
+
+std::string WineString(std::string_view text) {
+ std::string out = "\"";
+ for (const char value : text) {
+ if (value == '\\' || value == '"') out += '\\';
+ out += value;
+ }
+ return out + "\"";
+}
+
+std::map<std::string, std::string> InstalledPackages(const std::filesystem::path& prefix) {
+ std::map<std::string, std::string> out;
+ std::string text;
+ if (!ReadFile(prefix / kStateFile, 1024 * 1024, &text)) return out;
+ for (std::size_t at = 0; at < text.size();) {
+ auto end = text.find('\n', at);
+ if (end == std::string::npos) end = text.size();
+ const auto line = text.substr(at, end - at);
+ at = end + 1;
+ const auto space = line.find(' ');
+ if (space == 64) out[line.substr(0, space)] = line.substr(space + 1);
+ }
+ return out;
+}
+
+bool RecordPackage(const std::filesystem::path& prefix, const std::string& sha256, const std::string& package) {
+ auto packages = InstalledPackages(prefix);
+ packages[sha256] = package;
+ std::string text;
+ for (const auto& [hash, name] : packages) text += hash + " " + name + "\n";
+ auto directory = ManagedDirectory::Open(prefix, DirectoryPolicy::kApprovedTree);
+ return directory && WriteFileAt(*directory, kStateFile, text);
+}
+
+// Installs one package; returns the number of files written, or a reason in *reason.
+bool InstallPackage(const std::filesystem::path& package_path, const std::filesystem::path& prefix,
+ const RedistEntry& entry, std::int64_t unix_time, std::size_t* files, std::string* reason) {
+ std::string package;
+ if (!ReadFile(package_path, kMaxPackageBytes, &package)) {
+ *reason = "the package could not be read";
+ return false;
+ }
+ MsiInstallPlan plan;
+ if (!ReadMsiPackage(package, &plan, reason)) return false;
+ std::map<std::string, std::vector<const MsiFile*>> wanted; // member → files
+ for (const auto& file : plan.files) wanted[file.member].push_back(&file);
+ const auto drive = prefix / "drive_c";
+ for (std::size_t index = 0; index < plan.cabinets.size(); ++index) {
+ const auto& cabinet = plan.cabinets[index];
+ std::string bytes;
+ if (cabinet.embedded) {
+ auto stream = ReadMsiStream(package, cabinet.name);
+ if (!stream) {
+ *reason = "the package's cabinet " + cabinet.name + " is missing";
+ return false;
+ }
+ bytes = std::move(*stream);
+ } else if (cabinet.name.find('/') != std::string::npos || cabinet.name.find('\\') != std::string::npos ||
+ !ReadFile(package_path.parent_path() / cabinet.name, kMaxPackageBytes, &bytes)) {
+ *reason = "the cabinet " + cabinet.name + " beside the package could not be read";
+ return false;
+ }
+ std::string failure;
+ const bool ok = ExtractCabinet(bytes, [&](const std::string& member, std::string_view data) {
+ const auto found = wanted.find(member);
+ if (found == wanted.end()) return true;
+ for (const auto* file : found->second) {
+ if (file->cabinet != index) continue;
+ const auto slash = file->target.rfind('/');
+ const auto folder = slash == std::string::npos ? std::string() : file->target.substr(0, slash);
+ const auto name = slash == std::string::npos ? file->target : file->target.substr(slash + 1);
+ const auto directory = OpenPath(drive, folder, true);
+ if (!directory || !WriteFileAt(*directory, name, data)) {
+ failure = "could not write C:\\" + file->target;
+ return false;
+ }
+ ++*files;
+ }
+ return true;
+ }, reason);
+ if (!ok) {
+ if (!failure.empty()) *reason = failure;
+ return false;
+ }
+ }
+ auto machine = plan.machine;
+ if (!plan.path_prepend.empty() || !plan.path_append.empty()) {
+ const auto current = MachinePath(prefix);
+ const auto extended = ExtendPath(current, plan.path_prepend, plan.path_append);
+ if (extended != current) machine.push_back({kEnvironmentKey, "PATH", "str(2):" + WineString(extended)});
+ }
+ // Steam marks the entry as run under its HasRunKey (a DWORD named after the entry).
+ const auto run_key = Lower(entry.has_run_key);
+ if (run_key.rfind("hkey_local_machine\\software\\", 0) == 0 && run_key.rfind("hkey_local_machine\\software\\wow6432node\\", 0) != 0)
+ machine.push_back({"Software\\Wow6432Node\\" + entry.has_run_key.substr(28), entry.name, "dword:00000001"});
+ for (const auto& [hive, values] : {std::pair<const char*, const std::vector<RegistryValue>*>{"system.reg", &machine},
+ std::pair<const char*, const std::vector<RegistryValue>*>{"user.reg", &plan.user}}) {
+ if (!values->empty() && !ApplyBottleRegistryValues(*values, prefix.string(), unix_time, hive, reason)) return false;
+ }
+ return true;
+}
+
+} // namespace
+
+RedistAction ClassifyRedist(const RedistEntry& entry, const std::string& install_dir, std::string* package) {
+ const auto program = FileName(entry.process);
+ if (program == "msiexec" || program == "msiexec.exe") {
+ const auto arguments = Arguments(entry.command);
+ for (std::size_t index = 0; index + 1 < arguments.size(); ++index) {
+ const auto flag = Lower(arguments[index]);
+ if ((flag == "/i" || flag == "-i" || flag == "/package" || flag == "-package") &&
+ Lower(arguments[index + 1]).size() > 4 &&
+ Lower(arguments[index + 1]).compare(arguments[index + 1].size() - 4, 4, ".msi") == 0 &&
+ InsideGame(arguments[index + 1], install_dir, package))
+ return RedistAction::kMsi;
+ }
+ return RedistAction::kNotRun;
+ }
+ if (program.size() > 4 && program.compare(program.size() - 4, 4, ".msi") == 0 &&
+ InsideGame(entry.process, install_dir, package))
+ return RedistAction::kMsi;
+ // Installers whose DLLs and frameworks Wine and the kit already provide.
+ static constexpr const char* kCovered[] = {"vcredist", "vc_redist", "dxsetup", "dxwebsetup", "d3d11install",
+ "dotnetfx", "dotnetfx35", "ndp", "netfx", "xnafx"};
+ for (const auto* prefix : kCovered)
+ if (program.rfind(prefix, 0) == 0) return RedistAction::kCovered;
+ return RedistAction::kNotRun;
+}
+
+std::string ExtendPath(const std::string& current, const std::vector<std::string>& prepend,
+ const std::vector<std::string>& append) {
+ std::vector<std::string> entries;
+ for (std::size_t at = 0; at <= current.size();) {
+ auto end = current.find(';', at);
+ if (end == std::string::npos) end = current.size();
+ if (end > at) entries.push_back(current.substr(at, end - at));
+ at = end + 1;
+ }
+ const auto listed = [&](const std::string& folder) {
+ auto wanted = Lower(folder);
+ while (!wanted.empty() && wanted.back() == '\\') wanted.pop_back();
+ return std::any_of(entries.begin(), entries.end(), [&](const std::string& existing) {
+ auto have = Lower(existing);
+ while (!have.empty() && have.back() == '\\') have.pop_back();
+ return have == wanted;
+ });
+ };
+ std::vector<std::string> front;
+ for (const auto& folder : prepend)
+ if (!listed(folder)) front.push_back(folder);
+ entries.insert(entries.begin(), front.begin(), front.end());
+ for (const auto& folder : append)
+ if (!listed(folder)) entries.push_back(folder);
+ std::string out;
+ for (const auto& folder : entries) out += (out.empty() ? "" : ";") + folder;
+ return out;
+}
+
+RedistInstallResult InstallRedistributables(const std::string& game_root, const std::string& install_dir,
+ const std::string& prefix_dir, std::int64_t unix_time) {
+ RedistInstallResult result;
+ std::vector<std::string> scripts;
+ {
+ // The top level first (its scripts' registry values are ApplyInstallScripts' job too).
+ std::error_code error;
+ std::vector<std::string> top;
+ for (std::filesystem::directory_iterator it(game_root, error), end; !error && it != end; it.increment(error)) {
+ std::error_code type_error;
+ if (ScriptName(it->path().filename().string()) && it->is_regular_file(type_error) && !it->is_symlink(type_error))
+ top.push_back(it->path().filename().string());
+ }
+ std::sort(top.begin(), top.end());
+ scripts = top;
+ FindScripts(game_root, std::string(), 0, &scripts);
+ if (scripts.size() > kMaxScripts) scripts.resize(kMaxScripts);
+ }
+ const std::filesystem::path prefix(prefix_dir);
+ auto installed = InstalledPackages(prefix);
+ std::set<std::string> seen; // a package two scripts run is installed once
+ for (const auto& script : scripts) {
+ std::string text, reason;
+ std::vector<RedistEntry> entries;
+ if (!ReadInstallScript((std::filesystem::path(game_root) / script).string(), &text) ||
+ !ParseRunProcess(text, install_dir, &entries, &reason))
+ continue;
+ for (const auto& entry : entries) {
+ RedistOutcome outcome;
+ outcome.script = script;
+ outcome.name = entry.name;
+ std::string package;
+ const auto action = ClassifyRedist(entry, install_dir, &package);
+ if (action != RedistAction::kMsi) {
+ outcome.result = action == RedistAction::kCovered ? "covered" : "not-run";
+ outcome.detail = FileName(entry.process);
+ result.outcomes.push_back(std::move(outcome));
+ continue;
+ }
+ outcome.detail = package;
+ const auto path = std::filesystem::path(game_root) / package;
+ const auto hash = HashArtifactFile(path);
+ if (!hash) {
+ outcome.result = "failed";
+ outcome.detail = package + ": the package could not be read";
+ result.outcomes.push_back(std::move(outcome));
+ continue;
+ }
+ if (installed.count(*hash) || !seen.insert(*hash).second) {
+ outcome.result = "already";
+ result.outcomes.push_back(std::move(outcome));
+ continue;
+ }
+ std::string failure;
+ if (!InstallPackage(path, prefix, entry, unix_time, &outcome.files, &failure)) {
+ outcome.result = "failed";
+ outcome.detail = package + ": " + failure;
+ } else if (!RecordPackage(prefix, *hash, package)) {
+ outcome.result = "failed";
+ outcome.detail = package + ": installed, but could not be recorded";
+ } else {
+ outcome.result = "installed";
+ installed[*hash] = package;
+ }
+ result.outcomes.push_back(std::move(outcome));
+ }
+ }
+ return result;
+}
+
+} // namespace playden::runtime
diff --git a/src/runtime/redist_install.h b/src/runtime/redist_install.h
new file mode 100644
index 0000000..4ab1619
--- /dev/null
+++ b/src/runtime/redist_install.h
@@ -0,0 +1,48 @@
+#pragma once
+
+#include "runtime/install_script.h"
+
+#include <cstdint>
+#include <string>
+#include <string_view>
+#include <vector>
+
+namespace playden::runtime {
+
+// Redistributables a game's Steam install scripts run on its first start ("Run Process"
+// entries: PhysX, Visual C++, DirectX, .NET). The console can't start their installers, so:
+// Windows Installer packages are installed by Playden itself (runtime/msi_package.h), installers
+// whose DLLs Wine provides are skipped, and other programs are skipped and logged.
+
+enum class RedistAction { kMsi, kCovered, kNotRun };
+
+// What Playden does with an entry. For kMsi, package is the package's path inside the game
+// folder ('/' separators), found from `msiexec /i <package>` or a process that is the package.
+RedistAction ClassifyRedist(const RedistEntry& entry, const std::string& install_dir, std::string* package);
+
+struct RedistOutcome {
+ std::string script; // the install script, relative to the game folder
+ std::string name;
+ std::string result; // "installed", "already", "covered", "not-run", "failed"
+ std::string detail; // the package, program or failure reason
+ std::size_t files = 0;
+};
+
+struct RedistInstallResult {
+ std::vector<RedistOutcome> outcomes;
+};
+
+// Finds install scripts at the top of game_root and in its redistributable folders
+// (_CommonRedist, Redist, Support, __Installer…, up to four folders deep), and installs their
+// Windows Installer packages into the stopped bottle at prefix_dir. A package installed before
+// (the same SHA-256, listed in <prefix>/.playden-redist) is not installed again. A package that
+// fails is reported and left out; the others still install.
+RedistInstallResult InstallRedistributables(const std::string& game_root, const std::string& install_dir,
+ const std::string& prefix_dir, std::int64_t unix_time);
+
+// Adds folders to a PATH value: prepend in order before the existing entries, append after
+// them, each only when not already listed (case-insensitive).
+std::string ExtendPath(const std::string& current, const std::vector<std::string>& prepend,
+ const std::vector<std::string>& append);
+
+} // namespace playden::runtime
diff --git a/tests/runtime_redist_test.cpp b/tests/runtime_redist_test.cpp
new file mode 100644
index 0000000..56ba060
--- /dev/null
+++ b/tests/runtime_redist_test.cpp
@@ -0,0 +1,580 @@
+#include "runtime/install_script.h"
+#include "runtime/msi_package.h"
+#include "runtime/redist_install.h"
+
+#include <algorithm>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <filesystem>
+#include <fstream>
+#include <iterator>
+#include <map>
+#include <string>
+#include <unistd.h>
+#include <vector>
+
+#define CHECK(cond) \
+ do { \
+ if (!(cond)) { \
+ std::fprintf(stderr, "%s:%d: CHECK failed: %s\n", __FILE__, __LINE__, #cond); \
+ std::exit(1); \
+ } \
+ } while (0)
+
+using namespace playden::runtime;
+
+namespace {
+
+void Put16(std::string* out, unsigned value) {
+ out->push_back(static_cast<char>(value & 0xff));
+ out->push_back(static_cast<char>((value >> 8) & 0xff));
+}
+
+void Put32(std::string* out, std::uint32_t value) {
+ Put16(out, value & 0xffff);
+ Put16(out, value >> 16);
+}
+
+// Deflate bits, least significant first; Huffman codes go in most significant bit first.
+struct Bits {
+ std::string bytes;
+ unsigned current = 0, count = 0;
+ void Put(unsigned value, unsigned width) {
+ for (unsigned bit = 0; bit < width; ++bit) Push((value >> bit) & 1);
+ }
+ void Code(unsigned value, unsigned width) {
+ for (unsigned bit = width; bit-- > 0;) Push((value >> bit) & 1);
+ }
+ void Push(unsigned bit) {
+ current |= bit << count;
+ if (++count == 8) Flush();
+ }
+ void Flush() {
+ if (count) bytes.push_back(static_cast<char>(current));
+ current = count = 0;
+ }
+};
+
+// A cabinet with one MSZIP folder of two blocks: a stored block "0123456789", then a fixed
+// Huffman block that copies those ten bytes back (length 10, distance 10) — only right when
+// the second block sees the first one's output. Members: "first" (block 1), "second" (block 2),
+// "empty" (no bytes).
+std::string TwoBlockCabinet() {
+ std::string block1 = "CK";
+ {
+ Bits bits;
+ bits.Put(1, 1); // final
+ bits.Put(0, 2); // stored
+ bits.Flush();
+ block1 += bits.bytes;
+ Put16(&block1, 10);
+ Put16(&block1, 0xffff ^ 10);
+ block1 += "0123456789";
+ }
+ std::string block2 = "CK";
+ {
+ Bits bits;
+ bits.Put(1, 1); // final
+ bits.Put(1, 2); // fixed Huffman
+ bits.Code(264 - 256, 7); // length 10
+ bits.Code(6, 5); // distance 9-12
+ bits.Put(1, 2); // + 1 = 10
+ bits.Code(0, 7); // end of block
+ bits.Flush();
+ block2 += bits.bytes;
+ }
+ struct Member { const char* name; std::uint32_t size, offset; };
+ const Member members[] = {{"first", 10, 0}, {"second", 10, 10}, {"empty", 0, 20}};
+ std::string files;
+ for (const auto& member : members) {
+ Put32(&files, member.size);
+ Put32(&files, member.offset);
+ Put16(&files, 0); // folder
+ Put16(&files, 0);
+ Put16(&files, 0);
+ Put16(&files, 0x20);
+ files += member.name;
+ files.push_back('\0');
+ }
+ const std::uint32_t header = 36, folder = 8;
+ const std::uint32_t files_at = header + folder;
+ const std::uint32_t data_at = files_at + static_cast<std::uint32_t>(files.size());
+ std::string data;
+ for (const auto* block : {&block1, &block2}) {
+ Put32(&data, 0);
+ Put16(&data, static_cast<unsigned>(block->size()));
+ Put16(&data, 10);
+ data += *block;
+ }
+ 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, 3); // files
+ Put16(&cabinet, 0); // flags
+ Put16(&cabinet, 0);
+ Put16(&cabinet, 0);
+ Put32(&cabinet, data_at);
+ Put16(&cabinet, 2); // blocks
+ Put16(&cabinet, 1); // MSZIP
+ return cabinet + files + data;
+}
+
+// ---------------------------------------------------------------------------------------------
+// A minimal Windows Installer package: a compound file (512-byte sectors, every stream in
+// ordinary sectors) holding the string pool, _Columns and a few tables.
+
+std::vector<std::uint16_t> EncodeStreamName(const std::string& name) {
+ static const std::string kAlphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz._";
+ std::vector<std::uint16_t> out;
+ std::size_t at = 0;
+ if (!name.empty() && name[0] == '!') {
+ out.push_back(0x4840);
+ at = 1;
+ }
+ while (at < name.size()) {
+ const auto first = kAlphabet.find(name[at]);
+ if (first == std::string::npos) {
+ out.push_back(static_cast<unsigned char>(name[at++]));
+ continue;
+ }
+ const auto second = at + 1 < name.size() ? kAlphabet.find(name[at + 1]) : std::string::npos;
+ if (second != std::string::npos) {
+ out.push_back(static_cast<std::uint16_t>(0x3800 + first + (second << 6)));
+ at += 2;
+ } else {
+ out.push_back(static_cast<std::uint16_t>(0x4800 + first));
+ ++at;
+ }
+ }
+ return out;
+}
+
+std::string CompoundFile(const std::vector<std::pair<std::string, std::string>>& streams) {
+ constexpr std::uint32_t kSector = 512, kEnd = 0xfffffffe, kFree = 0xffffffff;
+ std::vector<std::uint32_t> stream_sectors;
+ std::uint32_t data_sectors = 0;
+ for (const auto& stream : streams) {
+ const auto count = static_cast<std::uint32_t>((stream.second.size() + kSector - 1) / kSector);
+ stream_sectors.push_back(count);
+ data_sectors += count;
+ }
+ const auto directory_sectors = static_cast<std::uint32_t>(((streams.size() + 1) * 128 + kSector - 1) / kSector);
+ std::uint32_t fat_sectors = 1;
+ while (fat_sectors * (kSector / 4) < fat_sectors + directory_sectors + data_sectors) ++fat_sectors;
+ const std::uint32_t total = fat_sectors + directory_sectors + data_sectors;
+ std::vector<std::uint32_t> fat(fat_sectors * (kSector / 4), kFree);
+ for (std::uint32_t index = 0; index < fat_sectors; ++index) fat[index] = 0xfffffffd;
+ const auto chain = [&](std::uint32_t first, std::uint32_t count) {
+ for (std::uint32_t index = 0; index < count; ++index) fat[first + index] = index + 1 < count ? first + index + 1 : kEnd;
+ };
+ chain(fat_sectors, directory_sectors);
+ std::string directory;
+ const auto entry = [&](const std::vector<std::uint16_t>& name, int type, std::uint32_t start, std::uint32_t size) {
+ std::string out;
+ for (const auto unit : name) Put16(&out, unit);
+ out.resize(64, '\0');
+ Put16(&out, static_cast<unsigned>((name.size() + 1) * 2));
+ out.push_back(static_cast<char>(type));
+ out.push_back(1);
+ Put32(&out, 0xffffffff);
+ Put32(&out, 0xffffffff);
+ Put32(&out, type == 5 ? 1 : 0xffffffff);
+ out.resize(0x74, '\0');
+ Put32(&out, start);
+ Put32(&out, size);
+ Put32(&out, 0);
+ directory += out;
+ };
+ entry({'R', 'o', 'o', 't', ' ', 'E', 'n', 't', 'r', 'y'}, 5, kEnd, 0);
+ std::uint32_t next = fat_sectors + directory_sectors;
+ std::string body;
+ for (std::size_t index = 0; index < streams.size(); ++index) {
+ const auto& [name, data] = streams[index];
+ entry(EncodeStreamName(name), 2, stream_sectors[index] ? next : kEnd, static_cast<std::uint32_t>(data.size()));
+ chain(next, stream_sectors[index]);
+ next += stream_sectors[index];
+ std::string padded = data;
+ padded.resize(stream_sectors[index] * kSector, '\0');
+ body += padded;
+ }
+ directory.resize(directory_sectors * kSector, '\0');
+ std::string header = "\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1";
+ header.resize(0x18, '\0');
+ Put16(&header, 0x3e);
+ Put16(&header, 3);
+ Put16(&header, 0xfffe);
+ Put16(&header, 9);
+ Put16(&header, 6);
+ header.resize(0x2c, '\0');
+ Put32(&header, fat_sectors);
+ Put32(&header, fat_sectors); // first directory sector
+ Put32(&header, 0);
+ Put32(&header, 0); // mini stream cutoff: nothing in the mini stream
+ Put32(&header, kEnd);
+ Put32(&header, 0);
+ Put32(&header, kEnd);
+ Put32(&header, 0);
+ for (std::uint32_t index = 0; index < 109; ++index) Put32(&header, index < fat_sectors ? index : kFree);
+ std::string fat_bytes;
+ for (const auto value : fat) Put32(&fat_bytes, value);
+ (void)total;
+ return header + fat_bytes + directory + body;
+}
+
+struct Column {
+ std::string name;
+ char kind; // 's' string, 'i' 2-byte integer, 'l' 4-byte integer
+};
+
+struct TableSpec {
+ std::string name;
+ std::vector<Column> columns;
+ std::vector<std::vector<std::string>> rows; // "" is null for strings; integers as text, "" null
+};
+
+std::string Package(const std::vector<TableSpec>& tables, const std::vector<std::pair<std::string, std::string>>& extra) {
+ std::vector<std::string> strings{""};
+ std::map<std::string, std::uint16_t> ids;
+ const auto id = [&](const std::string& text) -> std::uint16_t {
+ if (text.empty()) return 0;
+ const auto found = ids.find(text);
+ if (found != ids.end()) return found->second;
+ strings.push_back(text);
+ return ids[text] = static_cast<std::uint16_t>(strings.size() - 1);
+ };
+ std::vector<std::pair<std::string, std::string>> streams;
+ std::vector<std::string> column_table, column_name;
+ std::vector<unsigned> column_number, column_type;
+ for (const auto& table : tables) {
+ for (std::size_t index = 0; index < table.columns.size(); ++index) {
+ column_table.push_back(table.name);
+ column_name.push_back(table.columns[index].name);
+ column_number.push_back(static_cast<unsigned>(index + 1));
+ const char kind = table.columns[index].kind;
+ column_type.push_back(kind == 's' ? 0x1dff : kind == 'i' ? 0x1502 : 0x1104);
+ }
+ std::string data;
+ for (std::size_t column = 0; column < table.columns.size(); ++column) {
+ for (const auto& row : table.rows) {
+ const auto& cell = row[column];
+ const char kind = table.columns[column].kind;
+ if (kind == 's') Put16(&data, id(cell));
+ else if (kind == 'i') Put16(&data, cell.empty() ? 0 : static_cast<unsigned>(std::atoi(cell.c_str()) + 0x8000));
+ else Put32(&data, cell.empty() ? 0 : static_cast<std::uint32_t>(std::atoll(cell.c_str()) + 0x80000000ll));
+ }
+ }
+ streams.emplace_back("!" + table.name, data);
+ }
+ std::string columns;
+ for (const auto& name : column_table) Put16(&columns, id(name));
+ for (const auto number : column_number) Put16(&columns, number + 0x8000);
+ for (const auto& name : column_name) Put16(&columns, id(name));
+ for (const auto type : column_type) Put16(&columns, type | 0x8000);
+ streams.emplace_back("!_Columns", columns);
+ std::string pool, pool_data;
+ Put32(&pool, 1252);
+ for (std::size_t index = 1; index < strings.size(); ++index) {
+ Put16(&pool, static_cast<unsigned>(strings[index].size()));
+ Put16(&pool, 1);
+ pool_data += strings[index];
+ }
+ streams.emplace_back("!_StringPool", pool);
+ streams.emplace_back("!_StringData", pool_data);
+ for (const auto& stream : extra) streams.push_back(stream);
+ return CompoundFile(streams);
+}
+
+// A package like NVIDIA's legacy PhysX one: a 32-bit loader in Vendor\Common (added to PATH),
+// an engine in Vendor\Engine\v1 found through a registry value, a 64-bit feature turned on by
+// VersionNT64, a feature left off, and files in the two-block cabinet above.
+std::string SamplePackage() {
+ std::vector<TableSpec> tables;
+ tables.push_back({"Property", {{"Property", 's'}, {"Value", 's'}},
+ {{"ProductCode", "{11111111-2222-3333-4444-555555555555}"}, {"ProductName", "Sample Runtime"},
+ {"ProductVersion", "1.2.3"}, {"P_VERSION", "7"}}});
+ tables.push_back({"Directory", {{"Directory", 's'}, {"Directory_Parent", 's'}, {"DefaultDir", 's'}},
+ {{"TARGETDIR", "", "SourceDir"}, {"ProgramFilesFolder", "TARGETDIR", "."},
+ {"D_VENDOR", "ProgramFilesFolder", "vendor~1|Vendor Runtime"}, {"D_COMMON", "D_VENDOR", "Common"},
+ {"D_ENGINE", "D_VENDOR", "Engine"}, {"D_V1", "D_ENGINE", "v1~1|v1"},
+ {"D_DESKTOP", "DesktopFolder", "Sample"}}});
+ tables.push_back({"Feature", {{"Feature", 's'}, {"Feature_Parent", 's'}, {"Level", 'i'}},
+ {{"F_Main", "", "1"}, {"F_64", "", "0"}, {"F_Off", "", "0"}, {"F_Child", "F_Off", "1"}}});
+ tables.push_back({"Condition", {{"Feature_", 's'}, {"Level", 'i'}, {"Condition", 's'}},
+ {{"F_64", "1", "VersionNT64"}, {"F_Off", "1", "NOT VersionNT64"}}});
+ tables.push_back({"Component",
+ {{"Component", 's'}, {"ComponentId", 's'}, {"Directory_", 's'}, {"Attributes", 'i'}, {"Condition", 's'}, {"KeyPath", 's'}},
+ {{"C_LOADER", "{A}", "D_COMMON", "0", "", "F_LOADER"},
+ {"C_ENGINE", "{B}", "D_V1", "0", "VersionNT >= 501", "F_ENGINE"},
+ {"C_REG", "{C}", "D_COMMON", "4", "", ""},
+ {"C_REG64", "{D}", "D_COMMON", "260", "", ""},
+ {"C_ENV", "{E}", "D_COMMON", "0", "", ""},
+ {"C_OFF", "{F}", "D_COMMON", "0", "", "F_OFF"},
+ {"C_SHORTCUT", "{G}", "D_DESKTOP", "0", "", "F_EMPTY"}}});
+ tables.push_back({"FeatureComponents", {{"Feature_", 's'}, {"Component_", 's'}},
+ {{"F_Main", "C_LOADER"}, {"F_Main", "C_ENGINE"}, {"F_Main", "C_REG"}, {"F_64", "C_REG64"},
+ {"F_Main", "C_ENV"}, {"F_Child", "C_OFF"}, {"F_Main", "C_SHORTCUT"}}});
+ tables.push_back({"File",
+ {{"File", 's'}, {"Component_", 's'}, {"FileName", 's'}, {"FileSize", 'l'}, {"Version", 's'},
+ {"Language", 's'}, {"Attributes", 'i'}, {"Sequence", 'i'}},
+ {{"first", "C_LOADER", "loader~1.dll|Loader.dll", "10", "", "", "512", "1"},
+ {"second", "C_ENGINE", "Core.dll", "10", "", "", "512", "2"},
+ {"empty", "C_ENGINE", "Empty.dat", "0", "", "", "512", "3"},
+ {"off", "C_OFF", "Off.dll", "10", "", "", "512", "4"},
+ {"link", "C_SHORTCUT", "Link.txt", "0", "", "", "512", "5"}}});
+ tables.push_back({"Media", {{"DiskId", 'i'}, {"LastSequence", 'i'}, {"DiskPrompt", 's'}, {"Cabinet", 's'}},
+ {{"1", "5", "", "#data.cab"}}});
+ tables.push_back({"Registry",
+ {{"Registry", 's'}, {"Root", 'i'}, {"Key", 's'}, {"Name", 's'}, {"Value", 's'}, {"Component_", 's'}},
+ {{"r1", "2", "SOFTWARE\\Vendor", "Core Path", "[D_ENGINE]", "C_REG"},
+ {"r1b", "2", "SOFTWARE\\Vendor", "Core Path Short", "[D_VENDOR]Engine", "C_REG"},
+ {"r2", "2", "SOFTWARE\\Vendor", "Version", "#[P_VERSION]", "C_REG"},
+ {"r3", "2", "SOFTWARE\\Vendor", "Build", "#1", "C_REG64"},
+ {"r4", "2", "SOFTWARE\\Vendor", "+", "", "C_REG"},
+ {"r5", "2", "SOFTWARE\\Vendor", "Blob", "#x0102", "C_REG"},
+ {"r6", "2", "SOFTWARE\\Vendor\\Engines", "1.0", "#5", "C_ENGINE"},
+ {"r7", "1", "Software\\Vendor", "User", "[#first]", "C_REG"},
+ {"r8", "2", "SOFTWARE\\Vendor", "Hidden", "x", "C_OFF"}}});
+ tables.push_back({"Environment", {{"Environment", 's'}, {"Name", 's'}, {"Value", 's'}, {"Component_", 's'}},
+ {{"e1", "=-*PATH", "[D_COMMON];[~]", "C_ENV"}, {"e2", "=-*OTHER", "x", "C_ENV"}}});
+ tables.push_back({"CustomAction", {{"Action", 's'}, {"Type", 'i'}, {"Source", 's'}, {"Target", 's'}},
+ {{"CA1", "1", "Binary1", "Run"}}});
+ return Package(tables, {{"data.cab", TwoBlockCabinet()}});
+}
+
+const RegistryValue* FindValue(const std::vector<RegistryValue>& values, const std::string& key, const std::string& name) {
+ for (const auto& value : values)
+ if (value.key == key && value.name == name) return &value;
+ return nullptr;
+}
+
+std::string ReadText(const std::filesystem::path& path) {
+ std::ifstream input(path, std::ios::binary);
+ return std::string(std::istreambuf_iterator<char>(input), std::istreambuf_iterator<char>());
+}
+
+void WriteText(const std::filesystem::path& path, const std::string& text) {
+ std::filesystem::create_directories(path.parent_path());
+ std::ofstream(path, std::ios::binary) << text;
+}
+
+void TestConditions() {
+ const std::map<std::string, std::string> properties = {{"VersionNT", "601"}, {"VersionNT64", "601"}, {"Name", "Abc"}};
+ CHECK(EvaluateMsiCondition("", properties) == true);
+ CHECK(EvaluateMsiCondition("VersionNT64", properties) == true);
+ CHECK(EvaluateMsiCondition("NOT VersionNT64", properties) == false);
+ CHECK(EvaluateMsiCondition("Installed", properties) == false);
+ CHECK(EvaluateMsiCondition("VersionNT >= 501 AND (Missing OR VersionNT64)", properties) == true);
+ CHECK(EvaluateMsiCondition("VersionNT < 600 OR Name = \"Abc\"", properties) == true);
+ CHECK(EvaluateMsiCondition("Name ~= \"abc\"", properties) == true);
+ CHECK(EvaluateMsiCondition("Name = \"abc\"", properties) == false);
+ CHECK(EvaluateMsiCondition("Name >< \"b\" AND Name << \"A\" AND Name >> \"c\"", properties) == true);
+ CHECK(EvaluateMsiCondition("&Feature = 3", properties) == false);
+ CHECK(!EvaluateMsiCondition("VersionNT >", properties).has_value());
+ CHECK(!EvaluateMsiCondition("(VersionNT", properties).has_value());
+}
+
+void TestCabinet() {
+ std::map<std::string, std::string> members;
+ std::vector<std::string> order;
+ std::string reason;
+ CHECK(ExtractCabinet(TwoBlockCabinet(), [&](const std::string& name, std::string_view data) {
+ members[name] = std::string(data);
+ order.push_back(name);
+ return true;
+ }, &reason));
+ CHECK(members["first"] == "0123456789");
+ CHECK(members["second"] == "0123456789"); // copied from the previous block's history
+ CHECK(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.
+ 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(!ExtractCabinet(TwoBlockCabinet(), [](const std::string&, std::string_view) { return false; }, &reason));
+ CHECK(!ExtractCabinet("MSCF", [](const std::string&, std::string_view) { return true; }, &reason));
+}
+
+void TestPlan() {
+ MsiInstallPlan plan;
+ std::string reason;
+ CHECK(!ReadMsiPackage("not a package", &plan, &reason));
+ CHECK(ReadMsiPackage(SamplePackage(), &plan, &reason));
+ CHECK(plan.product_code == "{11111111-2222-3333-4444-555555555555}" && plan.product_name == "Sample Runtime");
+ CHECK(plan.custom_actions == 1);
+ CHECK(plan.cabinets.size() == 1 && plan.cabinets[0].name == "data.cab" && plan.cabinets[0].embedded);
+ // The off feature's file and the desktop file stay out; the rest go under Program Files (x86).
+ CHECK(plan.files.size() == 3);
+ CHECK(plan.files[0].target == "Program Files (x86)/Vendor Runtime/Common/Loader.dll" && plan.files[0].member == "first");
+ CHECK(plan.files[1].target == "Program Files (x86)/Vendor Runtime/Engine/v1/Core.dll");
+ CHECK(plan.files[2].target == "Program Files (x86)/Vendor Runtime/Engine/v1/Empty.dat");
+ CHECK(plan.skipped_files == 1); // Link.txt, under the per-user desktop
+ const auto* path = FindValue(plan.machine, "Software\\Wow6432Node\\Vendor", "Core Path");
+ CHECK(path && path->data == "\"C:\\\\Program Files (x86)\\\\Vendor Runtime\\\\Engine\\\\\"");
+ const auto* short_path = FindValue(plan.machine, "Software\\Wow6432Node\\Vendor", "Core Path Short");
+ CHECK(short_path && short_path->data == "\"C:\\\\Program Files (x86)\\\\Vendor Runtime\\\\Engine\"");
+ const auto* version = FindValue(plan.machine, "Software\\Wow6432Node\\Vendor", "Version");
+ CHECK(version && version->data == "dword:00000007");
+ const auto* build = FindValue(plan.machine, "SOFTWARE\\Vendor", "Build"); // a 64-bit component
+ CHECK(build && build->data == "dword:00000001");
+ CHECK(FindValue(plan.machine, "Software\\Wow6432Node\\Vendor\\Engines", "1.0"));
+ CHECK(!FindValue(plan.machine, "Software\\Wow6432Node\\Vendor", "Hidden"));
+ CHECK(!FindValue(plan.machine, "Software\\Wow6432Node\\Vendor", "Blob"));
+ const auto* user = FindValue(plan.user, "Software\\Vendor", "User");
+ CHECK(user && user->data == "\"C:\\\\Program Files (x86)\\\\Vendor Runtime\\\\Common\\\\Loader.dll\"");
+ CHECK(plan.skipped_registry == 2); // the binary value and the OTHER variable
+ CHECK((plan.path_prepend == std::vector<std::string>{"C:\\Program Files (x86)\\Vendor Runtime\\Common\\"}));
+ CHECK(plan.path_append.empty());
+}
+
+void TestPath() {
+ CHECK(ExtendPath("A;B", {"C:\\X"}, {}) == "C:\\X;A;B");
+ CHECK(ExtendPath("A;c:\\x\\", {"C:\\X"}, {"D"}) == "A;c:\\x\\;D");
+ CHECK(ExtendPath("", {}, {"D"}) == "D");
+}
+
+void TestScripts() {
+ const std::string script =
+ "\"InstallScript\"\n{\n\t\"Run Process\"\n\t{\n\t\t\"PhysX\"\n\t\t{\n"
+ "\t\t\t\"HasRunKey\"\t\t\"HKEY_LOCAL_MACHINE\\\\Software\\\\Valve\\\\Steam\\\\Apps\\\\696180\"\n"
+ "\t\t\t\"process 1\"\t\t\"msiexec\"\n"
+ "\t\t\t\"command 1\"\t\t\"/i \\\"%INSTALLDIR%\\\\_CommonRedist\\\\PhysX\\\\9.13.0604\\\\PhysX.msi\\\" /quiet /norestart\"\n"
+ "\t\t}\n\t\t\"DirectX\"\n\t\t{\n\t\t\t\"process 1\"\t\"%INSTALLDIR%\\\\DirectX\\\\DXSETUP.exe\"\n\t\t}\n"
+ "\t\t\"Launcher\"\n\t\t{\n\t\t\t\"process 1\"\t\"%INSTALLDIR%\\\\Setup.exe\"\n\t\t}\n"
+ "\t\t\"Lang\"\n\t\t{\n\t\t\t\"process 1\"\t\"%LANGUAGE%.exe\"\n\t\t}\n\t}\n}\n";
+ std::vector<RedistEntry> entries;
+ std::string reason;
+ CHECK(ParseRunProcess(script, "Z:\\data\\games\\696180", &entries, &reason));
+ CHECK(entries.size() == 3);
+ CHECK(entries[0].name == "PhysX" && entries[0].process == "msiexec");
+ CHECK(entries[0].command == "/i \"Z:\\data\\games\\696180\\_CommonRedist\\PhysX\\9.13.0604\\PhysX.msi\" /quiet /norestart");
+ CHECK(entries[0].has_run_key == "HKEY_LOCAL_MACHINE\\Software\\Valve\\Steam\\Apps\\696180");
+ std::string package;
+ CHECK(ClassifyRedist(entries[0], "Z:\\data\\games\\696180", &package) == RedistAction::kMsi);
+ CHECK(package == "_CommonRedist/PhysX/9.13.0604/PhysX.msi");
+ CHECK(ClassifyRedist(entries[1], "Z:\\data\\games\\696180", &package) == RedistAction::kCovered);
+ CHECK(ClassifyRedist(entries[2], "Z:\\data\\games\\696180", &package) == RedistAction::kNotRun);
+ // A package outside the game folder is not taken.
+ RedistEntry outside{"X", "msiexec", "/i C:\\other\\x.msi", ""};
+ CHECK(ClassifyRedist(outside, "Z:\\data\\games\\696180", &package) == RedistAction::kNotRun);
+ RedistEntry climbing{"X", "msiexec", "/i Z:\\data\\games\\696180\\..\\x.msi", ""};
+ CHECK(ClassifyRedist(climbing, "Z:\\data\\games\\696180", &package) == RedistAction::kNotRun);
+ RedistEntry direct{"X", "Z:\\data\\games\\696180\\redist\\x.msi", "", ""};
+ CHECK(ClassifyRedist(direct, "Z:\\data\\games\\696180", &package) == RedistAction::kMsi && package == "redist/x.msi");
+}
+
+void TestInstall() {
+ char pattern[] = "/tmp/playden-redist-XXXXXX";
+ CHECK(::mkdtemp(pattern));
+ const auto base = std::filesystem::canonical(pattern); // /tmp is a symlink on macOS
+ const auto game = base / "game", prefix = base / "prefix";
+ WriteText(game / "_CommonRedist/Sample/1.0/installscript.vdf",
+ "\"InstallScript\" { \"Run Process\" { \"Sample\" { "
+ "\"HasRunKey\" \"HKEY_LOCAL_MACHINE\\\\Software\\\\Valve\\\\Steam\\\\Apps\\\\42\" "
+ "\"process 1\" \"msiexec\" "
+ "\"command 1\" \"/i \\\"%INSTALLDIR%\\\\_CommonRedist\\\\Sample\\\\1.0\\\\sample.msi\\\" /quiet\" } "
+ "\"VC\" { \"process 1\" \"%INSTALLDIR%\\\\_CommonRedist\\\\vcredist_x86.exe\" } } }");
+ WriteText(game / "_CommonRedist/Sample/1.0/sample.msi", SamplePackage());
+ WriteText(game / "data/deep/installscript.vdf", "\"InstallScript\" { \"Run Process\" { \"Ignored\" { \"process 1\" \"x.exe\" } } }");
+ WriteText(prefix / "system.reg",
+ "WINE REGISTRY Version 2\n;; All keys relative to \\\\Machine\n\n#arch=win64\n\n"
+ "[System\\\\CurrentControlSet\\\\Control\\\\Session Manager\\\\Environment] 1700000000\n"
+ "\"PATH\"=str(2):\"%SystemRoot%\\\\system32;%SystemRoot%\"\n\"TEMP\"=str(2):\"%SystemRoot%\\\\temp\"\n");
+ WriteText(prefix / "user.reg", "WINE REGISTRY Version 2\n;; All keys relative to \\\\User\\\\S-1-5-21-0-0-0-1000\n\n#arch=win64\n");
+ std::filesystem::create_directories(prefix / "drive_c/program files (x86)");
+ // A bottle is private to Playden, as on the console.
+ std::filesystem::permissions(prefix, std::filesystem::perms::owner_all, std::filesystem::perm_options::replace);
+ for (const auto* hive : {"system.reg", "user.reg"})
+ std::filesystem::permissions(prefix / hive, std::filesystem::perms::owner_read | std::filesystem::perms::owner_write,
+ std::filesystem::perm_options::replace);
+ const auto result = InstallRedistributables(game.string(), "Z:\\games\\42", prefix.string(), 1700000100);
+ CHECK(result.outcomes.size() == 2);
+ CHECK(result.outcomes[0].script == "_CommonRedist/Sample/1.0/installscript.vdf");
+ CHECK(result.outcomes[0].name == "Sample" && result.outcomes[0].result == "installed" && result.outcomes[0].files == 3);
+ CHECK(result.outcomes[1].name == "VC" && result.outcomes[1].result == "covered");
+ // The existing folder is reused whatever its case.
+ CHECK(ReadText(prefix / "drive_c/program files (x86)/Vendor Runtime/Common/Loader.dll") == "0123456789");
+ CHECK(ReadText(prefix / "drive_c/program files (x86)/Vendor Runtime/Engine/v1/Core.dll") == "0123456789");
+ CHECK(std::filesystem::exists(prefix / "drive_c/program files (x86)/Vendor Runtime/Engine/v1/Empty.dat"));
+ std::vector<std::string> drive;
+ for (const auto& child : std::filesystem::directory_iterator(prefix / "drive_c")) drive.push_back(child.path().filename().string());
+ CHECK((drive == std::vector<std::string>{"program files (x86)"}));
+ const auto system = ReadText(prefix / "system.reg");
+ CHECK(system.find("[Software\\\\Wow6432Node\\\\Vendor]") != std::string::npos);
+ CHECK(system.find("\"Core Path\"=\"C:\\\\Program Files (x86)\\\\Vendor Runtime\\\\Engine\\\\\"") != std::string::npos);
+ CHECK(system.find("\"PATH\"=str(2):\"C:\\\\Program Files (x86)\\\\Vendor Runtime\\\\Common\\\\;%SystemRoot%\\\\system32;%SystemRoot%\"") !=
+ std::string::npos);
+ CHECK(system.find("\"TEMP\"=str(2):\"%SystemRoot%\\\\temp\"") != std::string::npos);
+ CHECK(system.find("[Software\\\\Wow6432Node\\\\Valve\\\\Steam\\\\Apps\\\\42]") != std::string::npos);
+ CHECK(system.find("\"Sample\"=dword:00000001") != std::string::npos);
+ CHECK(ReadText(prefix / "user.reg").find("\"User\"=") != std::string::npos);
+ CHECK(ReadText(prefix / ".playden-redist").find(" _CommonRedist/Sample/1.0/sample.msi\n") != std::string::npos);
+ // Installed once: the next Play leaves the bottle alone.
+ const auto again = InstallRedistributables(game.string(), "Z:\\games\\42", prefix.string(), 1700000200);
+ CHECK(again.outcomes.size() == 2 && again.outcomes[0].result == "already");
+ CHECK(ReadText(prefix / "system.reg") == system);
+ // A damaged package fails alone.
+ std::filesystem::remove(prefix / ".playden-redist");
+ WriteText(game / "_CommonRedist/Sample/1.0/sample.msi", "broken");
+ const auto broken = InstallRedistributables(game.string(), "Z:\\games\\42", prefix.string(), 1700000300);
+ CHECK(broken.outcomes.size() == 2 && broken.outcomes[0].result == "failed" && broken.outcomes[1].result == "covered");
+ CHECK(broken.outcomes[0].detail.find("not a Windows Installer package") != std::string::npos);
+ std::filesystem::remove_all(base);
+}
+
+// NVIDIA's legacy PhysX package (Bullet Witch's), when PLAYDEN_TEST_PHYSX_MSI names a copy.
+void TestPhysxPackage() {
+ const char* path = std::getenv("PLAYDEN_TEST_PHYSX_MSI");
+ if (!path || !*path) return;
+ const auto package = ReadText(path);
+ MsiInstallPlan plan;
+ std::string reason;
+ CHECK(ReadMsiPackage(package, &plan, &reason));
+ CHECK(plan.product_name == "NVIDIA PhysX (Legacy)");
+ const auto has = [&](const std::string& target) {
+ return std::any_of(plan.files.begin(), plan.files.end(), [&](const MsiFile& file) { return file.target == target; });
+ };
+ CHECK(has("Program Files (x86)/NVIDIA Corporation/PhysX/Common/PhysXLoader.dll"));
+ CHECK(has("Program Files (x86)/NVIDIA Corporation/PhysX/Common/PhysXLoader64.dll"));
+ CHECK(has("Program Files (x86)/NVIDIA Corporation/PhysX/Engine/v2.6.4/PhysXCore.dll"));
+ const auto* core = FindValue(plan.machine, "Software\\Wow6432Node\\AGEIA Technologies", "PhysXCore Path");
+ CHECK(core && core->data == "\"C:\\\\Program Files (x86)\\\\NVIDIA Corporation\\\\PhysX\\\\Engine\"");
+ CHECK((plan.path_prepend == std::vector<std::string>{"C:\\Program Files (x86)\\NVIDIA Corporation\\PhysX\\Common"}));
+ const auto cabinet = ReadMsiStream(package, plan.cabinets.at(0).name);
+ CHECK(cabinet);
+ // PLAYDEN_TEST_PHYSX_FILES may name a folder with the members another tool extracted.
+ const char* reference = std::getenv("PLAYDEN_TEST_PHYSX_FILES");
+ std::size_t count = 0, loader = 0, compared = 0;
+ CHECK(ExtractCabinet(*cabinet, [&](const std::string& name, std::string_view data) {
+ ++count;
+ if (name == "FILE_COMMON_PhysXLoader_dll") loader = data.size();
+ if (reference && *reference) {
+ CHECK(ReadText(std::filesystem::path(reference) / name) == data);
+ ++compared;
+ }
+ return true;
+ }, &reason));
+ CHECK(!reference || !*reference || compared == 43);
+ CHECK(count == 43 && loader == 57224);
+ std::fprintf(stderr, "PhysX package: %zu files, %zu machine values\n", plan.files.size(), plan.machine.size());
+}
+
+} // namespace
+
+int main() {
+ TestConditions();
+ TestCabinet();
+ TestPlan();
+ TestPath();
+ TestScripts();
+ TestInstall();
+ TestPhysxPackage();
+ return 0;
+}