Free fork of NotProton: Windows Steam games in Mac Steam, on CodeWeavers' Wine and Apple's Game Porting Toolkit
Swift apple-silicond3dmetaldxmtdxvkgame-porting-toolkitgptkmac-gamingmacosmetalfxrosetta-2steamsteam-playwinewinecx
Check installed NotProton files by content as well as version
NotProtonNot24e379c21214
diff --git a/Makefile b/Makefileindex 046312a..02b6726 100644--- a/Makefile+++ b/Makefile@@ -502,6 +502,7 @@ app-payload: $(TARGET) $(OVERLAY_SHIM) $(ICONMAKER) $(APPINFO)cp -f $(OVERLAY_SHIM) "$(APP_PAYLOAD)/overlay-shim.dylib"cp -f $(ICONMAKER) "$(APP_PAYLOAD)/iconmaker"cp -f $(APPINFO) "$(APP_PAYLOAD)/appinfo"+ cp -f dylib/feats/compat_run.sh "$(APP_PAYLOAD)/run"cp -f signatures/macos.arm64/*.json "$(APP_PAYLOAD)/signatures/macos.arm64/"@set -e; for spec in $(BRIDGE_FILES); do \src="$${spec%%:*}"; dst="$(APP_PAYLOAD)/bridge/$${spec##*:}"; \@@ -509,6 +510,7 @@ app-payload: $(TARGET) $(OVERLAY_SHIM) $(ICONMAKER) $(APPINFO)elif [ -f "$$dst" ]; then echo "==> keeping staged $${spec##*:}"; \else echo "$$src is missing and nothing is staged at $$dst, run: $(MAKE) bridge" >&2; exit 1; fi; \done+ @date -u +%s > "$(APP_PAYLOAD)/build-time"@echo "==> Staged app payload in $(APP_PAYLOAD)"APP_BUNDLE := $(OUT_DIR)/NotProton.appdiff --git a/app/Sources/NotProtonApp/App.swift b/app/Sources/NotProtonApp/App.swiftindex 8a0d5c9..8b3bd59 100644--- a/app/Sources/NotProtonApp/App.swift+++ b/app/Sources/NotProtonApp/App.swift@@ -64,13 +64,13 @@ struct NotProtonApp: App {CommandMenu("Setup") {Button("Install") { Task { await status.requestInstall() } }.keyboardShortcut("i", modifiers: .command)- .disabled(!status.isIdle)+ .disabled(!status.canInstall)Button("Set Up Compatibility Tool") { Task { await status.requestCompatibilityTool() } }- .disabled(!status.isIdle || status.setupSource == nil)+ .disabled(!status.canInstall || status.setupSource == nil)Button("Fetch Valve Binaries") { Task { await status.fetchValveBinaries() } }- .disabled(!status.isIdle)+ .disabled(!status.canInstall)Divider()diff --git a/app/Sources/NotProtonApp/Model/DeploymentContent.swift b/app/Sources/NotProtonApp/Model/DeploymentContent.swiftnew file mode 100644index 0000000..c75e22c--- /dev/null+++ b/app/Sources/NotProtonApp/Model/DeploymentContent.swift@@ -0,0 +1,185 @@+import Darwin+import Foundation++enum DeploymentContent {+ struct Build: Codable, Equatable, Sendable {+ let version: String+ let builtAt: Int64+ var dylibHashes: [String]? = nil++ func isNewer(than other: Build) -> Bool {+ let order = version.compare(other.version, options: .numeric)+ return order == .orderedDescending || (order == .orderedSame && builtAt > other.builtAt)+ }+ }++ struct File: Sendable {+ let source: URL+ let destination: URL+ let name: String+ var allowsResigning = false+ var executable = false++ func matches() throws -> Bool {+ let expected = try Digest.sha256(of: source)+ var info = stat()+ guard lstat(destination.path(percentEncoded: false), &info) == 0,+ info.st_mode & S_IFMT == S_IFREG else { return false }+ if executable && !FileManager.default.isExecutableFile(atPath: destination.path(percentEncoded: false)) {+ return false+ }+ if Digest.sha256IfPresent(destination) == expected { return true }+ guard allowsResigning else { return false }+ return try MachOBuild.matchesIgnoringSignature(source, destination)+ }+ }++ enum Status: Equatable, Sendable {+ case unchecked+ case current+ case update([String])+ case repair([String])+ case unrecorded([String])+ case newerInstalled+ case unavailable(String)++ var blocksInstallation: Bool {+ switch self {+ case .newerInstalled, .unavailable: true+ default: false+ }+ }+ }++ static func record(beside versionFile: URL) -> URL {+ versionFile.deletingLastPathComponent().appending(path: "install-build.json")+ }++ static func acquireInstallationLock(for app: URL) throws -> Int32 {+ let parent = app.deletingLastPathComponent().path(percentEncoded: false)+ let fd = open(parent, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)+ guard fd >= 0 else {+ throw StepFailure(step: SteamInstaller.step, detail: "Could not lock the installation at \(parent): \(String(cString: strerror(errno))).")+ }+ guard flock(fd, LOCK_EX | LOCK_NB) == 0 else {+ close(fd)+ throw StepFailure(step: SteamInstaller.step, detail: "Another installation operation is changing files here. Wait for it to finish.")+ }+ return fd+ }++ static func readBuild(at file: URL) throws -> Build? {+ guard FileManager.default.fileExists(atPath: file.path(percentEncoded: false)) else { return nil }+ let build = try JSONDecoder().decode(Build.self, from: Data(contentsOf: file))+ guard !build.version.isEmpty, build.builtAt > 0 else {+ throw StepFailure(step: "Check installed files", detail: "The installed build record is invalid.")+ }+ return build+ }++ static func inspect(files: [File], bundled: Build, installed: Build?, legacyVersion: String? = nil,+ additionalDifferences: [String] = []) throws -> Status {+ if let installed, installed.isNewer(than: bundled) { return .newerInstalled }+ if let legacyVersion, legacyVersion.compare(bundled.version, options: .numeric) == .orderedDescending {+ return .newerInstalled+ }+ let changed = try files.filter { try !$0.matches() }+ let differences = changed.map(\.name) + additionalDifferences+ guard !differences.isEmpty else { return .current }+ guard let installed else {+ if let legacyVersion, legacyVersion.compare(bundled.version, options: .numeric) == .orderedAscending {+ return .update(differences)+ }+ return .unrecorded(differences)+ }+ if let hashes = installed.dylibHashes,+ let dylib = changed.first(where: \.allowsResigning),+ try Shell.run("/usr/bin/codesign", ["--verify", "--strict", dylib.destination.path(percentEncoded: false)]).succeeded,+ let deployed = try MachOBuild.hashesIgnoringSignature(of: dylib.destination),+ hashes != deployed+ {+ throw StepFailure(step: "Check installed files",+ detail: "Steam's installed dylib does not match this account's build record. Finish or repair its installation with the NotProton app that last installed it.")+ }+ return bundled.isNewer(than: installed) ? .update(differences) : .repair(differences)+ }++ static func files(+ payload: InstallPayload.Located, bridgePayload: BridgePayload.Located,+ app: URL, bridge: URL, signatures: URL, overlayShim: URL, iconmaker: URL, appinfo: URL,+ compatTools: URL, tools: [InstalledTool], runners: URL+ ) -> [File] {+ var files = [+ File(source: payload.dylib, destination: SupportPaths.Steam.deployedDylib(inBundle: app),+ name: "notproton.dylib", allowsResigning: true),+ File(source: payload.overlayShim, destination: overlayShim, name: "overlay-shim.dylib"),+ File(source: payload.iconmaker, destination: iconmaker, name: "iconmaker", executable: true),+ File(source: payload.appinfo, destination: appinfo, name: "appinfo", executable: true),+ ]+ files += payload.signatures.map {+ File(source: $0, destination: signatures.appending(path: $0.lastPathComponent),+ name: "signatures/\($0.lastPathComponent)")+ }+ for entry in bridgePayload.sources {+ files += entry.bridgePaths.map {+ File(source: entry.source, destination: bridge.appending(path: $0), name: "bridge/\($0)")+ }+ }+ files += tools.map {+ File(source: payload.run, destination: compatTools.appending(path: "\($0.name)/run"),+ name: "\($0.name)/run", executable: true)+ }+ for build in Set(tools.map(\.build)).sorted() {+ let root = SupportPaths.clonedRoot(forBuild: build, runners: runners)+ for builtin in RunnerPatcher.builtins(in: root) {+ let path = "\(builtin.arch)/\(builtin.name)"+ if let entry = bridgePayload.sources.first(where: { $0.bridgePaths.contains(path) }) {+ files.append(File(source: entry.source, destination: root.appending(path: "lib/wine/\(path)"),+ name: "crossover-\(build)/\(path)"))+ }+ }+ }+ return files+ }++ static func current(version: String) -> Status {+ do {+ let payload = try InstallPayload.locate()+ let bridge = try BridgePayload.locate()+ let pinned = try pinnedFiles(bridge: SupportPaths.bridge, runners: SupportPaths.runners)+ .filter { Digest.sha256IfPresent($0.destination) != $0.hash }.map(\.name)+ let files = files(payload: payload, bridgePayload: bridge, app: SupportPaths.Steam.app,+ bridge: SupportPaths.bridge, signatures: SupportPaths.signatures,+ overlayShim: SupportPaths.overlayShim, iconmaker: SupportPaths.iconmaker,+ appinfo: SupportPaths.appinfo, compatTools: SupportPaths.Steam.compatTools,+ tools: CompatToolList.installed(), runners: SupportPaths.runners)+ return try inspect(files: files, bundled: Build(version: version, builtAt: payload.builtAt),+ installed: readBuild(at: record(beside: SupportPaths.deployedVersion)),+ legacyVersion: SteamBundle.deployedVersion(), additionalDifferences: pinned.sorted())+ } catch {+ return .unavailable(error.localizedDescription)+ }+ }++ static func pinnedFiles(bridge: URL, runners: URL) throws -> [(destination: URL, hash: String, name: String)] {+ let manifest = try ValvePackageManifest.bundled()+ var files = manifest.files.map {+ (destination: bridge.appending(path: $0.bridgePath), hash: $0.sha256, name: "bridge/\($0.bridgePath)")+ }+ let list = runners.deletingLastPathComponent().appending(path: "tools")+ let tools = CompatToolList.installed(runners: runners, file: list)+ if !tools.isEmpty || FileManager.default.fileExists(atPath: list.path(percentEncoded: false)) {+ files.append((list, Digest.sha256(of: Data(CompatToolList.contents(tools).utf8)), "tools"))+ }+ for build in RunnerStore.installedBuilds(in: runners) {+ for (arch, hash) in build.patchedNtdll {+ let file = SupportPaths.clonedRoot(forBuild: build.id, runners: runners)+ .appending(path: "lib/wine/\(arch.rawValue)/ntdll.dll")+ files.append((file, hash, "crossover-\(build.id)/\(arch.rawValue)/ntdll.dll"))+ files.append((NtdllPatcher.stagedCopy(of: arch, build: build.id, in: bridge), hash,+ "bridge/wine/\(build.id)/\(arch.rawValue)/ntdll.dll"))+ }+ }+ return files+ }+}diff --git a/app/Sources/NotProtonApp/Model/InstallPayload.swift b/app/Sources/NotProtonApp/Model/InstallPayload.swiftindex e095af3..228a397 100644--- a/app/Sources/NotProtonApp/Model/InstallPayload.swift+++ b/app/Sources/NotProtonApp/Model/InstallPayload.swift@@ -10,6 +10,8 @@ enum InstallPayload {let overlayShim: URLlet iconmaker: URLlet appinfo: URL+ let run: URL+ let builtAt: Int64let signatures: [URL]}@@ -35,6 +37,9 @@ enum InstallPayload {let shim = root.appending(path: "overlay-shim.dylib")let iconmaker = root.appending(path: "iconmaker")let appinfo = root.appending(path: "appinfo")+ let run = root.appending(path: "run")+ let stamp = try? String(contentsOf: root.appending(path: "build-time"), encoding: .utf8)+ let builtAt = stamp.flatMap { Int64($0.trimmingCharacters(in: .whitespacesAndNewlines)) }var missing: [String] = []if !files.fileExists(atPath: dylib.path(percentEncoded: false)) {@@ -49,6 +54,8 @@ enum InstallPayload {if !files.fileExists(atPath: appinfo.path(percentEncoded: false)) {missing.append("appinfo")}+ if !files.fileExists(atPath: run.path(percentEncoded: false)) { missing.append("run") }+ if (builtAt ?? 0) <= 0 { missing.append("build-time") }let signatureDir = root.appending(path: "signatures/macos.arm64")let signatures = ((try? files.contentsOfDirectory(@@ -57,7 +64,7 @@ enum InstallPayload {if signatures.isEmpty { missing.append("signatures/macos.arm64/*.json") }- guard missing.isEmpty else {+ guard missing.isEmpty, let builtAt, builtAt > 0 else {throw StepFailure(step: step,detail: "These components are missing: \(missing.joined(separator: ", ")). "@@ -67,7 +74,7 @@ enum InstallPayload {return Located(dylib: dylib, overlayShim: shim, iconmaker: iconmaker,- appinfo: appinfo, signatures: signatures+ appinfo: appinfo, run: run, builtAt: builtAt, signatures: signatures)}}diff --git a/app/Sources/NotProtonApp/Model/SteamInstaller.swift b/app/Sources/NotProtonApp/Model/SteamInstaller.swiftindex 0c40b56..c378516 100644--- a/app/Sources/NotProtonApp/Model/SteamInstaller.swift+++ b/app/Sources/NotProtonApp/Model/SteamInstaller.swift@@ -62,6 +62,15 @@ enum SteamInstaller {appinfo: URL = SupportPaths.appinfo,deployedVersion: URL = SupportPaths.deployedVersion,backups: URL = SupportPaths.backups,+ compatTools: URL = SupportPaths.Steam.compatTools,+ recordBuild: Bool = true,+ holdingInstallationLock: Bool = false,+ runnerIsRunning: @Sendable (URL) -> Bool = { RunnerInstaller.isRunning(from: $0) },+ verifyRunner: (RunnerBuild, URL) throws -> Void = RunnerInstaller.verifyClone,+ patchRunner: (RunnerBuild, URL, URL) throws -> Void = { build, root, bridge in+ _ = try NtdllPatcher.stage(build: build, runnerRoot: root, bridge: bridge)+ _ = try RunnerPatcher.install(build: build, root: root, bridge: bridge)+ },stopClient: ClientStopper = stopTheClient,register: BundleRegistrar = { SteamBundle.register($0) },report: @escaping @Sendable (InstallPhase) -> Void = { _ in }@@ -70,35 +79,79 @@ enum SteamInstaller {let payload = try suppliedPayload ?? InstallPayload.locate()let bridgeLocated = try suppliedBridge ?? BridgePayload.locate()- report(.stagingBridge)- let bridgeResult = try BridgePayload.stage(located: bridgeLocated, bridge: bridge)-report(.preflight)let plist = app.appending(path: "Contents/Info.plist")let dylib = app.appending(path: "Contents/MacOS/\(SupportPaths.dylibName)")try assertBundleIsPresent(app)try assertInsertIsDeployedOrAbsent(at: plist, dylib: dylib)+ let installationLock = holdingInstallationLock ? -1 : try DeploymentContent.acquireInstallationLock(for: app)+ defer { if installationLock >= 0 { close(installationLock) } }+ guard let dylibHashes = try MachOBuild.hashesIgnoringSignature(of: payload.dylib) else {+ throw StepFailure(step: step, detail: "The bundled NotProton dylib is invalid.")+ }+ let build = DeploymentContent.Build(version: version, builtAt: payload.builtAt,+ dylibHashes: dylibHashes)+ let record = DeploymentContent.record(beside: deployedVersion)+ let previousBuild = try DeploymentContent.readBuild(at: record)+ let support = deployedVersion.deletingLastPathComponent()+ let runners = support.appending(path: "runners")+ let tools = CompatToolList.installed(runners: runners, file: support.appending(path: "tools"))+ let files = DeploymentContent.files(+ payload: payload, bridgePayload: bridgeLocated, app: app, bridge: bridge,+ signatures: signatures, overlayShim: overlayShim, iconmaker: iconmaker, appinfo: appinfo,+ compatTools: compatTools, tools: tools, runners: runners)+ let content = try DeploymentContent.inspect(files: files, bundled: build, installed: previousBuild,+ legacyVersion: SteamBundle.deployedVersion(at: deployedVersion))+ guard content != .newerInstalled else {+ throw StepFailure(step: step, detail: "A newer NotProton build is installed. Use that build to update or repair the installed files.")+ }+ func refuseRunningRunners() throws {+ for id in RunnerStore.clonedBuilds(in: runners) where runnerIsRunning(SupportPaths.runnerRoot(forBuild: id, runners: runners)) {+ throw StepFailure(step: step, detail: "A game or Wine tool is running on build \(id). Quit it before updating NotProton.")+ }+ }+ try refuseRunningRunners()+ let builds = RunnerStore.installedBuilds(in: runners)+ for build in builds {+ try verifyRunner(build, SupportPaths.clonedRoot(forBuild: build.id, runners: runners))+ }let patching = try needsPatching(plist: plist, dylib: dylib, shipping: payload.dylib, app: app)+ let replacingFiles = try files.contains {+ try !$0.matches() && FileManager.default.fileExists(atPath: $0.destination.path(percentEncoded: false))+ }+ let pinned = try DeploymentContent.pinnedFiles(bridge: bridge, runners: runners)+ let existingAccount = previousBuild != nil || SteamBundle.deployedVersion(at: deployedVersion) != nil+ || pinned.contains { FileManager.default.fileExists(atPath: $0.destination.path(percentEncoded: false)) }+ let replacingPinned = existingAccount && pinned.contains { Digest.sha256IfPresent($0.destination) != $0.hash }var stopped = false- if patching {+ if patching || replacingFiles || replacingPinned {stopped = try stopClient(app) { report(.stoppingClient) }+ }+ try refuseRunningRunners()+ _ = try CompatToolList.sync(runners: runners, bridge: bridge,+ file: support.appending(path: "tools"), compatTools: compatTools)+ report(.stagingBridge)+ let bridgeResult = try BridgePayload.stage(located: bridgeLocated, bridge: bridge)+ for build in builds {+ try patchRunner(build, SupportPaths.clonedRoot(forBuild: build.id, runners: runners), bridge)+ }++ if patching {report(.copyingDylib)try install(payload.dylib, at: dylib)}- try write(version, to: deployedVersion)report(.installingSignatures)- try FileManager.default.createDirectory(at: signatures, withIntermediateDirectories: true)- for database in payload.signatures {- try install(database, at: signatures.appending(path: database.lastPathComponent))- }-report(.installingOverlayShim)- try install(payload.overlayShim, at: overlayShim)- try install(payload.iconmaker, at: iconmaker)- try install(payload.appinfo, at: appinfo)+ for file in files where file.destination != dylib {+ if try file.matches() { continue }+ try install(file.source, at: file.destination)+ if file.executable {+ try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: file.destination.path(percentEncoded: false))+ }+ }var backedUp = falseif patching {@@ -132,6 +185,15 @@ enum SteamInstaller {)}+ let remaining = try files.filter { try !$0.matches() }.map(\.name)+ guard remaining.isEmpty else {+ throw StepFailure(step: step, detail: "These files did not update: \(remaining.joined(separator: ", ")).")+ }+ if recordBuild {+ try write(version, to: deployedVersion)+ try atomicReplace(record, with: JSONEncoder().encode(build), step: step)+ }+report(.finished)return InstallOutcome(stoppedClient: stopped,@@ -168,9 +230,8 @@ enum SteamInstaller {static func needsPatching(plist: URL, dylib: URL, shipping: URL, app: URL) throws -> Bool {let deployed = SteamBundle.currentInsert(at: plist) == dylib.path(percentEncoded: false)- if deployed, let installed = MachOBuild.identity(of: dylib),- let current = MachOBuild.identity(of: shipping), installed == current- {+ let file = DeploymentContent.File(source: shipping, destination: dylib, name: "notproton.dylib", allowsResigning: true)+ if deployed, try file.matches() {AppLog.note("install: Steam already carries this dylib, installing for this account only")return false}@@ -212,13 +273,8 @@ enum SteamInstaller {}static func install(_ source: URL, at destination: URL) throws {- let files = FileManager.defaulttry WriteRefused.catching(destination) {- try files.createDirectory(- at: destination.deletingLastPathComponent(), withIntermediateDirectories: true- )- try? files.removeItem(at: destination)- try files.copyItem(at: source, to: destination)+ try atomicReplace(destination, from: source, step: step)}}diff --git a/app/Sources/NotProtonApp/Support/AppLog.swift b/app/Sources/NotProtonApp/Support/AppLog.swiftindex fe4c4e6..62cea7d 100644--- a/app/Sources/NotProtonApp/Support/AppLog.swift+++ b/app/Sources/NotProtonApp/Support/AppLog.swift@@ -29,6 +29,7 @@ enum AppLog {"state steam=\(describe(snapshot.steam))","state steamRunning=\(snapshot.steamRunning) updatesBlocked=\(snapshot.updateBlocked)","state runner=\(describe(snapshot.runner))",+ "state installContent=\(snapshot.installContent)",]if snapshot.crossOver.isEmpty {diff --git a/app/Sources/NotProtonApp/Support/MachOBuild.swift b/app/Sources/NotProtonApp/Support/MachOBuild.swiftindex b333e6c..bd1cc15 100644--- a/app/Sources/NotProtonApp/Support/MachOBuild.swift+++ b/app/Sources/NotProtonApp/Support/MachOBuild.swift@@ -18,6 +18,88 @@ enum MachOBuild {return found.isEmpty ? nil : found.sorted()}+ static func matchesIgnoringSignature(_ source: URL, _ destination: URL) throws -> Bool {+ guard let id = identity(of: source), id == identity(of: destination) else { return false }+ guard try Shell.run("/usr/bin/codesign", ["--verify", "--strict", destination.path(percentEncoded: false)]).succeeded else { return false }+ guard let expected = try hashesIgnoringSignature(of: source),+ let actual = try hashesIgnoringSignature(of: destination) else { return false }+ return expected == actual+ }++ static func hashesIgnoringSignature(of file: URL) throws -> [String]? {+ guard identity(of: file) != nil else { return nil }+ let files = FileManager.default+ let scratch = files.temporaryDirectory.appending(path: "np-signature-compare-\(UUID().uuidString)")+ try files.createDirectory(at: scratch, withIntermediateDirectories: true)+ defer { try? files.removeItem(at: scratch) }+ let copy = scratch.appending(path: "unsigned")+ try files.copyItem(at: file, to: copy)+ try files.setAttributes([.posixPermissions: 0o600], ofItemAtPath: copy.path(percentEncoded: false))+ guard try Shell.run("/usr/bin/codesign", ["--remove-signature", copy.path(percentEncoded: false)]).succeeded,+ let slices = unsignedSlices(try Data(contentsOf: copy)) else { return nil }+ return slices.map { Digest.sha256(of: $0) }.sorted()+ }++ static func unsignedSlices(_ bytes: Data) -> [Data]? {+ guard let magic = read(bytes, at: 0, bigEndian: false) else { return nil }+ var ranges = [0..<bytes.count]+ if magic.byteSwapped == fat32 || magic.byteSwapped == fat64 {+ let wide = magic.byteSwapped == fat64+ let stride = wide ? 32 : 20+ guard let count = read(bytes, at: 4, bigEndian: true),+ count > 0, Int(count) <= (bytes.count - 8) / stride else { return nil }+ ranges = []+ for index in 0..<Int(count) {+ let entry = 8 + index * stride+ if wide && (read(bytes, at: entry + 8, bigEndian: true) != 0+ || read(bytes, at: entry + 16, bigEndian: true) != 0) { return nil }+ guard let offset = read(bytes, at: entry + (wide ? 12 : 8), bigEndian: true),+ let size = read(bytes, at: entry + (wide ? 20 : 12), bigEndian: true), size > 0,+ Int(offset) >= 8 + Int(count) * stride,+ Int(offset) + Int(size) <= bytes.count else { return nil }+ let range = Int(offset)..<(Int(offset) + Int(size))+ guard !ranges.contains(where: { $0.overlaps(range) }) else { return nil }+ let sliceMagic = read(bytes, at: range.lowerBound, bigEndian: false)+ let flipped = sliceMagic == swapped64 || sliceMagic == swapped32+ guard read(bytes, at: entry, bigEndian: true) == read(bytes, at: range.lowerBound + 4, bigEndian: flipped),+ read(bytes, at: entry + 4, bigEndian: true) == read(bytes, at: range.lowerBound + 8, bigEndian: flipped)+ else { return nil }+ ranges.append(range)+ }+ }+ var result: [Data] = []+ for range in ranges {+ var slice = bytes.subdata(in: range)+ guard let magic = read(slice, at: 0, bigEndian: false),+ [thin64, thin32, swapped64, swapped32].contains(magic),+ let count = read(slice, at: 16, bigEndian: magic == swapped64 || magic == swapped32)+ else { return nil }+ let flipped = magic == swapped64 || magic == swapped32+ var cursor = magic == thin64 || magic == swapped64 ? 32 : 28+ guard let length = read(slice, at: 20, bigEndian: flipped),+ cursor + Int(length) <= slice.count, count <= length / 8 else { return nil }+ let end = cursor + Int(length)+ for _ in 0..<Int(count) {+ guard let command = read(slice, at: cursor, bigEndian: flipped),+ let size = read(slice, at: cursor + 4, bigEndian: flipped),+ size >= 8, cursor + Int(size) <= end else { return nil }+ if command == 0x19 || command == 0x1 {+ guard size >= (command == 0x19 ? 72 : 56) else { return nil }+ let name = String(decoding: slice[(cursor + 8)..<(cursor + 24)].prefix { $0 != 0 }, as: UTF8.self)+ if name == "__LINKEDIT" {+ // Signing can change __LINKEDIT's size, so it is ignored when comparing.+ let start = cursor + (command == 0x19 ? 32 : 28)+ let width = command == 0x19 ? 8 : 4+ slice.replaceSubrange(start..<(start + width), with: repeatElement(UInt8(0), count: width))+ }+ }+ cursor += Int(size)+ }+ result.append(slice)+ }+ return result+ }+private static func collect(_ bytes: Data, at offset: Int, into found: inout Set<String>) {guard let magic = read(bytes, at: offset, bigEndian: false) else { return }let fat = magic.byteSwappeddiff --git a/app/Sources/NotProtonApp/SystemStatus.swift b/app/Sources/NotProtonApp/SystemStatus.swiftindex 4f741df..b4d193f 100644--- a/app/Sources/NotProtonApp/SystemStatus.swift+++ b/app/Sources/NotProtonApp/SystemStatus.swift@@ -24,6 +24,7 @@ struct StatusSnapshot: Sendable {var installedRunners: [RunnerBuild] = []var orphanedRunners: [String] = []var damagedRunners: [String] = []+ var installContent: DeploymentContent.Status = .uncheckedstatic func capture(bundledVersion: String) -> StatusSnapshot {let installs = CrossOverSource.discover()@@ -45,7 +46,8 @@ struct StatusSnapshot: Sendable {payload: PayloadInspector.inspect(builds: installed),installedRunners: installed,orphanedRunners: RunnerStore.orphanedClones(),- damagedRunners: RunnerStore.damagedClones()+ damagedRunners: RunnerStore.damagedClones(),+ installContent: DeploymentContent.current(version: bundledVersion))}}@@ -69,6 +71,7 @@ final class SystemStatus {var isBusy: Bool { activity != nil || runInFlight || checkingLicense }var isIdle: Bool { !isBusy && !isRefreshing }+ var canInstall: Bool { isIdle && snapshot?.installContent.blocksInstallation != true }enum Confirmation: Identifiable, Hashable {case replaceSteam@@ -188,7 +191,7 @@ final class SystemStatus {}func requestInstall() async {- guard isIdle else { return }+ guard canInstall else { return }checkingLicense = truedefer { checkingLicense = false }if let question = Self.activationQuestion(@@ -205,7 +208,7 @@ final class SystemStatus {func requestCompatibilityTool(from chosen: CrossOverInstall? = nil, replacingExisting: Bool = false) async {- guard isIdle else { return }+ guard canInstall else { return }checkingLicense = truedefer { checkingLicense = false }let install = chosen ?? setupSource@@ -236,6 +239,8 @@ final class SystemStatus {guard let build = pendingRemoval else { return }pendingRemoval = nilawait perform(from: RunnerInstaller.removeStep) { _ in+ let lock = try DeploymentContent.acquireInstallationLock(for: SupportPaths.Steam.app)+ defer { close(lock) }let changed = try await Task.detached(priority: .userInitiated) {try RunnerInstaller.removeClone(forBuild: build)}.value@@ -328,6 +333,9 @@ final class SystemStatus {}await perform(from: RunnerSetup.Phase.cloning.label) { progress in+ let lock = try DeploymentContent.acquireInstallationLock(for: SupportPaths.Steam.app)+ defer { close(lock) }+ try await requireInstallableContent()let result = try await Task.detached(priority: .userInitiated) {try RunnerSetup.run(from: install, replacingExisting: replacingExisting) {progress($0.label)@@ -339,7 +347,11 @@ final class SystemStatus {}func fetchValveBinaries() async {+ guard canInstall else { return }await perform(from: ValveFetcher.Phase.verifying.label) { progress in+ let lock = try DeploymentContent.acquireInstallationLock(for: SupportPaths.Steam.app)+ defer { close(lock) }+ try await requireInstallableContent()let result = try await ValveFetcher.run { progress($0.label) }return result.wroteNothing ? nil : "Downloaded missing components."}@@ -350,10 +362,33 @@ final class SystemStatus {private static let toolNotActivated ="The compatibility tool was not set up because CrossOver is not activated."+ private func requireInstallableContent() async throws {+ let version = AppVersion.bundled+ let content = await Task.detached(priority: .utility) {+ DeploymentContent.current(version: version)+ }.value+ snapshot?.installContent = content+ guard !content.blocksInstallation else {+ throw StepFailure(step: SteamInstaller.step,+ detail: "Installation is blocked. Refresh Status and use the NotProton app that installed this build.")+ }+ let running = await Task.detached(priority: .utility) {+ RunnerStore.clonedBuilds().contains {+ RunnerInstaller.isRunning(from: SupportPaths.runnerRoot(forBuild: $0))+ }+ }.value+ guard !running else {+ throw StepFailure(step: SteamInstaller.step, detail: "A game or Wine tool is running. Quit it before updating NotProton.")+ }+ }+func installIntoSteam() async {await perform(from: InstallPhase.checkingPayload.label) { progress in+ let lock = try DeploymentContent.acquireInstallationLock(for: SupportPaths.Steam.app)+ defer { close(lock) }let result = try await Task.detached(priority: .userInitiated) {- try SteamInstaller.run(report: { progress($0.label) })+ try SteamInstaller.run(recordBuild: false, holdingInstallationLock: true,+ report: { progress($0.label) })}.valuevar parts = ["NotProton successfully installed."]@@ -378,11 +413,37 @@ final class SystemStatus {}// Fetch binaries from Valve- if state.payload.missing.contains(where: { $0.origin.isFetchable }) {+ let valve = try ValvePackageManifest.bundled()+ let needsValve = await Task.detached(priority: .utility) {+ valve.files.contains { Digest.sha256IfPresent(SupportPaths.bridge.appending(path: $0.bridgePath)) != $0.sha256 }+ }.value+ if needsValve {progress("Downloading missing components")_ = try await ValveFetcher.run { progress($0.label) }}+ try await Task.detached(priority: .userInitiated) {+ let payload = try InstallPayload.locate()+ for tool in CompatToolList.installed() {+ let destination = SupportPaths.Steam.compatTools.appending(path: "\(tool.name)/run")+ let file = DeploymentContent.File(source: payload.run, destination: destination, name: tool.name, executable: true)+ if try !file.matches() {+ try SteamInstaller.install(payload.run, at: destination)+ try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: destination.path(percentEncoded: false))+ }+ }+ let verified = DeploymentContent.current(version: result.version)+ guard verified == .current else {+ throw StepFailure(step: SteamInstaller.step,+ detail: "Installed content could not be verified. Refresh the Status view for the files that still need attention.")+ }+ let build = DeploymentContent.Build(version: result.version, builtAt: payload.builtAt,+ dylibHashes: try MachOBuild.hashesIgnoringSignature(of: payload.dylib))+ try SteamInstaller.write(result.version, to: SupportPaths.deployedVersion)+ try atomicReplace(DeploymentContent.record(beside: SupportPaths.deployedVersion),+ with: JSONEncoder().encode(build), step: SteamInstaller.step)+ }.value+return parts.joined(separator: " ")}}@@ -402,6 +463,8 @@ final class SystemStatus {func repairSteam() async {await perform(from: RepairPhase.checking.label) { progress in+ let lock = try DeploymentContent.acquireInstallationLock(for: SupportPaths.Steam.app)+ defer { close(lock) }let result = try await SteamRepair.run { progress($0.label) }var parts = ["Steam restored to its original state."]@@ -412,6 +475,8 @@ final class SystemStatus {func removeEverything() async {await perform(from: UninstallPhase.stoppingClient.label) { progress in+ let lock = try DeploymentContent.acquireInstallationLock(for: SupportPaths.Steam.app)+ defer { close(lock) }let result = try await Uninstall.run { progress($0.label) }return result.restoredValveSignature@@ -427,19 +492,11 @@ final class SystemStatus {let version = AppVersion.bundledlet captured = await Task.detached(priority: .userInitiated) {- do {- if try CompatToolList.sync() { AppLog.note("tool list rewritten") }- } catch {- AppLog.note("tool list not written: \(error.localizedDescription)")- }- for failure in NtdllPatcher.stageInstalled() {- AppLog.note("ntdll for \(failure.build) not staged: \(failure.error.localizedDescription)")- }- return StatusSnapshot.capture(bundledVersion: version)+ StatusSnapshot.capture(bundledVersion: version)}.valuesnapshot = capturedAppLog.note(captured)- await refreshRunnerStorage()+ await refreshRunnerStorage(cleanTemplates: !captured.installContent.blocksInstallation)}private(set) var runnerSizes: [String: Int64] = [:]@@ -447,11 +504,13 @@ final class SystemStatus {private(set) var templateCleanupFailure: String?func refreshRunnerStorage(- runners: URL = SupportPaths.runners, libraries: [SteamLibrary] = PrefixStore.libraries()+ runners: URL = SupportPaths.runners, libraries: [SteamLibrary] = PrefixStore.libraries(),+ cleanTemplates: Bool = true) async {let known = runnerSizeslet measured = await Task.detached(priority: .utility) {- let failures = RunnerInstaller.removeStalePrefixTemplates(runners: runners, libraries: libraries)+ let failures = cleanTemplates+ ? RunnerInstaller.removeStalePrefixTemplates(runners: runners, libraries: libraries) : []var sizes: [String: Int64] = [:]var templates: [String: [CompatTool.Flavor: Int64]] = [:]for build in RunnerStore.clonedBuilds(in: runners) {diff --git a/app/Sources/NotProtonApp/Views/StatusView.swift b/app/Sources/NotProtonApp/Views/StatusView.swiftindex 94af9d9..8d7ba68 100644--- a/app/Sources/NotProtonApp/Views/StatusView.swift+++ b/app/Sources/NotProtonApp/Views/StatusView.swift@@ -377,18 +377,72 @@ struct StatusView: View {.disabled(!status.isIdle)}- private func installAction(prominent: Bool) -> StatusAction {+ private func installAction(prominent: Bool, label: String = "Install") -> StatusAction {StatusAction(- label: "Install",+ label: label,isProminent: prominent,help: "Install NotProton into Steam.",- isEnabled: status.isIdle+ isEnabled: status.canInstall) {Task { await status.requestInstall() }}}+ @ViewBuilderprivate func steamRow(_ deployment: SteamDeployment, payload: PayloadState) -> some View {+ switch deployment {+ case .notInstalled:+ if let content = status.snapshot?.installContent, content.blocksInstallation {+ installedContentRow(content, deployment: deployment, payload: payload)+ } else {+ deploymentRow(deployment, payload: payload)+ }+ case .installed, .outdated:+ if let content = status.snapshot?.installContent, content != .unchecked {+ installedContentRow(content, deployment: deployment, payload: payload)+ } else {+ deploymentRow(deployment, payload: payload)+ }+ default:+ deploymentRow(deployment, payload: payload)+ }+ }++ @ViewBuilder+ private func installedContentRow(_ content: DeploymentContent.Status, deployment: SteamDeployment, payload: PayloadState) -> some View {+ switch content {+ case .unchecked, .current:+ let version: String? = switch deployment {+ case .installed(let version): version+ case .outdated(let deployed, _): deployed+ default: nil+ }+ deploymentRow(.installed(version: version), payload: payload)+ case .newerInstalled:+ StatusRow(title: "NotProton", value: "A newer build is installed.", tone: .neutral,+ detail: "Use the newer NotProton app to update or repair the installed files.")+ case .unavailable(let reason):+ StatusRow(title: "NotProton", value: "Could not check installed files.", tone: .warning, detail: reason)+ case .update(let files):+ StatusRow(title: "NotProton", value: "Update available.", tone: .warning,+ detail: "This app includes newer files than those installed for Steam.",+ action: installAction(prominent: true, label: "Update"))+ .help(files.joined(separator: "\n"))+ case .repair(let files):+ StatusRow(title: "NotProton", value: "Installed files differ from this build.", tone: .warning,+ detail: "Restore the files included with this app.",+ action: installAction(prominent: true, label: "Repair"))+ .help(files.joined(separator: "\n"))+ case .unrecorded(let files):+ StatusRow(title: "NotProton", value: "Update available.", tone: .warning,+ detail: "This app includes updated files for Steam.",+ action: installAction(prominent: true, label: "Update"))+ .help(files.joined(separator: "\n"))+ }+ }++ @ViewBuilder+ private func deploymentRow(_ deployment: SteamDeployment, payload: PayloadState) -> some View {switch deployment {case .steamMissing:StatusRow(title: "NotProton", value: "Steam not found.", tone: .bad)@@ -544,14 +598,14 @@ struct StatusView: View {label: "Set Up",isProminent: prominent,help: "Copy \(row.title) and set up its compatibility tool.",- isEnabled: status.isIdle+ isEnabled: status.canInstall) { Task { await status.requestCompatibilityTool(from: install) } }case .unpatched where row.canSetUp, .damaged where row.canSetUp:return StatusAction(label: "Repair",isProminent: true,help: "Copy \(row.title) again.",- isEnabled: status.isIdle+ isEnabled: status.canInstall) { Task { await status.requestCompatibilityTool(from: install) } }case .unsupported:return removeCopyAction(row.buildID, label: "Remove\u{2026}")@@ -567,7 +621,7 @@ struct StatusView: View {items.append(StatusAction(label: "Reinstall",help: "Copy \(row.title) again.",- isEnabled: status.isIdle && row.canSetUp+ isEnabled: status.canInstall && row.canSetUp) { Task { await status.requestCompatibilityTool(from: install, replacingExisting: true) } })}let shown = install?.bundle@@ -629,7 +683,7 @@ struct StatusView: View {label: "Fetch Valve Binaries",isProminent: true,help: "Download missing Valve binaries.",- isEnabled: status.isIdle+ isEnabled: status.canInstall) { Task { await status.fetchValveBinaries() } }}diff --git a/app/Tests/NotProtonAppTests/DeploymentContentTests.swift b/app/Tests/NotProtonAppTests/DeploymentContentTests.swiftnew file mode 100644index 0000000..41df001--- /dev/null+++ b/app/Tests/NotProtonAppTests/DeploymentContentTests.swift@@ -0,0 +1,239 @@+import Foundation+import Testing++@testable import NotProtonApp++@Suite("Installed content")+struct DeploymentContentTests {+ private let build = DeploymentContent.Build(version: "1.0.1", builtAt: 200)++ private func files(in root: URL) throws -> [DeploymentContent.File] {+ let source = root.appending(path: "source")+ let destination = root.appending(path: "installed")+ try Data("new!".utf8).write(to: source)+ try Data("old!".utf8).write(to: destination)+ return [.init(source: source, destination: destination, name: "run")]+ }++ @Test("Same-version builds with different contents offer an update by build time")+ func newerBuild() throws {+ let root = try scratchDirectory("content")+ defer { try? FileManager.default.removeItem(at: root) }+ let files = try files(in: root)+ try FileManager.default.setAttributes([.modificationDate: Date.distantFuture], ofItemAtPath: files[0].destination.path)+ #expect(try DeploymentContent.inspect(files: files, bundled: build,+ installed: .init(version: "1.0.1", builtAt: 100)) == .update(["run"]))+ }++ @Test("Matching bytes do not offer an update just because the app was rebuilt")+ func identicalContents() throws {+ let root = try scratchDirectory("content")+ defer { try? FileManager.default.removeItem(at: root) }+ let files = try files(in: root)+ try Data("new!".utf8).write(to: files[0].destination)+ #expect(try DeploymentContent.inspect(files: files, bundled: build,+ installed: .init(version: "1.0.1", builtAt: 100)) == .current)+ }++ @Test("An older app cannot offer its files over a newer installation")+ func newerInstallation() throws {+ #expect(try DeploymentContent.inspect(files: [], bundled: build,+ installed: .init(version: "1.0.1", builtAt: 300)) == .newerInstalled)+ #expect(try DeploymentContent.inspect(files: [], bundled: build,+ installed: .init(version: "1.0.2", builtAt: 100)) == .newerInstalled)+ #expect(try DeploymentContent.inspect(files: [], bundled: build, installed: nil,+ legacyVersion: "1.0.10") == .newerInstalled)+ }++ @Test("A changed or missing file from the recorded build offers repair")+ func damagedInstallation() throws {+ let root = try scratchDirectory("content")+ defer { try? FileManager.default.removeItem(at: root) }+ let files = try files(in: root)+ #expect(try DeploymentContent.inspect(files: files, bundled: build, installed: build) == .repair(["run"]))+ try FileManager.default.removeItem(at: files[0].destination)+ #expect(try DeploymentContent.inspect(files: files, bundled: build, installed: build) == .repair(["run"]))+ }++ @Test("Legacy installations report differences without guessing build order")+ func unrecordedBuild() throws {+ let root = try scratchDirectory("content")+ defer { try? FileManager.default.removeItem(at: root) }+ #expect(try DeploymentContent.inspect(files: files(in: root), bundled: build,+ installed: nil, legacyVersion: "1.0.1") == .unrecorded(["run"]))+ #expect(try DeploymentContent.inspect(files: files(in: root), bundled: build,+ installed: nil, legacyVersion: "1.0.0") == .update(["run"]))+ }++ @Test("A missing bundled file is an error rather than an update to install")+ func missingSource() throws {+ let root = try scratchDirectory("content")+ defer { try? FileManager.default.removeItem(at: root) }+ let files = try files(in: root)+ try FileManager.default.removeItem(at: files[0].source)+ #expect(throws: (any Error).self) { try DeploymentContent.inspect(files: files, bundled: build, installed: build) }+ }++ @Test("A matching script without execute permission still needs repair")+ func executablePermission() throws {+ let root = try scratchDirectory("content")+ defer { try? FileManager.default.removeItem(at: root) }+ var files = try files(in: root)+ files[0].executable = true+ try Data("new!".utf8).write(to: files[0].destination)+ try FileManager.default.setAttributes([.posixPermissions: 0o644], ofItemAtPath: files[0].destination.path)+ #expect(try DeploymentContent.inspect(files: files, bundled: build, installed: build) == .repair(["run"]))+ }++ @Test("A symlink is not mistaken for a matching installed file")+ func linkedDestination() throws {+ let root = try scratchDirectory("content")+ defer { try? FileManager.default.removeItem(at: root) }+ let files = try files(in: root)+ try FileManager.default.removeItem(at: files[0].destination)+ try FileManager.default.createSymbolicLink(at: files[0].destination, withDestinationURL: files[0].source)+ #expect(try !files[0].matches())+ }++ @Test("Corrupt build records do not silently become legacy installations")+ func invalidRecord() throws {+ let root = try scratchDirectory("content")+ defer { try? FileManager.default.removeItem(at: root) }+ let record = root.appending(path: "record")+ #expect(try DeploymentContent.readBuild(at: record) == nil)+ try Data("bad".utf8).write(to: record)+ #expect(throws: (any Error).self) { try DeploymentContent.readBuild(at: record) }+ }++ @Test("Re-signing is ignored but re-signed content changes with the same UUID are detected", arguments: [false, true])+ func signingDoesNotHideCodeChanges(largeSignature: Bool) throws {+ let root = try scratchDirectory("content-signing")+ defer { try? FileManager.default.removeItem(at: root) }+ let source = root.appending(path: "source.c")+ let library = root.appending(path: "source.dylib")+ let installed = root.appending(path: "installed.dylib")+ try Data("const char np_marker[] = \"np-before\";\n".utf8).write(to: source)+ try Shell.check("/usr/bin/clang", ["-dynamiclib", "-arch", "arm64", "-arch", "x86_64", "-o", library.path, source.path])+ try FileManager.default.copyItem(at: library, to: installed)+ let identifier = largeSignature ? String(repeating: "x", count: 20_000) : "installed-copy"+ try Shell.check("/usr/bin/codesign", ["-f", "-s", "-", "--identifier", identifier, installed.path])+ let file = DeploymentContent.File(source: library, destination: installed, name: "notproton.dylib", allowsResigning: true)+ #expect(Digest.sha256IfPresent(library) != Digest.sha256IfPresent(installed))+ #expect(try file.matches())++ var bytes = try Data(contentsOf: installed)+ let marker = try #require(bytes.range(of: Data("np-before".utf8)))+ bytes.replaceSubrange(marker, with: Data("np-after!".utf8))+ try bytes.write(to: installed)+ let recorded = DeploymentContent.Build(version: build.version, builtAt: build.builtAt,+ dylibHashes: try MachOBuild.hashesIgnoringSignature(of: library))+ #expect(try DeploymentContent.inspect(files: [file], bundled: build, installed: recorded) == .repair(["notproton.dylib"]))+ try Shell.check("/usr/bin/codesign", ["-f", "-s", "-", installed.path])+ #expect(MachOBuild.identity(of: library) == MachOBuild.identity(of: installed))+ #expect(try !file.matches())+ let staleRecord = DeploymentContent.Build(version: "1.0.1", builtAt: 100,+ dylibHashes: try MachOBuild.hashesIgnoringSignature(of: library))+ #expect(throws: StepFailure.self) {+ try DeploymentContent.inspect(files: [file], bundled: build, installed: staleRecord)+ }+ }++ @MainActor+ @Test("Build-record blockers also disable Install when the dylib is missing")+ func unavailableInstallAction() {+ let status = SystemStatus()+ let payload = PayloadState(expected: 0, present: 0, missing: [], overlayShimPresent: true,+ iconmakerPresent: true, appinfoPresent: true, signatureDatabase: "fixture",+ legacyCompatPresent: 0, legacyCompatExpected: 0, manifestProblem: nil)+ status.snapshot = StatusSnapshot(steam: .notInstalled, steamRunning: false, updateBlocked: false,+ crossOver: [], runner: .none, payload: payload,+ installContent: .newerInstalled)+ #expect(!status.canInstall)+ status.snapshot?.installContent = .unavailable("invalid record")+ #expect(!status.canInstall)+ status.snapshot?.installContent = .unrecorded(["notproton.dylib"])+ #expect(status.canInstall)+ }++ @Test("Installation locking excludes another caller and releases without a lock file")+ func installationLock() throws {+ let root = try scratchDirectory("content-lock")+ defer { try? FileManager.default.removeItem(at: root) }+ let app = root.appending(path: "Steam.app")+ do {+ let fd = try DeploymentContent.acquireInstallationLock(for: app)+ defer { close(fd) }+ #expect(throws: StepFailure.self) { try DeploymentContent.acquireInstallationLock(for: app) }+ let status = try Shell.run("/bin/sh", ["-c", #"exec 9< "$1"; /usr/bin/lockf -s -t 0 9"#, "fixture", root.path]).status+ #expect(status == 75)+ }+ let next = try DeploymentContent.acquireInstallationLock(for: app)+ close(next)+ #expect(try FileManager.default.contentsOfDirectory(atPath: root.path).isEmpty)+ }++ @Test("Missing and changed tool lists are included in the expected installed content")+ func includesToolList() throws {+ let root = try scratchDirectory("content-tools")+ defer { try? FileManager.default.removeItem(at: root) }+ let runners = root.appending(path: "runners")+ let runner = SupportPaths.clonedRoot(forBuild: "26.3.0.39832", runners: runners)+ try FileManager.default.createDirectory(at: runner.appending(path: "lib/wine"), withIntermediateDirectories: true)+ let list = root.appending(path: "tools")+ for text in [nil, "", "incorrect"] as [String?] {+ if let text { try Data(text.utf8).write(to: list) }+ let pins = try DeploymentContent.pinnedFiles(bridge: root.appending(path: "bridge"), runners: runners)+ let pin = try #require(pins.first { $0.name == "tools" })+ #expect(Digest.sha256IfPresent(pin.destination) != pin.hash)+ }+ try Data(CompatToolList.contents(CompatToolList.installed(runners: runners, file: list)).utf8).write(to: list)+ let pins = try DeploymentContent.pinnedFiles(bridge: root.appending(path: "bridge"), runners: runners)+ let pin = try #require(pins.first { $0.name == "tools" })+ #expect(Digest.sha256IfPresent(pin.destination) == pin.hash)+ }++ @Test("The staged ntdll and runner ntdll are checked independently")+ func includesStagedNtdll() throws {+ let root = try scratchDirectory("content-ntdll")+ defer { try? FileManager.default.removeItem(at: root) }+ let runners = root.appending(path: "runners")+ let build = SupportedRunners.all[0]+ let runner = SupportPaths.clonedRoot(forBuild: build.id, runners: runners)+ try FileManager.default.createDirectory(at: runner.appending(path: "lib/wine"), withIntermediateDirectories: true)+ let bridge = root.appending(path: "bridge")+ let pins = try DeploymentContent.pinnedFiles(bridge: bridge, runners: runners)+ for (arch, hash) in build.patchedNtdll {+ let staged = NtdllPatcher.stagedCopy(of: arch, build: build.id, in: bridge)+ let pin = try #require(pins.first { $0.destination == staged })+ #expect(pin.hash == hash)+ #expect(pins.contains { $0.destination == runner.appending(path: "lib/wine/\(arch.rawValue)/ntdll.dll") })+ try FileManager.default.createDirectory(at: staged.deletingLastPathComponent(), withIntermediateDirectories: true)+ try Data("wrong staged copy".utf8).write(to: staged)+ #expect(Digest.sha256IfPresent(pin.destination) != pin.hash)+ }+ }++ @Test("Signature comparison refuses truncated headers, overlapping slices and invalid command sizes")+ func malformedMachOLayouts() {+ #expect(MachOBuild.unsignedSlices(Data()) == nil)+ #expect(MachOBuild.unsignedSlices(Data([0xcf, 0xfa, 0xed, 0xfe])) == nil)+ var thin = Data(repeating: 0, count: 40)+ thin.replaceSubrange(0..<4, with: [0xcf, 0xfa, 0xed, 0xfe])+ thin[16] = 1+ thin[20] = 8+ thin[32] = 0x19+ #expect(MachOBuild.unsignedSlices(thin) == nil)+ thin[36] = 0xff+ #expect(MachOBuild.unsignedSlices(thin) == nil)+ thin.replaceSubrange(16..<20, with: [0xff, 0xff, 0xff, 0xff])+ #expect(MachOBuild.unsignedSlices(thin) == nil)+ var fat = Data(repeating: 0, count: 80)+ fat.replaceSubrange(0..<8, with: [0xca, 0xfe, 0xba, 0xbe, 0, 0, 0, 2])+ fat[19] = 48+ fat[23] = 32+ fat[39] = 48+ fat[43] = 32+ fat.replaceSubrange(48..<52, with: [0xcf, 0xfa, 0xed, 0xfe])+ #expect(MachOBuild.unsignedSlices(fat) == nil)+ }+}diff --git a/app/Tests/NotProtonAppTests/InstallPayloadTests.swift b/app/Tests/NotProtonAppTests/InstallPayloadTests.swiftindex d069d84..5f9411f 100644--- a/app/Tests/NotProtonAppTests/InstallPayloadTests.swift+++ b/app/Tests/NotProtonAppTests/InstallPayloadTests.swift@@ -14,6 +14,8 @@ struct InstallPayloadTests {if shim { try Data("shim".utf8).write(to: root.appending(path: "overlay-shim.dylib")) }if iconmaker { try Data("iconmaker".utf8).write(to: root.appending(path: "iconmaker")) }if appinfo { try Data("appinfo".utf8).write(to: root.appending(path: "appinfo")) }+ try Data("#!/bin/sh\nexit 0\n".utf8).write(to: root.appending(path: "run"))+ try Data("100\n".utf8).write(to: root.appending(path: "build-time"))for name in signatures {try Data("{}".utf8).write(to: signatureDir.appending(path: name))}@@ -98,4 +100,16 @@ struct InstallPayloadTests {#expect(failure.detail.contains("signatures/macos.arm64"))}}++ @Test("A missing script or invalid build timestamp cannot be installed")+ func refusesIncompleteBuildMetadata() throws {+ let root = try scratchDirectory("payload-build")+ defer { try? FileManager.default.removeItem(at: root) }+ try stage(root)+ try Data("not a timestamp".utf8).write(to: root.appending(path: "build-time"))+ #expect(throws: StepFailure.self) { try InstallPayload.locate(root: root) }+ try Data("100".utf8).write(to: root.appending(path: "build-time"))+ try FileManager.default.removeItem(at: root.appending(path: "run"))+ #expect(throws: StepFailure.self) { try InstallPayload.locate(root: root) }+ }}diff --git a/app/Tests/NotProtonAppTests/SteamInstallerTests.swift b/app/Tests/NotProtonAppTests/SteamInstallerTests.swiftindex c89e421..ffe3d59 100644--- a/app/Tests/NotProtonAppTests/SteamInstallerTests.swift+++ b/app/Tests/NotProtonAppTests/SteamInstallerTests.swift@@ -42,6 +42,8 @@ struct SteamInstallerTests {let appinfo = root.appending(path: "appinfo")try FileManager.default.copyItem(at: dylib, to: appinfo)+ try Data("#!/bin/sh\nexit 0\n".utf8).write(to: root.appending(path: "run"))+ try Data("100\n".utf8).write(to: root.appending(path: "build-time"))try Data("{}".utf8).write(to: signatureDir.appending(path: "1788400362.json"))try Data("{}".utf8).write(to: signatureDir.appending(path: "1788652215.json"))@@ -87,7 +89,10 @@ struct SteamInstallerTests {_ fixture: Fixture,version: String = "9.9.9-test",calls: Calls = Calls(),- stopped: Bool = false+ stopped: Bool = false,+ running: Bool = false,+ recordBuild: Bool = true,+ verifyRunner: (RunnerBuild, URL) throws -> Void = { _, _ in }) throws -> InstallOutcome {try SteamInstaller.run(payload: fixture.payload,@@ -100,6 +105,11 @@ struct SteamInstallerTests {appinfo: fixture.appinfo,deployedVersion: fixture.deployedVersion,backups: fixture.backups,+ compatTools: fixture.work.appending(path: "compatibilitytools.d"),+ recordBuild: recordBuild,+ runnerIsRunning: { _ in running },+ verifyRunner: verifyRunner,+ patchRunner: { _, _, _ in },stopClient: { _, onStopping in if stopped { onStopping() }; return stopped },register: { calls.register($0) })@@ -249,6 +259,8 @@ struct SteamInstallerTests {"the plist kept the insert, so the executable no longer matches its signature")#expect(SteamBundle.currentInsert(at: fixture.plist) == nil)+ #expect(!FileManager.default.fileExists(atPath: DeploymentContent.record(beside: fixture.deployedVersion).path))+ #expect(!FileManager.default.fileExists(atPath: fixture.deployedVersion.path))}@Test("The plist backup records the state before the first install only")@@ -428,4 +440,147 @@ struct SteamInstallerTests {#expect(throws: StepFailure.self) { try InstallPayload.locate(root: empty) }#expect(SteamBundle.currentInsert(at: fixture.plist) == nil)}++ @Test("The installer records the package build time rather than the installation time")+ func recordsPackageBuild() async throws {+ let work = try scratchDirectory("install-record")+ defer { try? FileManager.default.removeItem(at: work) }+ let fixture = try await self.fixture(into: work)+ _ = try install(fixture)+ let build = try #require(try DeploymentContent.readBuild(at: DeploymentContent.record(beside: fixture.deployedVersion)))+ #expect(build.builtAt == 100)+ #expect(build.version == "9.9.9-test")+ #expect(build.dylibHashes == (try MachOBuild.hashesIgnoringSignature(of: fixture.payload.dylib)))+ }++ @Test("An older package is refused before any installed files change")+ func refusesDowngrade() async throws {+ let work = try scratchDirectory("install-newer")+ defer { try? FileManager.default.removeItem(at: work) }+ let fixture = try await self.fixture(into: work)+ _ = try install(fixture)+ let record = DeploymentContent.record(beside: fixture.deployedVersion)+ let newer = DeploymentContent.Build(version: "9.9.9-test", builtAt: 300)+ try JSONEncoder().encode(newer).write(to: record)+ let before = try Data(contentsOf: fixture.deployedDylib)+ let calls = Calls()++ let error = try #require(throws: StepFailure.self) { try install(fixture, calls: calls, stopped: true) }++ #expect(error.detail.contains("newer NotProton"))+ #expect(try Data(contentsOf: fixture.deployedDylib) == before)+ #expect(try DeploymentContent.readBuild(at: record) == newer)+ #expect(calls.registrations.isEmpty)+ }++ @Test("Changed helpers are updated without replacing the matching dylib")+ func updatesHelperOnly() async throws {+ let work = try scratchDirectory("install-helper")+ defer { try? FileManager.default.removeItem(at: work) }+ let fixture = try await self.fixture(into: work)+ _ = try install(fixture)+ let before = try Data(contentsOf: fixture.deployedDylib)+ let helper = try Data(contentsOf: fixture.payload.appinfo)+ try Data(repeating: 7, count: helper.count).write(to: fixture.appinfo)++ let result = try install(fixture, stopped: true)++ #expect(result.stoppedClient)+ #expect(!result.backedUpPlist)+ #expect(try Data(contentsOf: fixture.appinfo) == helper)+ #expect(try Data(contentsOf: fixture.deployedDylib) == before)+ }++ @Test("Repairing missing pinned components stops Steam even when bundled files already match")+ func pinnedRepairStopsSteam() async throws {+ let work = try scratchDirectory("install-pinned")+ defer { try? FileManager.default.removeItem(at: work) }+ let fixture = try await self.fixture(into: work)+ _ = try install(fixture)+ #expect(try install(fixture, stopped: true).stoppedClient)+ }++ @Test("Install updates every deployed tool's script and runner bridge copy")+ func updatesScriptsAndRunnerCopies() async throws {+ let work = try scratchDirectory("install-scripts")+ defer { try? FileManager.default.removeItem(at: work) }+ let fixture = try await self.fixture(into: work)+ let runners = fixture.support.appending(path: "runners")+ let build = SupportedRunners.all[0]+ let runner = SupportPaths.clonedRoot(forBuild: build.id, runners: runners)+ try FileManager.default.createDirectory(at: runner.appending(path: "lib/wine"), withIntermediateDirectories: true)++ _ = try install(fixture)++ let tools = CompatToolList.installed(runners: runners, file: fixture.support.appending(path: "tools"))+ try #require(!tools.isEmpty)+ for tool in tools {+ let script = work.appending(path: "compatibilitytools.d/\(tool.name)/run")+ #expect(try Data(contentsOf: script) == Data(contentsOf: fixture.payload.run))+ #expect(FileManager.default.isExecutableFile(atPath: script.path))+ }+ let bridge = try BridgePayload.locate()+ let files = DeploymentContent.files(payload: fixture.payload, bridgePayload: bridge, app: fixture.app,+ bridge: fixture.bridge, signatures: fixture.signatures,+ overlayShim: fixture.overlayShim, iconmaker: fixture.iconmaker,+ appinfo: fixture.appinfo, compatTools: work.appending(path: "compatibilitytools.d"),+ tools: tools, runners: runners)+ #expect(try files.allSatisfy { try $0.matches() })+ }++ @Test("A running game prevents file replacement before Steam is stopped")+ func refusesRunningRunner() async throws {+ let work = try scratchDirectory("install-running")+ defer { try? FileManager.default.removeItem(at: work) }+ let fixture = try await self.fixture(into: work)+ let runner = SupportPaths.clonedRoot(forBuild: SupportedRunners.all[0].id,+ runners: fixture.support.appending(path: "runners"))+ try FileManager.default.createDirectory(at: runner.appending(path: "lib/wine"), withIntermediateDirectories: true)++ let error = try #require(throws: StepFailure.self) { try install(fixture, running: true) }++ #expect(error.detail.contains("is running"))+ #expect(!FileManager.default.fileExists(atPath: fixture.bridge.path))+ #expect(!FileManager.default.fileExists(atPath: fixture.deployedDylib.path))+ }++ @Test("Wine running from an unsupported clone also blocks installation")+ func refusesRunningOrphan() async throws {+ let work = try scratchDirectory("install-orphan")+ defer { try? FileManager.default.removeItem(at: work) }+ let fixture = try await self.fixture(into: work)+ let runner = SupportPaths.clonedRoot(forBuild: "99.0.0.12345", runners: fixture.support.appending(path: "runners"))+ try FileManager.default.createDirectory(at: runner.appending(path: "lib/wine"), withIntermediateDirectories: true)+ let error = try #require(throws: StepFailure.self) { try install(fixture, running: true) }+ #expect(error.detail.contains("99.0.0.12345"))+ #expect(!FileManager.default.fileExists(atPath: fixture.deployedDylib.path))+ }++ @Test("A recognized runner folder with invalid binaries is refused before deployment")+ func validatesExistingRunner() async throws {+ let work = try scratchDirectory("install-runner-validation")+ defer { try? FileManager.default.removeItem(at: work) }+ let fixture = try await self.fixture(into: work)+ let runners = fixture.support.appending(path: "runners")+ let build = SupportedRunners.all[0]+ let runner = SupportPaths.clonedRoot(forBuild: build.id, runners: runners)+ try FileManager.default.createDirectory(at: runner.appending(path: "lib/wine/x86_64-unix"), withIntermediateDirectories: true)+ try Data("wrong loader".utf8).write(to: runner.appending(path: "lib/wine/x86_64-unix/wine"))+ let error = try #require(throws: StepFailure.self) {+ try install(fixture, verifyRunner: RunnerInstaller.verifyClone)+ }+ #expect(error.detail.contains("does not match"))+ #expect(!FileManager.default.fileExists(atPath: fixture.bridge.path))+ #expect(!FileManager.default.fileExists(atPath: fixture.deployedDylib.path))+ }++ @Test("An install can defer its build record until remaining setup steps finish")+ func defersRecord() async throws {+ let work = try scratchDirectory("install-deferred")+ defer { try? FileManager.default.removeItem(at: work) }+ let fixture = try await self.fixture(into: work)+ _ = try install(fixture, recordBuild: false)+ #expect(!FileManager.default.fileExists(atPath: DeploymentContent.record(beside: fixture.deployedVersion).path))+ #expect(!FileManager.default.fileExists(atPath: fixture.deployedVersion.path))+ }}diff --git a/app/Tests/NotProtonAppTests/TemplateCleanupTests.swift b/app/Tests/NotProtonAppTests/TemplateCleanupTests.swiftindex 74cbfd0..1d674cf 100644--- a/app/Tests/NotProtonAppTests/TemplateCleanupTests.swift+++ b/app/Tests/NotProtonAppTests/TemplateCleanupTests.swift@@ -261,6 +261,17 @@ struct TemplateCleanupTests {#expect(!FileManager.default.fileExists(atPath: library.root.path))}+ @MainActor+ @Test("A blocked installation can measure storage without cleaning another build's templates")+ func skipsMaintenanceForNewerBuild() async throws {+ let layout = try Layout()+ defer { try? FileManager.default.removeItem(at: layout.root) }+ let status = SystemStatus()+ await status.refreshRunnerStorage(runners: layout.runners, libraries: [layout.library], cleanTemplates: false)+ #expect(FileManager.default.fileExists(atPath: layout.template.path))+ #expect(!FileManager.default.fileExists(atPath: layout.lock.path))+ }+@Test("A read-only library without a cache needs no cleanup lock")func skipsMissingCacheOnReadOnlyLibrary() throws {let layout = try Layout()