Play your Steam library's Windows games on a jailbroken PS5.
C++
Let recipes set values in a game's INI files
Leonardo Lobato97523ac24b1a
diff --git a/cmake/HomebrewUI.cmake b/cmake/HomebrewUI.cmakeindex 4ea8d5f..d299cf3 100644--- a/cmake/HomebrewUI.cmake+++ b/cmake/HomebrewUI.cmake@@ -68,6 +68,7 @@ add_library(playden_steam_cm_codec STATIC"${CMAKE_SOURCE_DIR}/src/steam/backend/app_info.cpp""${CMAKE_SOURCE_DIR}/src/runtime/prospero_profile.cpp""${CMAKE_SOURCE_DIR}/src/runtime/game_settings.cpp"+ "${CMAKE_SOURCE_DIR}/src/runtime/recipe_ini.cpp""${CMAKE_SOURCE_DIR}/src/runtime/install_script.cpp""${CMAKE_SOURCE_DIR}/src/runtime/msi_package.cpp""${CMAKE_SOURCE_DIR}/src/runtime/lzx_decoder.cpp"@@ -570,6 +571,9 @@ if(BUILD_TESTING)add_executable(runtime_dotnet_heap_test tests/runtime_dotnet_heap_test.cpp)target_link_libraries(runtime_dotnet_heap_test PRIVATE playden_runtime_steamworks)add_test(NAME runtime_dotnet_heap COMMAND runtime_dotnet_heap_test)+ add_executable(runtime_recipe_ini_test tests/runtime_recipe_ini_test.cpp)+ target_link_libraries(runtime_recipe_ini_test PRIVATE playden_steam_cm_codec)+ add_test(NAME runtime_recipe_ini COMMAND runtime_recipe_ini_test)# Inject failures only at the POSIX I/O boundary of this test's production# compilation; the shipped settings implementation has ordinary syscalls.add_executable(runtime_settings_publication_test tests/runtime_settings_publication_test.cpp)diff --git a/docs/community-recipes.md b/docs/community-recipes.mdindex cfe5b18..7e02bb9 100644--- a/docs/community-recipes.md+++ b/docs/community-recipes.md@@ -68,6 +68,7 @@ Recipe fields:| `locked` | Setting ids the player must choose "Change anyway" to change. || `requirements` | What the runtime kit's template bottle must provide: `{"audio": "ps5"}` (Wine's PS5 audio driver) is the only one so far. On a kit without it, Playden refuses to prepare or start the game and names what is missing. || `registry` | Values the bottle gets under `HKEY_CURRENT_USER` when the game's files are prepared, as a Steam install script's would be: `{"Software\\Wine\\AppDefaults\\game.exe\\Direct3D": {"VideoMemorySize": "4096"}}`. Only some keys are allowed; see [Registry values](#registry-values). |+| `ini` | Values the game's own INI files get when the game's files are prepared, written only when the key is missing or empty: `{"BmGame/Config/UserEngine.ini": {"Engine.Engine": {"Language": "int"}}}`. See [INI values](#ini-values). |Community fields:@@ -133,6 +134,31 @@ Other rules: string values only, at most 16 values, printable ASCII, no `"` innames or values, no `\` in values, no `[` or `]` in keys, and each value once(letter case does not make two values different).+## INI values++Use `ini` only for a value that the game's own launcher writes before it starts+the game. The console cannot start a second program, so the launcher cannot+start the game. Batman: Arkham Asylum starts its launcher, and stops, while+`BmGame/Config/UserEngine.ini` has no `Language` under `[Engine.Engine]`.++Playden writes the values into the game folder whenever it prepares the game or+applies its settings:++- A value is written only when its key is missing or empty in the section. A+ value that the player or the game wrote stays.+- A missing key goes after the last line of its section. A missing section goes+ at the end of the file. All other lines stay as they are, with the file's own+ line endings.+- A missing file is not made: the game makes its own file from its defaults.+ Playden also leaves a link or a UTF-16 file alone.+- File, section and key names ignore letter case, as on Windows.++Rules: the file is a `.ini` path in the game folder, with `/` between folders+and no `.` or `..` part. At most 16 values. Printable ASCII only. No `[` or `]`+in a section, no `=`, `[` or `]` in a key, and a key does not start with `;` or+`#`. A value is not empty. Each value once (letter case does not make two+values different).+## Shipped recipesA recipe Playden ships lives in `runtime/recipes/` and is used for that gamediff --git a/src/homebrew/runtime_host.cpp b/src/homebrew/runtime_host.cppindex a57c117..11999a3 100644--- a/src/homebrew/runtime_host.cpp+++ b/src/homebrew/runtime_host.cpp@@ -10,6 +10,7 @@#include "runtime/prospero_profile.h"#include "runtime/settings_publication_journal.h"#include "runtime/dotnet_heap.h"+#include "runtime/recipe_ini.h"#include "runtime/game_probe.h"#include "runtime/install_script.h"#include "runtime/layout_migration.h"@@ -1075,6 +1076,21 @@ std::string RuntimeHost::RecipeRegistryStep(const GameFiles& files) {return {};}+// Generic step: values the recipe puts in the game's own INI files (docs/community-recipes.md), only where the key+// is missing or empty, for a setting the game's launcher would write before starting the game.+std::string RuntimeHost::RecipeIniStep(const GameFiles& files) {+ const auto& ini = files.recipe->ini;+ if (ini.empty()) return {};+ const auto applied = rt::ApplyRecipeIniValues(files.root.string(), ini);+ std::string changed, skipped;+ for (const auto& file : applied.changed) changed += (changed.empty() ? "" : ",") + file;+ for (const auto& file : applied.skipped) skipped += (skipped.empty() ? "" : ",") + file;+ Log("recipe ini app=" + std::to_string(files.record.runtime_number) + " values=" + std::to_string(ini.size()) ++ " changed=" + (changed.empty() ? "-" : changed) + (skipped.empty() ? std::string() : " skipped=" + skipped) ++ (applied.ok ? std::string() : " failed=" + applied.message));+ return applied.ok ? std::string() : applied.message;+}+// Generic step: self-contained .NET games reserve more address space than the console grants unless their// garbage collector is given a heap limit (runtime/dotnet_heap.h).std::string RuntimeHost::DotnetHeapStep(const GameFiles& files) {@@ -1089,8 +1105,8 @@ std::string RuntimeHost::DotnetHeapStep(const GameFiles& files) {}// The steps run in this order for every game, whatever its store: generic ones (media, EULA, Direct3D 12,-// the bottle's Environment, MFC, the recipe's registry values, the .NET heap) and Steam-file ones, which act only-// on the Steam files a game has (SteamStub, Steamworks and steam.dll, install scripts and redistributables).+// the bottle's Environment, MFC, the recipe's registry and INI values, the .NET heap) and Steam-file ones, which act+// only on the Steam files a game has (SteamStub, Steamworks and steam.dll, install scripts and redistributables).std::string RuntimeHost::ApplyPreparationSteps(Composition& c, const rt::RuntimeInstall& record, bool steam_account_known) {MediaStep(c, record);GameFiles files{record};@@ -1132,6 +1148,7 @@ std::string RuntimeHost::ApplyPreparationSteps(Composition& c, const rt::Runtimeif (auto refused = InstallScriptsStep(files); !refused.empty()) return refused;MfcStep(files);if (auto refused = RecipeRegistryStep(files); !refused.empty()) return refused;+ if (auto refused = RecipeIniStep(files); !refused.empty()) return refused;return DotnetHeapStep(files);}diff --git a/src/homebrew/runtime_host.hpp b/src/homebrew/runtime_host.hppindex cae9e67..eac5e3c 100644--- a/src/homebrew/runtime_host.hpp+++ b/src/homebrew/runtime_host.hpp@@ -607,6 +607,7 @@ class RuntimeHost {void KitMonoStep(Composition& composition, const runtime::RuntimeInstall& record, const char* when); // never stops the startstd::string BottleEnvironmentStep(const GameFiles& files);std::string RecipeRegistryStep(const GameFiles& files);+ std::string RecipeIniStep(const GameFiles& files);std::string DotnetHeapStep(const GameFiles& files);void MfcStep(const GameFiles& files); // an upgrade: never stops the start// Steam-file steps.diff --git a/src/runtime/game_settings.cpp b/src/runtime/game_settings.cppindex dfc7003..335574c 100644--- a/src/runtime/game_settings.cpp+++ b/src/runtime/game_settings.cpp@@ -1343,6 +1343,76 @@ bool RecipeRegistryValueAllowed(const std::string& key, const std::string& name,return false;}+constexpr std::size_t kMaxRecipeIniValues = 16;++// An INI value a recipe may carry (docs/community-recipes.md): a .ini file inside the game folder,+// named with '/' and no "." or ".." part, and printable ASCII that keeps each value on its own line+// under its own [section]: no brackets in the section, no '=' in the key, and no leading ';' or '#',+// which would make the line a comment.+bool RecipeIniValueAllowed(const IniValue& value, std::string* why) {+ const auto printable = [](const std::string& text) {+ for (const unsigned char c : text)+ if (c < 0x20 || c > 0x7e) return false;+ return true;+ };+ const auto& file = value.file;+ bool parts_ok = !file.empty() && file.size() <= 200 && printable(file) &&+ file.find_first_of("\\:*?\"<>|") == std::string::npos && file.front() != '/' && file.back() != '/';+ for (std::size_t start = 0; parts_ok && start <= file.size();) {+ const auto end = std::min(file.find('/', start), file.size());+ const auto part = file.substr(start, end - start);+ parts_ok = !part.empty() && part != "." && part != "..";+ start = end + 1;+ }+ if (!parts_ok || file.size() < 5 || LowerAscii(file.substr(file.size() - 4)) != ".ini") {+ *why = "file is not a .ini path inside the game folder";+ return false;+ }+ if (value.section.empty() || value.section.size() > 128 || !printable(value.section) ||+ value.section.find_first_of("[]") != std::string::npos) {+ *why = "section is not printable ASCII without brackets";+ return false;+ }+ const auto& key = value.key;+ if (key.empty() || key.size() > 64 || !printable(key) || key.find_first_of("=[]") != std::string::npos ||+ key.front() == ';' || key.front() == '#' || key.front() == ' ' || key.back() == ' ') {+ *why = "key is not printable ASCII without '=' or brackets";+ return false;+ }+ if (value.value.empty() || value.value.size() > 256 || !printable(value.value) || value.value.front() == ' ' ||+ value.value.back() == ' ') {+ *why = "value is not printable ASCII";+ return false;+ }+ return true;+}++// The ini field as ParseGameRecipe reads it, grouped by file and section; each file starts on+// file_break (empty for the compact form) and the closing brace on end_break.+std::string SerializeIniValues(const std::vector<IniValue>& values, const std::string& file_break,+ const std::string& end_break) {+ const auto quoted = [](const std::string& text) { return "\"" + json::escape(text) + "\""; };+ const std::string space = file_break.empty() ? "" : " ";+ std::map<std::string, std::map<std::string, std::vector<const IniValue*>>> files;+ for (const auto& value : values) files[value.file][value.section].push_back(&value);+ std::string text = "{";+ bool first_file = true;+ for (const auto& [file, sections] : files) {+ text += std::string(first_file ? "" : ",") + file_break + quoted(file) + ":" + space + "{";+ first_file = false;+ bool first_section = true;+ for (const auto& [section, keys] : sections) {+ text += std::string(first_section ? "" : "," + space) + quoted(section) + ":" + space + "{";+ first_section = false;+ for (std::size_t index = 0; index < keys.size(); ++index)+ text += std::string(index ? "," + space : "") + quoted(keys[index]->key) + ":" + space + quoted(keys[index]->value);+ text += "}";+ }+ text += "}";+ }+ return text + end_break + "}";+}+} // namespacebool ParseGameRecipe(std::string_view text, GameRecipe* recipe, std::string* reason) {@@ -1428,6 +1498,28 @@ bool ParseGameRecipe(std::string_view text, GameRecipe* recipe, std::string* rea}}}+ if (const auto* ini = root->get("ini")) {+ const auto* files = ini->object();+ if (!files) return fail("ini must map files to their sections");+ // Windows reads the files, sections and keys ignoring case, so each value is named once.+ std::set<std::string> identities;+ for (const auto& [file, sections] : *files) {+ if (!sections.object()) return fail("ini file " + file + " must map sections to their values");+ for (const auto& [section, keys] : *sections.object()) {+ if (!keys.object()) return fail("ini section " + section + " must map keys to strings");+ for (const auto& [key, value] : *keys.object()) {+ if (!value.string()) return fail("ini value " + key + " must be a string");+ IniValue entry{file, section, key, *value.string()};+ std::string why;+ if (!RecipeIniValueAllowed(entry, &why)) return fail("ini " + file + " [" + section + "] " + key + ": " + why);+ if (out.ini.size() >= kMaxRecipeIniValues) return fail("ini has too many values");+ if (!identities.insert(LowerAscii(file + "\n" + section + "\n" + key)).second)+ return fail("ini " + file + " [" + section + "] " + key + " appears twice");+ out.ini.push_back(std::move(entry));+ }+ }+ }+ }if (out.dll_overrides.size() && !IsProsperoDllOverrides(out.dll_overrides)) return fail("recipe dll_overrides are invalid");if (out.architecture != "pe32" && out.architecture != "pe64") return fail("architecture must be pe32 or pe64");for (const auto& [id, value] : out.defaults) {@@ -1607,6 +1699,7 @@ std::string SerializeGameRecipe(const GameRecipe& recipe) {}text += "}";}+ if (!recipe.ini.empty()) text += ",\"ini\":" + SerializeIniValues(recipe.ini, "", "");return text + "}\n";}@@ -3141,6 +3234,7 @@ CommunityRecipe BuildCommunityRecipe(const GameRecipe& recipe, const EffectiveSeif (!settings.values.at(id).unlocked) shared.locked.insert(id);// What the bottle gets and what the kit must provide stay with the game.shared.registry = recipe.registry;+ shared.ini = recipe.ini;shared.requirements = recipe.requirements;out.status = "untested";return out;@@ -3203,6 +3297,7 @@ std::string SerializeCommunityRecipe(const CommunityRecipe& community) {}text += "\n }";}+ if (!recipe.ini.empty()) text += ",\n \"ini\": " + SerializeIniValues(recipe.ini, "\n ", "\n ");text += ",\n \"steam_appid\": " + std::to_string(recipe.app_id) + ",\n \"executable\": " +quoted(community.executable) + ",\n \"community\": {\n \"format_version\": 1,\n \"min_kit\": " +quoted(community.min_kit) + ",\n \"tested_firmware\": " + quoted(community.tested_firmware) +diff --git a/src/runtime/game_settings.h b/src/runtime/game_settings.hindex 80c118c..b05dd65 100644--- a/src/runtime/game_settings.h+++ b/src/runtime/game_settings.h@@ -135,6 +135,19 @@ struct RegistryValue {bool default_value = false; // Wine uses @= for a key's unnamed value};+// One value a recipe puts in an INI file of the game's own folder (runtime/recipe_ini.h): written+// only while the key is missing or empty, so the player's own choice is never replaced.+struct IniValue {+ std::string file; // relative to the game folder, '/' separators, e.g. BmGame/Config/UserEngine.ini+ std::string section; // without brackets, e.g. Engine.Engine+ std::string key;+ std::string value;+};++inline bool operator==(const IniValue& left, const IniValue& right) {+ return left.file == right.file && left.section == right.section && left.key == right.key && left.value == right.value;+}+struct GameRecipe {std::string id;int version = 0;@@ -160,6 +173,9 @@ struct GameRecipe {// Values the bottle's user.reg gets when the game's files are prepared, as a Steam install// script's would be (docs/community-recipes.md): strings under HKEY_CURRENT_USER.std::vector<RegistryValue> registry;+ // Values the game's own INI files get when its files are prepared, for a setting the game's+ // launcher would write before starting the game, which the console can't do (Batman: Arkham Asylum).+ std::vector<IniValue> ini;// What the kit's template bottle must provide ("audio": "ps5"); see UnmetRecipeRequirements.std::map<std::string, std::string> requirements;};diff --git a/src/runtime/recipe_ini.cpp b/src/runtime/recipe_ini.cppnew file mode 100644index 0000000..2e570cc--- /dev/null+++ b/src/runtime/recipe_ini.cpp@@ -0,0 +1,222 @@+// SPDX-License-Identifier: GPL-3.0-or-later+#include "runtime/recipe_ini.h"++#include <cerrno>+#include <fcntl.h>+#include <filesystem>+#include <map>+#include <optional>+#include <string_view>+#include <sys/stat.h>+#include <unistd.h>++namespace playden::runtime {+namespace {+namespace fs = std::filesystem;++constexpr std::size_t kMaxIniFile = 256 * 1024;++char Lower(char c) { return c >= 'A' && c <= 'Z' ? static_cast<char>(c + 32) : c; }++bool SameIgnoringCase(std::string_view a, std::string_view b) {+ if (a.size() != b.size()) return false;+ for (std::size_t i = 0; i < a.size(); ++i)+ if (Lower(a[i]) != Lower(b[i])) return false;+ return true;+}++std::string_view Trim(std::string_view text) {+ while (!text.empty() && (text.front() == ' ' || text.front() == '\t')) text.remove_prefix(1);+ while (!text.empty() && (text.back() == ' ' || text.back() == '\t' || text.back() == '\r')) text.remove_suffix(1);+ return text;+}++// One line of the file: where it starts and ends (before its line ending).+struct Line {+ std::size_t begin = 0;+ std::size_t end = 0;+};++std::vector<Line> Lines(const std::string& text) {+ std::vector<Line> lines;+ for (std::size_t begin = 0; begin < text.size();) {+ const auto newline = text.find('\n', begin);+ const auto stop = newline == std::string::npos ? text.size() : newline;+ lines.push_back({begin, stop > begin && text[stop - 1] == '\r' ? stop - 1 : stop});+ begin = newline == std::string::npos ? text.size() : newline + 1;+ }+ return lines;+}++// The section a [header] line opens, or nothing for other lines.+std::optional<std::string_view> Header(std::string_view line) {+ line = Trim(line);+ if (line.size() < 2 || line.front() != '[') return std::nullopt;+ const auto close = line.find(']');+ if (close == std::string_view::npos) return std::nullopt;+ return Trim(line.substr(1, close - 1));+}++// A path in the game folder, matched part by part ignoring case; nothing when a part is missing or a link.+std::optional<fs::path> FindIgnoringCase(const fs::path& root, const std::string& relative, bool* linked) {+ fs::path cursor = root;+ std::size_t start = 0;+ while (start <= relative.size()) {+ const auto end = std::min(relative.find('/', start), relative.size());+ const auto part = relative.substr(start, end - start);+ const bool last = end == relative.size();+ std::optional<fs::path> found;+ struct stat info {};+ if (::lstat((cursor / part).c_str(), &info) == 0) {+ found = cursor / part;+ } else {+ std::error_code error;+ for (fs::directory_iterator it(cursor, error), done; !error && it != done; it.increment(error))+ if (SameIgnoringCase(it->path().filename().string(), part)) {+ found = it->path();+ break;+ }+ if (!found || ::lstat(found->c_str(), &info) != 0) return std::nullopt;+ }+ if (S_ISLNK(info.st_mode)) {+ *linked = true;+ return std::nullopt;+ }+ if (last ? !S_ISREG(info.st_mode) : !S_ISDIR(info.st_mode)) return std::nullopt;+ cursor = *found;+ start = end + 1;+ }+ return cursor;+}++bool ReadSmall(const fs::path& path, std::string* bytes, mode_t* mode) {+ const int file = ::open(path.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC);+ if (file < 0) return false;+ struct stat info {};+ bool ok = ::fstat(file, &info) == 0 && S_ISREG(info.st_mode);+ *mode = info.st_mode & 07777;+ bytes->clear();+ char buffer[4096];+ while (ok) {+ const auto count = ::read(file, buffer, sizeof(buffer));+ if (count < 0 && errno == EINTR) continue;+ if (count < 0 || bytes->size() + static_cast<std::size_t>(count) > kMaxIniFile) ok = false;+ else if (count == 0) break;+ else bytes->append(buffer, static_cast<std::size_t>(count));+ }+ return ::close(file) == 0 && ok;+}++// Through a temporary file in the same folder, synced, then renamed over the original. The game may write the file+// back, so the temporary gets the original's permissions; a file system without them (exFAT) refuses the chmod and+// keeps its own, which is fine.+bool WriteAtomic(const fs::path& path, std::string_view bytes, mode_t mode) {+ const auto temporary = path.parent_path() / (".playden-" + path.filename().string() + ".tmp");+ ::unlink(temporary.c_str());+ const int file = ::open(temporary.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0600);+ if (file < 0) return false;+ bool ok = ::fchmod(file, mode) == 0 || errno == EPERM || errno == ENOTSUP || errno == EINVAL;+ std::size_t done = 0;+ while (ok && done < bytes.size()) {+ const auto count = ::write(file, bytes.data() + done, bytes.size() - done);+ if (count < 0 && errno == EINTR) continue;+ if (count <= 0) ok = false;+ else done += static_cast<std::size_t>(count);+ }+ ok = ::fsync(file) == 0 && ok;+ ok = ::close(file) == 0 && ok;+ if (!ok || ::rename(temporary.c_str(), path.c_str()) != 0) {+ ::unlink(temporary.c_str());+ return false;+ }+ return true;+}++} // namespace++bool SetIniValueIfEmpty(std::string* text, const std::string& section, const std::string& key, const std::string& value) {+ const std::string newline = text->find("\r\n") != std::string::npos ? "\r\n" : "\n";+ const auto lines = Lines(*text);+ bool inside = false;+ std::optional<std::size_t> last_line; // the first matching section's last non-blank line+ std::optional<std::size_t> empty_value; // where an empty value of the key starts+ bool first_section_done = false;+ for (std::size_t index = 0; index < lines.size(); ++index) {+ const std::string_view line(text->data() + lines[index].begin, lines[index].end - lines[index].begin);+ if (const auto header = Header(line)) {+ if (inside) first_section_done = true;+ inside = SameIgnoringCase(*header, section);+ if (inside && !first_section_done) last_line = index;+ continue;+ }+ if (!inside) continue;+ const auto trimmed = Trim(line);+ if (!trimmed.empty() && !first_section_done) last_line = index;+ if (trimmed.empty() || trimmed.front() == ';' || trimmed.front() == '#') continue;+ const auto equals = trimmed.find('=');+ if (equals == std::string_view::npos || !SameIgnoringCase(Trim(trimmed.substr(0, equals)), key)) continue;+ if (!Trim(trimmed.substr(equals + 1)).empty()) return false; // the player's or the game's own value+ if (!empty_value) empty_value = lines[index].begin + (line.find('=') + 1);+ }+ if (empty_value) {+ // After any spaces that follow '=', so the line ending stays.+ auto at = *empty_value;+ while (at < text->size() && ((*text)[at] == ' ' || (*text)[at] == '\t')) ++at;+ text->insert(at, value);+ return true;+ }+ if (last_line) {+ const auto at = lines[*last_line].end;+ if (at == text->size()) text->append(newline + key + "=" + value + newline);+ else text->insert(at, newline + key + "=" + value);+ return true;+ }+ if (!text->empty() && text->back() != '\n') text->append(newline);+ if (!text->empty()) text->append(newline);+ text->append("[" + section + "]" + newline + key + "=" + value + newline);+ return true;+}++RecipeIniResult ApplyRecipeIniValues(const std::string& game_root, const std::vector<IniValue>& values) {+ RecipeIniResult result;+ // One read and at most one write per file, in the order the recipe names them.+ std::vector<std::string> order;+ std::map<std::string, std::vector<const IniValue*>> files;+ for (const auto& value : values) {+ if (!files.count(value.file)) order.push_back(value.file);+ files[value.file].push_back(&value);+ }+ for (const auto& relative : order) {+ bool linked = false;+ const auto path = FindIgnoringCase(game_root, relative, &linked);+ if (!path) {+ result.skipped.push_back(relative + (linked ? ": a link" : ": missing"));+ continue;+ }+ std::string bytes;+ mode_t mode = 0644;+ if (!ReadSmall(*path, &bytes, &mode)) {+ result.skipped.push_back(relative + ": unreadable or too large");+ continue;+ }+ // UTF-16 (a byte-order mark, or NULs in the text) would need wide edits; such a file is left as it is.+ if (bytes.compare(0, 2, "\xFF\xFE") == 0 || bytes.compare(0, 2, "\xFE\xFF") == 0 ||+ bytes.find('\0') != std::string::npos) {+ result.skipped.push_back(relative + ": not a plain text INI");+ continue;+ }+ bool changed = false;+ for (const auto* value : files[relative])+ changed = SetIniValueIfEmpty(&bytes, value->section, value->key, value->value) || changed;+ if (!changed) continue;+ if (!WriteAtomic(*path, bytes, mode)) {+ result.ok = false;+ result.message = "Playden could not update the game's settings file (" + relative + ").";+ return result;+ }+ result.changed.push_back(relative);+ }+ return result;+}++} // namespace playden::runtimediff --git a/src/runtime/recipe_ini.h b/src/runtime/recipe_ini.hnew file mode 100644index 0000000..63f2db3--- /dev/null+++ b/src/runtime/recipe_ini.h@@ -0,0 +1,36 @@+// SPDX-License-Identifier: GPL-3.0-or-later+#pragma once++#include <string>+#include <vector>++#include "runtime/game_settings.h"++namespace playden::runtime {++// Some games start their settings launcher, and exit, until it has written a value to an INI file in the game+// folder: Batman: Arkham Asylum's ShippingPC-BmGame.exe starts BmLauncher.exe while BmGame/Config/UserEngine.ini has+// no [Engine.Engine] Language. The launcher can't start the game on the console (no second process), so a recipe+// writes the value instead (GameRecipe::ini).++// Puts value under [section] in the INI text when its key is missing or empty there; a value the player or the game+// wrote stays. Every other byte is kept: a key missing from the section goes after the section's last line, a+// section missing from the file goes at its end, and new lines use the file's own line ending. Sections and keys+// match ignoring case, as Windows' INI calls do. Returns whether the text changed.+bool SetIniValueIfEmpty(std::string* text, const std::string& section, const std::string& key, const std::string& value);++struct RecipeIniResult {+ bool ok = true;+ std::string message; // on failure: a sentence for the player+ std::vector<std::string> changed; // files (relative) that were written+ std::vector<std::string> skipped; // "<file>: <why>" for files left alone (missing, not a plain text INI)+};++// Applies a recipe's INI values to the game folder at game_root. File names match ignoring case, as on Windows.+// A missing file is skipped, not created: the game makes its own from its defaults, and a file with only the+// recipe's lines could hide them. Links are never followed. A file is rewritten only when a value changes,+// through a synced temporary file renamed over it, with the original's permissions. Idempotent; the game must be+// stopped.+RecipeIniResult ApplyRecipeIniValues(const std::string& game_root, const std::vector<IniValue>& values);++} // namespace playden::runtimediff --git a/tests/game_settings_test.cpp b/tests/game_settings_test.cppindex 9e408ac..c45e9d5 100644--- a/tests/game_settings_test.cpp+++ b/tests/game_settings_test.cpp@@ -1292,6 +1292,43 @@ int main(int argc, char** argv) {CHECK(ReadText(registry_root / "user.reg").find("\n[Software\\\\Wine\\\\AppDefaults\\\\a.exe\\\\Direct3D] 1791500000\n\"VideoMemorySize\"=\"4096\"\n") != std::string::npos);std::filesystem::remove_all(registry_root);}+ // A recipe can carry values for the game's own INI files, written at preparation while the key is missing or+ // empty (runtime/recipe_ini.h): a .ini inside the game folder, one value per line under its own section.+ {+ const std::string head = R"({"recipe_id":"x","recipe_version":1,"app_id":1,"launch_entries":[{"id":"a","label":"A","executable":"a.exe"}],"ini":)";+ GameRecipe with_ini;+ CHECK(ParseGameRecipe(head + R"({"BmGame/Config/UserEngine.ini":{"Engine.Engine":{"Language":"int","Other":"1"}},"b.ini":{"S":{"k":"v"}}}})",+ &with_ini, &reason));+ CHECK(with_ini.ini.size() == 3);+ CHECK(std::count(with_ini.ini.begin(), with_ini.ini.end(),+ IniValue{"BmGame/Config/UserEngine.ini", "Engine.Engine", "Language", "int"}) == 1);+ GameRecipe reread;+ CHECK(ParseGameRecipe(SerializeGameRecipe(with_ini), &reread, &reason));+ CHECK(std::is_permutation(reread.ini.begin(), reread.ini.end(), with_ini.ini.begin(), with_ini.ini.end()));+ CHECK(SerializeGameRecipe(hl2).find("\"ini\"") == std::string::npos); // absent when empty+ GameRecipe refused;+ const auto refuses = [&](const std::string& ini) {+ return !ParseGameRecipe(head + ini + "}", &refused, &reason);+ };+ CHECK(refuses(R"([])")); // not an object+ CHECK(refuses(R"({"a.ini":{"S":{"k":1}}})")); // not a string+ CHECK(refuses(R"({"a.ini":{"S":"k=v"}})")); // a section maps keys+ CHECK(refuses(R"({"/etc/a.ini":{"S":{"k":"v"}}})")); // outside the game folder+ CHECK(refuses(R"({"Config/../../a.ini":{"S":{"k":"v"}}})"));+ CHECK(refuses(R"({"Config\\a.ini":{"S":{"k":"v"}}})")); // '/' separators only+ CHECK(refuses(R"({"Config//a.ini":{"S":{"k":"v"}}})"));+ CHECK(refuses(R"({"Config/a.cfg":{"S":{"k":"v"}}})")); // only .ini files+ CHECK(refuses(R"({"a.ini":{"S]":{"k":"v"}}})")); // would end the header early+ CHECK(refuses(R"({"a.ini":{"S":{"k=x":"v"}}})")); // would be another key+ CHECK(refuses(R"({"a.ini":{"S":{";k":"v"}}})")); // would be a comment+ CHECK(refuses(R"({"a.ini":{"S":{"k":"two\nlines"}}})"));+ CHECK(refuses(R"({"a.ini":{"S":{"k":""}}})")); // nothing to write+ CHECK(refuses(R"({"a.ini":{"S":{"k":"v"}},"A.INI":{"s":{"K":"w"}}})")); // the same value twice, ignoring case+ CHECK(reason.find("appears twice") != std::string::npos);+ std::string many = "{\"a.ini\":{\"S\":{";+ for (int index = 0; index < 17; ++index) many += std::string(index ? "," : "") + "\"k" + std::to_string(index) + "\":\"v\"";+ CHECK(refuses(many + "}}}") && reason.find("too many") != std::string::npos);+ }// Final Fantasy XIII asks DxDiag for its video memory, which Wine answers from wined3d, so the shipped// recipe sets wined3d's VideoMemorySize for its program. Its Direct3D 9 goes to DXVK (a shipped recipe// names its own overrides), and it wants the Steam emulator, not the game's own files.@@ -2094,8 +2131,10 @@ int main(int argc, char** argv) {with_extras.registry = {{"Software\\Wine\\AppDefaults\\a.exe\\Direct3D", "VideoMemorySize", "\"4096\""},{"Software\\Studio\\Game", "Language", "\"en\""}};with_extras.requirements = {{"audio", "ps5"}};+ with_extras.ini = {{"BmGame/Config/UserEngine.ini", "Engine.Engine", "Language", "int"}};CHECK(ParseGameRecipe(SerializeCommunityRecipe(BuildCommunityRecipe(with_extras, settings)), &exported, &reason));CHECK(exported.requirements == with_extras.requirements && exported.registry.size() == 2);+ CHECK(exported.ini == with_extras.ini);for (const auto& value : with_extras.registry)CHECK(std::any_of(exported.registry.begin(), exported.registry.end(), [&](const RegistryValue& read) {return read.key == value.key && read.name == value.name && read.data == value.data;diff --git a/tests/runtime_recipe_ini_test.cpp b/tests/runtime_recipe_ini_test.cppnew file mode 100644index 0000000..e5a9bbc--- /dev/null+++ b/tests/runtime_recipe_ini_test.cpp@@ -0,0 +1,126 @@+// SPDX-License-Identifier: GPL-3.0-or-later+#include "runtime/recipe_ini.h"++#include <cstdio>+#include <cstdlib>+#include <filesystem>+#include <fstream>+#include <iterator>+#include <string>+#include <sys/stat.h>+#include <unistd.h>++#define CHECK(condition) \+ do { \+ if (!(condition)) { \+ std::fprintf(stderr, "%s:%d: CHECK failed: %s\n", __FILE__, __LINE__, #condition); \+ std::exit(1); \+ } \+ } while (false)++namespace fs = std::filesystem;+using namespace playden::runtime;++namespace {+void Write(const fs::path& path, const std::string& bytes) {+ fs::create_directories(path.parent_path());+ std::ofstream(path, std::ios::binary) << bytes;+}+std::string Read(const fs::path& path) {+ std::ifstream in(path, std::ios::binary);+ return {std::istreambuf_iterator<char>(in), {}};+}+std::string Set(std::string text, const std::string& section, const std::string& key, const std::string& value,+ bool* changed = nullptr) {+ const bool did = SetIniValueIfEmpty(&text, section, key, value);+ if (changed) *changed = did;+ return text;+}+} // namespace++int main() {+ // Batman: Arkham Asylum's shipped UserEngine.ini (CRLF): Language goes after the section's last line.+ const std::string asylum =+ "[Configuration]\r\nBasedOn=..\\BmGame\\Config\\DefaultEngine.ini\r\n\r\n[Engine.Engine]\r\n"+ "bOnScreenKismetWarnings=FALSE\r\nbSubtitlesEnabled=FALSE\r\n";+ bool changed = false;+ CHECK(Set(asylum, "Engine.Engine", "Language", "int", &changed) == asylum + "Language=int\r\n" && changed);+ // The player's own language stays, whatever the case of the section and key.+ const auto chosen = asylum + "Language=fra\r\n";+ CHECK(Set(chosen, "engine.engine", "LANGUAGE", "int", &changed) == chosen && !changed);+ // An empty value is filled where it is, with spaces around '=' and the line ending kept.+ CHECK(Set("[Engine.Engine]\r\nLanguage = \r\nOther=1\r\n", "Engine.Engine", "Language", "int") ==+ "[Engine.Engine]\r\nLanguage = int\r\nOther=1\r\n");+ // Inserted before blank lines and the next section, in the first matching section.+ CHECK(Set("[A]\nx=1\n\n[B]\ny=2\n[A]\nz=3\n", "A", "Language", "int") == "[A]\nx=1\nLanguage=int\n\n[B]\ny=2\n[A]\nz=3\n");+ // A value in a repeated section counts too.+ CHECK(Set("[A]\nx=1\n[B]\n[A]\nLanguage=deu\n", "A", "Language", "int", &changed) == "[A]\nx=1\n[B]\n[A]\nLanguage=deu\n" &&+ !changed);+ // Comments and other keys that start the same way don't count.+ CHECK(Set("[A]\n;Language=deu\nLanguageX=1\n", "A", "Language", "int") == "[A]\n;Language=deu\nLanguageX=1\nLanguage=int\n");+ // An empty section, the last line without a line ending, a missing section and an empty file.+ CHECK(Set("[A]\n[B]\n", "A", "k", "v") == "[A]\nk=v\n[B]\n");+ CHECK(Set("[A]\nx=1", "A", "k", "v") == "[A]\nx=1\nk=v\n");+ CHECK(Set("[A]\r\nx=1\r\n", "Engine.Engine", "Language", "int") == "[A]\r\nx=1\r\n\r\n[Engine.Engine]\r\nLanguage=int\r\n");+ CHECK(Set("[A]\nx=1", "B", "k", "v") == "[A]\nx=1\n\n[B]\nk=v\n");+ CHECK(Set("", "B", "k", "v") == "[B]\nk=v\n");++ const auto root = fs::temp_directory_path() / ("playden-recipe-ini-" + std::to_string(::getpid()));+ fs::remove_all(root);+ const auto config = root / "BmGame/Config";+ Write(config / "UserEngine.ini", asylum);+ ::chmod((config / "UserEngine.ini").c_str(), 0666);+ const std::vector<IniValue> values = {{"BmGame/Config/UserEngine.ini", "Engine.Engine", "Language", "int"}};+ auto result = ApplyRecipeIniValues(root.string(), values);+ CHECK(result.ok && result.changed == std::vector<std::string>{"BmGame/Config/UserEngine.ini"} && result.skipped.empty());+ CHECK(Read(config / "UserEngine.ini") == asylum + "Language=int\r\n");+ // The file keeps its permissions (the game writes it back), and no temporary file is left.+ struct stat info {};+ CHECK(::stat((config / "UserEngine.ini").c_str(), &info) == 0 && (info.st_mode & 0777) == 0666);+ CHECK(std::distance(fs::directory_iterator(config), fs::directory_iterator()) == 1);+ // Idempotent: nothing to change, nothing written.+ const auto written = fs::last_write_time(config / "UserEngine.ini");+ result = ApplyRecipeIniValues(root.string(), values);+ CHECK(result.ok && result.changed.empty() && fs::last_write_time(config / "UserEngine.ini") == written);++ // File names match ignoring case, as on Windows; several values in one file are one write.+ fs::remove_all(root);+ Write(root / "bmgame/CONFIG/userengine.INI", "[Engine.Engine]\n");+ result = ApplyRecipeIniValues(root.string(), {{"BmGame/Config/UserEngine.ini", "Engine.Engine", "Language", "int"},+ {"BmGame/Config/UserEngine.ini", "Engine.Engine", "Other", "1"}});+ CHECK(result.ok && result.changed.size() == 1);+ CHECK(Read(root / "bmgame/CONFIG/userengine.INI") == "[Engine.Engine]\nLanguage=int\nOther=1\n");++ // A missing file is not created; a link is not followed; UTF-16 and oversized files are left alone.+ fs::remove_all(root);+ fs::create_directories(root / "Config");+ Write(root / "outside.ini", "[A]\n");+ fs::create_symlink(root / "outside.ini", root / "Config/Linked.ini");+ fs::create_symlink(root / "Config", root / "Folder");+ Write(root / "Config/Wide.ini", std::string("\xFF\xFE[\0A\0]\0", 8));+ Write(root / "Config/Big.ini", "[A]\n" + std::string(300 * 1024, ';'));+ result = ApplyRecipeIniValues(root.string(), {{"Config/Missing.ini", "A", "k", "v"},+ {"Config/Linked.ini", "A", "k", "v"},+ {"Folder/Wide.ini", "A", "k", "v"},+ {"Config/Wide.ini", "A", "k", "v"},+ {"Config/Big.ini", "A", "k", "v"}});+ CHECK(result.ok && result.changed.empty());+ CHECK(result.skipped == (std::vector<std::string>{"Config/Missing.ini: missing", "Config/Linked.ini: a link",+ "Folder/Wide.ini: a link", "Config/Wide.ini: not a plain text INI",+ "Config/Big.ini: unreadable or too large"}));+ CHECK(!fs::exists(root / "Config/Missing.ini") && Read(root / "outside.ini") == "[A]\n");++ // A folder the file can't be written in fails with a sentence for the player.+ if (::geteuid() != 0) {+ fs::remove_all(root);+ Write(root / "Config/Game.ini", "[A]\n");+ ::chmod((root / "Config").c_str(), 0555);+ result = ApplyRecipeIniValues(root.string(), {{"Config/Game.ini", "A", "k", "v"}});+ CHECK(!result.ok && result.message.find("Config/Game.ini") != std::string::npos);+ CHECK(Read(root / "Config/Game.ini") == "[A]\n");+ ::chmod((root / "Config").c_str(), 0755);+ }++ fs::remove_all(root);+ std::puts("recipe ini tests passed");+}