Free fork of NotProton: Windows Steam games in Mac Steam, on CodeWeavers' Wine and Apple's Game Porting Toolkit
Swift apple-silicond3dmetaldxmtdxvkgame-porting-toolkitgptkmac-gamingmacosmetalfxrosetta-2steamsteam-playwinewinecx
Fix prefix and appinfo edge cases
NotProtonNot83e62d90d808
diff --git a/Makefile b/Makefileindex 5d74238..40ac529 100644--- a/Makefile+++ b/Makefile@@ -268,7 +268,7 @@ NATIVEPLATFORMCHECK := $(OUT_DIR)/nativeplatformcheck$(NATIVEPLATFORMCHECK): dylib/tests/nativeplatformcheck.c dylib/feats/nativeplatform.c dylib/feats/nativeplatform.h dylib/util/file.c@mkdir -p $(dir $@)- $(TEST_CC) -O1 -o $@ dylib/tests/nativeplatformcheck.c dylib/feats/nativeplatform.c dylib/util/file.c+ $(TEST_CC) -O1 -DHELPER_TIMEOUT_MS=1000 -o $@ dylib/tests/nativeplatformcheck.c dylib/feats/nativeplatform.c dylib/util/file.cwebpatch-fixtures:@if [ ! -d $(WEBPATCH_FIXTURES) ] || [ ! -f dylib/tests/gatecheck.c ]; then \diff --git a/app/Sources/NotProtonApp/Model/PrefixRebuild.swift b/app/Sources/NotProtonApp/Model/PrefixRebuild.swiftindex 37eff23..4c50ba3 100644--- a/app/Sources/NotProtonApp/Model/PrefixRebuild.swift+++ b/app/Sources/NotProtonApp/Model/PrefixRebuild.swift@@ -299,8 +299,8 @@ private final class Carry {private func escapes(_ landing: URL) -> Bool {let values = try? landing.resourceValues(forKeys: [.isSymbolicLinkKey])guard values?.isSymbolicLink == true else { return false }- let inside = fresh.resolvingSymlinksInPath().path(percentEncoded: false)- return !landing.resolvingSymlinksInPath().path(percentEncoded: false).hasPrefix(inside)+ let inside = fresh.resolvingSymlinksInPath().pathComponents+ return !landing.resolvingSymlinksInPath().pathComponents.starts(with: inside)}private func directoryExists(_ url: URL) -> Bool {diff --git a/app/Sources/NotProtonApp/PrefixesModel.swift b/app/Sources/NotProtonApp/PrefixesModel.swiftindex 2509465..33cb7f2 100644--- a/app/Sources/NotProtonApp/PrefixesModel.swift+++ b/app/Sources/NotProtonApp/PrefixesModel.swift@@ -97,7 +97,7 @@ final class PrefixesModel {prefixes = foundusage = usage.filter { id, _ in found.contains { $0.id == id } }let listTools = installedTools- (tools, records, stale, currentTools) = await Task.detached {+ let resolved = await Task.detached {let tools = listTools()var records: [String: PrefixBuildRecord] = [:]var stale = Set<String>()@@ -114,6 +114,7 @@ final class PrefixesModel {return (tools, records, stale, current)}.valueguard run == loadGeneration else { return }+ (tools, records, stale, currentTools) = resolvedselection = selection.filter { id in found.contains { $0.id == id } }var kept: [PrefixBackup] = []diff --git a/app/Tests/NotProtonAppTests/AppInfoToolTests.swift b/app/Tests/NotProtonAppTests/AppInfoToolTests.swiftindex ccb65c5..1d8126b 100644--- a/app/Tests/NotProtonAppTests/AppInfoToolTests.swift+++ b/app/Tests/NotProtonAppTests/AppInfoToolTests.swift@@ -245,6 +245,34 @@ struct AppInfoToolTests {#expect(result.stdout.isEmpty)}+ @Test("Deeply nested appinfo sections fail without crashing the helper", arguments: [false, true])+ func refusesExcessiveNesting(stringTable: Bool) throws {+ let depth = 32_768+ var keys = Cache()+ for _ in 0..<depth {+ keys.bytes.append(0x00)+ if stringTable { keys.u32(0) }+ else { keys.cstring("nested") }+ }+ keys.bytes.append(contentsOf: repeatElement(UInt8(0x08), count: depth + 1))+ let body = Self.entry(appID: 2100, keyData: keys.bytes)+ var file = Cache()+ file.u32(stringTable ? 0x0756_4429 : 0x0756_4428)+ file.u32(1)+ if stringTable { file.u64(UInt64(16 + body.count + 4)) }+ file.bytes.append(contentsOf: body)+ file.u32(0)+ if stringTable {+ file.u32(1)+ file.cstring("nested")+ }++ let result = try read(Data(file.bytes), "--platforms")+ #expect(result.status == 1)+ #expect(result.stdout.isEmpty)+ #expect(result.stderr.contains("cannot parse"))+ }+@Test("A cache that is not a cache fails instead of printing garbage")func refusesUnparsableFile() throws {let result = try read(Data(repeating: 0xab, count: 4096), "2100")diff --git a/app/Tests/NotProtonAppTests/PrefixToolsTests.swift b/app/Tests/NotProtonAppTests/PrefixToolsTests.swiftindex e209893..11d085f 100644--- a/app/Tests/NotProtonAppTests/PrefixToolsTests.swift+++ b/app/Tests/NotProtonAppTests/PrefixToolsTests.swift@@ -1400,6 +1400,32 @@ struct PrefixToolsTests {#expect(try String(contentsOf: parked, encoding: .utf8) == "progress")}+ @Test("A similarly named sibling directory is outside the rebuilt prefix")+ func siblingLandingDoesNotOverwriteOutsideFiles() throws {+ let fm = FileManager.default+ let dir = URL(filePath: fm.temporaryDirectory.path(percentEncoded: false))+ .appending(path: "np-sibling-escape-\(UUID().uuidString)")+ defer { try? fm.removeItem(at: dir) }+ let home = dir.appending(path: "home/Documents")+ try fm.createDirectory(at: home, withIntermediateDirectories: true)+ let prefix = try usedPrefix(in: dir, home: home)+ let old = prefix.pfx.appending(path: "drive_c/users/crossover/Saves/game.sav")+ try fm.createDirectory(at: old.deletingLastPathComponent(), withIntermediateDirectories: true)+ try Data("progress".utf8).write(to: old)+ let runner = try fakeRunner(in: dir, home: home, extra: """+ mkdir -p "$WINEPREFIX-outside"+ printf untouched > "$WINEPREFIX-outside/game.sav"+ ln -s "$WINEPREFIX-outside" "$WINEPREFIX/drive_c/users/steamuser/Saves"+ """)+ try PrefixTools.recreate(prefix, runner: runner)++ let root = SteamLibrary(root: dir).compatdata.appending(path: "1574480")+ let outside = root.appending(path: "pfx.rebuild-outside/game.sav")+ let parked = root.appending(path: "pfx/drive_c/users/steamuser/Saves BACKUP/game.sav")+ #expect(try String(contentsOf: outside, encoding: .utf8) == "untouched")+ #expect(try String(contentsOf: parked, encoding: .utf8) == "progress")+ }+@Test("A save file is kept when a directory holds its name")func fileUnderADirectoryLandingIsKept() throws {let dir = try rebuild(diff --git a/app/Tests/NotProtonAppTests/PrefixesModelTests.swift b/app/Tests/NotProtonAppTests/PrefixesModelTests.swiftindex eb8d89b..d5b5310 100644--- a/app/Tests/NotProtonAppTests/PrefixesModelTests.swift+++ b/app/Tests/NotProtonAppTests/PrefixesModelTests.swift@@ -77,6 +77,29 @@ private final class Asked: @unchecked Sendable {}}+private final class DelayedToolScan: @unchecked Sendable {+ private let lock = NSLock()+ private var calls = 0+ private let tools: [InstalledTool]+ let entered = DispatchSemaphore(value: 0)+ let resume = DispatchSemaphore(value: 0)++ init(_ tools: [InstalledTool]) { self.tools = tools }++ func list() -> [InstalledTool] {+ let first = lock.withLock {+ calls += 1+ return calls == 1+ }+ if first {+ entered.signal()+ resume.wait()+ return []+ }+ return tools+ }+}+@MainActor@Suite("Loading prefixes")struct PrefixesModelTests {@@ -203,6 +226,45 @@ struct PrefixesModelTests {#expect(!model.isLoading)}+ @Test("A superseded tool scan cannot replace the newer prefix records")+ func supersededToolScanPublishesNothing() async throws {+ let (oldDir, oldLibrary) = try makeLibrary(appIDs: ["1574480"])+ defer { try? FileManager.default.removeItem(at: oldDir) }+ let (newDir, newLibrary) = try makeLibrary(appIDs: ["4401430"])+ defer { try? FileManager.default.removeItem(at: newDir) }+ for (library, appID) in [(oldLibrary, "1574480"), (newLibrary, "4401430")] {+ try write("\(Self.tool.build)\n\(Self.tool.display)\n",+ to: library.compatdata.appending(path: "\(appID)/\(PrefixTools.buildRecordName)"))+ }+ let libraries = Libraries([oldLibrary])+ let scan = DelayedToolScan([Self.tool])+ defer { scan.resume.signal() }+ let model = PrefixesModel(libraries: { libraries.current }, installedTools: { scan.list() })+ let first = Task { await model.load() }+ let entered = await withCheckedContinuation { continuation in+ DispatchQueue.global().async {+ continuation.resume(returning: scan.entered.wait(timeout: .now() + 5) == .success)+ }+ }+ try #require(entered)++ libraries.current = [newLibrary]+ await model.load()+ let current = try #require(model.prefixes.first)+ #expect(model.tools.map(\.build) == [Self.tool.build])+ #expect(Set(model.currentTools.keys) == [current.id])++ scan.resume.signal()+ await first.value+ #expect(model.prefixes.map(\.id) == [current.id])+ #expect(model.tools.map(\.build) == [Self.tool.build])+ #expect(Set(model.records.keys) == [current.id])+ #expect(Set(model.currentTools.keys) == [current.id])+ #expect(!model.isStale(current))+ #expect(!model.isStale(WinePrefix(appID: "1574480", name: nil, library: oldLibrary, lastUsed: nil)))+ #expect(!model.isLoading)+ }+@Test("Loading again from a changed library replaces the previous results")func reloadReplacesResults() async throws {let (oldDir, oldLibrary) = try makeLibrary(appIDs: ["1574480", "1649240"])diff --git a/dylib/feats/nativeplatform.c b/dylib/feats/nativeplatform.cindex 70cc76d..7be2842 100644--- a/dylib/feats/nativeplatform.c+++ b/dylib/feats/nativeplatform.c@@ -20,7 +20,9 @@#define OUTPUT_MAX (4u << 20)// sp.js is held up until this returns.+#ifndef HELPER_TIMEOUT_MS#define HELPER_TIMEOUT_MS 10000+#endifstatic long long now_ms(void) {struct timespec ts;@@ -28,10 +30,9 @@ static long long now_ms(void) {return (long long)ts.tv_sec * 1000 + ts.tv_nsec / 1000000;}-static char *read_output(int fd, pid_t pid) {+static char *read_output(int fd, pid_t pid, long long deadline) {char *buf = malloc(OUTPUT_MAX + 1);size_t len = 0;- long long deadline = now_ms() + HELPER_TIMEOUT_MS;while (buf) {long long left = deadline - now_ms();struct pollfd p = { fd, POLLIN, 0 };@@ -92,6 +93,7 @@ static char *run_helper(void) {posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETSIGMASK | POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_CLOEXEC_DEFAULT);char *argv[] = { tool, vdf, "--platforms", NULL };pid_t pid;+ long long deadline = now_ms() + HELPER_TIMEOUT_MS;int rc = posix_spawn(&pid, tool, &actions, &attr, argv, *_NSGetEnviron());posix_spawnattr_destroy(&attr);posix_spawn_file_actions_destroy(&actions);@@ -102,11 +104,25 @@ static char *run_helper(void) {return NULL;}- char *out = read_output(fds[0], pid);+ char *out = read_output(fds[0], pid, deadline);close(fds[0]);+ if (!out) kill(pid, SIGKILL);int status = 0;pid_t done;- while ((done = waitpid(pid, &status, 0)) < 0 && errno == EINTR) {}+ for (;;) {+ done = waitpid(pid, &status, WNOHANG);+ if (done == pid || (done < 0 && errno != EINTR)) break;+ long long left = deadline - now_ms();+ if (left <= 0) {+ if (out) NP_WARN("nativeplatform: appinfo helper timed out before exiting");+ kill(pid, SIGKILL);+ free(out);+ out = NULL;+ while ((done = waitpid(pid, &status, 0)) < 0 && errno == EINTR) {}+ break;+ }+ poll(NULL, 0, (int)(left < 10 ? left : 10));+ }if (done != pid || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {if (out) NP_WARN("nativeplatform: appinfo helper failed (status %d)", status);free(out);diff --git a/dylib/tests/nativeplatformcheck.c b/dylib/tests/nativeplatformcheck.cindex 87ade6c..116aa99 100644--- a/dylib/tests/nativeplatformcheck.c+++ b/dylib/tests/nativeplatformcheck.c@@ -60,6 +60,9 @@ int main(void) {expect("a swapped order", "printf 'windows=2\\nmac=1\\n'", NULL);expect("an extra line", "printf 'mac=1\\nwindows=2\\nlinux=3\\n'", NULL);expect("no newline at the end", "printf 'mac=1\\nwindows=2'", NULL);+ expect("a helper that stalls after closing stdout",+ "printf 'mac=1\\nwindows=2\\n'; exec 1>&-; exec /bin/sleep 3", NULL);+ expect("a helper that stalls without output", "exec /bin/sleep 3", NULL);helper(NULL);rmdir(dir);diff --git a/helpers/appinfo.swift b/helpers/appinfo.swiftindex feb9c61..9a87550 100644--- a/helpers/appinfo.swift+++ b/helpers/appinfo.swift@@ -27,6 +27,7 @@ enum VDFError: Error {case unknownType(UInt8)case unknownMagic(UInt32)case badStringIndex(UInt32)+ case excessiveNesting}indirect enum Value {@@ -111,7 +112,8 @@ func readStringTable(_ b: [UInt8], at offset: Int) throws -> [String] {return out}-func readSection(_ c: inout Cursor, _ table: [String]?) throws -> [String: Value] {+func readSection(_ c: inout Cursor, _ table: [String]?, depth: Int = 0) throws -> [String: Value] {+ guard depth < 64 else { throw VDFError.excessiveNesting }var out: [String: Value] = [:]while true {let type = try c.u8()@@ -128,7 +130,7 @@ func readSection(_ c: inout Cursor, _ table: [String]?) throws -> [String: Valueswitch type {// Handles every type the format defines. An unused-but-legal type inside// an app entry would otherwise drop the whole entry and its name.- case 0x00: out[key] = .section(try readSection(&c, table))+ case 0x00: out[key] = .section(try readSection(&c, table, depth: depth + 1))case 0x01: out[key] = .string(try c.cstring())case 0x02: out[key] = .number(Int64(Int32(bitPattern: try c.u32())))case 0x03: try c.skip(4)