Skip to content

Free fork of NotProton: Windows Steam games in Mac Steam, on CodeWeavers' Wine and Apple's Game Porting Toolkit

fix(prefix): judge a rebuilt prefix by its last registry keys, and stop backup pile-up (#1947)

Raystormse5f7bba9e212
diff --git a/app/Sources/BridgeplayApp/Model/PrefixRebuild.swift b/app/Sources/BridgeplayApp/Model/PrefixRebuild.swift
index 23d0eba..4efe914 100644
--- a/app/Sources/BridgeplayApp/Model/PrefixRebuild.swift
+++ b/app/Sources/BridgeplayApp/Model/PrefixRebuild.swift
@@ -44,11 +44,6 @@ extension PrefixTools {
// A wineboot whose wineserver died never exits. Slow runs on a loaded Mac take under a minute.
private static let wineTimeLimit: DispatchTimeInterval = .seconds(300)
- // A healthy system.reg is 3.4 MB. A wineboot whose installer was killed exits 0 at 2 MB,
- // and the next launch does not repair it.
- // CEILING: a size floor, so an engine with a much smaller registry is refused — a list of late keys would not be.
- private static let smallestSystemRegistry = 3_000_000
-
private static func rebuild(
_ prefix: WinePrefix, runner: URL, flavor: CompatTool.Flavor,
now: Date, keepBackup: Bool, record: InstalledTool? = nil,
@@ -113,7 +108,7 @@ extension PrefixTools {
detail: String(localized: "Wine did not finish building the new prefix. The prefix has been left as it was and nothing has been lost.")
)
}
- guard builtWhole(fresh) else {
+ guard builtWhole(fresh, runner: runner) else {
AppLog.note("rebuild \(prefix.appID) refused, wineboot left an incomplete prefix")
throw StepFailure(
step: String(localized: "Recreate prefix"),
@@ -211,13 +206,32 @@ extension PrefixTools {
return slot
}
- private static func builtWhole(_ fresh: URL) -> Bool {
+ // A wineboot whose wine.inf installer was killed still exits 0, with a registry the next
+ // launch does not repair. Each install writes its keys after the slow DLL registration:
+ // the services come last in the 64-bit one, AeDebug last in the 32-bit one, which only
+ // runs on an engine with 32-bit Windows DLLs.
+ static func builtWhole(_ fresh: URL, runner: URL) -> Bool {
func size(_ name: String) -> Int {
let values = try? fresh.appending(path: name).resourceValues(forKeys: [.fileSizeKey])
return values?.fileSize ?? 0
}
- return size("system.reg") >= smallestSystemRegistry
- && size("user.reg") > 0 && size("userdef.reg") > 0
+ guard size("user.reg") > 0, size("userdef.reg") > 0,
+ let system = try? Data(contentsOf: fresh.appending(path: "system.reg"))
+ else { return false }
+ var keys = Set<String>()
+ for line in String(decoding: system, as: UTF8.self).lowercased().split(separator: "\n")
+ where line.hasPrefix("[") {
+ if let end = line.firstIndex(of: "]") { keys.insert(String(line[...end])) }
+ }
+ let services = ["controlset001", "currentcontrolset"].contains {
+ keys.contains(#"[system\\\#($0)\\services\\nsiproxy]"#)
+ }
+ let wow64 = runner.appending(path: "lib/wine/i386-windows")
+ guard FileManager.default.fileExists(atPath: wow64.path(percentEncoded: false)) else {
+ return services
+ }
+ return services
+ && keys.contains(#"[software\\wow6432node\\microsoft\\windows nt\\currentversion\\aedebug]"#)
}
private static func layOutProfile(in fresh: URL) {
@@ -390,6 +404,14 @@ private final class Carry {
private func park(_ source: URL, beside landing: URL) {
let parent = landing.deletingLastPathComponent()
+ // Each engine switch would park the other engine's copy again. Kept as carried, so a
+ // later file of the same name is parked rather than put over it.
+ if let same = family(of: landing).first(where: {
+ fm.contentsEqual(atPath: source.path(percentEncoded: false), andPath: $0.path(percentEncoded: false))
+ }) {
+ carried.insert(identity(of: same))
+ return
+ }
var name = landing.lastPathComponent + " BACKUP"
var next = 2
while fm.fileExists(atPath: parent.appending(path: name).path(percentEncoded: false)) {
@@ -401,6 +423,18 @@ private final class Carry {
carried.insert(identity(of: parked))
}
+ // The name and its parked copies, "Name BACKUP", "Name BACKUP 2" and "Name BACKUP BACKUP".
+ private func family(of landing: URL) -> [URL] {
+ let parent = landing.deletingLastPathComponent()
+ let suffix = #/( BACKUP( \d+)?)+$/#
+ let root = landing.lastPathComponent.replacing(suffix, with: "")
+ let names = (try? fm.contentsOfDirectory(atPath: parent.path(percentEncoded: false))) ?? []
+ return names.filter { name in
+ name == root
+ || (name.hasPrefix(root) && name.dropFirst(root.count).wholeMatch(of: suffix) != nil)
+ }.map { parent.appending(path: $0) }
+ }
+
// realpath gives the name on disk, so the volume's own folding decides which names are one
// file, including folds lowercased() misses. Lowercased too: on a volume that keeps names
// apart, a false match only parks a copy.
diff --git a/app/Sources/BridgeplayApp/Model/SetupChecks.swift b/app/Sources/BridgeplayApp/Model/SetupChecks.swift
index c1d509e..43f987e 100644
--- a/app/Sources/BridgeplayApp/Model/SetupChecks.swift
+++ b/app/Sources/BridgeplayApp/Model/SetupChecks.swift
@@ -109,22 +109,18 @@ enum SetupChecks {
// would pass as installed. A Steam.app that appeared meanwhile is kept.
let fm = FileManager.default
let staged = app.deletingLastPathComponent().appending(path: "\(stagedPrefix)\(UUID().uuidString)")
- let stale = stages.claim(staged)
+ let hold = try StageLock(claiming: staged)
defer {
try? fm.removeItem(at: staged)
- stages.release(staged)
- }
- for leftover in stale {
- do { try fm.removeItem(at: leftover) }
- catch { AppLog.note("setup: could not remove \(leftover.lastPathComponent): \(error.localizedDescription)") }
+ hold.release()
}
+ StageLock.sweep(in: staged.deletingLastPathComponent(), prefix: stagedPrefix)
try copy(mounted, staged)
do { try fm.moveItem(at: staged, to: app) }
catch where isAppBundle(app) {}
}
private static let stagedPrefix = ".Steam.app-"
- private static let stages = Stages()
private static func isAppBundle(_ app: URL) -> Bool {
var isDirectory: ObjCBool = false
@@ -132,29 +128,6 @@ enum SetupChecks {
return FileManager.default.fileExists(atPath: plist, isDirectory: &isDirectory) && !isDirectory.boolValue
}
- // A force quit leaves its staged copy behind. Listed under the lock, so a copy that has
- // claimed its name is never taken for one, and one that claims later isn't in the list yet.
- private final class Stages: @unchecked Sendable {
- private let lock = NSLock()
- private var inUse: Set<String> = []
-
- func claim(_ staged: URL) -> [URL] {
- let folder = staged.deletingLastPathComponent()
- return lock.withLock {
- inUse.insert(staged.lastPathComponent)
- let names = (try? FileManager.default.contentsOfDirectory(atPath: folder.path(percentEncoded: false))) ?? []
- return names.filter { name in
- name.hasPrefix(stagedPrefix) && !inUse.contains(name)
- && UUID(uuidString: String(name.dropFirst(stagedPrefix.count))) != nil
- }.map { folder.appending(path: $0) }
- }
- }
-
- func release(_ staged: URL) {
- _ = lock.withLock { inUse.remove(staged.lastPathComponent) }
- }
- }
-
static let step = String(localized: "Install Steam")
}
diff --git a/app/Sources/BridgeplayApp/Support/GameDefaults.swift b/app/Sources/BridgeplayApp/Support/GameDefaults.swift
index f78c838..5bb94be 100644
--- a/app/Sources/BridgeplayApp/Support/GameDefaults.swift
+++ b/app/Sources/BridgeplayApp/Support/GameDefaults.swift
@@ -113,7 +113,7 @@ enum GameDefaults {
var requirement: Requirement? {
switch self {
- case .nvapi, .metalFX: .d3dmetal
+ case .nvapi, .dlssFrameGen, .metalFX: .d3dmetal
default: nil
}
}
diff --git a/app/Sources/BridgeplayApp/Support/StageLock.swift b/app/Sources/BridgeplayApp/Support/StageLock.swift
new file mode 100644
index 0000000..b09dc73
--- /dev/null
+++ b/app/Sources/BridgeplayApp/Support/StageLock.swift
@@ -0,0 +1,65 @@
+import Darwin
+import Foundation
+
+// A lock file beside a copy staged in a shared folder, held while the copy is made. flock holds
+// across processes and users, so the CLI or another user's app never takes a live copy for one
+// a force quit left behind.
+struct StageLock {
+ private let file: String
+ private let descriptor: Int32
+
+ init(claiming staged: URL) throws {
+ file = Self.lockPath(for: staged)
+ // Locked as it is made, so a sweep never finds it unheld. Readable by every user, who
+ // need only open it to test the lock.
+ descriptor = open(file, O_RDONLY | O_CREAT | O_EXCL | O_EXLOCK | O_CLOEXEC, 0o644)
+ guard descriptor >= 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) }
+ }
+
+ // After the staged copy is gone, so a sweep that finds the copy finds the lock held.
+ func release() {
+ unlink(file)
+ close(descriptor)
+ }
+
+ // Removes the copies whose lock nobody holds. One with no lock file comes from a build
+ // before these and is left until it is older than any copy takes.
+ static func sweep(in folder: URL, prefix: String, unlockedAge: TimeInterval = 3600, now: Date = .now) {
+ let fm = FileManager.default
+ let names = (try? fm.contentsOfDirectory(atPath: folder.path(percentEncoded: false))) ?? []
+ for name in names where name.hasPrefix(prefix) {
+ var token = name.dropFirst(prefix.count)
+ let isLock = token.hasSuffix(lockSuffix)
+ if isLock { token = token.dropLast(lockSuffix.count) }
+ guard UUID(uuidString: String(token)) != nil else { continue }
+ let staged = folder.appending(path: "\(prefix)\(token)")
+ let lock = lockPath(for: staged)
+ let held = open(lock, O_RDONLY | O_EXLOCK | O_NONBLOCK | O_CLOEXEC)
+ if held >= 0 {
+ defer { close(held) }
+ if remove(staged) { unlink(lock) }
+ } else if errno == ENOENT, !isLock {
+ let made = (try? staged.resourceValues(forKeys: [.creationDateKey]))?.creationDate
+ if let made, now.timeIntervalSince(made) > unlockedAge { _ = remove(staged) }
+ }
+ }
+ }
+
+ private static let lockSuffix = ".lock"
+
+ private static func lockPath(for staged: URL) -> String {
+ staged.path(percentEncoded: false) + lockSuffix
+ }
+
+ private static func remove(_ staged: URL) -> Bool {
+ let fm = FileManager.default
+ guard fm.fileExists(atPath: staged.path(percentEncoded: false)) else { return true }
+ do {
+ try fm.removeItem(at: staged)
+ return true
+ } catch {
+ AppLog.note("setup: could not remove \(staged.lastPathComponent): \(error.localizedDescription)")
+ return false
+ }
+ }
+}
diff --git a/app/Tests/BridgeplayAppTests/GameDefaultsTests.swift b/app/Tests/BridgeplayAppTests/GameDefaultsTests.swift
index 38d5e10..f534029 100644
--- a/app/Tests/BridgeplayAppTests/GameDefaultsTests.swift
+++ b/app/Tests/BridgeplayAppTests/GameDefaultsTests.swift
@@ -63,6 +63,12 @@ import Testing
#expect(GameDefaults.value(.frameGen, in: "BRIDGEPLAY_FRAMEGEN=1\n") == "2")
}
+ // The run script applies these only on D3DMetal, so their rows carry its caption.
+ @Test func d3dMetalSettingsNameTheirRequirement() {
+ let needing = GameDefaults.Setting.allCases.filter { $0.requirement == .d3dmetal }
+ #expect(Set(needing) == [.nvapi, .dlssFrameGen, .metalFX])
+ }
+
@Test func layersResolveAsTheRunScriptReadsThem() {
let shipped = "NVAPI=1\nBACKEND=dxmt\n"
let user = "BACKEND=dxvk\n"
diff --git a/app/Tests/BridgeplayAppTests/PrefixToolsTests.swift b/app/Tests/BridgeplayAppTests/PrefixToolsTests.swift
index 8d81003..8c230aa 100644
--- a/app/Tests/BridgeplayAppTests/PrefixToolsTests.swift
+++ b/app/Tests/BridgeplayAppTests/PrefixToolsTests.swift
@@ -598,7 +598,9 @@ struct PrefixToolsTests {
printf template > "$WINEPREFIX/drive_c/users/crossover/AppData/wine.ini"
printf template > "$WINEPREFIX/drive_c/users/crossover/AppData/fresh.ini"
printf 'fresh user' > "$WINEPREFIX/user.reg"
- { printf 'fresh system'; head -c 3000000 /dev/zero; } > "$WINEPREFIX/system.reg"
+ cat > "$WINEPREFIX/system.reg" <<'REG'
+ \(Self.wholeSystemRegistry)
+ REG
printf 'fresh userdef' > "$WINEPREFIX/userdef.reg"
ln -s "\(home.path(percentEncoded: false))" "$WINEPREFIX/drive_c/users/crossover/Documents"
\(extra)
@@ -906,10 +908,79 @@ struct PrefixToolsTests {
#expect(text("same.ini BACKUP") == nil)
}
- // A killed installer leaves wineboot exiting 0 with a registry too small to be a prefix.
+ @Test("Switching engines back and forth does not park the same file again")
+ func rebuildsDoNotPileUpBackups() throws {
+ let fm = FileManager.default
+ let dir = URL(filePath: NSTemporaryDirectory()).appending(path: UUID().uuidString)
+ defer { try? fm.removeItem(at: dir) }
+ let home = dir.appending(path: "home")
+ try fm.createDirectory(at: home, withIntermediateDirectories: true)
+ let engines = try ["a", "b"].map { engine in
+ try fakeRunner(in: dir.appending(path: engine), home: home, extra: """
+ mkdir -p "$WINEPREFIX/drive_c/Program Files/game"
+ printf \(engine) > "$WINEPREFIX/drive_c/Program Files/game/x.dll"
+ """)
+ }
+ let prefix = try usedPrefix(in: dir, home: home)
+ let game = prefix.pfx.appending(path: "drive_c/Program Files/game")
+ try fm.createDirectory(at: game, withIntermediateDirectories: true)
+ try Data("mine".utf8).write(to: game.appending(path: "x.dll"))
+
+ for round in 0..<5 {
+ try PrefixTools.recreate(prefix, runner: engines[round % 2], keepBackup: false)
+ }
+
+ var kept: [String: String] = [:]
+ for name in try fm.contentsOfDirectory(atPath: game.path(percentEncoded: false)) {
+ kept[name] = try String(contentsOf: game.appending(path: name), encoding: .utf8)
+ }
+ #expect(kept == ["x.dll": "a", "x.dll BACKUP": "b", "x.dll BACKUP BACKUP": "mine"])
+ }
+
+ @Test("A prefix is whole by the keys wineboot writes last, not by its size")
+ func wholePrefixIsJudgedByItsLastKeys() throws {
+ let fm = FileManager.default
+ let dir = URL(filePath: NSTemporaryDirectory()).appending(path: UUID().uuidString)
+ defer { try? fm.removeItem(at: dir) }
+ let fresh = dir.appending(path: "pfx")
+ let runner = dir.appending(path: "runner")
+ try fm.createDirectory(at: fresh, withIntermediateDirectories: true)
+ try Data("user".utf8).write(to: fresh.appending(path: "user.reg"))
+ try Data("userdef".utf8).write(to: fresh.appending(path: "userdef.reg"))
+ func whole(_ registry: String) throws -> Bool {
+ try Data(registry.utf8).write(to: fresh.appending(path: "system.reg"))
+ return PrefixTools.builtWhole(fresh, runner: runner)
+ }
+ let lines = Self.wholeSystemRegistry.split(separator: "\n").map(String.init)
+ let services = lines[1]
+ let aeDebug = lines[2]
+
+ #expect(try whole(Self.wholeSystemRegistry))
+ #expect(try whole(services))
+ #expect(try whole(services.replacing("ControlSet001", with: "CurrentControlSet").uppercased()))
+ #expect(try !whole(aeDebug))
+ #expect(try !whole(String(repeating: "[Software\\\\Classes\\\\x] 1\n", count: 200_000)))
+
+ try fm.createDirectory(at: runner.appending(path: "lib/wine/i386-windows"), withIntermediateDirectories: true)
+ #expect(try whole(Self.wholeSystemRegistry))
+ #expect(try !whole(services))
+ }
+
+ // The last keys the 64-bit and the 32-bit wine.inf installs write, far short of the 3.4 MB
+ // a WineCX prefix has.
+ static let wholeSystemRegistry = #"""
+ fresh system
+ [System\\ControlSet001\\Services\\nsiproxy] 1792492724
+ [Software\\Wow6432Node\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug] 1792492786
+ """#
+
+ // A killed installer leaves wineboot exiting 0 with a registry missing what it writes last.
@Test("A wineboot that exits 0 with a partial registry leaves the prefix alone", arguments: [
#"printf small > "$WINEPREFIX/system.reg""#,
#"rm -f "$WINEPREFIX/userdef.reg""#,
+ #"sed -i '' /nsiproxy/d "$WINEPREFIX/system.reg""#,
+ // The 32-bit install killed on an engine that has one.
+ #"mkdir -p "${0%/*}/../i386-windows"; sed -i '' /AeDebug/d "$WINEPREFIX/system.reg""#,
])
func rebuildRefusesAPartialPrefix(extra: String) throws {
let fm = FileManager.default
diff --git a/app/Tests/BridgeplayAppTests/SetupAssistantTests.swift b/app/Tests/BridgeplayAppTests/SetupAssistantTests.swift
index 8431cbe..e6efd3c 100644
--- a/app/Tests/BridgeplayAppTests/SetupAssistantTests.swift
+++ b/app/Tests/BridgeplayAppTests/SetupAssistantTests.swift
@@ -374,8 +374,18 @@ struct SetupChecksTests {
let dir = try scratchDirectory("setup-steam-stale")
defer { try? fm.removeItem(at: dir) }
let (image, applications) = try steamImage(in: dir)
- let stale = ".Steam.app-\(UUID().uuidString)"
- try fm.createDirectory(at: applications.appending(path: "\(stale)/Contents"), withIntermediateDirectories: true)
+ func stage(_ name: String) throws {
+ try fm.createDirectory(at: applications.appending(path: "\(name)/Contents"), withIntermediateDirectories: true)
+ }
+ // A lock file nobody holds, a lock file alone, and a lock-less copy from an older build.
+ let unlocked = ".Steam.app-\(UUID().uuidString)"
+ try stage(unlocked)
+ try Data().write(to: applications.appending(path: "\(unlocked).lock"))
+ try Data().write(to: applications.appending(path: ".Steam.app-\(UUID().uuidString).lock"))
+ let old = ".Steam.app-\(UUID().uuidString)"
+ try stage(old)
+ try fm.setAttributes([.creationDate: Date.now.addingTimeInterval(-7200)],
+ ofItemAtPath: applications.appending(path: old).path(percentEncoded: false))
let kept = [".Steam.app-notes", ".Steam.app-\(UUID().uuidString)x", "Steam.app-\(UUID().uuidString)"]
for name in kept { try Data().write(to: applications.appending(path: name)) }
@@ -385,6 +395,29 @@ struct SetupChecksTests {
== (kept + ["Steam.app"]).sorted())
}
+ // Another process's lock, or an older build's copy that may still be under way.
+ @Test("A copy another process holds, or a recent lock-less one, is kept")
+ func liveStagedCopiesAreKept() throws {
+ let fm = FileManager.default
+ let dir = try scratchDirectory("setup-steam-live")
+ defer { try? fm.removeItem(at: dir) }
+ let (image, applications) = try steamImage(in: dir)
+ let held = ".Steam.app-\(UUID().uuidString)"
+ let recent = ".Steam.app-\(UUID().uuidString)"
+ for name in [held, recent] {
+ try fm.createDirectory(at: applications.appending(path: "\(name)/Contents"), withIntermediateDirectories: true)
+ }
+ let lock = open(applications.appending(path: "\(held).lock").path(percentEncoded: false),
+ O_RDONLY | O_CREAT | O_EXLOCK, 0o644)
+ #expect(lock >= 0)
+ defer { close(lock) }
+
+ try SetupChecks.copySteam(from: image, to: applications.appending(path: "Steam.app"), verify: { _ in })
+
+ #expect(try fm.contentsOfDirectory(atPath: applications.path(percentEncoded: false)).sorted()
+ == [held, "\(held).lock", recent, "Steam.app"].sorted())
+ }
+
@Test("A staged copy still being written is not swept by another install")
func stagedCopyInUseIsKept() throws {
let fm = FileManager.default