Merge pull request #24722 from WhiteAssassins/feat/web-local-game-patch

feat(web): apply a local game patch during conversion
This commit is contained in:
Dean authored and GitHub committed 2026-11-28 03:45:39 +13:00
commit c9ff6441ec
9 files changed
+104 -3

No files matched your search

+14
View File
@@ -76,8 +76,22 @@ emscripten::val Convert(const emscripten::val& request, const emscripten::val& c
options.WindowsGui = false;
options.WindowsDiagnostics = target == "windows";
options.ToIntel = request["toIntel"].as<bool>();
const auto patch = request["patch"];
if (!patch.isUndefined()) {
const auto text = patch.as<std::string>();
if (text.size() > 1024 * 1024) throw std::invalid_argument("Patch TOML exceeds 1 MiB");
options.TargetName = name;
options.Patches = Relinker::GamePatch::ParsePatchFile(text).Entries;
if (options.Patches.empty()) throw std::invalid_argument("Patch TOML has no patch entries");
}
const auto moduleRoot = input.ModuleRoot;
BrowserProgress progress(callback);
auto output = Relinker::Conversion(progress).Convert(std::move(input), options);
if (!options.Patches.empty()) {
std::vector<std::string> targets{name};
for (const auto& module : output.Modules) targets.push_back(Relinker::GamePatch::ModuleTargetName(module.SourcePath, moduleRoot));
Relinker::GamePatch::MatchTargets(options.Patches, targets);
}
result.set("executable", CopyBytes(output.Executable));
result.set("diagnostics", output.WindowsDiagnostics);
auto artifacts = emscripten::val::array();
+6 -1
View File
@@ -69,6 +69,8 @@ function update() {
const target = document.querySelector('input[name="target"]:checked').value;
const multi = selectedInputs.length > 1;
const inspected = inspectionComplete && summaries.length === selectedInputs.length;
$("patch-options").hidden = !inspected || multi;
$("patch").disabled = working || !inspected || multi;
const folderBlocked = $("save").value === "disk" && (target === "windows" || multi);
const folderOption = $("save").querySelector('[value="disk"]');
folderOption.disabled = !canStream || target === "windows" || multi;
@@ -391,6 +393,7 @@ async function selectInputs(inputs) {
worker?.terminate();
if (downloadUrl) { URL.revokeObjectURL(downloadUrl); downloadUrl = null; }
selectedInputs = inputs;
$("patch").value = "";
summaries = [];
inspectionComplete = false;
working = true;
@@ -433,6 +436,7 @@ $("change").onclick = () => {
inspectionComplete = false;
$("file").value = "";
$("folder").value = "";
$("patch").value = "";
$("app-list").replaceChildren();
for (const id of ["selection", "warnings", "error", "done", "download", "app-list"]) $(id).hidden = true;
$("acknowledge").checked = false;
@@ -512,7 +516,8 @@ $("convert").onclick = async () => {
$("status").hidden = false;
$("cancel").hidden = false;
$("error").hidden = true;
currentWorker.postMessage({ type: "convert", target, toIntel: $("intel").checked, mode: $("save").value, locale });
const patchFile = selectedInputs.length === 1 ? $("patch").files?.[0] : undefined;
currentWorker.postMessage({ type: "convert", target, toIntel: $("intel").checked, mode: $("save").value, patchFile, locale });
} catch (error) {
if (currentWorker === worker && preparingOutput && error.name !== "AbortError") {
await fail(error, { keepInspection: true });
+25
View File
@@ -40,6 +40,11 @@ export const messages = {
"saveOptionZip": "Save ZIP to disk · large apps",
"saveOptionDisk": "Save to folder · uncompressed",
"convertIntel": "Convert AMD-specific instructions for Intel CPUs",
"patchLabel": "Game patch (optional)",
"patchNote": "Choose one TOML file to apply during conversion. Maximum 1 MiB.",
"patchRequiresSingleApp": "A game patch can only be applied when converting one app.",
"patchTooLarge": "The game patch exceeds the 1 MiB limit.",
"patchReadError": "Could not read the game patch as UTF-8.",
"convertButton": "Convert & save →",
"cancelButton": "Cancel",
"conversionLog": "Conversion log",
@@ -404,6 +409,11 @@ export const messages = {
"saveOptionZip": "ZIP auf Datenträger speichern · große Apps",
"saveOptionDisk": "In Ordner speichern · unkomprimiert",
"convertIntel": "AMD-spezifische Befehle für Intel-CPUs konvertieren",
"patchLabel": "Spielpatch (optional)",
"patchNote": "Wähle eine TOML-Datei für die Konvertierung. Maximal 1 MiB.",
"patchRequiresSingleApp": "Ein Spielpatch kann nur bei der Konvertierung einer einzelnen App angewendet werden.",
"patchTooLarge": "Der Spielpatch überschreitet das Limit von 1 MiB.",
"patchReadError": "Der Spielpatch konnte nicht als UTF-8 gelesen werden.",
"convertButton": "Konvertieren & speichern →",
"cancelButton": "Abbrechen",
"conversionLog": "Konvertierungsprotokoll",
@@ -586,6 +596,11 @@ export const messages = {
"saveOptionZip": "حفظ ZIP على القرص · للتطبيقات الكبيرة",
"saveOptionDisk": "حفظ في مجلد · دون ضغط",
"convertIntel": "تحويل التعليمات الخاصة بـ AMD لتعمل على معالجات Intel",
"patchLabel": "رقعة اللعبة (اختياري)",
"patchNote": "اختر ملف TOML واحدًا لتطبيقه أثناء التحويل. الحد الأقصى 1 MiB.",
"patchRequiresSingleApp": "لا يمكن تطبيق رقعة اللعبة إلا عند تحويل تطبيق واحد.",
"patchTooLarge": "يتجاوز حجم رقعة اللعبة الحد الأقصى البالغ 1 MiB.",
"patchReadError": "تعذرت قراءة رقعة اللعبة بترميز UTF-8.",
"convertButton": "تحويل وحفظ ←",
"cancelButton": "إلغاء",
"conversionLog": "سجل التحويل",
@@ -768,6 +783,11 @@ export const messages = {
"saveOptionZip": "Enregistrer le ZIP sur le disque · applications volumineuses",
"saveOptionDisk": "Enregistrer dans un dossier · sans compression",
"convertIntel": "Convertir les instructions spécifiques à AMD pour les processeurs Intel",
"patchLabel": "Correctif de jeu (facultatif)",
"patchNote": "Choisissez un fichier TOML à appliquer pendant la conversion. Maximum 1 Mio.",
"patchRequiresSingleApp": "Un correctif de jeu ne peut être appliqué que lors de la conversion d’une seule application.",
"patchTooLarge": "Le correctif de jeu dépasse la limite de 1 Mio.",
"patchReadError": "Impossible de lire le correctif de jeu en UTF-8.",
"convertButton": "Convertir et enregistrer →",
"cancelButton": "Annuler",
"conversionLog": "Journal de conversion",
@@ -1307,6 +1327,11 @@ export const messages = {
"saveOptionZip": "ZIP olarak diske kaydet · büyük uygulamalar",
"saveOptionDisk": "Klasöre kaydet · sıkıştırılmamış",
"convertIntel": "Intel CPU'lar için AMD'ye özgü yönergeleri dönüştür",
"patchLabel": "Oyun yaması (isteğe bağlı)",
"patchNote": "Dönüştürme sırasında uygulamak için bir TOML dosyası seçin. En fazla 1 MiB.",
"patchRequiresSingleApp": "Oyun yaması yalnızca tek bir uygulama dönüştürülürken uygulanabilir.",
"patchTooLarge": "Oyun yaması 1 MiB sınırını aşıyor.",
"patchReadError": "Oyun yaması UTF-8 olarak okunamadı.",
"convertButton": "Dönüştür ve kaydet →",
"cancelButton": "İptal",
"conversionLog": "Dönüştürme günlüğü",
+1
View File
@@ -17,6 +17,7 @@
<div id="warnings" class="warnings" hidden><ul id="warning-list"></ul><label><input id="acknowledge" type="checkbox"> <span data-i18n="acknowledgeLabel">I understand and want to continue with these apps.</span></label></div>
<div class="settings"><fieldset id="target"><legend data-i18n="convertForLegend">Convert for</legend><div class="choices"><label><input type="radio" name="target" value="windows" checked> Windows <span>.exe</span></label><label><input type="radio" name="target" value="linux"> Linux <span>.elf</span></label></div></fieldset><div class="save-settings"><label for="save" data-i18n="saveResultLabel">Save the result</label><select id="save"><option value="memory" data-i18n="saveOptionMemory">Download in memory · small apps</option><option value="zip" data-i18n="saveOptionZip">Save ZIP to disk · large apps</option><option value="disk" data-i18n="saveOptionDisk">Save to folder · uncompressed</option></select><p id="save-note" class="fine"></p></div></div>
<div class="options"><label><input type="checkbox" id="intel"> <span data-i18n="convertIntel">Convert AMD-specific instructions for Intel CPUs</span></label></div>
<div id="patch-options" class="options" hidden><label for="patch" data-i18n="patchLabel">Game patch (optional)</label> <input id="patch" type="file" accept=".toml" aria-describedby="patch-note"><p id="patch-note" class="fine" data-i18n="patchNote">Choose one TOML file to apply during conversion. Maximum 1 MiB.</p></div>
<div class="action-row"><p id="ready-note" class="muted" data-i18n="readyNoteFallback">Choose a ZIP or folder to get started.</p><button id="convert" class="button" disabled data-i18n="convertButton">Convert &amp; save →</button><button id="cancel" class="plain" hidden data-i18n="cancelButton">Cancel</button></div>
<div id="status" class="status" hidden><div class="status-line"><strong id="phase" role="status"></strong><span id="percent"></span></div><progress id="progress" max="100" aria-labelledby="phase"></progress><p id="current-file" class="fine"></p><details><summary data-i18n="conversionLog">Conversion log</summary><pre id="log" dir="auto"></pre></details></div>
<div id="error" class="error" role="alert" hidden></div>
+6
View File
@@ -228,6 +228,7 @@ for (const kind of ["zip", "batch", "folder"]) {
assert.equal(get("warnings").hidden, false);
assert.equal(get("app-list").children.length, first.messages[0].inputs.length);
assert.equal(get("app-list").hidden, kind !== "batch");
assert.equal(get("patch-options").hidden, kind === "batch");
get("acknowledge").checked = true;
get("acknowledge").listeners.get("change")();
assert.equal(get("convert").disabled, false);
@@ -236,6 +237,8 @@ for (const kind of ["zip", "batch", "folder"]) {
assert.equal(first.terminated, true);
assert.equal(get("file").value, "");
assert.equal(get("folder").value, "");
assert.equal(get("patch").value, "");
assert.equal(get("patch-options").hidden, true);
assert.equal(get("selection").hidden, true);
assert.equal(get("warnings").hidden, true);
assert.equal(get("app-list").hidden, true);
@@ -262,8 +265,11 @@ for (const kind of ["zip", "batch", "folder"]) {
get("acknowledge").checked = true;
get("acknowledge").listeners.get("change")();
assert.equal(get("convert").disabled, false);
const patch = new File(["format = 1"], "patch.toml");
get("patch").files = [patch];
await get("convert").onclick();
assert.equal(replacement.messages.at(-1).type, "convert");
assert.equal(replacement.messages.at(-1).patchFile, patch);
assert.equal(replacement.terminated, false);
});
}
+26
View File
@@ -94,6 +94,32 @@ for (const target of ["windows", "linux"]) {
const converted = native.Convert(input, event => events.push(event));
assert.equal(converted.ok, true, converted.error);
assert.equal(converted.executable[0], target === "windows" ? 77 : 127);
if (kind === "ZIP") {
const readPatch = name => readFile(path.join(process.argv[3], name), "utf8");
const patch = await readPatch("valid.toml");
const patched = native.Convert({ ...input, patch }, () => {});
assert.equal(patched.ok, true, patched.error);
assert.notDeepEqual(patched.executable, converted.executable);
const modulePatch = await readPatch("module.toml");
const patchedModule = native.Convert({ ...input, patch: modulePatch }, () => {});
assert.equal(patchedModule.ok, true, patchedModule.error);
assert.equal(patchedModule.modules.length, 1);
assert.notDeepEqual(patchedModule.modules[0].bytes, converted.modules[0].bytes);
const mismatch = await readPatch("mismatch.toml");
for (const [badPatch, message] of [
[mismatch, /expected [0-9a-f]+ found [0-9a-f]+/iu],
[patch.replace("program.dat", "other.elf"), /unmatched patch target/iu],
["format = 1", /no patch entries/iu],
["format = 2", /unsupported format/iu]
]) {
const rejected = native.Convert({ ...input, patch: badPatch }, () => {});
assert.equal(rejected.ok, false);
assert.match(rejected.error, message);
assert.equal(rejected.executable, undefined);
assert.equal(rejected.modules, undefined);
}
assert.deepEqual(input.executable, executable);
}
if (target === "windows") {
const image = new DataView(converted.executable.buffer, converted.executable.byteOffset, converted.executable.byteLength);
assert.equal(image.getUint16(image.getUint32(60, true) + 24 + 68, true), 3);
+10
View File
@@ -92,6 +92,7 @@ async function convertInput(item, index, native, libraries, data, destination, d
const itemReport = reportFor(item, index);
if (inputs.length > 1) await current.inspect(itemReport);
const input = await current.conversionInput(data.target, data.toIntel, itemReport);
if (data.patch !== undefined) input.patch = data.patch;
const converted = native.Convert(input, itemReport);
if (!converted.ok) throw new Error(converted.error);
const { revision, release: { tag } } = libraries;
@@ -149,6 +150,15 @@ self.onmessage = async ({ data }) => {
if (data.target === "windows" && data.mode === "disk") throw new Error(translate(locale, "windowsFolderUnavailable"));
if (!inputs.length || summaries.length !== inputs.length) throw new Error(translate(locale, "inspectBeforeConvert"));
if (inputs.length > 1 && data.mode === "disk") throw new Error(translate(locale, "batchRequiresZip"));
if (data.patchFile !== undefined) {
if (inputs.length !== 1) throw new Error(translate(locale, "patchRequiresSingleApp"));
if (data.patchFile.size > 1024 * 1024) throw new Error(translate(locale, "patchTooLarge"));
try {
data.patch = new TextDecoder("utf-8", { fatal: true }).decode(await data.patchFile.arrayBuffer());
} catch {
throw new Error(translate(locale, "patchReadError"));
}
}
for (const summary of summaries) {
const selectedBytes = data.target === "windows" ? summary.windowsSelectedBytes : summary.selectedBytes;
if (data.target === "windows" && summary.windowsIconTooLarge) throw new Error(translate(locale, "iconTooLargeHint"));
+4
View File
@@ -8,6 +8,10 @@ The web converter also relinks ELF modules directly inside `Media/Modules/` and
The online converter can save Linux output as an uncompressed folder in supported browsers. It does not overwrite an existing destination folder. If conversion fails or is cancelled, it aborts the active file and attempts to remove the newly created output folder. If the browser prevents cleanup, the error names the folder that may contain incomplete files.
### Browser game patches
When converting one app, use **Game patch (optional)** to select one UTF-8 TOML file of up to 1 MiB. The browser uses the same patch parser and byte checks as the command line. Use the original executable file name or the module path relative to the app directory as the patch target. A patch that cannot be applied stops the conversion before packaging the output. The patch stays on your device.
### Browser batch conversion
Select or drop multiple app ZIP archives to convert them into one ZIP bundle. The converter inspects each app separately and puts its executable, libraries and `app0/` files in a numbered folder, so archives with the same filename remain separate. Batch output uses ZIP mode; saving to an uncompressed folder remains available for one Linux app at a time. The 256 MiB memory-download limit applies to the whole bundle, so use **Save ZIP to disk** for larger batches. If a batch is cancelled or any app fails, the converter aborts the incomplete bundle; any cleanup failure is reported instead of offering it as a completed result.
+12 -2
View File
@@ -11,6 +11,7 @@ import urllib.request
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT / "core/relinker/relinker/tests"))
from test_guest_intel_trampolines import main_fixture
from test_game_patches import patch_site, patch_text
from test_guest_module_directories import module_with_symbol
@@ -33,8 +34,17 @@ def main(argv=None):
) + ("directory-writer.test.mjs",))], check=True)
with tempfile.TemporaryDirectory(prefix="anyps5-web-") as directory:
fixture = Path(directory)
(fixture / "main.elf").write_bytes(main_fixture())
(fixture / "module.elf").write_bytes(module_with_symbol(True))
executable = bytes(main_fixture())
(fixture / "main.elf").write_bytes(executable)
address, expected = patch_site(executable)
(fixture / "valid.toml").write_text(patch_text(address, expected, target="program.dat"), encoding="utf-8")
(fixture / "mismatch.toml").write_text(patch_text(address, expected ^ 1, target="program.dat"), encoding="utf-8")
module = bytes(module_with_symbol(True))
(fixture / "module.elf").write_bytes(module)
address, expected = patch_site(module)
(fixture / "module.toml").write_text(
patch_text(address, expected, target="sce_module/library.prx.esbak"), encoding="utf-8"
)
source = archive.read_text(encoding="utf-8-sig")
match = re.search(r'from "(https://cdn.jsdelivr.net/[^"\n]+)"', source)
if not match: