Skip to content

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

Rebuild prefixes from the game's Compatibility page when switching CrossOver versions

NotProtonNot730f10055b85
diff --git a/.github/workflows/app.yml b/.github/workflows/app.yml
index 0332cd0..bf5565d 100644
--- a/.github/workflows/app.yml
+++ b/.github/workflows/app.yml
@@ -119,6 +119,7 @@ jobs:
make -s activatecheck
make -s compatcheck
make -s compatsvc-check
+ make -s prefixstate-check
make -s shortcutcheck
make -s launch-shell
make -s envcheck
diff --git a/Makefile b/Makefile
index d7741d7..f181576 100644
--- a/Makefile
+++ b/Makefile
@@ -44,6 +44,7 @@ SRCS := \
dylib/feats/compat.c \
dylib/feats/webui.c \
dylib/feats/compatsvc.c \
+ dylib/feats/prefixstate.c \
dylib/feats/usershortcuts.c \
dylib/feats/webpatch.c \
dylib/feats/nativeplatform.c \
@@ -70,7 +71,7 @@ DEPS := $(OBJS:.o=.d)
tests-list overlay-shim overlay-shim-install overlay-shim-tests \
overlay-shim-bench iconmaker icon \
appinfo helpers-install ntdll-resolve bridge runcheck compatcheck \
- compatsvc-check shortcutcheck scriptcheck envcheck buildcheck settingscheck routecheck bridgecheck gamedrivecheck launchercheck launch-shell activatecheck FORCE
+ compatsvc-check prefixstate-check shortcutcheck scriptcheck envcheck buildcheck settingscheck routecheck bridgecheck gamedrivecheck launchercheck launch-shell activatecheck FORCE
APP_PAYLOAD := app/Sources/NotProtonApp/Resources/payload
@@ -163,6 +164,14 @@ compatcheck: $(RUN_SCRIPT_H)
-o $(COMPATCHECK) dylib/tests/compatcheck.c && \
$(COMPATCHECK)
+PREFIXSTATE_CHECK := $(OUT_DIR)/prefixstate-check
+
+prefixstate-check:
+ @if [ ! -f dylib/tests/prefixstate-check.c ]; then $(call SKIP,prefixstate-check,dylib/tests/prefixstate-check.c); exit 0; fi; \
+ mkdir -p $(OUT_DIR) && \
+ $(TEST_CC) -o $(PREFIXSTATE_CHECK) dylib/tests/prefixstate-check.c && \
+ $(PREFIXSTATE_CHECK)
+
COMPATSVC_CHECK := $(OUT_DIR)/compatsvc-check
compatsvc-check:
@@ -377,6 +386,7 @@ panel-behavior:
node $(PANEL_TESTS)/migration.js $(OUT_DIR)/panel-emit && \
node $(PANEL_TESTS)/localization.js $(OUT_DIR)/panel-emit && \
node $(PANEL_TESTS)/fex.js $(OUT_DIR)/panel-emit && \
+ node $(PANEL_TESTS)/prefix-row.js $(OUT_DIR)/panel-emit && \
echo "==> panel behavior: renders as expected, no stale arguments"
CX_ROOT ?= /Applications/CrossOver Preview.app
@@ -610,10 +620,14 @@ APP_VERSION := $(shell sed -n 's/^\#define NOTPROTON_VERSION "\(.*\)"/\1/p' dyli
APP_SIGN_ID ?= -
.PHONY: prefix-command-install
-prefix-command-install: app
- @mkdir -p "$(SUPPORT_DIR)"
- @printf '%s' "$(CURDIR)/$(APP_BUNDLE)/Contents/MacOS/NotProtonApp" > "$(SUPPORT_DIR)/app-executable.new"
- @mv -f "$(SUPPORT_DIR)/app-executable.new" "$(SUPPORT_DIR)/app-executable"
+# Records an app bundle that is already built. Building it here would make every deploy
+# build the whole app.
+prefix-command-install:
+ @if [ ! -x "$(APP_BUNDLE)/Contents/MacOS/NotProtonApp" ]; then \
+ echo "==> no $(APP_BUNDLE) yet, run make app for rebuilds from Steam"; exit 0; fi; \
+ mkdir -p "$(SUPPORT_DIR)" && \
+ printf '%s' "$(CURDIR)/$(APP_BUNDLE)/Contents/MacOS/NotProtonApp" > "$(SUPPORT_DIR)/app-executable.new" && \
+ mv -f "$(SUPPORT_DIR)/app-executable.new" "$(SUPPORT_DIR)/app-executable"
ICONGEN := $(OUT_DIR)/icongen
ICON_DOC := $(OUT_DIR)/NotProton.icon
diff --git a/app/Sources/NotProtonApp/Model/DeploymentContent.swift b/app/Sources/NotProtonApp/Model/DeploymentContent.swift
index c32c5c7..c5f18f9 100644
--- a/app/Sources/NotProtonApp/Model/DeploymentContent.swift
+++ b/app/Sources/NotProtonApp/Model/DeploymentContent.swift
@@ -66,12 +66,15 @@ enum DeploymentContent {
static func acquireInstallationLock(
in folder: URL = SupportPaths.applicationSupport,
- steamFolder: URL? = SupportPaths.Steam.app.deletingLastPathComponent()
+ steamFolder: URL? = SupportPaths.Steam.app.deletingLastPathComponent(),
+ waiting: Bool = false,
+ waitTimeout: TimeInterval = 120
) throws -> InstallationLock {
- let own = try lock(folder, required: true)!
+ let deadline = waiting ? ProcessInfo.processInfo.systemUptime + waitTimeout : nil
+ let own = try lock(folder, required: true, deadline: deadline)!
guard let steamFolder else { return InstallationLock(descriptors: [own]) }
do {
- guard let steam = try lock(steamFolder, required: false, unless: own) else {
+ guard let steam = try lock(steamFolder, required: false, unless: own, deadline: deadline) else {
return InstallationLock(descriptors: [own])
}
return InstallationLock(descriptors: [own, steam])
@@ -86,7 +89,9 @@ enum DeploymentContent {
return InstallationLock(descriptors: descriptor.map { [$0] } ?? [])
}
- private static func lock(_ folder: URL, required: Bool, unless held: Int32? = nil) throws -> Int32? {
+ private static func lock(
+ _ folder: URL, required: Bool, unless held: Int32? = nil, deadline: TimeInterval? = nil
+ ) throws -> Int32? {
let parent = folder.path(percentEncoded: false)
let fd = open(parent, O_RDONLY | O_DIRECTORY | O_CLOEXEC | (required ? O_NOFOLLOW : 0))
guard fd >= 0 else {
@@ -100,7 +105,15 @@ enum DeploymentContent {
return nil
}
}
- guard flock(fd, LOCK_EX | LOCK_NB) == 0 else {
+ var locked = flock(fd, LOCK_EX | LOCK_NB) == 0
+ var failure = errno
+ while !locked, let deadline, failure == EWOULDBLOCK || failure == EINTR,
+ ProcessInfo.processInfo.systemUptime < deadline {
+ Thread.sleep(forTimeInterval: 0.05)
+ locked = flock(fd, LOCK_EX | LOCK_NB) == 0
+ failure = errno
+ }
+ guard locked else {
close(fd)
throw StepFailure(step: SteamInstaller.step, detail: String(localized: "Another installation operation is changing files here. Wait for it to finish."))
}
diff --git a/app/Sources/NotProtonApp/Model/PrefixRebuild.swift b/app/Sources/NotProtonApp/Model/PrefixRebuild.swift
index b33eba9..4b54b09 100644
--- a/app/Sources/NotProtonApp/Model/PrefixRebuild.swift
+++ b/app/Sources/NotProtonApp/Model/PrefixRebuild.swift
@@ -2,6 +2,14 @@
import Foundation
+// What the Compatibility page shows while a rebuild runs. The raw values are what
+// notproton-rebuild holds, which the dylib reads.
+enum RebuildPhase: String {
+ case settingUp = "setup"
+ case copying = "copy"
+ case finishing = "finish"
+}
+
extension PrefixTools {
@discardableResult
static func recreate(
@@ -9,11 +17,13 @@ extension PrefixTools {
as tool: InstalledTool,
runners: URL = SupportPaths.runners,
now: Date = .now,
- keepBackup: Bool = true
+ keepBackup: Bool = true,
+ progress: (RebuildPhase) -> Void = { _ in }
) throws -> URL? {
try rebuild(
prefix, runner: SupportPaths.clonedRoot(forBuild: tool.build, runners: runners),
- flavor: tool.tool.flavor, now: now, keepBackup: keepBackup, record: tool
+ flavor: tool.tool.flavor, now: now, keepBackup: keepBackup, record: tool,
+ progress: progress
)
}
@@ -30,7 +40,8 @@ extension PrefixTools {
private static func rebuild(
_ prefix: WinePrefix, runner: URL, flavor: CompatTool.Flavor,
- now: Date, keepBackup: Bool, record: InstalledTool? = nil
+ now: Date, keepBackup: Bool, record: InstalledTool? = nil,
+ progress: (RebuildPhase) -> Void = { _ in }
) throws -> URL? {
guard let claim = PrefixStore.claim(prefix) else {
throw StepFailure(
@@ -66,11 +77,13 @@ extension PrefixTools {
defer { try? fm.removeItem(at: fresh) }
try fm.createDirectory(at: fresh, withIntermediateDirectories: true)
+ progress(.settingUp)
var environment = environment(prefix: prefix, runner: runner, flavor: flavor)
environment["WINEPREFIX"] = fresh.path(percentEncoded: false)
layOutProfile(in: fresh)
_ = try Shell.check(loader.path(percentEncoded: false), ["wineboot", "--init"], environment: environment)
+ progress(.copying)
let carry = Carry(from: prefix.pfx, to: fresh)
carry.userData()
carry.strayFolders()
@@ -83,6 +96,7 @@ extension PrefixTools {
)
}
+ progress(.finishing)
let parked = fm.fileExists(atPath: prefix.pfx.path(percentEncoded: false))
let previous = backupSlot(in: prefix.root, at: now)
if parked {
diff --git a/app/Sources/NotProtonApp/Model/SteamInstaller.swift b/app/Sources/NotProtonApp/Model/SteamInstaller.swift
index efcd570..96084bd 100644
--- a/app/Sources/NotProtonApp/Model/SteamInstaller.swift
+++ b/app/Sources/NotProtonApp/Model/SteamInstaller.swift
@@ -197,7 +197,11 @@ enum SteamInstaller {
}
if let executable = Bundle.main.executableURL {
- try RebuildPrefixCommand.recordExecutable(executable, in: support)
+ do {
+ try RebuildPrefixCommand.recordExecutable(executable, in: support)
+ } catch {
+ AppLog.note("install: could not record the rebuild app: \(error.localizedDescription)")
+ }
}
report(.finished)
return InstallOutcome(
diff --git a/app/Sources/NotProtonApp/Resources/Localization/Localizable.xcstrings b/app/Sources/NotProtonApp/Resources/Localization/Localizable.xcstrings
index a2b50e9..90f0a13 100644
--- a/app/Sources/NotProtonApp/Resources/Localization/Localizable.xcstrings
+++ b/app/Sources/NotProtonApp/Resources/Localization/Localizable.xcstrings
@@ -2092,6 +2092,22 @@
}
}
},
+ "Copying your files…" : {
+ "localizations" : {
+ "it" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Copying your files…"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Copying your files…"
+ }
+ }
+ }
+ },
"Could not check installed files." : {
"localizations" : {
"it" : {
@@ -2799,6 +2815,22 @@
}
}
},
+ "Finishing…" : {
+ "localizations" : {
+ "it" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Finishing…"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Finishing…"
+ }
+ }
+ }
+ },
"Game" : {
"localizations" : {
"it" : {
@@ -3714,6 +3746,38 @@
}
}
},
+ "NotProton is rebuilding the prefix for %@." : {
+ "localizations" : {
+ "it" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "NotProton is rebuilding the prefix for %@."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "NotProton is rebuilding the prefix for %@."
+ }
+ }
+ }
+ },
+ "NotProton is rebuilding this game's prefix." : {
+ "localizations" : {
+ "it" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "NotProton is rebuilding this game's prefix."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "NotProton is rebuilding this game's prefix."
+ }
+ }
+ }
+ },
"NotProton needs the App Management permission." : {
"localizations" : {
"it" : {
@@ -4194,6 +4258,38 @@
}
}
},
+ "Rebuilding the prefix" : {
+ "localizations" : {
+ "it" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Rebuilding the prefix"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Rebuilding the prefix"
+ }
+ }
+ }
+ },
+ "Rebuilding…" : {
+ "localizations" : {
+ "it" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Rebuilding…"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Rebuilding…"
+ }
+ }
+ }
+ },
"Rebuilt %lld prefixes." : {
"localizations" : {
"it" : {
diff --git a/app/Sources/NotProtonApp/Support/Launch.swift b/app/Sources/NotProtonApp/Support/Launch.swift
index f5aa427..48ee491 100644
--- a/app/Sources/NotProtonApp/Support/Launch.swift
+++ b/app/Sources/NotProtonApp/Support/Launch.swift
@@ -4,8 +4,13 @@ import Foundation
enum Launch {
static func main() {
if CommandLine.arguments.dropFirst().first == RebuildPrefixCommand.flag {
+ // Out of the launching process group, so stopping the game in Steam cannot take
+ // the rebuild with it.
+ _ = setsid()
+ let arguments = Array(CommandLine.arguments.dropFirst(2))
+ if RebuildProgressCommand.requested { RebuildProgressCommand.run(arguments) }
do {
- try RebuildPrefixCommand.run(Array(CommandLine.arguments.dropFirst(2)))
+ try RebuildPrefixCommand.run(arguments)
exit(0)
} catch {
FileHandle.standardError.write(Data("\(error.localizedDescription)\n".utf8))
@@ -56,14 +61,84 @@ enum RebuildPrefixCommand {
)
}
- static func run(_ arguments: [String]) throws {
- let lock = try DeploymentContent.acquireInstallationLock()
- defer { lock.release() }
- let request = try request(arguments, tools: CompatToolList.installed())
- try PrefixTools.recreate(request.prefix, as: request.tool, keepBackup: request.keepBackup)
+ // Phase, then this process's pid. The dylib reads it for the Compatibility page and takes
+ // a pid that is gone as a rebuild that died.
+ static let statusName = "notproton-rebuild"
+ static let rebuildLockName = ".notproton-rebuild.lock"
+
+ static func run(
+ _ arguments: [String], tools: () -> [InstalledTool] = { CompatToolList.installed() },
+ observe: (String?, RebuildPhase) -> Void = { _, _ in }
+ ) throws {
+ let name = try request(arguments, tools: tools()).prefix.name
+ let status = arguments.first.flatMap(statusFile)
+ // One rebuild per prefix. A second one exits before it can overwrite the first one's
+ // progress with a failure that is not the first one's.
+ let held = try status.map { try claimRebuild(beside: $0) } ?? -1
+ defer { if held >= 0 { FileLock.release(held) } }
+ func report(_ phase: String) {
+ guard let status else { return }
+ try? atomicReplace(status, with: Data("\(phase)\n\(getpid())\n".utf8), step: "Record rebuild progress")
+ }
+ report(RebuildPhase.settingUp.rawValue)
+ observe(name, .settingUp)
+ do {
+ // Another game's rebuild or an install holds this. Waiting keeps the page on
+ // "Rebuilding prefix" rather than failing a rebuild that only had to queue.
+ let lock = try DeploymentContent.acquireInstallationLock(waiting: true)
+ defer { lock.release() }
+ let request = try request(arguments, tools: tools())
+ let kept = try PrefixTools.recreate(
+ request.prefix, as: request.tool, keepBackup: request.keepBackup,
+ progress: { report($0.rawValue); observe(name, $0) })
+ // A rebuild answers the crash the run script was tracking.
+ try? FileManager.default.removeItem(at: request.prefix.root.appending(path: "notproton-switch"))
+ report(kept != nil ? "done-backup" : "done")
+ } catch {
+ report("failed")
+ throw error
+ }
+ }
+
+ static func claimRebuild(beside status: URL) throws -> Int32 {
+ let path = status.deletingLastPathComponent().appending(path: rebuildLockName)
+ let fd = open(path.path(percentEncoded: false), O_RDWR | O_CREAT | O_NOFOLLOW | O_CLOEXEC, 0o600)
+ var claimed = fd >= 0 && flock(fd, LOCK_EX | LOCK_NB) == 0
+ let deadline = ProcessInfo.processInfo.systemUptime + 1
+ while fd >= 0 && !claimed && errno == EWOULDBLOCK && ProcessInfo.processInfo.systemUptime < deadline {
+ Thread.sleep(forTimeInterval: 0.02)
+ claimed = flock(fd, LOCK_EX | LOCK_NB) == 0
+ }
+ guard claimed else {
+ if fd >= 0 { close(fd) }
+ throw StepFailure(step: "Rebuild prefix", detail: "Another rebuild of this prefix is running.")
+ }
+ return fd
+ }
+
+ static func statusFile(_ path: String) -> URL? {
+ guard path.hasPrefix("/") else { return nil }
+ let root = URL(filePath: path).standardizedFileURL
+ var isDirectory: ObjCBool = false
+ guard root.deletingLastPathComponent().lastPathComponent == "compatdata",
+ root.deletingLastPathComponent().deletingLastPathComponent().lastPathComponent == "steamapps",
+ !root.lastPathComponent.isEmpty,
+ root.lastPathComponent.utf8.allSatisfy({ (48...57).contains($0) }),
+ FileManager.default.fileExists(atPath: root.path(percentEncoded: false), isDirectory: &isDirectory),
+ isDirectory.boolValue
+ else { return nil }
+ return root.appending(path: statusName)
}
static func recordExecutable(_ executable: URL, in support: URL) throws {
+ // A translocated copy or a mounted disk image is gone by the next launch, so nothing
+ // recorded from there would still run.
+ let readOnly = (try? executable.resourceValues(forKeys: [.volumeIsReadOnlyKey]))?.volumeIsReadOnly == true
+ if readOnly || executable.pathComponents.contains("AppTranslocation") {
+ AppLog.note("install: NotProton runs from \(executable.path), so Steam cannot start rebuilds")
+ try? FileManager.default.removeItem(at: support.appending(path: executableRecord))
+ return
+ }
try atomicReplace(support.appending(path: executableRecord),
with: Data(executable.path(percentEncoded: false).utf8), step: "Record NotProton app")
}
diff --git a/app/Sources/NotProtonApp/Support/RebuildProgressWindow.swift b/app/Sources/NotProtonApp/Support/RebuildProgressWindow.swift
new file mode 100644
index 0000000..1a6b650
--- /dev/null
+++ b/app/Sources/NotProtonApp/Support/RebuildProgressWindow.swift
@@ -0,0 +1,121 @@
+import AppKit
+
+// A rebuild started from Play runs while Steam shows the game as running, with nothing
+// else on screen saying why it has not started. The Compatibility page shows its own
+// progress, so only the run script asks for this.
+enum RebuildProgressCommand {
+ static let environmentKey = "NOTPROTON_REBUILD_WINDOW"
+
+ static var requested: Bool { ProcessInfo.processInfo.environment[environmentKey] == "1" }
+
+ // Never returns. The rebuild runs off the main thread, which AppKit needs for the window.
+ static func run(_ arguments: [String]) -> Never {
+ MainActor.assumeIsolated {
+ let app = NSApplication.shared
+ app.setActivationPolicy(.accessory)
+ let window = RebuildProgressWindow()
+ DispatchQueue.main.async { MainActor.assumeIsolated { window.present() } }
+ Thread.detachNewThread {
+ var code: Int32 = 0
+ do {
+ try RebuildPrefixCommand.run(arguments, observe: { name, phase in
+ DispatchQueue.main.async {
+ MainActor.assumeIsolated { window.show(game: name, phase: phase) }
+ }
+ })
+ } catch {
+ FileHandle.standardError.write(Data("\(error.localizedDescription)\n".utf8))
+ code = 1
+ }
+ DispatchQueue.main.async { exit(code) }
+ }
+ app.run()
+ }
+ exit(1)
+ }
+}
+
+// Laid out like the alert that asked for the rebuild, so the one reads as following the other.
+@MainActor
+final class RebuildProgressWindow {
+ private static let width: CGFloat = 440
+ private static let textWidth: CGFloat = width - 20 - 64 - 16 - 20
+
+ private let panel: NSPanel
+ private let message = NSTextField(wrappingLabelWithString: "")
+ private let phase = NSTextField(labelWithString: "")
+ private let bar = NSProgressIndicator()
+
+ init() {
+ panel = NSPanel(contentRect: NSRect(x: 0, y: 0, width: Self.width, height: 120),
+ styleMask: [.titled], backing: .buffered, defer: false)
+ panel.title = String(localized: "Rebuilding the prefix")
+ panel.level = .floating
+ panel.isReleasedWhenClosed = false
+ // macOS may refuse to activate a background helper while Steam is in front, and a
+ // panel that hides on deactivate then never shows.
+ panel.hidesOnDeactivate = false
+
+ let icon = NSImageView(image: NSApp.applicationIconImage)
+ icon.imageScaling = .scaleProportionallyUpOrDown
+ icon.setAccessibilityElement(false)
+ message.font = .systemFont(ofSize: NSFont.systemFontSize)
+ message.preferredMaxLayoutWidth = Self.textWidth
+ message.maximumNumberOfLines = 3
+ message.lineBreakMode = .byWordWrapping
+ message.cell?.truncatesLastVisibleLine = true
+ phase.font = .systemFont(ofSize: NSFont.smallSystemFontSize)
+ phase.textColor = .secondaryLabelColor
+ bar.style = .bar
+ bar.isIndeterminate = true
+ bar.startAnimation(nil)
+
+ let text = NSStackView(views: [message, bar, phase])
+ text.orientation = .vertical
+ text.alignment = .leading
+ text.spacing = 8
+ text.setCustomSpacing(12, after: message)
+ let content = NSView()
+ for view in [icon, text] as [NSView] {
+ view.translatesAutoresizingMaskIntoConstraints = false
+ content.addSubview(view)
+ }
+ NSLayoutConstraint.activate([
+ content.widthAnchor.constraint(equalToConstant: Self.width),
+ icon.widthAnchor.constraint(equalToConstant: 64),
+ icon.heightAnchor.constraint(equalToConstant: 64),
+ icon.leadingAnchor.constraint(equalTo: content.leadingAnchor, constant: 20),
+ icon.topAnchor.constraint(equalTo: content.topAnchor, constant: 20),
+ text.leadingAnchor.constraint(equalTo: icon.trailingAnchor, constant: 16),
+ text.trailingAnchor.constraint(equalTo: content.trailingAnchor, constant: -20),
+ text.topAnchor.constraint(equalTo: content.topAnchor, constant: 20),
+ bar.widthAnchor.constraint(equalTo: text.widthAnchor),
+ message.widthAnchor.constraint(equalTo: text.widthAnchor),
+ content.bottomAnchor.constraint(greaterThanOrEqualTo: icon.bottomAnchor, constant: 20),
+ content.bottomAnchor.constraint(greaterThanOrEqualTo: text.bottomAnchor, constant: 20),
+ ])
+ panel.contentView = content
+ show(game: nil, phase: .settingUp)
+ panel.center()
+ }
+
+ // Ordering the panel front before the application has finished launching leaves it
+ // off screen, so this waits for the run loop.
+ func present() {
+ panel.orderFrontRegardless()
+ NSApp.activate()
+ }
+
+ func show(game name: String?, phase current: RebuildPhase) {
+ message.stringValue = name.map {
+ String(localized: "NotProton is rebuilding the prefix for \($0).")
+ } ?? String(localized: "NotProton is rebuilding this game's prefix.")
+ phase.stringValue = switch current {
+ case .settingUp: String(localized: "Rebuilding…")
+ case .copying: String(localized: "Copying your files…")
+ case .finishing: String(localized: "Finishing…")
+ }
+ bar.setAccessibilityLabel(phase.stringValue)
+ panel.setContentSize(panel.contentView?.fittingSize ?? panel.frame.size)
+ }
+}
diff --git a/app/Tests/NotProtonAppTests/PrefixToolsTests.swift b/app/Tests/NotProtonAppTests/PrefixToolsTests.swift
index 6bf8c30..5caf25c 100644
--- a/app/Tests/NotProtonAppTests/PrefixToolsTests.swift
+++ b/app/Tests/NotProtonAppTests/PrefixToolsTests.swift
@@ -406,7 +406,10 @@ struct PrefixToolsTests {
#expect(PrefixTools.buildRecord(of: prefix) == nil)
#expect(PrefixStore.backups(of: prefix).isEmpty)
claim.release()
- let backup = try PrefixTools.recreate(prefix, as: tool, runners: runners, keepBackup: keepBackup)
+ var phases: [RebuildPhase] = []
+ let backup = try PrefixTools.recreate(
+ prefix, as: tool, runners: runners, keepBackup: keepBackup, progress: { phases.append($0) })
+ #expect(phases == [.settingUp, .copying, .finishing])
#expect((backup != nil) == keepBackup)
#expect(PrefixStore.backups(of: prefix).count == (keepBackup ? 1 : 0))
#expect(PrefixTools.buildRecord(of: prefix)?.build == tool.build)
@@ -414,6 +417,80 @@ struct PrefixToolsTests {
#expect(try String(contentsOf: save, encoding: .utf8) == "save")
}
+ @Test("Rebuild progress lands beside the prefix and nowhere else")
+ func rebuildStatusFile() throws {
+ let dir = FileManager.default.temporaryDirectory.appending(path: "np-status-\(UUID().uuidString)")
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let root = dir.appending(path: "steamapps/compatdata/480")
+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
+ #expect(RebuildPrefixCommand.statusFile(root.path(percentEncoded: false))
+ == root.standardizedFileURL.appending(path: "notproton-rebuild"))
+ #expect(RebuildPrefixCommand.statusFile("relative/compatdata/480") == nil)
+ #expect(RebuildPrefixCommand.statusFile(dir.path(percentEncoded: false)) == nil)
+ #expect(RebuildPrefixCommand.statusFile(root.appending(path: "missing").path(percentEncoded: false)) == nil)
+ }
+
+ @Test("A second rebuild of a prefix is refused and leaves the first one's progress alone")
+ func secondRebuildIsRefused() throws {
+ let dir = FileManager.default.temporaryDirectory.appending(path: "np-second-\(UUID().uuidString)")
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let root = dir.appending(path: "steamapps/compatdata/480")
+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
+ let status = try #require(RebuildPrefixCommand.statusFile(root.path(percentEncoded: false)))
+ try Data("copy\n4242\n".utf8).write(to: status)
+
+ let first = try RebuildPrefixCommand.claimRebuild(beside: status)
+ defer { FileLock.release(first) }
+ try FileManager.default.createDirectory(at: root.appending(path: "pfx"), withIntermediateDirectories: true)
+ let tool = InstalledTool(tool: CompatTool(name: "t", flavor: .rosetta, display: "T"), build: "b")
+ #expect(throws: StepFailure.self) {
+ try RebuildPrefixCommand.run([root.path(percentEncoded: false), "t", "b", "rosetta", "keep-backup"], tools: { [tool] })
+ }
+ #expect(try String(contentsOf: status, encoding: .utf8) == "copy\n4242\n")
+ }
+
+ @Test("Invalid rebuild requests create no progress or lock files")
+ func invalidRebuildWritesNothing() throws {
+ let (dir, _, prefix) = try usedPrefixAndRunner()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ #expect(throws: StepFailure.self) {
+ try RebuildPrefixCommand.run([prefix.root.path, "missing", "b", "fex", "keep-backup"], tools: { [] })
+ }
+ for name in [RebuildPrefixCommand.statusName, RebuildPrefixCommand.rebuildLockName] {
+ #expect(!FileManager.default.fileExists(atPath: prefix.root.appending(path: name).path))
+ }
+ }
+
+ @Test("A translocated rebuild app is not recorded as a persistent path")
+ func translocatedRebuildAppIsNotRecorded() throws {
+ let dir = FileManager.default.temporaryDirectory.appending(path: "np-helper-\(UUID().uuidString)")
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let source = dir.appending(path: "AppTranslocation/id/d/NotProton.app/Contents/MacOS/NotProtonApp")
+ let support = dir.appending(path: "support")
+ try FileManager.default.createDirectory(at: source.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try FileManager.default.createDirectory(at: support, withIntermediateDirectories: true)
+ try Data("stale".utf8).write(to: support.appending(path: RebuildPrefixCommand.executableRecord))
+ try RebuildPrefixCommand.recordExecutable(source, in: support)
+ #expect(!FileManager.default.fileExists(atPath: support.appending(path: RebuildPrefixCommand.executableRecord).path))
+ }
+
+ @Test("A queued installation lock times out without disturbing its holder")
+ func rebuildLockWaitIsBounded() throws {
+ let dir = FileManager.default.temporaryDirectory.appending(path: "np-wait-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let held = try DeploymentContent.acquireInstallationLock(in: dir, steamFolder: nil)
+ defer { held.release() }
+ let start = ProcessInfo.processInfo.systemUptime
+ #expect(throws: StepFailure.self) {
+ try DeploymentContent.acquireInstallationLock(in: dir, steamFolder: nil, waiting: true, waitTimeout: 0.1)
+ }
+ #expect(ProcessInfo.processInfo.systemUptime - start < 2)
+ #expect(throws: StepFailure.self) {
+ try DeploymentContent.acquireInstallationLock(in: dir, steamFolder: nil)
+ }
+ }
+
@Test("The Rosetta flavor takes the x86_64 tree on a runner that has both")
func rosettaFlavorTakesX86() throws {
let fm = FileManager.default
diff --git a/dylib/feats/compat_run.sh b/dylib/feats/compat_run.sh
index 39a7f11..cdcf82d 100755
--- a/dylib/feats/compat_run.sh
+++ b/dylib/feats/compat_run.sh
@@ -300,7 +300,11 @@ tool_name() {
# CrossOver's previews are versioned by date, which reads as a release without the word.
preview_name() {
case "$1" in
- "CrossOver 20"[0-9][0-9]" "*) printf 'CrossOver Preview %s' "${1#CrossOver }" ;;
+ # The date keeps its spaces and the arch its hyphen, but the dialog may only wrap
+ # before the version, never inside it.
+ "CrossOver 20"[0-9][0-9]" "*)
+ printf 'CrossOver Preview %s' "$(printf '%s' "${1#CrossOver }" \
+ | sed "s/ /$(printf '\302\240')/g; s/-/$(printf '\342\200\221')/g")" ;;
*) printf '%s' "$1" ;;
esac
}
@@ -338,7 +342,39 @@ on run argv
end run
APPLESCRIPT
) || answer=""
- [ "$answer" != "Open Log" ] || open "$log" >/dev/null 2>&1 || true
+ [ "$answer" != "Open Log" ] || { [ -f "$log" ] && [ ! -L "$log" ] && open -t "$log" >/dev/null 2>&1; } || true
+}
+
+# Steam shows the game as running while this waits, and Stop kills the script's process
+# group and children. A rebuild killed between its two renames leaves no pfx at all, so the
+# app runs outside both: the inner subshell is reparented to launchd and the app calls
+# setsid. The script only waits for the exit status the subshell leaves behind.
+run_rebuild() {
+ rebuild_exit="$STEAM_COMPAT_DATA_PATH/notproton-rebuild-exit"
+ rebuild_lock="$STEAM_COMPAT_DATA_PATH/.notproton-rebuild.lock"
+ rm -f "$rebuild_exit"
+ (
+ (
+ env -i HOME="$HOME" TMPDIR="${TMPDIR:-/tmp}" PATH=/usr/bin:/bin:/usr/sbin:/sbin \
+ NOTPROTON_REBUILD_WINDOW=1 \
+ "$1" --rebuild-prefix "$STEAM_COMPAT_DATA_PATH" "${np_tool_dir##*/}" \
+ "$np_build" "$np_flavor" "$2" >> "$log" 2>&1 < /dev/null
+ echo "$?" > "$rebuild_exit.$$" && mv -f "$rebuild_exit.$$" "$rebuild_exit"
+ ) &
+ )
+ waited=0
+ while [ ! -f "$rebuild_exit" ]; do
+ sleep 1
+ waited=$((waited + 1))
+ # Nothing holds the lock once the app is gone. The grace covers its startup.
+ if [ "$waited" -gt 30 ] && /usr/bin/lockf -s -t 0 "$rebuild_lock" true 2>/dev/null; then
+ sleep 2
+ [ -f "$rebuild_exit" ] || return 1
+ fi
+ done
+ read -r rebuild_status_code < "$rebuild_exit" || rebuild_status_code=1
+ rm -f "$rebuild_exit"
+ [ "$rebuild_status_code" = 0 ]
}
# $1 is the title, $2 the message. With $3, that button skips the rebuild and the launch goes on.
@@ -350,9 +386,18 @@ rebuild_prefix() {
exit 1
}
exec 8>&- 9>&-
- choice=$(osascript - "$1" "$2" "${3:-Cancel}" <<'APPLESCRIPT'
+ # AppleScript run from a shell has no icon of its own, so caution comes badged with a folder.
+ icon=$(cat "$np_support/app-executable" 2>/dev/null) || icon=""
+ icon="${icon%/Contents/MacOS/*}/Contents/Resources/NotProton.icns"
+ [ -f "$icon" ] || icon=""
+ choice=$(osascript - "$1" "$2" "${3:-Cancel}" "$icon" <<'APPLESCRIPT'
on run argv
- set answer to display dialog (item 2 of argv) with title (item 1 of argv) buttons {item 3 of argv, "Rebuild Prefix", "Backup & Rebuild Prefix"} default button "Backup & Rebuild Prefix" cancel button (item 3 of argv) with icon caution
+ set choices to {item 3 of argv, "Rebuild Prefix", "Backup & Rebuild Prefix"}
+ if item 4 of argv is "" then
+ set answer to display dialog (item 2 of argv) with title (item 1 of argv) buttons choices default button "Backup & Rebuild Prefix" cancel button (item 3 of argv) with icon caution
+ else
+ set answer to display dialog (item 2 of argv) with title (item 1 of argv) buttons choices default button "Backup & Rebuild Prefix" cancel button (item 3 of argv) with icon ((POSIX file (item 4 of argv)) as alias)
+ end if
return button returned of answer
end run
APPLESCRIPT
@@ -368,18 +413,24 @@ APPLESCRIPT
esac
executable=$(cat "$np_support/app-executable" 2>/dev/null) || executable=""
if [ ! -x "$executable" ]; then
- show_alert "Couldn't find the NotProton app" "The prefix wasn't rebuilt and the game wasn't launched, because the NotProton app was moved or deleted since it was installed. Open NotProton and click Install again, then launch the game."
+ show_alert "Couldn't find the NotProton app" "The prefix wasn't rebuilt and the game wasn't launched, because the NotProton app was moved or deleted since it was installed, or was installed from a disk image or Downloads. Move NotProton to Applications, open it and click Install again, then launch the game."
exit 1
fi
- if ! "$executable" --rebuild-prefix "$STEAM_COMPAT_DATA_PATH" "${np_tool_dir##*/}" \
- "$np_build" "$np_flavor" "$backup" >> "$log" 2>&1; then
+ if ! run_rebuild "$executable" "$backup"; then
+ # This dialog says it failed, so the page should not say it again later. A refusal
+ # because another rebuild runs left that rebuild's progress, which stays.
+ rebuild_status="$STEAM_COMPAT_DATA_PATH/notproton-rebuild"
+ [ "$(head -n 1 "$rebuild_status" 2>/dev/null)" != failed ] || rm -f "$rebuild_status"
show_rebuild_failure
exit 1
fi
- rm -f "$STEAM_COMPAT_DATA_PATH/notproton-switch"
+ rm -f "$STEAM_COMPAT_DATA_PATH/notproton-switch" "$STEAM_COMPAT_DATA_PATH/notproton-rebuild"
# A competing launch or rebuild may have run while the dialog was open.
# Retake the normal launch lock and check both mismatches before touching Wine.
- prepare_prefix_directory || exit 1
+ if ! prepare_prefix_directory; then
+ show_alert "Prefix rebuilt" "Another launch is using this prefix. Wait for it to finish, then launch the game again."
+ exit 1
+ fi
np_rebuilt=1
note_other_build
refuse_foreign_prefix
@@ -448,6 +499,9 @@ note_other_build() {
fi
if [ -n "$had_build" ] && [ "$had_build" != "$np_build" ]; then
echo "=== prefix was last run by build $had_build (${had_display:-unknown}), Wine updates it for $np_build ===" >> "$log" 2>&1 || true
+ case "${wine_unix##*/}:$(prefix_machine)" in
+ aarch64-unix:8664 | aarch64-unix:014c | x86_64-unix:aa64 | x86_64-unix:014c) return 0 ;;
+ esac
switch="$STEAM_COMPAT_DATA_PATH/notproton-switch"
rm -f "$switch"
# Only a build the game is known to have run on can be blamed for a crash after the switch.
diff --git a/dylib/feats/compatsvc.c b/dylib/feats/compatsvc.c
index 7bf5542..b722914 100644
--- a/dylib/feats/compatsvc.c
+++ b/dylib/feats/compatsvc.c
@@ -1,17 +1,35 @@
// CompatManager WebUI service.
+#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <signal.h>
+#include <spawn.h>
+#include <stdio.h>
#include <stdlib.h>
#include <string.h>
+#include <sys/wait.h>
+#include <sys/stat.h>
+#include <sys/file.h>
+#include <unistd.h>
#include "compatsvc.h"
#include "compat.h"
+#include "prefixstate.h"
#include "webui.h"
#include "../resolver/anchor.h"
+#include "../util/file.h"
#include "../util/log.h"
// Route names carry the interface version the page asks for.
#define ROUTE_GET_COMPAT_TOOLS "CompatManager.GetCompatTools#1"
#define ROUTE_SPECIFY_COMPAT_TOOL "CompatManager.SpecifyCompatTool#1"
#define ROUTE_NOTIFY_STATE_CHANGED "CompatManager.NotifyStateChanged#1"
+// Our own route. It borrows the GetCompatTools types, and the answer is JSON in
+// default_tool_identifier, so the page needs no message class of its own.
+#define ROUTE_PREFIX_STATE "NotProton.PrefixState#1"
+#define ROUTE_REBUILD "NotProton.RebuildPrefix#1"
+#define ROUTE_BACKUP_REBUILD "NotProton.BackupAndRebuildPrefix#1"
+#define ROUTE_OPEN_LOG "NotProton.OpenPrefixLog#1"
// Mangled RTTI names of the message types. A client that builds the CompatManager
// page compiles these without registering the service, so the vtables are there to
@@ -290,6 +308,179 @@ static int specify_compat_tool(uintptr_t request, uintptr_t response) {
return RESULT_OK;
}
+#define STATE_JSON_MAX 2048
+
+// Every path and tool is worked out here from the appid alone, since any page can call
+// these routes and two of them start processes.
+static int read_state(uint32_t appid, np_prefix_state_t *st) {
+ const char *home = np_home_dir();
+ uint8_t *mgr = (uint8_t *)np_compat_manager();
+ if (!appid || !home || !mgr) {
+ NP_WARN("compatsvc: no prefix state for app %u without %s", appid,
+ !appid ? "an appid" : !home ? "a home folder" : "a manager");
+ return 0;
+ }
+ char steam[PATH_MAX], support[PATH_MAX], server[PATH_MAX];
+ snprintf(steam, sizeof steam, "%s/Library/Application Support/Steam", home);
+ snprintf(support, sizeof support, "%s/Library/Application Support/notproton", home);
+ snprintf(server, sizeof server, "/tmp/.wine-%u", (unsigned)getuid());
+ np_prefix_roots_t roots = { steam, support, server };
+ np_prefix_state(appid, tool_name(np_compat_tool_for_app(mgr, appid)), &roots, st);
+ return 1;
+}
+
+static uint32_t request_appid(uintptr_t request) {
+ uint32_t has_bits = *(const uint32_t *)(request + REQ_HAS_BITS_OFF);
+ return (has_bits & REQ_HAS_APPID) ? *(const uint32_t *)(request + REQ_APPID_OFF) : 0;
+}
+
+static int answer_json(uintptr_t response, uint32_t appid, const char *json) {
+ uint8_t body[STATE_JSON_MAX + 8];
+ np_pb_t w = { body, sizeof body, 0, 1 };
+ pb_string(&w, RESP_DEFAULT, json);
+ if (!w.ok || !np_webui_parse_into(response, body, (uint32_t)w.len)) {
+ NP_ERR("compatsvc: the client rejected the answer for app %u", appid);
+ return RESULT_FAIL;
+ }
+ return RESULT_OK;
+}
+
+// JSON for the CrossOver panel, in default_tool_identifier.
+static int prefix_state(uintptr_t request, uintptr_t response) {
+ uint32_t appid = request_appid(request);
+ np_prefix_state_t st;
+ if (!read_state(appid, &st)) return RESULT_FAIL;
+
+ char json[STATE_JSON_MAX];
+ if (np_prefix_state_json(appid, &st, json, sizeof json) < 0) {
+ NP_ERR("compatsvc: the prefix state for app %u does not fit %d bytes", appid,
+ STATE_JSON_MAX);
+ return RESULT_FAIL;
+ }
+ NP_DBG("compatsvc: app %u prefix state %s", appid, json);
+ return answer_json(response, appid, json);
+}
+
+// Runs argv with nothing of Steam's environment, so neither the insert nor Steam's own
+// variables reach the child. Waits for it, which is short for everything started here.
+static int run_detached(char *const argv[]) {
+ const char *home = np_home_dir();
+ char env_home[PATH_MAX + 8], env_tmp[PATH_MAX + 8];
+ snprintf(env_home, sizeof env_home, "HOME=%s", home ? home : "/");
+ snprintf(env_tmp, sizeof env_tmp, "TMPDIR=%s", getenv("TMPDIR") ? getenv("TMPDIR") : "/tmp");
+ char *envp[] = { env_home, env_tmp, "PATH=/usr/bin:/bin:/usr/sbin:/sbin", NULL };
+
+ posix_spawn_file_actions_t actions;
+ posix_spawnattr_t attr;
+ sigset_t none, all;
+ sigemptyset(&none);
+ sigfillset(&all);
+ if (posix_spawn_file_actions_init(&actions) != 0) return 0;
+ if (posix_spawnattr_init(&attr) != 0) {
+ posix_spawn_file_actions_destroy(&actions);
+ return 0;
+ }
+ posix_spawn_file_actions_addopen(&actions, STDIN_FILENO, "/dev/null", O_RDONLY, 0);
+ posix_spawn_file_actions_addopen(&actions, STDOUT_FILENO, "/dev/null", O_WRONLY, 0);
+ posix_spawn_file_actions_addopen(&actions, STDERR_FILENO, "/dev/null", O_WRONLY, 0);
+ posix_spawnattr_setsigmask(&attr, &none);
+ posix_spawnattr_setsigdefault(&attr, &all);
+ posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETSIGMASK | POSIX_SPAWN_SETSIGDEF |
+ POSIX_SPAWN_CLOEXEC_DEFAULT | POSIX_SPAWN_SETPGROUP);
+ posix_spawnattr_setpgroup(&attr, 0);
+ pid_t pid;
+ int rc = posix_spawn(&pid, argv[0], &actions, &attr, argv, envp);
+ posix_spawnattr_destroy(&attr);
+ posix_spawn_file_actions_destroy(&actions);
+ if (rc != 0) {
+ NP_WARN("compatsvc: cannot run %s (%d)", argv[0], rc);
+ return 0;
+ }
+ int status = 0;
+ while (waitpid(pid, &status, 0) < 0 && errno == EINTR) {}
+ return WIFEXITED(status) && WEXITSTATUS(status) == 0;
+}
+
+// The shell backgrounds the app and exits, so the rebuild belongs to launchd and outlives
+// both the page and Steam.
+#define REBUILD_SCRIPT \
+ "log=$1; shift; \"$0\" --rebuild-prefix \"$@\" >> \"$log\" 2>&1 < /dev/null &"
+
+static int start_rebuild(uintptr_t request, uintptr_t response, int keep_backup) {
+ uint32_t appid = request_appid(request);
+ np_prefix_state_t st;
+ if (!read_state(appid, &st)) return RESULT_FAIL;
+
+ const char *refused = !st.needs_rebuild ? "none"
+ : np_prefix_rebuilding(&st) ? "busy"
+ : st.running ? "running"
+ : !st.app[0] ? "app" : NULL;
+ if (!refused) {
+ char status[PATH_MAX], log[PATH_MAX], lock_path[PATH_MAX];
+ snprintf(lock_path, sizeof lock_path, "%s/.notproton-rebuild.lock", st.compatdata);
+ int claim = open(lock_path, O_RDWR | O_CREAT | O_NOFOLLOW | O_CLOEXEC, 0600);
+ // A page polling the state holds this for a moment to see whether a rebuild runs.
+ int claimed = claim >= 0 && flock(claim, LOCK_EX | LOCK_NB) == 0;
+ for (int i = 0; claim >= 0 && !claimed && errno == EWOULDBLOCK && i < 10; i++) {
+ usleep(10000);
+ claimed = flock(claim, LOCK_EX | LOCK_NB) == 0;
+ }
+ if (!claimed) {
+ if (claim >= 0) close(claim);
+ return answer_json(response, appid, "{\"error\":\"busy\"}");
+ }
+ snprintf(status, sizeof status, "%s/notproton-rebuild", st.compatdata);
+ snprintf(log, sizeof log, "%s/notproton-run.log", st.compatdata);
+ int fd = open(status, O_WRONLY | O_CREAT | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC, 0600);
+ struct stat info;
+ int recorded = fd >= 0 && fstat(fd, &info) == 0 && S_ISREG(info.st_mode)
+ && ftruncate(fd, 0) == 0 && write(fd, "setup\n0\n", 8) == 8;
+ if (fd >= 0) close(fd);
+ char *argv[] = { "/bin/sh", "-c", REBUILD_SCRIPT, st.app, log, st.compatdata,
+ st.tool, st.tool_build, st.tool_flavor,
+ keep_backup ? "keep-backup" : "discard-backup", NULL };
+ if (!recorded) {
+ refused = "spawn";
+ } else if (!run_detached(argv)) {
+ unlink(status);
+ refused = "spawn";
+ }
+ close(claim);
+ }
+ if (refused)
+ NP_WARN("compatsvc: app %u was not rebuilt (%s)", appid, refused);
+ else
+ NP_LOG("compatsvc: rebuilding app %u for %s, %s the original", appid, st.tool,
+ keep_backup ? "keeping" : "discarding");
+
+ char json[64];
+ snprintf(json, sizeof json, refused ? "{\"error\":\"%s\"}" : "{\"started\":true}",
+ refused ? refused : "");
+ return answer_json(response, appid, json);
+}
+
+static int rebuild_prefix(uintptr_t request, uintptr_t response) {
+ return start_rebuild(request, response, 0);
+}
+
+static int backup_and_rebuild_prefix(uintptr_t request, uintptr_t response) {
+ return start_rebuild(request, response, 1);
+}
+
+static int open_prefix_log(uintptr_t request, uintptr_t response) {
+ uint32_t appid = request_appid(request);
+ np_prefix_state_t st;
+ if (!read_state(appid, &st) || !st.compatdata[0]) return RESULT_FAIL;
+ char log[PATH_MAX];
+ snprintf(log, sizeof log, "%s/notproton-run.log", st.compatdata);
+ // open waits on LaunchServices, which is not something Steam's WebUI thread should do.
+ char *argv[] = { "/bin/sh", "-c", "/usr/bin/open -t \"$0\" &", log, NULL };
+ struct stat info;
+ int opened = lstat(log, &info) == 0 && S_ISREG(info.st_mode)
+ && access(log, R_OK) == 0 && run_detached(argv);
+ return answer_json(response, appid, opened ? "{\"opened\":true}" : "{\"error\":\"log\"}");
+}
+
static uintptr_t g_state_changed;
static int g_routes = NP_COMPATSVC_UNTRIED;
@@ -335,6 +526,13 @@ void np_compatsvc_register(const struct mach_header_64 *mh, intptr_t slide,
g_routes = NP_COMPATSVC_READY;
+ if (!np_webui_register_route(ROUTE_PREFIX_STATE, request, response, prefix_state)
+ || !np_webui_register_route(ROUTE_REBUILD, request, response, rebuild_prefix)
+ || !np_webui_register_route(ROUTE_BACKUP_REBUILD, request, response,
+ backup_and_rebuild_prefix)
+ || !np_webui_register_route(ROUTE_OPEN_LOG, request, response, open_prefix_log))
+ NP_WARN("compatsvc: the Compatibility page cannot rebuild prefixes");
+
uintptr_t notification = np_rtti_vptr(mh, slide, text_base, text_size,
TYPE_STATE_CHANGED);
g_state_changed = notification ? np_webui_new_message(notification) : 0;
diff --git a/dylib/feats/prefixstate.c b/dylib/feats/prefixstate.c
new file mode 100644
index 0000000..7a7bd25
--- /dev/null
+++ b/dylib/feats/prefixstate.c
@@ -0,0 +1,346 @@
+// Prefix state for the Compatibility page. Mirrors the run script's checks
+// (prefix_machine, notproton-build) so the page can say what a launch would say.
+#include "prefixstate.h"
+
+#include <errno.h>
+#include <fcntl.h>
+#include <sys/file.h>
+#include <signal.h>
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <time.h>
+#include <unistd.h>
+
+#define LIBRARIES_MAX 16
+#define LINE_MAX_LEN 2048
+#define FIELD_MAX NP_PREFIX_FIELD_MAX
+
+// A rebuild the dylib started but the app has not reported on yet.
+#define STARTING_GRACE_SECONDS 30
+// A result nobody saw while it was fresh says nothing about the prefix any more.
+#define FINISHED_SHOWN_SECONDS 600
+
+// PE machine words in system32/ntdll.dll.
+#define MACHINE_AMD64 0x8664
+#define MACHINE_ARM64 0xaa64
+#define MACHINE_I386 0x014c
+
+// Anything further in is not a header Wine wrote.
+#define PE_OFFSET_MAX 0x1000
+
+typedef struct {
+ char paths[LIBRARIES_MAX][PATH_MAX];
+ int count;
+} libraries_t;
+
+static int is_dir(const char *path) {
+ struct stat st;
+ return stat(path, &st) == 0 && S_ISDIR(st.st_mode);
+}
+
+static int is_file(const char *path) {
+ struct stat st;
+ return stat(path, &st) == 0 && S_ISREG(st.st_mode);
+}
+
+// Next quoted VDF token on the line, with Steam's escapes decoded.
+static const char *vdf_token(const char *p, char *out, size_t cap) {
+ while (*p && *p != '"') p++;
+ if (*p != '"') return NULL;
+ p++;
+ size_t n = 0;
+ for (; *p && *p != '"'; p++) {
+ char c = *p;
+ if (c == '\\' && p[1]) {
+ p++;
+ c = *p == 'n' ? '\n' : *p == 't' ? '\t' : *p;
+ }
+ if (n + 1 < cap) out[n++] = c;
+ }
+ out[n] = '\0';
+ return *p == '"' ? p + 1 : NULL;
+}
+
+static void add_library(libraries_t *libs, const char *path) {
+ if (!*path || libs->count >= LIBRARIES_MAX) return;
+ for (int i = 0; i < libs->count; i++)
+ if (strcmp(libs->paths[i], path) == 0) return;
+ snprintf(libs->paths[libs->count++], PATH_MAX, "%s", path);
+}
+
+static void read_libraries(const char *steam_root, libraries_t *libs) {
+ libs->count = 0;
+ char vdf[PATH_MAX];
+ snprintf(vdf, sizeof vdf, "%s/steamapps/libraryfolders.vdf", steam_root);
+ FILE *f = fopen(vdf, "r");
+ if (f) {
+ char line[LINE_MAX_LEN], key[FIELD_MAX], value[PATH_MAX];
+ while (fgets(line, sizeof line, f)) {
+ const char *rest = vdf_token(line, key, sizeof key);
+ if (!rest || strcmp(key, "path") != 0) continue;
+ if (vdf_token(rest, value, sizeof value)) add_library(libs, value);
+ }
+ fclose(f);
+ }
+ // A missing or empty file still means the default library, as in PrefixStore.
+ if (libs->count == 0) add_library(libs, steam_root);
+}
+
+// compatdata/<appid> of the library holding the game. A shortcut has no manifest,
+// so its prefix is wherever one already exists.
+static int find_compatdata(uint32_t appid, const libraries_t *libs, char *out, size_t cap) {
+ char probe[PATH_MAX];
+ for (int i = 0; i < libs->count; i++) {
+ snprintf(probe, sizeof probe, "%s/steamapps/appmanifest_%u.acf", libs->paths[i], appid);
+ if (!is_file(probe)) continue;
+ snprintf(out, cap, "%s/steamapps/compatdata/%u", libs->paths[i], appid);
+ return 1;
+ }
+ for (int i = 0; i < libs->count; i++) {
+ snprintf(probe, sizeof probe, "%s/steamapps/compatdata/%u/pfx", libs->paths[i], appid);
+ if (!is_dir(probe)) continue;
+ snprintf(out, cap, "%s/steamapps/compatdata/%u", libs->paths[i], appid);
+ return 1;
+ }
+ return 0;
+}
+
+static int prefix_machine(const char *compatdata, uint16_t *machine) {
+ char dll[PATH_MAX];
+ snprintf(dll, sizeof dll, "%s/pfx/drive_c/windows/system32/ntdll.dll", compatdata);
+ int fd = open(dll, O_RDONLY);
+ if (fd < 0) return 0;
+ uint32_t off = 0;
+ uint8_t pe[6];
+ int ok = pread(fd, &off, 4, 0x3c) == 4 && off < PE_OFFSET_MAX
+ && pread(fd, pe, 6, off) == 6 && memcmp(pe, "PE\0\0", 4) == 0;
+ close(fd);
+ if (ok) *machine = (uint16_t)(pe[4] | pe[5] << 8);
+ return ok;
+}
+
+static const char *machine_arch(uint16_t machine) {
+ switch (machine) {
+ case MACHINE_AMD64: return "rosetta";
+ case MACHINE_ARM64: return "fex";
+ case MACHINE_I386: return "32-bit";
+ default: return "";
+ }
+}
+
+static void chomp(char *s) {
+ size_t n = strlen(s);
+ while (n && (s[n - 1] == '\n' || s[n - 1] == '\r')) s[--n] = '\0';
+}
+
+// notproton-build is the build on one line and its display name on the next.
+static void read_build_record(const char *compatdata, char *build, char *display) {
+ build[0] = display[0] = '\0';
+ char path[PATH_MAX];
+ snprintf(path, sizeof path, "%s/notproton-build", compatdata);
+ FILE *f = fopen(path, "r");
+ if (!f) return;
+ if (fgets(build, FIELD_MAX, f)) chomp(build);
+ if (fgets(display, FIELD_MAX, f)) chomp(display);
+ fclose(f);
+}
+
+// The tools file is name, build, flavor and display, one tool per tab separated line.
+static void read_tool(const char *support_root, np_prefix_state_t *st) {
+ st->tool_build[0] = st->tool_flavor[0] = st->tool_display[0] = '\0';
+ if (!st->tool[0]) return;
+ char path[PATH_MAX];
+ snprintf(path, sizeof path, "%s/tools", support_root);
+ FILE *f = fopen(path, "r");
+ if (!f) return;
+ char line[LINE_MAX_LEN];
+ while (fgets(line, sizeof line, f)) {
+ chomp(line);
+ char *fields[4] = { line, NULL, NULL, NULL };
+ for (int i = 1; i < 4; i++) {
+ char *tab = fields[i - 1] ? strchr(fields[i - 1], '\t') : NULL;
+ if (!tab) break;
+ *tab = '\0';
+ fields[i] = tab + 1;
+ }
+ if (!fields[3] || strcmp(fields[0], st->tool) != 0) continue;
+ snprintf(st->tool_build, FIELD_MAX, "%s", fields[1]);
+ snprintf(st->tool_flavor, FIELD_MAX, "%s", fields[2]);
+ snprintf(st->tool_display, FIELD_MAX, "%s", fields[3]);
+ break;
+ }
+ fclose(f);
+}
+
+// Wine's server for a prefix lives in server-<dev>-<ino> and holds a write lock on its
+// lock file for as long as it runs. F_GETLK sees another process's lock without taking one.
+static int server_running(const char *server_root, const char *compatdata) {
+ char pfx[PATH_MAX], lock[PATH_MAX];
+ struct stat st;
+ snprintf(pfx, sizeof pfx, "%s/pfx", compatdata);
+ if (!server_root || stat(pfx, &st) != 0) return 0;
+ snprintf(lock, sizeof lock, "%s/server-%llx-%llx/lock", server_root,
+ (unsigned long long)st.st_dev, (unsigned long long)st.st_ino);
+ int fd = open(lock, O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC);
+ if (fd < 0) return 0;
+ if (fstat(fd, &st) != 0 || !S_ISREG(st.st_mode) || st.st_uid != getuid()) {
+ close(fd);
+ return 0;
+ }
+ struct flock fl = { .l_type = F_WRLCK, .l_whence = SEEK_SET, .l_start = 0, .l_len = 1 };
+ int held = fcntl(fd, F_GETLK, &fl) == 0 && fl.l_type != F_UNLCK;
+ close(fd);
+ return held;
+}
+
+static int is_phase(const char *p, const char *const *set) {
+ for (; *set; set++)
+ if (strcmp(p, *set) == 0) return 1;
+ return 0;
+}
+
+static const char *const ACTIVE_PHASES[] = { "setup", "copy", "finish", NULL };
+static const char *const DONE_PHASES[] = { "done", "done-backup", "failed", NULL };
+
+// notproton-rebuild is the phase on one line and the app's pid on the next. A pid of 0 is
+// a rebuild the dylib just started, before the app has written anything.
+static void read_rebuild(const char *compatdata, char *phase, size_t cap) {
+ phase[0] = '\0';
+ char path[PATH_MAX], line[FIELD_MAX], pid_text[FIELD_MAX] = "";
+ snprintf(path, sizeof path, "%s/notproton-rebuild", compatdata);
+ struct stat st;
+ FILE *f = fopen(path, "r");
+ if (!f) return;
+ int ok = fgets(line, sizeof line, f) != NULL;
+ if (ok && !fgets(pid_text, sizeof pid_text, f)) pid_text[0] = '\0';
+ int have_stat = fstat(fileno(f), &st) == 0;
+ fclose(f);
+ if (!ok) return;
+ chomp(line);
+ if (is_phase(line, DONE_PHASES)) {
+ if (have_stat && time(NULL) - st.st_mtime < FINISHED_SHOWN_SECONDS)
+ snprintf(phase, cap, "%s", line);
+ return;
+ }
+ if (!is_phase(line, ACTIVE_PHASES)) return;
+
+ char lock_path[PATH_MAX];
+ snprintf(lock_path, sizeof lock_path, "%s/.notproton-rebuild.lock", compatdata);
+ int fd = open(lock_path, O_RDWR | O_NOFOLLOW | O_CLOEXEC);
+ int held = fd >= 0 && flock(fd, LOCK_EX | LOCK_NB) != 0 && errno == EWOULDBLOCK;
+ if (fd >= 0) close(fd);
+ int alive = held || (strcmp(pid_text, "0\n") == 0 && have_stat
+ && time(NULL) - st.st_mtime < STARTING_GRACE_SECONDS);
+ snprintf(phase, cap, "%s", alive ? line : "failed");
+}
+
+static void read_app(const char *support_root, char *out, size_t cap) {
+ out[0] = '\0';
+ char path[PATH_MAX];
+ snprintf(path, sizeof path, "%s/app-executable", support_root);
+ FILE *f = fopen(path, "r");
+ if (!f) return;
+ char line[PATH_MAX];
+ int ok = fgets(line, sizeof line, f) != NULL;
+ fclose(f);
+ if (!ok) return;
+ chomp(line);
+ if (line[0] == '/' && access(line, X_OK) == 0) snprintf(out, cap, "%s", line);
+}
+
+typedef struct {
+ char *buf;
+ size_t cap;
+ size_t len;
+ int ok;
+} json_t;
+
+static void json_raw(json_t *j, const char *s) {
+ size_t n = strlen(s);
+ if (!j->ok || j->len + n >= j->cap) { j->ok = 0; return; }
+ memcpy(j->buf + j->len, s, n + 1);
+ j->len += n;
+}
+
+static void json_string(json_t *j, const char *key, const char *value) {
+ char piece[16];
+ json_raw(j, j->len > 1 ? ",\"" : "\"");
+ json_raw(j, key);
+ json_raw(j, "\":\"");
+ for (const unsigned char *p = (const unsigned char *)value; *p && j->ok; p++) {
+ if (*p == '"' || *p == '\\') {
+ piece[0] = '\\'; piece[1] = (char)*p; piece[2] = '\0';
+ } else if (*p < 0x20) {
+ snprintf(piece, sizeof piece, "\\u%04x", *p);
+ } else {
+ piece[0] = (char)*p; piece[1] = '\0';
+ }
+ json_raw(j, piece);
+ }
+ json_raw(j, "\"");
+}
+
+static void json_bool(json_t *j, const char *key, int value) {
+ json_raw(j, j->len > 1 ? ",\"" : "\"");
+ json_raw(j, key);
+ json_raw(j, value ? "\":true" : "\":false");
+}
+
+void np_prefix_state(uint32_t appid, const char *tool, const np_prefix_roots_t *roots,
+ np_prefix_state_t *st) {
+ memset(st, 0, sizeof *st);
+ snprintf(st->tool, sizeof st->tool, "%s", tool ? tool : "");
+
+ libraries_t libs;
+ read_libraries(roots->steam_root, &libs);
+ int found = find_compatdata(appid, &libs, st->compatdata, sizeof st->compatdata);
+ if (!found) st->compatdata[0] = '\0';
+
+ uint16_t machine = 0;
+ if (found) {
+ if (prefix_machine(st->compatdata, &machine)) {
+ st->has_prefix = 1;
+ snprintf(st->prefix_arch, sizeof st->prefix_arch, "%s", machine_arch(machine));
+ }
+ read_build_record(st->compatdata, st->last_build, st->last_display);
+ read_rebuild(st->compatdata, st->rebuild, sizeof st->rebuild);
+ st->running = server_running(roots->server_root, st->compatdata);
+ }
+
+ read_tool(roots->support_root, st);
+ if (strcmp(st->tool_flavor, "fex") != 0 && strcmp(st->tool_flavor, "rosetta") != 0)
+ st->tool_flavor[0] = '\0';
+ read_app(roots->support_root, st->app, sizeof st->app);
+
+ st->needs_rebuild = st->has_prefix && st->tool_flavor[0] && st->prefix_arch[0]
+ && strcmp(st->prefix_arch, st->tool_flavor) != 0;
+}
+
+int np_prefix_rebuilding(const np_prefix_state_t *st) {
+ return is_phase(st->rebuild, ACTIVE_PHASES);
+}
+
+int np_prefix_state_json(uint32_t appid, const np_prefix_state_t *st, char *out, size_t cap) {
+ char appid_text[16];
+ snprintf(appid_text, sizeof appid_text, "%u", appid);
+
+ json_t j = { out, cap, 0, cap > 0 };
+ json_raw(&j, "{\"appid\":");
+ json_raw(&j, appid_text);
+ json_string(&j, "tool", st->tool);
+ json_string(&j, "toolDisplay", st->tool_display);
+ json_string(&j, "toolArch", st->tool_flavor);
+ json_bool(&j, "prefix", st->has_prefix);
+ json_string(&j, "prefixArch", st->prefix_arch);
+ json_string(&j, "lastBuild", st->last_build);
+ json_string(&j, "lastDisplay", st->last_display);
+ json_bool(&j, "needsRebuild", st->needs_rebuild);
+ json_bool(&j, "running", st->running);
+ json_string(&j, "rebuild", st->rebuild);
+ json_bool(&j, "app", st->app[0] != '\0');
+ json_raw(&j, "}");
+ return j.ok ? (int)j.len : -1;
+}
diff --git a/dylib/feats/prefixstate.h b/dylib/feats/prefixstate.h
new file mode 100644
index 0000000..58b1b76
--- /dev/null
+++ b/dylib/feats/prefixstate.h
@@ -0,0 +1,47 @@
+// What the Compatibility page needs to know about a game's prefix before it runs.
+#ifndef NOTPROTON_FEATS_PREFIXSTATE_H
+#define NOTPROTON_FEATS_PREFIXSTATE_H
+
+#include <limits.h>
+#include <stddef.h>
+#include <stdint.h>
+
+#define NP_PREFIX_FIELD_MAX 256
+
+typedef struct {
+ // Where to look. server_root is Wine's /tmp/.wine-<uid>.
+ const char *steam_root;
+ const char *support_root;
+ const char *server_root;
+} np_prefix_roots_t;
+
+typedef struct {
+ int has_prefix;
+ char compatdata[PATH_MAX];
+ char prefix_arch[16];
+ char last_build[NP_PREFIX_FIELD_MAX];
+ char last_display[NP_PREFIX_FIELD_MAX];
+ char tool[NP_PREFIX_FIELD_MAX];
+ char tool_build[NP_PREFIX_FIELD_MAX];
+ char tool_flavor[NP_PREFIX_FIELD_MAX];
+ char tool_display[NP_PREFIX_FIELD_MAX];
+ int needs_rebuild;
+ // A wineserver holds the prefix, so the game or a Wine tool is running.
+ int running;
+ // setup, copy or finish while the app rebuilds, then done, done-backup or failed.
+ char rebuild[16];
+ // The app the installer recorded, empty when it is gone.
+ char app[PATH_MAX];
+} np_prefix_state_t;
+
+// Fills `st` for `appid` as `tool` would run it.
+void np_prefix_state(uint32_t appid, const char *tool, const np_prefix_roots_t *roots,
+ np_prefix_state_t *st);
+
+// 1 while a rebuild is under way.
+int np_prefix_rebuilding(const np_prefix_state_t *st);
+
+// The page's JSON. Returns the length written, or -1 when it does not fit.
+int np_prefix_state_json(uint32_t appid, const np_prefix_state_t *st, char *out, size_t cap);
+
+#endif // NOTPROTON_FEATS_PREFIXSTATE_H
diff --git a/dylib/feats/webpatch.c b/dylib/feats/webpatch.c
index 13188c9..82461e8 100644
--- a/dylib/feats/webpatch.c
+++ b/dylib/feats/webpatch.c
@@ -248,10 +248,15 @@ static int out_expand(np_out_t *o, const char *replace, const np_cap_t *caps) {
"||k===\"CX_GRAPHICS_BACKEND\"&&L.g(k)===\"d3dmetal\");" \
"ks.length&&L.s(ks.map(k=>[k,\"\"]))}"
+// The picker refetches after the client's state notification, by which point the mapping
+// has changed, so a new selection here is when the prefix row asks again.
#define NP_CX_TOOL_QUERY \
- "(r,id)=>[r[0],v=>{r[1](v);const d=r[0].data;if(!id||!d)return;" \
+ "(r,id)=>{const q=r[0].data;if(id&&q){const k=q.selected_tool_identifier+\"|\"+q.default_tool_identifier," \
+ "M=globalThis.MSCXSeen||(globalThis.MSCXSeen=new Map);" \
+ "M.has(id)&&M.get(id)!==k&&queueMicrotask(()=>globalThis.dispatchEvent?.(new CustomEvent(\"mscxstate\",{detail:id})));" \
+ "M.set(id,k)}return[r[0],v=>{r[1](v);const d=r[0].data;if(!id||!d)return;" \
"const n=v||d.default_tool_identifier||\"" NP_FALLBACK_TOOL "\",a=(d.aliases||[]).find(x=>x.alias===n)," \
- "t=globalThis.appDetailsStore?.GetAppDetails(id);t&&MSCXPick(t,a?a.current_tool_name:n)}]"
+ "t=globalThis.appDetailsStore?.GetAppDetails(id);t&&MSCXPick(t,a?a.current_tool_name:n)}]}"
// CrossOver options panel. Not in great shape, but it'll do
#define NP_WEB_IS_ZH \
@@ -285,12 +290,86 @@ static int out_expand(np_out_t *o, const char *replace, const np_cap_t *caps) {
"Runs on Windows, no Mac OS version", \
"Funziona su Windows, nessuna versione macOS")
+// Rebuild row in the CrossOver panel. Chinese and Italian wait for a translator.
+// The row is redrawn on every poll, so the bar keeps its phase from when the rebuild started
+// instead of restarting on each redraw.
+#define NP_PREFIX_NEED NP_WEB_TEXT("Switching to this compatibility tool requires a prefix rebuild. Rebuild now?", "Switching to this compatibility tool requires a prefix rebuild. Rebuild now?", "Switching to this compatibility tool requires a prefix rebuild. Rebuild now?")
+#define NP_PREFIX_BACKUP NP_WEB_TEXT("Backup & Rebuild Prefix", "Backup & Rebuild Prefix", "Backup & Rebuild Prefix")
+#define NP_PREFIX_REBUILD NP_WEB_TEXT("Rebuild Prefix", "Rebuild Prefix", "Rebuild Prefix")
+#define NP_PREFIX_RUNNING NP_WEB_TEXT("Quit the game to rebuild.", "Quit the game to rebuild.", "Quit the game to rebuild.")
+#define NP_PREFIX_SETUP NP_WEB_TEXT("Rebuilding prefix\\u2026", "Rebuilding prefix\\u2026", "Rebuilding prefix\\u2026")
+#define NP_PREFIX_COPY NP_WEB_TEXT("Copying your files\\u2026", "Copying your files\\u2026", "Copying your files\\u2026")
+#define NP_PREFIX_FINISH NP_WEB_TEXT("Finishing\\u2026", "Finishing\\u2026", "Finishing\\u2026")
+#define NP_PREFIX_DONE NP_WEB_TEXT("Prefix rebuilt.", "Prefix rebuilt.", "Prefix rebuilt.")
+#define NP_PREFIX_DONE_BACKUP NP_WEB_TEXT("Prefix rebuilt. A backup of the original is in NotProton's Prefixes view.", "Prefix rebuilt. A backup of the original is in NotProton's Prefixes view.", "Prefix rebuilt. A backup of the original is in NotProton's Prefixes view.")
+#define NP_PREFIX_FAILED NP_WEB_TEXT("Prefix rebuild failed!", "Prefix rebuild failed!", "Prefix rebuild failed!")
+#define NP_PREFIX_LOG NP_WEB_TEXT("Open Log", "Open Log", "Open Log")
+#define NP_PREFIX_APP NP_WEB_TEXT("Couldn't find the NotProton app. Move NotProton to Applications, open it and click Install again.", "Couldn't find the NotProton app. Move NotProton to Applications, open it and click Install again.", "Couldn't find the NotProton app. Move NotProton to Applications, open it and click Install again.")
+
+#define NP_CX_PREFIX_ROW \
+ "globalThis.MSCXPrefixRow=(e,id)=>{if(e.npApp===id)return;e.npStop&&e.npStop();e.npApp=id;let ter" \
+ "m='',busy=0,timer=0,t0=0,stopped=0,live=0;const T={need:" \
+ NP_PREFIX_NEED \
+ ",backup:" \
+ NP_PREFIX_BACKUP \
+ ",rebuild:" \
+ NP_PREFIX_REBUILD \
+ ",running:" \
+ NP_PREFIX_RUNNING \
+ ",setup:" \
+ NP_PREFIX_SETUP \
+ ",copy:" \
+ NP_PREFIX_COPY \
+ ",finish:" \
+ NP_PREFIX_FINISH \
+ ",done:" \
+ NP_PREFIX_DONE \
+ ",doneBackup:" \
+ NP_PREFIX_DONE_BACKUP \
+ ",failed:" \
+ NP_PREFIX_FAILED \
+ ",log:" \
+ NP_PREFIX_LOG \
+ ",app:" \
+ NP_PREFIX_APP \
+ "},el=(tag,cls,txt)=>{const n=e.ownerDocument.createElement(tag);if(cls)n.className=cls;if(txt!=n" \
+ "ull)n.textContent=txt;return n},btn=(txt,main,off,on)=>{const b=el('button','MSCXBtn'+(main?' MS" \
+ "CXMain':''),txt);b.disabled=!!off;b.onclick=on;return b},call=r=>MSCXRoute(r,id).then(j=>JSON.pa" \
+ "rse(j||'{}')),refresh=()=>{if(stopped)return;if(!e.isConnected||e.npApp!==id)return stop();return MSCXRoute('NotProton.PrefixState#1',id).t" \
+ "hen(j=>draw(JSON.parse(j))).catch(()=>{if(stopped||!e.isConnected||e.npApp!==id)return;clearTimeout(timer);if(busy||live)timer=setTimeout(refresh,500);else e.style.display='none'})},start=r=>{term='';busy=1;t0=Date.now();draw(null);cal" \
+ "l(r).then(j=>{j.error==='spawn'&&(term='failed')},()=>0).finally(()=>{busy=0;refresh()})},pair=off=>{const r=el('div','MSCXBtns');r.app" \
+ "end(btn(T.backup,1,off,()=>start('NotProton.BackupAndRebuildPrefix#1')),btn(T.rebuild,0,off,()=>" \
+ "start('NotProton.RebuildPrefix#1')));return r},draw=s=>{if(stopped||!e.isConnected||e.npApp!==id)return;clearTimeout(timer);live=0;const ph=s?s.rebuild" \
+ ":'',k=[];if(ph==='done'||ph==='done-backup'||ph==='failed')term=ph;if(busy||ph==='setup'||ph==='" \
+ "copy'||ph==='finish'){k.push(el('div','',ph==='copy'?T.copy:ph==='finish'?T.finish:T.setup));con" \
+ "st b=el('div','MSCXBar');t0||(t0=Date.now());const m=el('div','');m.style.animationDelay=-((Date.now()-t0)%1200)+'ms';b.append(m);k.push(b);live=1;timer=setTimeout(refresh,500)}else if((t0=0)||" \
+ "term==='failed'){k.push(el('div','',T.failed));const r=el('div','MSCXBtns');r.append(btn(T.log,0" \
+ ",0,()=>call('NotProton.OpenPrefixLog#1').catch(()=>0)));k.push(r);s&&s.needsRebuild&&s.app&&!s.r" \
+ "unning&&k.push(pair(0))}else if(term)k.push(el('div','',term==='done-backup'?T.doneBackup:T.done" \
+ "));else if(s&&s.needsRebuild){if(!s.app)k.push(el('div','',T.app));else{k.push(el('div','',s.run" \
+ "ning?T.running:T.need),pair(s.running));s.running&&(timer=setTimeout(refresh,3e3))}}e.replaceChi" \
+ "ldren(...k);e.style.display=k.length?'':'none'};e.style.flexDirection='column';e.style.gap='8px'" \
+ ";e.style.display='none';const on=v=>{if(!e.isConnected)return e.npStop();v.detail===id&&!busy&&(" \
+ "term='',refresh())};const stop=e.npStop=()=>{stopped=1;clearTimeout(timer);observer?.disconnect();globalThis.removeEventListener?.('mscxstat" \
+ "e',on)};const observer=globalThis.MutationObserver?new globalThis.MutationObserver(()=>{if(!e.isConnected)stop()}):null;observer?.observe(e.ownerDocument,{childList:true,subtree:true});globalThis.addEventListener?.('mscxstate',on);refresh()};"
+
#define NP_CX_OPTIONS_CSS \
"\".MSCXPanel{margin-top:10px}" \
".MSCXPanel .MSCXRow{display:flex;flex-direction:row;padding:9px;margin:0;" \
"color:#dfe3e6;background:rgba(59,63,72,.5);border-radius:3px}" \
".MSCXPanel .MSCXRow:hover{box-shadow:0 6px 8px 0 rgba(0,0,0,.16)}" \
- ".MSCXNoBottomGap{margin-bottom:0}\""
+ ".MSCXNoBottomGap{margin-bottom:0}" \
+ ".MSCXBtns{display:flex;gap:8px}" \
+ ".MSCXBtn{background:#3d4450;color:#fff;border:none;border-radius:2px;padding:6px 14px;" \
+ "font-size:14px;cursor:pointer}.MSCXBtn:hover{background:#4c5361}" \
+ ".MSCXBtn.MSCXMain{background:#1a9fff}.MSCXBtn.MSCXMain:hover{background:#47b4ff}" \
+ ".MSCXBtn:disabled{opacity:.5;cursor:default}" \
+ ".MSCXBtn:focus-visible{outline:2px solid #fff;outline-offset:1px}" \
+ ".MSCXBar{position:relative;align-self:stretch;width:100%;height:4px;overflow:hidden;" \
+ "border-radius:2px;background:rgba(255,255,255,.12)}" \
+ ".MSCXBar>div{position:absolute;top:0;bottom:0;left:-30%;width:30%;background:#1a9fff;" \
+ "animation:MSCXSlide 1.2s linear infinite}" \
+ "@keyframes MSCXSlide{from{left:-30%}to{left:100%}}\""
// FEX runs arm64 Wine, which has no D3DMetal and never runs under Rosetta.
#define NP_CX_OPTIONS_BODY(ARG, RT, BARREL) \
@@ -328,6 +407,7 @@ static int out_expand(np_out_t *o, const char *replace, const np_cap_t *caps) {
"&&!t.strCompatToolName)return null;" \
"return(0," RT ".jsx)(\"div\",{className:\"MSCXPanel\",children:(0," RT ".jsxs)(" RT ".Fragment,{children:[" \
"(0," RT ".jsx)(\"style\",{children:" NP_CX_OPTIONS_CSS "})," \
+ "typeof MSCXPrefixRow==\"function\"&&(0," RT ".jsx)(\"div\",{className:\"MSCXRow\",ref:e=>e&&MSCXPrefixRow(e,t.unAppID)},\"npstate\")," \
"(0," RT ".jsxs)(" BARREL ".XY,{label:npL(\"Graphics\",\"图形\",\"Grafica\"),children:[" \
"(0," RT ".jsx)(" BARREL ".m,{rgOptions:B,selectedOption:b," \
"onChange:v=>s([[\"CX_GRAPHICS_BACKEND\",v.data]]" \
@@ -472,6 +552,21 @@ static const np_gate_t g_gates_selecttool[] = {
"[" NP_C1 "," NP_C2 "]=(typeof MSCXToolQuery==\"function\"?MSCXToolQuery:r=>r)"
"((0," NP_C3 ".cT)(" NP_C4 ")," NP_C4 ");if(" NP_C1
".isLoading||!" NP_C1 ".data?.tools?.length)return null;", 1, 1 },
+ // CompatManager service: hands the page's transport to MSCXRoute for NotProton's own routes
+ { NP_C7 "=" NP_C7 "||(0," NP_C8 ".OI)().GetDefaultTransport(),"
+ NP_C7 "==null?new Promise((" NP_C9 "," NP_C10 ")=>{console.error(\"Transport Error: no transport is available for request\"),"
+ NP_C10 "(\"Transport Error: no transport is available for request\")}):"
+ NP_C7 ".SendMsg(\"CompatManager.GetCompatTools#1\",(0," NP_C1 ".I8)(" NP_C2 "," NP_C3 ")," NP_C4 ","
+ "{ePrivilege:1,eClientExecutionSite:2})}" NP_C5 ".GetCompatTools=" NP_C6 ";",
+ NP_C7 "=" NP_C7 "||(0," NP_C8 ".OI)().GetDefaultTransport(),"
+ NP_C7 "==null?new Promise((" NP_C9 "," NP_C10 ")=>{console.error(\"Transport Error: no transport is available for request\"),"
+ NP_C10 "(\"Transport Error: no transport is available for request\")}):"
+ NP_C7 ".SendMsg(\"CompatManager.GetCompatTools#1\",(0," NP_C1 ".I8)(" NP_C2 "," NP_C3 ")," NP_C4 ","
+ "{ePrivilege:1,eClientExecutionSite:2})}"
+ "globalThis.MSCXRoute=(r,id)=>{const t=(0," NP_C8 ".OI)().GetDefaultTransport();"
+ "return t?t.SendMsg(r,(0," NP_C1 ".I8)(" NP_C2 ",{appid:id})," NP_C4 ",{ePrivilege:1,eClientExecutionSite:2})"
+ ".then(x=>x.BSuccess()?x.Body().toObject().default_tool_identifier||\"\":Promise.reject(\"result \"+x.GetEResult()))"
+ ":Promise.reject(\"no transport\")};" NP_CX_PREFIX_ROW NP_C5 ".GetCompatTools=" NP_C6 ";", 1, 1 },
{ "get is_invalid_os_type(){return this.most_available_per_client_data.is_invalid_os_type}",
"get is_invalid_os_type(){return false}", 1, 0 },
// Reminder banner for 32 bit Mac games
diff --git a/dylib/feats/webui.c b/dylib/feats/webui.c
index e9c5511..df321cc 100644
--- a/dylib/feats/webui.c
+++ b/dylib/feats/webui.c
@@ -23,7 +23,7 @@ static inline int32_t sign_extend(uint32_t val, int bits) {
#define VT_RUN_MIN 8
-#define MAX_ROUTES 4
+#define MAX_ROUTES 8
#define REGISTRY_MAP_OFF 96
#define MAP_ELEMENTS_OFF 48
@@ -55,10 +55,12 @@ typedef uintptr_t (*np_job_factory_fn)(uintptr_t dispatcher, uintptr_t arg);
typedef void (*np_send_response_fn)(uintptr_t job, uintptr_t ctx);
typedef int (*np_register_fn)(uintptr_t registry, void *record);
+// Routes can share request types, so each gets its own job vtable and the job's
+// vptr says which route it belongs to.
typedef struct {
uintptr_t descriptor[DESC_QWORDS];
- uintptr_t request_vptr;
np_webui_handler_fn handler;
+ uintptr_t vtable[2 + VT_SLOTS];
} np_route_t;
static uintptr_t g_registry;
@@ -78,7 +80,7 @@ static int g_route_count;
static uintptr_t g_stock_factory;
static uintptr_t g_clone[2 + VT_SLOTS];
-static uintptr_t g_clone_vptr;
+static size_t g_clone_words;
static uintptr_t g_route_flags;
static int bl_target(uint32_t insn, uintptr_t pc, uintptr_t *out) {
@@ -419,11 +421,11 @@ static uintptr_t vtable_from_factory(uintptr_t factory, int *slot_out, int *run_
static int64_t job_handler(uintptr_t job, uintptr_t ctx) {
uintptr_t request = *(const uintptr_t *)(ctx + 8);
uintptr_t response = *(const uintptr_t *)(ctx + 16);
- uintptr_t vptr = np_plausible_ptr(request) ? *(const uintptr_t *)request : 0;
+ uintptr_t job_vptr = *(const uintptr_t *)job;
int result = RESULT_FAIL;
for (int i = 0; i < g_route_count; i++) {
- if (g_routes[i].request_vptr != vptr) continue;
+ if ((uintptr_t)&g_routes[i].vtable[2] != job_vptr) continue;
result = g_routes[i].handler(request, response);
break;
}
@@ -457,7 +459,7 @@ static int borrow_from_served_route(void) {
// information, and code that asks a job what it is reads them.
memcpy(g_clone, (const void *)(vptr - 16), 16 + 8 * (size_t)run);
g_clone[2 + slot] = (uintptr_t)job_handler;
- g_clone_vptr = (uintptr_t)&g_clone[2];
+ g_clone_words = 2 + (size_t)run;
g_stock_factory = factory;
g_route_flags = *(const uintptr_t *)(elem + ELEM_FLAGS_OFF);
@@ -472,13 +474,23 @@ static int borrow_from_served_route(void) {
return 0;
}
-static uintptr_t job_factory(uintptr_t dispatcher, uintptr_t arg) {
+static uintptr_t build_job(int route, uintptr_t dispatcher, uintptr_t arg) {
uintptr_t job = ((np_job_factory_fn)g_stock_factory)(dispatcher, arg);
- if (job && g_clone_vptr)
- *(uintptr_t *)job = g_clone_vptr;
+ if (job)
+ *(uintptr_t *)job = (uintptr_t)&g_routes[route].vtable[2];
return job;
}
+// The dispatcher calls a factory with no route, so each route needs a factory of its own.
+#define JOB_FACTORY(i) \
+ static uintptr_t job_factory_##i(uintptr_t d, uintptr_t a) { return build_job(i, d, a); }
+JOB_FACTORY(0) JOB_FACTORY(1) JOB_FACTORY(2) JOB_FACTORY(3)
+JOB_FACTORY(4) JOB_FACTORY(5) JOB_FACTORY(6) JOB_FACTORY(7)
+static const np_job_factory_fn g_job_factories[MAX_ROUTES] = {
+ job_factory_0, job_factory_1, job_factory_2, job_factory_3,
+ job_factory_4, job_factory_5, job_factory_6, job_factory_7,
+};
+
int np_webui_register_route(const char *name, uintptr_t request_vptr,
uintptr_t response_vptr, np_webui_handler_fn handler) {
if (!g_registry || !g_register_fn || !name || !handler) return 0;
@@ -491,7 +503,7 @@ int np_webui_register_route(const char *name, uintptr_t request_vptr,
return 0;
}
- if (!g_clone_vptr && !borrow_from_served_route())
+ if (!g_clone_words && !borrow_from_served_route())
return 0;
uintptr_t request_new = *(const uintptr_t *)(request_vptr + MSG_NEW_OFF);
@@ -504,9 +516,9 @@ int np_webui_register_route(const char *name, uintptr_t request_vptr,
np_route_t *route = &g_routes[g_route_count];
route->descriptor[DESC_NAME] = (uintptr_t)name;
route->descriptor[DESC_CONSTANT] = DESC_CONSTANT_VALUE;
- route->descriptor[DESC_FACTORY] = (uintptr_t)job_factory;
- route->request_vptr = request_vptr;
+ route->descriptor[DESC_FACTORY] = (uintptr_t)g_job_factories[g_route_count];
route->handler = handler;
+ memcpy(route->vtable, g_clone, sizeof(uintptr_t) * g_clone_words);
uintptr_t record[4] = {
(uintptr_t)route->descriptor,
diff --git a/dylib/feats/webui.h b/dylib/feats/webui.h
index 1cc4d9a..97238f4 100644
--- a/dylib/feats/webui.h
+++ b/dylib/feats/webui.h
@@ -37,8 +37,8 @@ int np_webui_notify(const char *name, uintptr_t message);
typedef int (*np_webui_handler_fn)(uintptr_t request, uintptr_t response);
// Serves `name` from `handler`. The vptrs name the client's constructors
-// (vtable slot 3 is no-argument New). `request_vptr` also identifies which route
-// a request belongs to. Returns 1 once the route is live.
+// (vtable slot 3 is no-argument New). Routes may share message types. Returns 1
+// once the route is live.
int np_webui_register_route(const char *name, uintptr_t request_vptr,
uintptr_t response_vptr, np_webui_handler_fn handler);
diff --git a/dylib/tests/buildcheck.sh b/dylib/tests/buildcheck.sh
index d5275ce..e696687 100644
--- a/dylib/tests/buildcheck.sh
+++ b/dylib/tests/buildcheck.sh
@@ -6,7 +6,7 @@ SRC="${1:-$(dirname "$0")/../feats/compat_run.sh}"
extract() { sed -n "/^$1() {\$/,/^}\$/p" "$SRC"; }
functions=""
-for name in last_wine_build note_other_build claim_prefix; do
+for name in prefix_machine last_wine_build note_other_build claim_prefix; do
body=$(extract "$name")
[ -n "$body" ] || { echo "FAIL: $name not found in $SRC"; exit 1; }
functions="$functions
@@ -138,21 +138,27 @@ arch_case() {
}
is "an architecture mismatch offers rebuilding" 'rebuild: This game needs its prefix rebuilt: Rosetta prefixes cannot be used with versions of CrossOver that run through FEX unless they are rebuilt.
-Do you want to rebuild the prefix for CrossOver Preview 2026 10 15-ARM64, running through FEX? Your save games will be preserved and not lost.' "$(arch_case aarch64-unix)"
+Do you want to rebuild the prefix for CrossOver Preview 2026 10 15‑ARM64, running through FEX? Your save games will be preserved and not lost.' "$(arch_case aarch64-unix)"
is "the build that set up the prefix is named" 'rebuild: This game needs its prefix rebuilt: This game'"'"'s prefix was last used by CrossOver 26.3, running through Rosetta. Rosetta prefixes cannot be used with versions of CrossOver that run through FEX unless they are rebuilt.
-Do you want to rebuild the prefix for CrossOver Preview 2026 10 15-ARM64, running through FEX? Your save games will be preserved and not lost.' "$(arch_case aarch64-unix 'CrossOver 26.3')"
-is "a tool name's own arch suffix is not repeated" 'rebuild: This game needs its prefix rebuilt: This game'"'"'s prefix was last used by CrossOver Preview 2026 10 15-ARM64, running through Rosetta. Rosetta prefixes cannot be used with versions of CrossOver that run through FEX unless they are rebuilt.
+Do you want to rebuild the prefix for CrossOver Preview 2026 10 15‑ARM64, running through FEX? Your save games will be preserved and not lost.' "$(arch_case aarch64-unix 'CrossOver 26.3')"
+is "a tool name's own arch suffix is not repeated" 'rebuild: This game needs its prefix rebuilt: This game'"'"'s prefix was last used by CrossOver Preview 2026 10 15‑ARM64, running through Rosetta. Rosetta prefixes cannot be used with versions of CrossOver that run through FEX unless they are rebuilt.
-Do you want to rebuild the prefix for CrossOver Preview 2026 10 15-ARM64, running through FEX? Your save games will be preserved and not lost.' "$(arch_case aarch64-unix 'CrossOver 2026 10 15-ARM64 - Rosetta')"
+Do you want to rebuild the prefix for CrossOver Preview 2026 10 15‑ARM64, running through FEX? Your save games will be preserved and not lost.' "$(arch_case aarch64-unix 'CrossOver 2026 10 15-ARM64 - Rosetta')"
is "a matching architecture needs no rebuild" "" "$(arch_case x86_64-unix)"
-rebuild=$(extract rebuild_prefix)
+rebuild="$(extract run_rebuild)
+$(extract rebuild_prefix)"
mkdir -p "$work/app with spaces"
cat > "$work/app with spaces/NotProtonApp" <<'SH'
#!/bin/sh
-printf '%s\n' "$@" > "$TEST_DATA/arguments"
-/usr/bin/lockf -s -t 0 "$TEST_DATA/.notproton-prefix.lock" true || exit 66
-exit "$TEST_STATUS"
+data=$2
+[ -z "$DYLD_INSERT_LIBRARIES$TEST_LEAK" ] || exit 65
+printf '%s\n' "$@" > "$data/arguments"
+printf '%s' "$NOTPROTON_REBUILD_WINDOW" > "$data/window"
+/usr/bin/lockf -s -t 0 "$data/.notproton-prefix.lock" true || exit 66
+[ ! -f "$data/slow" ] || sleep 3
+echo finished > "$data/finished"
+exit "$(cat "$data/status")"
SH
chmod +x "$work/app with spaces/NotProtonApp"
printf '%s' "$work/app with spaces/NotProtonApp" > "$np_support/app-executable"
@@ -161,7 +167,8 @@ rebuild_case() {
choice=$1 command_status=$2 launch_verb=$3 skip=${4:-}
data=$(mktemp -d "$work/compat data.XXXXXX")
(
- export TEST_DATA="$data" TEST_STATUS="$command_status"
+ export TEST_LEAK=1
+ printf '%s' "$command_status" > "$data/status"
STEAM_COMPAT_DATA_PATH=$data np_tool_dir=/tools/chosen np_build=selected-build np_flavor=rosetta
np_display='Selected "tool" with \ and a newline
in its name'
@@ -173,7 +180,7 @@ in its name'
# shellcheck disable=SC2329
show_rebuild_failure() { echo "rebuild failed" >> "$data/alerts"; }
# shellcheck disable=SC2329
- prepare_prefix_directory() { exec 8>> "$data/.notproton-prefix.lock"; /usr/bin/lockf -s -t 0 8; echo locked >> "$data/checks"; }
+ prepare_prefix_directory() { [ -z "${relock_fails:-}" ] || [ ! -f "$data/arguments" ] || return 1; exec 8>> "$data/.notproton-prefix.lock"; /usr/bin/lockf -s -t 0 8; echo locked >> "$data/checks"; }
# shellcheck disable=SC2329
note_other_build() { echo build >> "$data/checks"; }
# shellcheck disable=SC2329
@@ -217,19 +224,42 @@ is "skipping an offered rebuild goes on with the launch" 0 "$status"
is "a skipped rebuild retakes the lock and launches" "locked
launched" "$(cat "$data/checks")"
is "a skipped rebuild never calls the app" no "$([ -f "$data/arguments" ] && echo yes || echo no)"
-is "the skip button is labelled as asked" "Launch Without Rebuilding" "$(tail -1 "$data/prompt-args")"
+is "the skip button is labelled as asked" "Launch Without Rebuilding" "$(tail -2 "$data/prompt-args" | head -1)"
+is "a missing NotProton icon falls back to caution" "" "$(tail -1 "$data/prompt-args")"
rebuild_case 'Rebuild Prefix' 0 run 'Launch Without Rebuilding'
is "install helpers skip an offered rebuild silently" 0 "$status"
rebuild_case 'Rebuild Prefix' 0 waitforexitandrun
+is "the app gets none of Steam's environment" 0 "$status"
+is "a rebuild from Play asks the app for its progress window" 1 "$(cat "$data/window")"
is "a finished rebuild clears the switch record" no "$([ -f "$data/notproton-switch" ] && echo yes || echo no)"
+relock_fails=1
+rebuild_case 'Rebuild Prefix' 0 waitforexitandrun
+relock_fails=
+is "a launch that cannot retake its lock after a rebuild stops" 1 "$status"
+is "and says another launch has the prefix" "Prefix rebuilt" "$(cat "$data/alerts")"
printf '%s' "$work/missing" > "$np_support/app-executable"
rebuild_case 'Rebuild Prefix' 0 waitforexitandrun
is "a moved or missing app stops the launch" 1 "$status"
is "a missing app explains how to repair" "Couldn't find the NotProton app" "$(cat "$data/alerts")"
+data=$(mktemp -d "$work/stopped.XXXXXX")
+printf 0 > "$data/status"
+: > "$data/slow"
+(
+ STEAM_COMPAT_DATA_PATH=$data np_tool_dir=/tools/chosen np_build=b np_flavor=rosetta log="$data/log"
+ eval "$rebuild"
+ run_rebuild "$work/app with spaces/NotProtonApp" keep-backup
+) &
+waiter=$!
+sleep 1
+pkill -KILL -P "$waiter" 2>/dev/null || true
+kill -KILL "$waiter" 2>/dev/null || true
+sleep 4
+is "Stop kills the launch but not the rebuild under it" finished "$(cat "$data/finished" 2>/dev/null)"
echo "== crashes after a switch =="
-health_functions="$(extract note_other_build)
+health_functions="$(extract prefix_machine)
+$(extract note_other_build)
$(extract preview_name)
$(extract running_name)
$(extract tool_name)
diff --git a/dylib/tests/compatsvc-check.c b/dylib/tests/compatsvc-check.c
index bc8e0e1..7841bcd 100644
--- a/dylib/tests/compatsvc-check.c
+++ b/dylib/tests/compatsvc-check.c
@@ -145,6 +145,47 @@ int np_log_first_hit(const void *anchor, unsigned long tag) {
return 1;
}
+// The prefix state has its own check, so here it is whatever the test sets.
+#include "../feats/prefixstate.h"
+#include <spawn.h>
+#include <sys/wait.h>
+const char *np_home_dir(void) { return "/home"; }
+static np_prefix_state_t stub_state;
+static int stub_rebuilding;
+void np_prefix_state(uint32_t appid, const char *tool, const np_prefix_roots_t *roots,
+ np_prefix_state_t *st) {
+ (void)appid; (void)roots;
+ *st = stub_state;
+ snprintf(st->tool, sizeof st->tool, "%s", tool ? tool : "");
+}
+int np_prefix_rebuilding(const np_prefix_state_t *st) { (void)st; return stub_rebuilding; }
+int np_prefix_state_json(uint32_t appid, const np_prefix_state_t *st, char *out, size_t cap) {
+ return snprintf(out, cap, "{\"appid\":%u,\"tool\":\"%s\"}", appid, st->tool);
+}
+
+// Spawns are recorded instead of run, so the routes that start processes are checked by
+// what they would have started.
+#define SPAWN_ARGS_MAX 16
+static char spawned[SPAWN_ARGS_MAX][1024];
+static int spawned_count;
+static int spawn_result;
+static int stub_posix_spawn(pid_t *pid, const char *path, const posix_spawn_file_actions_t *fa,
+ const posix_spawnattr_t *attr, char *const argv[], char *const envp[]) {
+ (void)path; (void)fa; (void)attr; (void)envp;
+ spawned_count = 0;
+ for (; argv[spawned_count] && spawned_count < SPAWN_ARGS_MAX; spawned_count++)
+ snprintf(spawned[spawned_count], sizeof spawned[0], "%s", argv[spawned_count]);
+ *pid = 4242;
+ return spawn_result;
+}
+static pid_t stub_waitpid(pid_t pid, int *status, int options) {
+ (void)options;
+ *status = 0;
+ return pid;
+}
+#define posix_spawn stub_posix_spawn
+#define waitpid stub_waitpid
+
#include "../feats/compatsvc.c"
// Minimal protobuf decoder for the captured reply. Enough to find field values.
@@ -664,6 +705,147 @@ static void routes_state_cases(void) {
stub_absent_type = NULL;
}
+static char scratch[PATH_MAX];
+
+static const char *answer(void) {
+ static char json[256];
+ json[0] = '\0';
+ pb_copy_string(captured_pb, captured_pb_len, RESP_DEFAULT, json, sizeof json);
+ return json;
+}
+
+static int exists(const char *name) {
+ char path[PATH_MAX];
+ snprintf(path, sizeof path, "%s/%s", scratch, name);
+ return access(path, F_OK) == 0;
+}
+
+static void put(const char *name, const char *text) {
+ char path[PATH_MAX];
+ snprintf(path, sizeof path, "%s/%s", scratch, name);
+ FILE *f = fopen(path, "w");
+ fputs(text, f);
+ fclose(f);
+}
+
+static void ready_to_rebuild(void) {
+ reset();
+ memset(&stub_state, 0, sizeof stub_state);
+ stub_rebuilding = 0;
+ spawned_count = 0;
+ spawn_result = 0;
+ stub_state.has_prefix = 1;
+ stub_state.needs_rebuild = 1;
+ snprintf(stub_state.compatdata, sizeof stub_state.compatdata, "%s", scratch);
+ snprintf(stub_state.tool_build, sizeof stub_state.tool_build, "27.0.0.41073-fex");
+ snprintf(stub_state.tool_flavor, sizeof stub_state.tool_flavor, "fex");
+ snprintf(stub_state.app, sizeof stub_state.app, "/Applications/NotProton.app/Contents/MacOS/NotProtonApp");
+ stub_tool_for_app_name = "notproton-fex-41073";
+ char status[PATH_MAX];
+ snprintf(status, sizeof status, "%s/notproton-rebuild", scratch);
+ unlink(status);
+}
+
+// Any page can call these, and two of them start the app, so each refusal is checked.
+static void rebuild_route_cases(void) {
+ snprintf(scratch, sizeof scratch, "%s/compatsvc.XXXXXX", getenv("TMPDIR") ? getenv("TMPDIR") : "/tmp");
+ if (!mkdtemp(scratch)) { check(0, "a scratch compatdata exists"); return; }
+
+ struct { const char *why; void (*set)(void); const char *want; } refusals[] = {
+ { "a prefix that needs no rebuild is not rebuilt", NULL, "{\"error\":\"none\"}" },
+ { "a rebuild already under way is not started twice", NULL, "{\"error\":\"busy\"}" },
+ { "a running game is not rebuilt under it", NULL, "{\"error\":\"running\"}" },
+ { "a missing app is reported, not started", NULL, "{\"error\":\"app\"}" },
+ };
+ for (int i = 0; i < 4; i++) {
+ ready_to_rebuild();
+ if (i == 0) stub_state.needs_rebuild = 0;
+ if (i == 1) stub_rebuilding = 1;
+ if (i == 2) stub_state.running = 1;
+ if (i == 3) stub_state.app[0] = '\0';
+ int rc = rebuild_prefix(build_request(REQ_HAS_APPID, 480), (uintptr_t)response_buf);
+ check(rc == RESULT_OK && strcmp(answer(), refusals[i].want) == 0, refusals[i].why);
+ check(spawned_count == 0, "a refused rebuild starts nothing");
+ check(!exists("notproton-rebuild"), "a refused rebuild writes no progress");
+ }
+
+ ready_to_rebuild();
+ int rc = backup_and_rebuild_prefix(build_request(REQ_HAS_APPID, 480), (uintptr_t)response_buf);
+ check(rc == RESULT_OK && strcmp(answer(), "{\"started\":true}") == 0, "a rebuild starts");
+ char log[PATH_MAX];
+ snprintf(log, sizeof log, "%s/notproton-run.log", scratch);
+ const char *want[] = { "/bin/sh", "-c", REBUILD_SCRIPT, stub_state.app, log, scratch,
+ "notproton-fex-41073", "27.0.0.41073-fex", "fex", "keep-backup" };
+ int same = spawned_count == 10;
+ for (int i = 0; same && i < 10; i++) same = strcmp(spawned[i], want[i]) == 0;
+ check(same, "the app gets the prefix, the tool Steam would run, and the backup choice");
+ check(exists("notproton-rebuild"), "a started rebuild reads as under way before the app reports");
+
+ ready_to_rebuild();
+ char status_path[PATH_MAX], victim[PATH_MAX], lock_path[PATH_MAX];
+ snprintf(status_path, sizeof status_path, "%s/notproton-rebuild", scratch);
+ snprintf(victim, sizeof victim, "%s/keep", scratch);
+ snprintf(lock_path, sizeof lock_path, "%s/.notproton-rebuild.lock", scratch);
+ put("keep", "untouched");
+ symlink(victim, status_path);
+ rebuild_prefix(build_request(REQ_HAS_APPID, 480), (uintptr_t)response_buf);
+ struct stat info;
+ check(spawned_count == 0 && stat(victim, &info) == 0 && info.st_size == 9,
+ "a symlinked status neither truncates its target nor starts a rebuild");
+ ready_to_rebuild();
+ int claim = open(lock_path, O_RDWR);
+ if (claim < 0 || flock(claim, LOCK_EX | LOCK_NB) != 0) abort();
+ put("notproton-rebuild", "copy\n4242\n");
+ rebuild_prefix(build_request(REQ_HAS_APPID, 480), (uintptr_t)response_buf);
+ check(spawned_count == 0 && strcmp(answer(), "{\"error\":\"busy\"}") == 0,
+ "the actual rebuild lock refuses a launch even when the state snapshot is stale");
+ close(claim);
+
+ ready_to_rebuild();
+ rebuild_prefix(build_request(REQ_HAS_APPID, 480), (uintptr_t)response_buf);
+ check(spawned_count == 10 && strcmp(spawned[9], "discard-backup") == 0,
+ "a plain rebuild discards the original");
+
+ ready_to_rebuild();
+ spawn_result = 1;
+ rebuild_prefix(build_request(REQ_HAS_APPID, 480), (uintptr_t)response_buf);
+ check(strcmp(answer(), "{\"error\":\"spawn\"}") == 0, "a rebuild that cannot start says so");
+ check(!exists("notproton-rebuild"), "a rebuild that cannot start leaves no progress behind");
+
+ ready_to_rebuild();
+ rc = rebuild_prefix(build_request(0, 0), (uintptr_t)response_buf);
+ check(rc == RESULT_FAIL && spawned_count == 0, "a request with no appid starts nothing");
+
+ ready_to_rebuild();
+ open_prefix_log(build_request(REQ_HAS_APPID, 480), (uintptr_t)response_buf);
+ check(strcmp(answer(), "{\"error\":\"log\"}") == 0 && spawned_count == 0,
+ "a missing log is not opened");
+ put("notproton-run.log", "x\n");
+ open_prefix_log(build_request(REQ_HAS_APPID, 480), (uintptr_t)response_buf);
+ check(strcmp(answer(), "{\"opened\":true}") == 0 && spawned_count == 4
+ && strcmp(spawned[0], "/bin/sh") == 0 && strcmp(spawned[3], log) == 0
+ && strcmp(spawned[2], "/usr/bin/open -t \"$0\" &") == 0,
+ "the log opens in the background, so Steam does not wait on LaunchServices");
+ unlink(log);
+ symlink(victim, log);
+ spawned_count = 0;
+ open_prefix_log(build_request(REQ_HAS_APPID, 480), (uintptr_t)response_buf);
+ check(spawned_count == 0, "a symlinked log is not opened");
+
+ ready_to_rebuild();
+ put("notproton-rebuild", "done\n1\n");
+ prefix_state(build_request(REQ_HAS_APPID, 480), (uintptr_t)response_buf);
+ check(exists("notproton-rebuild"), "a finished rebuild remains available to other pages");
+ put("notproton-rebuild", "copy\n1\n");
+ stub_rebuilding = 1;
+ prefix_state(build_request(REQ_HAS_APPID, 480), (uintptr_t)response_buf);
+ check(exists("notproton-rebuild"), "a rebuild under way keeps its progress");
+
+ char cmd[PATH_MAX + 16];
+ snprintf(cmd, sizeof cmd, "rm -rf '%s'", scratch);
+ if (system(cmd) != 0) fprintf(stderr, "could not remove %s\n", scratch);
+}
+
static void string_field_cases(void) {
// string_field reads an arena-tagged pointer. Low bit set = arena, cleared before
// deref. A long string (byte[23] < 0) dereferences the first qword as a pointer to
@@ -716,12 +898,13 @@ int main(void) {
no_manager_cases();
routes_state_cases();
string_field_cases();
+ rebuild_route_cases();
if (failures) {
printf("==> compatsvc: %d check(s) failed\n", failures);
return 1;
}
printf("==> compatsvc: the tool list, the none entry, the priorities, the specify "
- "handler, and the route states all answer\n");
+ "handler, the route states and the rebuild routes all answer\n");
return 0;
}
diff --git a/dylib/tests/panel-behavior/emit.c b/dylib/tests/panel-behavior/emit.c
index 031ad54..a4fa9a8 100644
--- a/dylib/tests/panel-behavior/emit.c
+++ b/dylib/tests/panel-behavior/emit.c
@@ -30,6 +30,10 @@ int main(int argc, char **argv) {
: NP_CX_OPTIONS_STATEMENT);
return 0;
}
+ if (argc == 2 && strcmp(argv[1], "prefix-row") == 0) {
+ fputs(NP_CX_PREFIX_ROW, stdout);
+ return 0;
+ }
if (argc == 2 && strcmp(argv[1], "migration") == 0) {
fputs(NP_LAUNCH_MIGRATION, stdout);
return 0;
@@ -51,6 +55,6 @@ int main(int argc, char **argv) {
return 0;
}
fputs("usage: emit component|statement [fallback [fex-tool...]]|migration|compat-hint|"
- "image-files-label|library-windows-hint|library-windows-summary\n", stderr);
+ "image-files-label|library-windows-hint|library-windows-summary|prefix-row\n", stderr);
return 2;
}
diff --git a/dylib/tests/panel-behavior/prefix-row.js b/dylib/tests/panel-behavior/prefix-row.js
new file mode 100644
index 0000000..2d4b6a3
--- /dev/null
+++ b/dylib/tests/panel-behavior/prefix-row.js
@@ -0,0 +1,149 @@
+'use strict';
+// The rebuild row in the CrossOver panel, driven against a fake DOM, fake timers and a
+// fake route. Each step answers the row's next request the way the dylib would.
+const assert = require('node:assert/strict');
+const { execFileSync } = require('node:child_process');
+
+const emit = process.argv[2];
+if (!emit) throw new Error('usage: prefix-row.js <emit>');
+const src = execFileSync(emit, ['prefix-row'], { encoding: 'utf8' });
+
+class Node {
+ constructor(tag) { this.tag = tag; this.children = []; this.style = {}; this.className = ''; this.textContent = ''; }
+ append(...n) { this.children.push(...n); }
+ replaceChildren(...n) { this.children = n; }
+}
+
+function world(states, startReply = '{"started":true}') {
+ const calls = [], timers = [], listeners = {};
+ const doc = { createElement: tag => new Node(tag), documentElement: { lang: 'en' } };
+ const g = {
+ document: doc, navigator: { language: 'en' },
+ setTimeout: (f, ms) => { timers.push({ f, ms }); return timers.length; }, clearTimeout: () => {},
+ addEventListener: (n, f) => { listeners[n] = f; }, removeEventListener: n => { delete listeners[n]; },
+ MSCXRoute: (route, id) => {
+ calls.push(route);
+ if (route === 'NotProton.PrefixState#1') {
+ const state = states.shift() || {};
+ if (state instanceof Error) return Promise.reject(state);
+ if (state instanceof Promise) return state;
+ return Promise.resolve(JSON.stringify(state));
+ }
+ return Promise.resolve(startReply);
+ },
+ };
+ new Function('globalThis', 'document', 'navigator', 'setTimeout', 'clearTimeout', 'MSCXRoute', src)(
+ g, doc, g.navigator, g.setTimeout, g.clearTimeout, g.MSCXRoute);
+ const row = new Node('div');
+ row.ownerDocument = doc;
+ row.isConnected = true;
+ const settle = () => new Promise(r => setImmediate(r));
+ const tick = async () => { const t = timers.shift(); t && t.f(); await settle(); await settle(); return t; };
+ const texts = () => row.children.filter(c => c.tag === 'div' && !c.children.length).map(c => c.textContent);
+ const buttons = () => row.children.flatMap(c => c.children).filter(c => c.tag === 'button');
+ return { g, row, calls, timers, listeners, settle, tick, texts, buttons };
+}
+
+const need = { needsRebuild: true, app: true, running: false, rebuild: '' };
+
+(async () => {
+ {
+ const w = world([{ ...need, rebuild: 'copy' }, new Error('transport'), { rebuild: 'done' }]);
+ w.g.MSCXPrefixRow(w.row, 480); await w.settle();
+ await w.tick();
+ assert.equal(w.texts()[0], 'Copying your files\u2026');
+ await w.tick();
+ assert.equal(w.texts()[0], 'Prefix rebuilt.');
+ }
+ {
+ const w = world([new Error('no transport')]);
+ w.g.MSCXPrefixRow(w.row, 480); await w.settle(); await w.settle();
+ assert.equal(w.row.style.display, 'none', 'a route that cannot answer hides the row');
+ assert.equal(w.timers.length, 0, 'and nothing keeps asking');
+ }
+ {
+ let answer;
+ const pending = new Promise(resolve => { answer = resolve; });
+ const w = world([pending, { needsRebuild: false }]);
+ w.g.MSCXPrefixRow(w.row, 480);
+ w.g.MSCXPrefixRow(w.row, 481); await w.settle();
+ answer(JSON.stringify(need)); await w.settle();
+ assert.equal(w.row.style.display, 'none', 'an old answer cannot rebuild the wrong game');
+ }
+ {
+ const w = world([{ needsRebuild: false, app: true, rebuild: '' }]);
+ w.g.MSCXPrefixRow(w.row, 480); await w.settle(); await w.settle();
+ assert.equal(w.row.style.display, 'none', 'no rebuild needed keeps the row hidden');
+ w.g.MSCXPrefixRow(w.row, 480); await w.settle();
+ assert.equal(w.calls.length, 1, 'rendering again for the same app does not ask again');
+ }
+ {
+ const w = world([need, { ...need, rebuild: 'setup' }, { ...need, rebuild: 'copy' },
+ { ...need, rebuild: 'finish' }, { needsRebuild: false, app: true, rebuild: 'done-backup' }]);
+ w.g.MSCXPrefixRow(w.row, 480); await w.settle(); await w.settle();
+ assert.equal(w.row.style.display, '');
+ assert.deepEqual(w.texts(), ['Switching to this compatibility tool requires a prefix rebuild. Rebuild now?']);
+ assert.deepEqual(w.buttons().map(b => b.textContent), ['Backup & Rebuild Prefix', 'Rebuild Prefix']);
+ assert.equal(w.buttons()[0].className, 'MSCXBtn MSCXMain', 'Backup & Rebuild is the main button');
+ w.buttons()[0].onclick(); await w.settle(); await w.settle(); await w.settle();
+ assert(w.calls.includes('NotProton.BackupAndRebuildPrefix#1'), 'backup rebuild is asked for');
+ assert.equal(w.texts()[0], 'Rebuilding prefix\u2026');
+ assert(w.row.children.some(c => c.className === 'MSCXBar'), 'a bar shows while it runs');
+ const delay = parseInt(w.row.children.find(c => c.className === 'MSCXBar').children[0].style.animationDelay);
+ assert(delay <= 0 && delay > -200, `the bar starts from the left when the rebuild starts (${delay}ms)`);
+ await w.tick(); assert.equal(w.texts()[0], 'Copying your files\u2026');
+ await w.tick(); assert.equal(w.texts()[0], 'Finishing\u2026');
+ assert.equal(w.timers.at(-1).ms, 500, 'it asks again every half second');
+ await w.tick();
+ assert.deepEqual(w.texts(), ["Prefix rebuilt. A backup of the original is in NotProton's Prefixes view."]);
+ const left = w.timers.length;
+ w.g.MSCXPrefixRow(w.row, 480);
+ assert.equal(w.timers.length, left, 'nothing polls once it is done');
+ // The dylib reports done once, so the next answer is empty, and the row keeps saying done.
+ w.listeners.mscxstate({ detail: 481 }); await w.settle();
+ assert.deepEqual(w.texts(), ["Prefix rebuilt. A backup of the original is in NotProton's Prefixes view."]);
+ }
+ {
+ const w = world([need, { ...need, rebuild: 'failed' }, need]);
+ w.g.MSCXPrefixRow(w.row, 480); await w.settle(); await w.settle();
+ w.buttons()[1].onclick(); await w.settle(); await w.settle(); await w.settle();
+ assert(w.calls.includes('NotProton.RebuildPrefix#1'), 'a plain rebuild is asked for');
+ await w.tick();
+ assert.deepEqual(w.texts(), ['Prefix rebuild failed!']);
+ assert.deepEqual(w.buttons().map(b => b.textContent), ['Open Log', 'Backup & Rebuild Prefix', 'Rebuild Prefix'],
+ 'a failure offers the log and another try');
+ w.buttons()[0].onclick(); await w.settle();
+ assert(w.calls.includes('NotProton.OpenPrefixLog#1'));
+ }
+ {
+ const w = world([{ ...need, running: true }, need]);
+ w.g.MSCXPrefixRow(w.row, 480); await w.settle(); await w.settle();
+ assert.deepEqual(w.texts(), ['Quit the game to rebuild.']);
+ assert(w.buttons().every(b => b.disabled), 'nothing can start while the game runs');
+ assert.equal(w.timers.at(-1).ms, 3000, 'it checks again for the game quitting');
+ await w.tick();
+ assert(w.buttons().every(b => !b.disabled), 'quitting the game enables the buttons');
+ }
+ {
+ const w = world([{ ...need, app: false }]);
+ w.g.MSCXPrefixRow(w.row, 480); await w.settle(); await w.settle();
+ assert.deepEqual(w.texts(), ["Couldn't find the NotProton app. Move NotProton to Applications, open it and click Install again."]);
+ assert.equal(w.buttons().length, 0);
+ }
+ {
+ const w = world([need, need], '{"error":"spawn"}');
+ w.g.MSCXPrefixRow(w.row, 480); await w.settle(); await w.settle();
+ w.buttons()[1].onclick(); await w.settle(); await w.settle(); await w.settle();
+ assert.deepEqual(w.texts(), ['Prefix rebuild failed!'], 'a rebuild that cannot start says so');
+ }
+ {
+ const w = world([need, { needsRebuild: false, app: true, rebuild: '' }]);
+ w.g.MSCXPrefixRow(w.row, 480); await w.settle(); await w.settle();
+ w.listeners.mscxstate({ detail: 480 }); await w.settle(); await w.settle();
+ assert.equal(w.row.style.display, 'none', 'picking a matching tool hides the row');
+ w.row.isConnected = false;
+ w.listeners.mscxstate({ detail: 480 });
+ assert(!w.listeners.mscxstate, 'a row that left the page stops listening');
+ }
+ console.log('PASS: rebuild row hides, offers, progresses, finishes, fails, waits for the game and finds no app');
+})().catch(e => { console.error(e); process.exit(1); });
diff --git a/dylib/tests/prefixstate-check.c b/dylib/tests/prefixstate-check.c
new file mode 100644
index 0000000..e56cf74
--- /dev/null
+++ b/dylib/tests/prefixstate-check.c
@@ -0,0 +1,229 @@
+// The prefix state the Compatibility page reads, against a scratch Steam layout.
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/time.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+#include "../feats/prefixstate.c"
+
+static int fails;
+static char root[PATH_MAX];
+
+static void check(const char *what, const char *want, const char *got) {
+ if (strcmp(want, got) == 0) { printf(" ok %s\n", what); return; }
+ printf(" FAIL %s\n want [%s]\n got [%s]\n", what, want, got);
+ fails++;
+}
+
+static void mkdirs(const char *rel) {
+ char path[PATH_MAX];
+ snprintf(path, sizeof path, "%s/%s", root, rel);
+ for (char *p = path + strlen(root) + 1; *p; p++) {
+ if (*p != '/') continue;
+ *p = '\0'; mkdir(path, 0755); *p = '/';
+ }
+ mkdir(path, 0755);
+}
+
+static void put(const char *rel, const void *bytes, size_t len) {
+ char path[PATH_MAX], dir[PATH_MAX];
+ snprintf(path, sizeof path, "%s/%s", root, rel);
+ snprintf(dir, sizeof dir, "%s", rel);
+ char *slash = strrchr(dir, '/');
+ if (slash) { *slash = '\0'; mkdirs(dir); }
+ FILE *f = fopen(path, "wb");
+ fwrite(bytes, 1, len, f);
+ fclose(f);
+}
+
+static void put_text(const char *rel, const char *text) { put(rel, text, strlen(text)); }
+
+static void put_ntdll(const char *compatdata, uint16_t machine) {
+ uint8_t dll[0x46] = { 'M', 'Z' };
+ dll[0x3c] = 0x40;
+ memcpy(dll + 0x40, "PE\0\0", 4);
+ dll[0x44] = (uint8_t)machine;
+ dll[0x45] = (uint8_t)(machine >> 8);
+ char rel[PATH_MAX];
+ snprintf(rel, sizeof rel, "%s/pfx/drive_c/windows/system32/ntdll.dll", compatdata);
+ put(rel, dll, sizeof dll);
+}
+
+static np_prefix_state_t st;
+
+static const char *state(uint32_t appid, const char *tool) {
+ static char out[2048];
+ char steam[PATH_MAX], support[PATH_MAX], server[PATH_MAX];
+ snprintf(steam, sizeof steam, "%s/Steam", root);
+ snprintf(support, sizeof support, "%s/support", root);
+ snprintf(server, sizeof server, "%s/server", root);
+ np_prefix_roots_t roots = { steam, support, server };
+ np_prefix_state(appid, tool, &roots, &st);
+ if (np_prefix_state_json(appid, &st, out, sizeof out) < 0)
+ snprintf(out, sizeof out, "(did not fit)");
+ return out;
+}
+
+static const char *flag(int v) { return v ? "yes" : "no"; }
+
+// Holds the wineserver lock of a prefix from another process, as a running server does.
+static pid_t hold_server_lock(const char *compatdata) {
+ char pfx[PATH_MAX], dir[PATH_MAX], lock[PATH_MAX];
+ struct stat s;
+ snprintf(pfx, sizeof pfx, "%s/%s/pfx", root, compatdata);
+ stat(pfx, &s);
+ snprintf(dir, sizeof dir, "server/server-%llx-%llx", (unsigned long long)s.st_dev,
+ (unsigned long long)s.st_ino);
+ mkdirs(dir);
+ snprintf(lock, sizeof lock, "%s/%s/lock", root, dir);
+ int ready[2];
+ if (pipe(ready) != 0) return -1;
+ pid_t pid = fork();
+ if (pid == 0) {
+ int fd = open(lock, O_CREAT | O_RDWR, 0600);
+ struct flock fl = { .l_type = F_WRLCK, .l_whence = SEEK_SET, .l_start = 0, .l_len = 1 };
+ fcntl(fd, F_SETLK, &fl);
+ if (write(ready[1], "x", 1) != 1) _exit(1);
+ pause();
+ _exit(0);
+ }
+ char c;
+ close(ready[1]);
+ if (read(ready[0], &c, 1) != 1) pid = -1;
+ close(ready[0]);
+ return pid;
+}
+
+int main(void) {
+ snprintf(root, sizeof root, "%s/prefixstate.XXXXXX", getenv("TMPDIR") ? getenv("TMPDIR") : "/tmp");
+ if (!mkdtemp(root)) { perror("mkdtemp"); return 1; }
+
+ char vdf[PATH_MAX * 2];
+ snprintf(vdf, sizeof vdf,
+ "\"libraryfolders\"\n{\n\t\"0\"\n\t{\n\t\t\"path\"\t\t\"%s/Steam\"\n\t}\n"
+ "\t\"1\"\n\t{\n\t\t\"path\"\t\t\"%s/External \\\"Games\\\" SSD\"\n\t}\n}\n", root, root);
+ put_text("Steam/steamapps/libraryfolders.vdf", vdf);
+ put_text("support/tools",
+ "notproton-26.3\t26.3.0.39832\trosetta\tCrossOver 26.3\n"
+ "notproton-fex-41073\t27.0.0.41073-fex\tfex\tCrossOver 2026 10 15-ARM64 - FEX\n"
+ "short\tline\n");
+
+ // A game on the second library, last run by 26.3 under Rosetta.
+ const char *ikaruga = "External \"Games\" SSD/steamapps/compatdata/480";
+ put_text("External \"Games\" SSD/steamapps/appmanifest_480.acf", "\"AppState\"\n{\n}\n");
+ put_ntdll(ikaruga, 0x8664);
+ put_text("External \"Games\" SSD/steamapps/compatdata/480/notproton-build",
+ "26.3.0.39832\nCrossOver \"26.3\"\n");
+
+ printf("== prefix state ==\n");
+ check("the page gets every field, escaped",
+ "{\"appid\":480,\"tool\":\"notproton-fex-41073\",\"toolDisplay\":\"CrossOver 2026 10 15-ARM64 - FEX\","
+ "\"toolArch\":\"fex\",\"prefix\":true,\"prefixArch\":\"rosetta\",\"lastBuild\":\"26.3.0.39832\","
+ "\"lastDisplay\":\"CrossOver \\\"26.3\\\"\",\"needsRebuild\":true,\"running\":false,"
+ "\"rebuild\":\"\",\"app\":false}",
+ state(480, "notproton-fex-41073"));
+ check("the tool's build is what the app is asked to rebuild with", "27.0.0.41073-fex", st.tool_build);
+ check("the prefix is found on the library holding the game",
+ "External \"Games\" SSD/steamapps/compatdata/480", st.compatdata + strlen(root) + 1);
+ state(480, "notproton-26.3");
+ check("the same arch needs none", "no", flag(st.needs_rebuild));
+ state(480, "proton_9");
+ check("a tool that is not ours never asks for a rebuild", "no", flag(st.needs_rebuild));
+
+ put_text("Steam/steamapps/appmanifest_620.acf", "\"AppState\"\n{\n}\n");
+ state(620, "notproton-fex-41073");
+ check("a game with no prefix yet needs none", "no no", st.has_prefix || st.needs_rebuild ? "yes" : "no no");
+
+ mkdirs("Steam/steamapps/compatdata/700/pfx");
+ state(700, "notproton-26.3");
+ check("a prefix Steam only laid out has no arch and needs none", "no", flag(st.needs_rebuild));
+
+ put_ntdll("External \"Games\" SSD/steamapps/compatdata/3000000000", 0xaa64);
+ state(3000000000u, "notproton-26.3");
+ check("a shortcut's prefix is found without a manifest", "fex yes", st.needs_rebuild && strcmp(st.prefix_arch, "fex") == 0 ? "fex yes" : st.prefix_arch);
+
+ put_text("Steam/steamapps/appmanifest_800.acf", "\"AppState\"\n{\n}\n");
+ put_ntdll("Steam/steamapps/compatdata/800", 0x014c);
+ state(800, "notproton-26.3");
+ check("a 32-bit prefix needs a rebuild under Rosetta", "32-bit yes",
+ st.needs_rebuild && strcmp(st.prefix_arch, "32-bit") == 0 ? "32-bit yes" : st.prefix_arch);
+
+ printf("== app, server and rebuild ==\n");
+ char app[PATH_MAX + 16];
+ snprintf(app, sizeof app, "%s/support/NotProtonApp", root);
+ put_text("support/NotProtonApp", "#!/bin/sh\n");
+ chmod(app, 0755);
+ char record[PATH_MAX + 2];
+ snprintf(record, sizeof record, "%s\n", app);
+ put_text("support/app-executable", record);
+ state(480, "notproton-fex-41073");
+ check("the recorded app is found", app, st.app);
+ chmod(app, 0644);
+ state(480, "notproton-fex-41073");
+ check("an app that cannot run is not offered", "", st.app);
+
+ check("no server is not running", "no", flag(st.running));
+ pid_t holder = hold_server_lock(ikaruga);
+ state(480, "notproton-fex-41073");
+ check("a server holding the prefix is running", "yes", flag(st.running));
+ if (holder > 0) { kill(holder, SIGKILL); waitpid(holder, NULL, 0); }
+ state(480, "notproton-fex-41073");
+ check("a server that exited is not running", "no", flag(st.running));
+
+ char status[PATH_MAX + 64];
+ snprintf(status, sizeof status, "%s/notproton-rebuild", ikaruga);
+ char text[64];
+ char rebuild_lock[PATH_MAX];
+ snprintf(rebuild_lock, sizeof rebuild_lock, "%s/%s/.notproton-rebuild.lock", root, ikaruga);
+ int rebuild_fd = open(rebuild_lock, O_CREAT | O_RDWR, 0600);
+ if (rebuild_fd < 0 || flock(rebuild_fd, LOCK_EX | LOCK_NB) != 0) abort();
+ snprintf(text, sizeof text, "copy\n%d\n", (int)getpid());
+ put_text(status, text);
+ state(480, "notproton-fex-41073");
+ check("a live rebuild reports its phase", "copy", st.rebuild);
+ check("a live rebuild is under way", "yes", flag(np_prefix_rebuilding(&st)));
+ close(rebuild_fd);
+ state(480, "notproton-fex-41073");
+ check("a live unrelated pid does not keep a rebuild busy", "failed", st.rebuild);
+
+ pid_t gone = fork();
+ if (gone == 0) _exit(0);
+ waitpid(gone, NULL, 0);
+ snprintf(text, sizeof text, "setup\n%d\n", (int)gone);
+ put_text(status, text);
+ state(480, "notproton-fex-41073");
+ check("a rebuild whose app died has failed", "failed", st.rebuild);
+ check("a failed rebuild is not under way", "no", flag(np_prefix_rebuilding(&st)));
+
+ put_text(status, "setup\n0\n");
+ state(480, "notproton-fex-41073");
+ check("a rebuild just started is under way before the app reports", "setup", st.rebuild);
+
+ put_text(status, "done-backup\n123\n");
+ state(480, "notproton-fex-41073");
+ check("a finished rebuild says so", "done-backup", st.rebuild);
+ char status_path[PATH_MAX + 64];
+ snprintf(status_path, sizeof status_path, "%s/%s", root, status);
+ struct timeval old[2] = { { time(NULL) - 3600, 0 }, { time(NULL) - 3600, 0 } };
+ utimes(status_path, old);
+ state(480, "notproton-fex-41073");
+ check("a result nobody saw for an hour is not shown", "", st.rebuild);
+ put_text(status, "anything\n");
+ state(480, "notproton-fex-41073");
+ check("an unknown phase is ignored", "", st.rebuild);
+
+ char small[16];
+ check("an answer that does not fit is refused", "-1",
+ np_prefix_state_json(480, &st, small, sizeof small) < 0 ? "-1" : small);
+
+ char cmd[PATH_MAX + 16];
+ snprintf(cmd, sizeof cmd, "rm -rf '%s'", root);
+ if (system(cmd) != 0) fprintf(stderr, "could not remove %s\n", root);
+
+ if (fails) { printf("==> prefixstate: %d failed\n", fails); return 1; }
+ printf("==> prefixstate: libraries, arches, records, tools, servers and rebuilds read as expected\n");
+ return 0;
+}