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
Seed new prefixes from a per-runner template instead of a full wineboot
NotProtonNot696b409d6c26
diff --git a/.github/workflows/app.yml b/.github/workflows/app.ymlindex 9eb5d2e..06408e1 100644--- a/.github/workflows/app.yml+++ b/.github/workflows/app.yml@@ -107,6 +107,7 @@ jobs:make -s settingscheckmake -s routecheckmake -s bridgecheck+ make -s seedcheck- name: Run the Swift testsrun: make -s app-testsdiff --git a/Makefile b/Makefileindex fed71fb..046312a 100644--- a/Makefile+++ b/Makefile@@ -90,6 +90,11 @@ runcheck:shellcheck dylib/feats/compat_run.sh && sh -n dylib/feats/compat_run.sh && \echo "==> runcheck: the run script lints and parses clean"+.PHONY: seedcheck+seedcheck:+ @if [ ! -f dylib/tests/seedcheck.sh ]; then $(call SKIP,seedcheck,dylib/tests/seedcheck.sh); exit 0; fi; \+ sh dylib/tests/seedcheck.sh dylib/feats/compat_run.sh+envcheck:@if [ ! -f dylib/tests/envcheck.sh ]; then $(call SKIP,envcheck,dylib/tests/envcheck.sh); exit 0; fi; \sh dylib/tests/envcheck.sh dylib/feats/compat_run.shdiff --git a/app/Sources/NotProtonApp/Model/PrefixStore.swift b/app/Sources/NotProtonApp/Model/PrefixStore.swiftindex 06d9e52..a8db072 100644--- a/app/Sources/NotProtonApp/Model/PrefixStore.swift+++ b/app/Sources/NotProtonApp/Model/PrefixStore.swift@@ -212,11 +212,58 @@ enum PrefixStore {return PrefixUsage(bytes: bytes, profileFiles: files)}- static func directoryBytes(_ url: URL) -> Int64 {- guard let out = try? Shell.check("/usr/bin/du", ["-sk", url.path(percentEncoded: false)]),- let kb = Int64(out.split(separator: "\t").first?.trimmingCharacters(in: .whitespaces) ?? "")- else { return 0 }- return kb * 1024+ enum SizeMetric {+ case privateSize, allocated+ }++ static let privateSizeHelp: LocalizedStringResource = "Private size excludes shared APFS extents. Other filesystems use allocated size when private size is unavailable. This is not guaranteed space reclaimed by deletion."++ static func directoryBytes(_ url: URL, metric: SizeMetric = .privateSize) -> Int64 {+ struct FileID: Hashable {+ let device: dev_t+ let inode: ino_t+ }+ var seen: Set<FileID> = []+ var total: Int64 = 0+ var root = url.path(percentEncoded: false)+ while root.count > 1, root.hasSuffix("/") { root.removeLast() }+ var paths = [root]+ while let path = paths.popLast() {+ var info = stat()+ guard lstat(path, &info) == 0,+ seen.insert(FileID(device: info.st_dev, inode: info.st_ino)).inserted+ else { continue }+ total += metric == .allocated ? Int64(info.st_blocks) * 512 : privateBytes(path)+ guard info.st_mode & S_IFMT == S_IFDIR,+ let children = try? FileManager.default.contentsOfDirectory(atPath: path)+ else { continue }+ paths += children.map { path + "/" + $0 }+ }+ return total+ }++ // st_blocks * 512 is the fallback when ATTR_CMNEXT_PRIVATESIZE is unavailable.+ static func privateBytes(_ path: String) -> Int64 {+ var info = stat()+ guard lstat(path, &info) == 0 else { return 0 }+ let allocated = Int64(info.st_blocks) * 512++ var request = attrlist()+ request.bitmapcount = u_short(ATTR_BIT_MAP_COUNT)+ request.commonattr = attrgroup_t(ATTR_CMN_RETURNED_ATTRS)+ request.forkattr = attrgroup_t(ATTR_CMNEXT_PRIVATESIZE)++ // getattrlist fills in a header, then the private size.+ var buffer = [UInt8](repeating: 0, count: 4 + MemoryLayout<attribute_set_t>.size + 8)+ let options = UInt32(FSOPT_NOFOLLOW) | UInt32(FSOPT_ATTR_CMN_EXTENDED)+ guard getattrlist(path, &request, &buffer, buffer.count, options) == 0 else { return allocated }++ return buffer.withUnsafeBytes { raw in+ let returned = raw.loadUnaligned(fromByteOffset: 4, as: attribute_set_t.self)+ guard returned.forkattr & attrgroup_t(ATTR_CMNEXT_PRIVATESIZE) != 0 else { return allocated }+ return raw.loadUnaligned(+ fromByteOffset: 4 + MemoryLayout<attribute_set_t>.size, as: Int64.self)+ }}@@ -261,6 +308,17 @@ enum PrefixStore {_ prefix: WinePrefix, root: URL = serverRoot, lsof: String = "/usr/sbin/lsof",drainTimeout: DispatchTimeInterval = .seconds(2)) -> Bool {+ let lock = open(prefix.root.appending(path: ".notproton-prefix.lock").path(percentEncoded: false), O_RDWR | O_NOFOLLOW | O_CLOEXEC)+ if lock >= 0 {+ defer { close(lock) }+ var info = stat()+ guard fstat(lock, &info) == 0, info.st_mode & S_IFMT == S_IFREG,+ flock(lock, LOCK_EX | LOCK_NB) == 0+ else { return true }+ } else if errno != ENOENT {+ return true+ }+guard let dir = serverDirectory(of: prefix, root: root),FileManager.default.fileExists(atPath: dir.path(percentEncoded: false))else { return false }diff --git a/app/Sources/NotProtonApp/Model/RunnerInstaller.swift b/app/Sources/NotProtonApp/Model/RunnerInstaller.swiftindex 324f8ef..d4b3f6c 100644--- a/app/Sources/NotProtonApp/Model/RunnerInstaller.swift+++ b/app/Sources/NotProtonApp/Model/RunnerInstaller.swift@@ -1,5 +1,6 @@// Clones CrossOver's Wine runtime into ~/Library/Application Support/notproton/runners+import Darwinimport Foundationenum RunnerInstaller {@@ -50,6 +51,7 @@ enum RunnerInstaller {bridge: URL = SupportPaths.bridge,toolList: URL = SupportPaths.toolList,compatTools: URL = SupportPaths.Steam.compatTools,+ libraries: [SteamLibrary] = PrefixStore.libraries(),running: (URL) -> Bool = { RunnerInstaller.isRunning(from: $0) }) throws -> Bool {let target = SupportPaths.runnerRoot(forBuild: build, runners: runners)@@ -66,9 +68,123 @@ enum RunnerInstaller {}try WriteRefused.catching(path) { try FileManager.default.removeItem(at: target) }- return try CompatToolList.sync(+ let changed = try CompatToolList.sync(runners: runners, bridge: bridge, file: toolList, compatTools: compatTools)+ let failures = removeStalePrefixTemplates(runners: runners, libraries: libraries)+ if !failures.isEmpty {+ throw StepFailure(step: removeStep, detail: failures.map(\.detail).joined(separator: "\n"))+ }+ return changed+ }++ // Also catches templates left on a drive that was not present (unplugged or unmounted)+ // at the time the deployed copy of CrossOver was removed.+ static func removeStalePrefixTemplates(runners: URL, libraries: [SteamLibrary]) -> [StepFailure] {+ removePrefixTemplates(keeping: Set(RunnerStore.clonedBuilds(in: runners)), libraries: libraries)+ }++ static func removePrefixTemplates(keeping builds: Set<String>, libraries: [SteamLibrary]) -> [StepFailure] {+ var failures: [StepFailure] = []+ for library in libraries {+ let kept = Set(builds.flatMap {+ SupportPaths.prefixTemplates(forBuild: $0, in: library).map(\.lastPathComponent)+ })+ let folder = library.compatdata.appending(path: SupportPaths.prefixTemplateFolder)+ do {+ let parent = open(library.compatdata.path(percentEncoded: false), O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)+ guard parent >= 0 else {+ if errno == ENOENT { continue }+ throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO)+ }+ defer { close(parent) }+ var cacheInfo = stat()+ guard fstatat(parent, SupportPaths.prefixTemplateFolder, &cacheInfo, AT_SYMLINK_NOFOLLOW) == 0 else {+ if errno == ENOENT { continue }+ throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO)+ }+ let lock = openat(parent, ".notproton-template.lock", O_RDWR | O_CREAT | O_NOFOLLOW | O_CLOEXEC, 0o600)+ guard lock >= 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) }+ defer { close(lock) }+ var lockInfo = stat()+ guard fstat(lock, &lockInfo) == 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) }+ guard lockInfo.st_mode & S_IFMT == S_IFREG else { throw POSIXError(.EINVAL) }+ guard flock(lock, LOCK_EX | LOCK_NB) == 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) }++ let root = openat(parent, SupportPaths.prefixTemplateFolder, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)+ guard root >= 0 else {+ if errno == ENOENT { continue }+ throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO)+ }+ defer { close(root) }+ var info = stat()+ guard fstat(root, &info) == 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) }+ guard info.st_mode & S_IFMT == S_IFDIR else { throw POSIXError(.ENOTDIR) }++ for name in try templateDirectoryNames(root) where !kept.contains(name) {+ guard name.wholeMatch(of: #/crossover-[A-Za-z0-9.-]+-(x86_64|aarch64)-unix/#) != nil else { continue }+ do {+ try removeTemplateEntry(name, in: root, device: info.st_dev)+ } catch {+ failures.append(StepFailure(+ step: removeStep,+ detail: "Could not remove prefix template \(folder.appending(path: name).path(percentEncoded: false)): \(error.localizedDescription) Refresh to retry."+ ))+ }+ }+ } catch {+ failures.append(StepFailure(+ step: removeStep,+ detail: "Could not clean prefix templates at \(folder.path(percentEncoded: false)): \(error.localizedDescription) Refresh to retry."+ ))+ }+ }+ return failures+ }++ private static func templateDirectoryNames(_ fd: Int32) throws -> [String] {+ let copy = dup(fd)+ guard copy >= 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) }+ guard let directory = fdopendir(copy) else {+ let code = errno+ close(copy)+ throw POSIXError(POSIXErrorCode(rawValue: code) ?? .EIO)+ }+ defer { closedir(directory) }+ var names: [String] = []+ while true {+ errno = 0+ guard let entry = readdir(directory) else {+ guard errno == 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) }+ return names+ }+ let name = withUnsafePointer(to: &entry.pointee.d_name) {+ $0.withMemoryRebound(to: CChar.self, capacity: Int(entry.pointee.d_namlen) + 1) { String(cString: $0) }+ }+ if name != ".", name != ".." { names.append(name) }+ }+ }++ private static func removeTemplateEntry(_ name: String, in parent: Int32, device: dev_t) throws {+ var info = stat()+ guard fstatat(parent, name, &info, AT_SYMLINK_NOFOLLOW) == 0 else {+ if errno == ENOENT { return }+ throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO)+ }+ if info.st_mode & S_IFMT == S_IFDIR {+ let child = openat(parent, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)+ guard child >= 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) }+ defer { close(child) }+ var opened = stat()+ guard fstat(child, &opened) == 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) }+ guard opened.st_dev == device, opened.st_ino == info.st_ino else { throw POSIXError(.EBUSY) }+ for entry in try templateDirectoryNames(child) {+ try removeTemplateEntry(entry, in: child, device: device)+ }+ guard unlinkat(parent, name, AT_REMOVEDIR) == 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) }+ } else {+ guard unlinkat(parent, name, 0) == 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) }+ }}// Wine keeps a wineserver running inside the clone, so a process running from there is adiff --git a/app/Sources/NotProtonApp/Model/Uninstall.swift b/app/Sources/NotProtonApp/Model/Uninstall.swiftindex fd6d916..f0c5ae5 100644--- a/app/Sources/NotProtonApp/Model/Uninstall.swift+++ b/app/Sources/NotProtonApp/Model/Uninstall.swift@@ -44,6 +44,7 @@ enum Uninstall {SupportPaths.support,SupportPaths.packageDownloads.deletingLastPathComponent(),],+ libraries: [SteamLibrary] = PrefixStore.libraries(),report: @escaping @Sendable (UninstallPhase) -> Void = { _ in },repair: Repair = { report in _ = try await SteamRepair.run(report: report) },stop: Stop = { onStopping in try SteamBundle.stopClient(step: step, onStopping: onStopping) }@@ -65,6 +66,10 @@ enum Uninstall {let removed = try remove(legacyCompat: legacyCompat, compatTools: compatTools, directories: directories)+ let templateFailures = RunnerInstaller.removePrefixTemplates(keeping: [], libraries: libraries)+ if !templateFailures.isEmpty {+ throw StepFailure(step: step, detail: templateFailures.map(\.detail).joined(separator: "\n"))+ }report(.finished)return UninstallOutcome(diff --git a/app/Sources/NotProtonApp/Support/SupportPaths.swift b/app/Sources/NotProtonApp/Support/SupportPaths.swiftindex 64f12c2..1f92790 100644--- a/app/Sources/NotProtonApp/Support/SupportPaths.swift+++ b/app/Sources/NotProtonApp/Support/SupportPaths.swift@@ -54,6 +54,17 @@ enum SupportPaths {runnerRoot(forBuild: build, runners: runners).appending(path: "CrossOver")}+ static func prefixTemplates(forBuild build: String, in library: SteamLibrary) -> [URL] {+ [.rosetta, .fex].map { prefixTemplate(forBuild: build, flavor: $0, in: library) }+ }++ static func prefixTemplate(forBuild build: String, flavor: CompatTool.Flavor, in library: SteamLibrary) -> URL {+ let unix = flavor == .fex ? "aarch64-unix" : "x86_64-unix"+ return library.compatdata.appending(path: prefixTemplateFolder).appending(path: "crossover-\(build)-\(unix)")+ }++ static let prefixTemplateFolder = "notproton-template"+enum Steam {static var app: URL { URL(filePath: "/Applications/Steam.app") }static var infoPlist: URL { infoPlist(inBundle: app) }diff --git a/app/Sources/NotProtonApp/SystemStatus.swift b/app/Sources/NotProtonApp/SystemStatus.swiftindex cbcdcd4..4f741df 100644--- a/app/Sources/NotProtonApp/SystemStatus.swift+++ b/app/Sources/NotProtonApp/SystemStatus.swift@@ -439,23 +439,38 @@ final class SystemStatus {}.valuesnapshot = capturedAppLog.note(captured)- await measureRunnerSizes()+ await refreshRunnerStorage()}private(set) var runnerSizes: [String: Int64] = [:]+ private(set) var templateSizes: [String: [CompatTool.Flavor: Int64]] = [:]+ private(set) var templateCleanupFailure: String?- func measureRunnerSizes() async {- let known = Set(runnerSizes.keys)- let present = await Task.detached(priority: .utility) {- Set(RunnerStore.clonedBuilds())+ func refreshRunnerStorage(+ runners: URL = SupportPaths.runners, libraries: [SteamLibrary] = PrefixStore.libraries()+ ) async {+ let known = runnerSizes+ let measured = await Task.detached(priority: .utility) {+ let failures = RunnerInstaller.removeStalePrefixTemplates(runners: runners, libraries: libraries)+ var sizes: [String: Int64] = [:]+ var templates: [String: [CompatTool.Flavor: Int64]] = [:]+ for build in RunnerStore.clonedBuilds(in: runners) {+ sizes[build] = known[build] ?? RunnerStore.cloneSize(forBuild: build, runners: runners)+ templates[build] = libraries.reduce(into: [:]) { totals, library in+ let folder = library.compatdata.appending(path: SupportPaths.prefixTemplateFolder)+ var info = stat()+ guard lstat(folder.path(percentEncoded: false), &info) == 0,+ info.st_mode & S_IFMT == S_IFDIR else { return }+ for flavor in [CompatTool.Flavor.rosetta, .fex] {+ let template = SupportPaths.prefixTemplate(forBuild: build, flavor: flavor, in: library)+ totals[flavor, default: 0] += PrefixStore.directoryBytes(template, metric: .allocated)+ }+ }+ }+ return (sizes, templates, failures)}.value-- for stale in known.subtracting(present) { runnerSizes[stale] = nil }-- for build in present.subtracting(known) {- runnerSizes[build] = await Task.detached(priority: .utility) {- RunnerStore.cloneSize(forBuild: build)- }.value- }+ runnerSizes = measured.0+ templateSizes = measured.1+ templateCleanupFailure = measured.2.isEmpty ? nil : measured.2.map(\.detail).joined(separator: "\n")}}diff --git a/app/Sources/NotProtonApp/Views/BackupsView.swift b/app/Sources/NotProtonApp/Views/BackupsView.swiftindex 0e1f8b1..ae4e5a5 100644--- a/app/Sources/NotProtonApp/Views/BackupsView.swift+++ b/app/Sources/NotProtonApp/Views/BackupsView.swift@@ -71,7 +71,7 @@ struct BackupsView: View {guard !model.backups.isEmpty else { return "" }let size = model.backupBytes.formatted(.byteCount(style: .file))let count = model.backups.count == 1 ? "1 backup" : "\(model.backups.count) backups"- return "\(count), \(size)"+ return "\(count), \(size) private size"}private var selected: [PrefixBackup] {@@ -155,10 +155,11 @@ struct BackupsView: View {}.width(min: 44, ideal: libraryWidth)- TableColumn("Size") { backup in+ TableColumn("Private Size") { backup inText(backup.bytes.formatted(.byteCount(style: .file))).monospacedDigit().foregroundStyle(.secondary)+ .help(Text(PrefixStore.privateSizeHelp))}.width(min: 56, ideal: 90)diff --git a/app/Sources/NotProtonApp/Views/PrefixesView.swift b/app/Sources/NotProtonApp/Views/PrefixesView.swiftindex c2c766d..b3a432a 100644--- a/app/Sources/NotProtonApp/Views/PrefixesView.swift+++ b/app/Sources/NotProtonApp/Views/PrefixesView.swift@@ -256,11 +256,12 @@ struct PrefixesView: View {}.width(min: 44, ideal: libraryWidth)- TableColumn("Size") { prefix in+ TableColumn("Private Size") { prefix inif let usage = model.usage[prefix.id] {Text(usage.bytes.formatted(.byteCount(style: .file))).monospacedDigit().foregroundStyle(.secondary)+ .help(Text(PrefixStore.privateSizeHelp))} else {Text("Calculating…").foregroundStyle(contrast == .increased ? .secondary : .tertiary)diff --git a/app/Sources/NotProtonApp/Views/StatusView.swift b/app/Sources/NotProtonApp/Views/StatusView.swiftindex 70887b3..94af9d9 100644--- a/app/Sources/NotProtonApp/Views/StatusView.swift+++ b/app/Sources/NotProtonApp/Views/StatusView.swift@@ -50,6 +50,7 @@ struct StatusRow: View {var tone: StatusTone?var detail: String?var trailing: String?+ var trailingHelp: LocalizedStringResource = ""var secondaryAction: StatusAction?var action: StatusAction?var menu: [StatusAction] = []@@ -91,6 +92,8 @@ struct StatusRow: View {Text(trailing).monospacedDigit().foregroundStyle(.secondary)+ .multilineTextAlignment(.trailing)+ .help(Text(trailingHelp)).padding(.trailing, action == nil && menu.isEmpty ? 0 : 8)}if let toggle {@@ -297,6 +300,10 @@ struct StatusView: View {StatusRow(title: "Done", value: outcome, tone: .ok)}+ if let failure = status.templateCleanupFailure {+ StatusRow(title: "Template cleanup incomplete", value: failure, tone: .warning)+ }+if let activity = status.activity {HStack(spacing: 10) {ProgressView()@@ -469,6 +476,7 @@ struct StatusView: View {tone: crossOverTone(row),detail: crossOverDetail(row, tools: tools),trailing: row.copy == .ready ? buildSize(row.buildID) : nil,+ trailingHelp: "Runner and template allocated footprints are shown separately. Templates include mounted Steam libraries and may share APFS extents with prefixes. These are not additive physical usage or guaranteed space reclaimed by deletion.",action: crossOverAction(row, prominent: snapshot.runner == .none),menu: crossOverMenu(row))@@ -585,9 +593,24 @@ struct StatusView: View {}private func buildSize(_ build: String) -> String? {- status.runnerSizes[build].map {- ByteCountFormatter.string(fromByteCount: $0, countStyle: .file)+ guard let runner = status.runnerSizes[build] else { return nil }+ let flavors = SupportedRunners.build(id: build)?.tools.map(\.flavor) ?? []+ return Self.sizeText(runner: runner, templates: status.templateSizes[build] ?? [:], flavors: flavors)+ }++ nonisolated static func sizeText(runner: Int64, templates: [CompatTool.Flavor: Int64], flavors: [CompatTool.Flavor]) -> String {+ let lines: [String]+ if flavors.count > 1 {+ lines = flavors.compactMap { flavor in+ guard let bytes = templates[flavor], bytes > 0 else { return nil }+ let name = flavor == .fex ? "FEX" : "Rosetta"+ return "\(name) templates \(bytes.formatted(.byteCount(style: .file)))"+ }+ } else {+ let bytes = templates.values.reduce(0, +)+ lines = bytes > 0 ? ["Templates \(bytes.formatted(.byteCount(style: .file)))"] : []}+ return (["Runner \(runner.formatted(.byteCount(style: .file)))"] + lines).joined(separator: "\n")}private func removeCopyAction(_ build: String, label: String) -> StatusAction {diff --git a/app/Tests/NotProtonAppTests/PrefixStoreTests.swift b/app/Tests/NotProtonAppTests/PrefixStoreTests.swiftindex 97a823a..8edbda4 100644--- a/app/Tests/NotProtonAppTests/PrefixStoreTests.swift+++ b/app/Tests/NotProtonAppTests/PrefixStoreTests.swift@@ -139,6 +139,115 @@ struct PrefixStoreTests {#expect(usage.bytes > 0)}+ @Test("A linked folder outside the prefix adds nothing to its size")+ func sizeSkipsLinkedFolders() throws {+ let dir = try scratchDirectory("pfx")+ defer { try? FileManager.default.removeItem(at: dir) }+ let outside = dir.appending(path: "outside")+ let inside = dir.appending(path: "inside")+ try FileManager.default.createDirectory(at: outside, withIntermediateDirectories: true)+ try FileManager.default.createDirectory(at: inside, withIntermediateDirectories: true)+ try Data(repeating: 7, count: 4 << 20).write(to: outside.appending(path: "big"))+ try FileManager.default.createSymbolicLink(+ at: inside.appending(path: "Documents"), withDestinationURL: outside)++ #expect(PrefixStore.directoryBytes(outside) >= 4 << 20)+ #expect(PrefixStore.directoryBytes(inside) < 1 << 20)+ }++ @Test("Private bytes exclude shared clone extents until the source is deleted")+ func privateSizeExcludesSharedExtents() throws {+ let dir = try scratchDirectory("pfx")+ defer { try? FileManager.default.removeItem(at: dir) }+ let source = dir.appending(path: "template")+ let clone = dir.appending(path: "clone")+ try FileManager.default.createDirectory(at: source, withIntermediateDirectories: true)+ let bytes = Data((0..<(4 << 20)).map { UInt8(truncatingIfNeeded: $0 &* 2_654_435_761 >> 13) })+ try bytes.write(to: source.appending(path: "ntdll.dll"))+ try #require(+ clonefile(source.path(percentEncoded: false), clone.path(percentEncoded: false), 0) == 0,+ "scratch volume cannot clone")++ #expect(PrefixStore.directoryBytes(clone) < 1 << 20)+ #expect(PrefixStore.directoryBytes(source) < 1 << 20)+ #expect(PrefixStore.directoryBytes(clone, metric: .allocated) >= 4 << 20)+ #expect(PrefixStore.directoryBytes(source, metric: .allocated) >= 4 << 20)++ try FileManager.default.removeItem(at: source)+ #expect(PrefixStore.directoryBytes(clone) >= 4 << 20)+ }++ @Test("A symlink passed as the size root is not traversed")+ func sizeDoesNotFollowLinkedRoot() throws {+ let dir = try scratchDirectory("pfx-size-root")+ defer { try? FileManager.default.removeItem(at: dir) }+ let outside = dir.appending(path: "outside")+ try FileManager.default.createDirectory(at: outside, withIntermediateDirectories: true)+ try Data(repeating: 7, count: 4 << 20).write(to: outside.appending(path: "big"))+ let link = dir.appending(path: "pfx")+ try FileManager.default.createSymbolicLink(at: link, withDestinationURL: outside)++ #expect(PrefixStore.directoryBytes(link) < 1 << 20)+ #expect(PrefixStore.directoryBytes(link, metric: .allocated) < 1 << 20)+ let directoryURL = URL(filePath: link.path + "/", directoryHint: .isDirectory)+ #expect(PrefixStore.directoryBytes(directoryURL) < 1 << 20)+ #expect(PrefixStore.directoryBytes(directoryURL, metric: .allocated) < 1 << 20)+ }++ @Test("Hardlinks within a folder are counted once by device and inode")+ func sizeDeduplicatesHardlinks() throws {+ let dir = try scratchDirectory("pfx-hardlinks")+ defer { try? FileManager.default.removeItem(at: dir) }+ let file = dir.appending(path: "original")+ try Data(repeating: 7, count: 4 << 20).write(to: file)+ try FileManager.default.linkItem(at: file, to: dir.appending(path: "same-inode"))++ #expect(PrefixStore.directoryBytes(dir) >= 4 << 20)+ #expect(PrefixStore.directoryBytes(dir) < 5 << 20)+ #expect(PrefixStore.directoryBytes(dir, metric: .allocated) >= 4 << 20)+ #expect(PrefixStore.directoryBytes(dir, metric: .allocated) < 5 << 20)+ }++ @Test("The shell preparation lock marks a prefix in use before a server exists")+ func preparationLockIsInUse() throws {+ let dir = try scratchDirectory("pfx-preparing")+ defer { try? FileManager.default.removeItem(at: dir) }+ let prefix = try prefix(in: dir)+ let root = dir.appending(path: "sockets")+ let lock = prefix.root.appending(path: ".notproton-prefix.lock")+ #expect(!PrefixStore.isInUse(prefix, root: root))+ #expect(!FileManager.default.fileExists(atPath: lock.path))+ let fd = open(lock.path, O_RDWR | O_CREAT | O_NOFOLLOW, 0o600)+ try #require(fd >= 0)+ defer { close(fd) }+ try #require(flock(fd, LOCK_EX | LOCK_NB) == 0)++ #expect(PrefixStore.isInUse(prefix, root: root))+ let deletion = try #require(throws: StepFailure.self) { try PrefixTools.delete(prefix) }+ #expect(deletion.detail.contains("is running"))+ let rebuild = try #require(throws: StepFailure.self) {+ try PrefixTools.recreate(prefix, runner: dir.appending(path: "runner"))+ }+ #expect(rebuild.detail.contains("is running"))+ #expect(FileManager.default.fileExists(atPath: prefix.pfx.path))+ try #require(flock(fd, LOCK_UN) == 0)+ #expect(!PrefixStore.isInUse(prefix, root: root))+ }++ @Test("A linked preparation lock is not mistaken for an idle prefix")+ func linkedPreparationLockIsInUse() throws {+ let dir = try scratchDirectory("pfx-preparation-link")+ defer { try? FileManager.default.removeItem(at: dir) }+ let prefix = try prefix(in: dir)+ let outside = dir.appending(path: "outside")+ try Data("keep".utf8).write(to: outside)+ try FileManager.default.createSymbolicLink(+ at: prefix.root.appending(path: ".notproton-prefix.lock"), withDestinationURL: outside)++ #expect(PrefixStore.isInUse(prefix, root: dir.appending(path: "sockets")))+ #expect(try String(contentsOf: outside, encoding: .utf8) == "keep")+ }+@Test("Only the parked prefixes count as backups")func backupsIgnoreEverythingElseInTheEntry() throws {let dir = try scratchDirectory("pfx")diff --git a/app/Tests/NotProtonAppTests/PrefixToolsTests.swift b/app/Tests/NotProtonAppTests/PrefixToolsTests.swiftindex c9c85d1..b083830 100644--- a/app/Tests/NotProtonAppTests/PrefixToolsTests.swift+++ b/app/Tests/NotProtonAppTests/PrefixToolsTests.swift@@ -1031,7 +1031,7 @@ struct PrefixToolsTests {let source = try Self.compatSource()let definition = try #require(source.range(of: "lay_out_proton_profile() {"))- let call = try #require(source.range(of: " lay_out_proton_profile\n"))+ let call = try #require(source.range(of: " if ! lay_out_proton_profile; then\n"))let settings = try #require(source.range(of: " import_prefix_settings\n"))// sh reads a script top to bottom, so a call above the definition is only an@@ -1132,7 +1132,7 @@ struct PrefixToolsTests {let source = try Self.compatSource()let definition = try #require(source.range(of: "migrate_user_paths() {"))- let call = try #require(source.range(of: " migrate_user_paths \"$profile\"\n"))+ let call = try #require(source.range(of: " migrate_user_paths \"$profile\" || return 1\n"))let layout = try #require(source.range(of: "lay_out_proton_profile() {"))// sh reads a script top to bottom, so a call above the definition is only an@@ -1267,7 +1267,7 @@ struct PrefixToolsTests {let source = try Self.compatSource()let gate = try #require(source.range(of: #"if ! merge_user_dir "$old" "$new"; then"#))- let rename = try #require(source.range(of: #"mv "$old" "$old BACKUP""#))+ let rename = try #require(source.range(of: #"mv "$old" "$backup""#))#expect(gate.lowerBound < rename.lowerBound)// A bare call could not report anything: the walk reads from a pipe, so it runs in a// subshell and only the group's status comes back.@@ -1286,7 +1286,7 @@ struct PrefixToolsTests {let source = try Self.compatSource()let refusal = try #require(source.range(of: #"if [ -L "$new" ]; then"#))- let rename = try #require(source.range(of: #"mv "$old" "$old BACKUP""#))+ let rename = try #require(source.range(of: #"mv "$old" "$backup""#))#expect(refusal.lowerBound < rename.lowerBound)}diff --git a/app/Tests/NotProtonAppTests/RealRebuildTests.swift b/app/Tests/NotProtonAppTests/RealRebuildTests.swiftindex b0f0ea0..59800ae 100644--- a/app/Tests/NotProtonAppTests/RealRebuildTests.swift+++ b/app/Tests/NotProtonAppTests/RealRebuildTests.swift@@ -16,6 +16,7 @@ enum RealPrefixes {static var tool: InstalledTool? { CompatToolList.installed().first }static var candidates: [WinePrefix] {+ guard ProcessInfo.processInfo.environment["NOTPROTON_TEST_WINE"] == "1" else { return [] }guard tool != nil else { return [] }func realDirectory(_ url: URL) -> Bool {let values = try? url.resourceValues(forKeys: [.isSymbolicLinkKey, .isDirectoryKey])diff --git a/app/Tests/NotProtonAppTests/RunnerSwitchTests.swift b/app/Tests/NotProtonAppTests/RunnerSwitchTests.swiftindex bb5e310..68e74a1 100644--- a/app/Tests/NotProtonAppTests/RunnerSwitchTests.swift+++ b/app/Tests/NotProtonAppTests/RunnerSwitchTests.swift@@ -422,15 +422,83 @@ struct RunnerRemovalTests {return runners}- private func remove(_ build: String, runners: URL, running: Bool = false) throws -> Bool {+ private func remove(+ _ build: String, runners: URL, libraries: [SteamLibrary] = [], running: Bool = false+ ) throws -> Bool {try RunnerInstaller.removeClone(forBuild: build, runners: runners,bridge: runners.appending(path: "bridge"), toolList: runners.appending(path: "tools"),compatTools: runners.appending(path: "compatibilitytools.d"),+ libraries: libraries,running: { _ in running })}+ @Test("Removing a build deletes its prefix templates in every library and keeps the others")+ func removesThatBuildsTemplates() throws {+ let runners = try makeRunners(cloning: [Self.rosetta.id, Self.fex.id])+ defer { try? FileManager.default.removeItem(at: runners) }+ let fm = FileManager.default+ let libraries = ["internal", "external"].map {+ SteamLibrary(root: runners.appending(path: "libraries/\($0)"))+ }+ for library in libraries {+ for build in [Self.rosetta.id, Self.fex.id] {+ for template in SupportPaths.prefixTemplates(forBuild: build, in: library) {+ try fm.createDirectory(+ at: template.appending(path: "pfx/drive_c"), withIntermediateDirectories: true)+ }+ }+ }++ _ = try remove(Self.rosetta.id, runners: runners, libraries: libraries)++ for library in libraries {+ let left = try fm.contentsOfDirectory(+ atPath: library.compatdata.appending(path: SupportPaths.prefixTemplateFolder)+ .path(percentEncoded: false)+ ).sorted()+ #expect(left == SupportPaths.prefixTemplates(forBuild: Self.fex.id, in: library)+ .map(\.lastPathComponent).sorted())+ }+ }++ @Test("Removing a build also clears templates left by builds removed while their drive was away")+ func removesTemplatesOfBuildsAlreadyGone() throws {+ let runners = try makeRunners(cloning: [Self.rosetta.id, Self.fex.id])+ defer { try? FileManager.default.removeItem(at: runners) }+ let fm = FileManager.default+ let library = SteamLibrary(root: runners.appending(path: "libraries/external"))+ let gone = SupportPaths.prefixTemplates(forBuild: "26.3.0.39832", in: library)+ for template in gone {+ try fm.createDirectory(at: template.appending(path: "pfx"), withIntermediateDirectories: true)+ }++ _ = try remove(Self.rosetta.id, runners: runners, libraries: [library])++ for template in gone { #expect(!fm.fileExists(atPath: template.path(percentEncoded: false))) }+ }++ @Test("A template is named by the build and the unix arch, under notproton-template")+ func templateNamesMatchTheScript() throws {+ let library = SteamLibrary(root: URL(filePath: "/L"))+ let repo = URL(filePath: #filePath)+ .deletingLastPathComponent().deletingLastPathComponent()+ .deletingLastPathComponent().deletingLastPathComponent()+ let script = try String(contentsOf: repo.appending(path: "dylib/feats/compat_run.sh"), encoding: .utf8)+ let expression = try #require(script.firstMatch(of: #/runner_id="([^"]+)"/#)).1+ let cache = script.split(separator: "\n").first { $0.contains("template_cache=\"") }+ #expect(cache?.contains("$(dirname \"$STEAM_COMPAT_DATA_PATH\")/\(SupportPaths.prefixTemplateFolder)\"") == true)+ let template = script.split(separator: "\n").first { $0.contains("template_dir=\"") }+ #expect(template?.contains("template_dir=\"$template_cache/$runner_id\"") == true)+ let names = ["x86_64-unix", "aarch64-unix"].map { arch in+ expression.replacingOccurrences(of: "$np_build", with: "27.0.0.40921-fex")+ .replacingOccurrences(of: "${wine_unix##*/}", with: arch)+ }+ #expect(SupportPaths.prefixTemplates(forBuild: "27.0.0.40921-fex", in: library).map(\.path)+ == names.map { library.compatdata.appending(path: SupportPaths.prefixTemplateFolder).appending(path: $0).path })+ }+@Test("A build with a game still running on it is not removed")func keepsRunningBuild() throws {let runners = try makeRunners(cloning: [Self.rosetta.id])diff --git a/app/Tests/NotProtonAppTests/TemplateCleanupTests.swift b/app/Tests/NotProtonAppTests/TemplateCleanupTests.swiftnew file mode 100644index 0000000..74cbfd0--- /dev/null+++ b/app/Tests/NotProtonAppTests/TemplateCleanupTests.swift@@ -0,0 +1,319 @@+import Darwin+import Foundation+import Testing++@testable import NotProtonApp++@Suite("Prefix template cleanup")+struct TemplateCleanupTests {+ private struct Layout {+ let root: URL+ var runners: URL { root.appending(path: "runners") }+ var library: SteamLibrary { SteamLibrary(root: root.appending(path: "library")) }+ var folder: URL { library.compatdata.appending(path: SupportPaths.prefixTemplateFolder) }+ var template: URL { SupportPaths.prefixTemplates(forBuild: "26.3.0.39832", in: library)[0] }+ var lock: URL { library.compatdata.appending(path: ".notproton-template.lock") }++ init() throws {+ root = try scratchDirectory("template-cleanup")+ try FileManager.default.createDirectory(at: template, withIntermediateDirectories: true)+ }++ func removeBuild() throws {+ let build = "1.2.3.4567"+ try FileManager.default.createDirectory(+ at: SupportPaths.runnerRoot(forBuild: build, runners: runners),+ withIntermediateDirectories: true)+ try Data("old tool list\n".utf8).write(to: root.appending(path: "tools"))+ try RunnerInstaller.removeClone(+ forBuild: build, runners: runners, bridge: root.appending(path: "bridge"),+ toolList: root.appending(path: "tools"), compatTools: root.appending(path: "compat-tools"),+ libraries: [library], running: { _ in false })+ }+ }++ @Test("A linked template root cannot delete the directory it points at")+ func refusesLinkedRoot() throws {+ let layout = try Layout()+ defer { try? FileManager.default.removeItem(at: layout.root) }+ let outside = layout.root.appending(path: "outside")+ try FileManager.default.moveItem(at: layout.folder, to: outside)+ try FileManager.default.createSymbolicLink(at: layout.folder, withDestinationURL: outside)++ let failures = RunnerInstaller.removeStalePrefixTemplates(runners: layout.runners, libraries: [layout.library])++ #expect(failures.count == 1)+ #expect(failures.first?.detail.contains(layout.folder.path) == true)+ #expect(FileManager.default.fileExists(atPath: outside.appending(path: layout.template.lastPathComponent).path))+ }++ @Test("Only recognized template names are removed")+ func preservesUnknownChildren() throws {+ let layout = try Layout()+ defer { try? FileManager.default.removeItem(at: layout.root) }+ let names = ["notes", "crossover--x86_64-unix", "crossover-bad_build-x86_64-unix", "crossover-26.3.0.39832-i386-unix"]+ for name in names {+ try Data("keep".utf8).write(to: layout.folder.appending(path: name))+ }++ let failures = RunnerInstaller.removeStalePrefixTemplates(runners: layout.runners, libraries: [layout.library])++ #expect(failures.isEmpty)+ #expect(!FileManager.default.fileExists(atPath: layout.template.path))+ for name in names {+ #expect(FileManager.default.fileExists(atPath: layout.folder.appending(path: name).path))+ }+ }++ @Test("Linked template children are unlinked without touching their targets")+ func unlinksChildrenOnly() throws {+ let layout = try Layout()+ defer { try? FileManager.default.removeItem(at: layout.root) }+ let outside = layout.root.appending(path: "outside")+ try FileManager.default.createDirectory(at: outside, withIntermediateDirectories: true)+ let sentinel = outside.appending(path: "keep")+ try Data("keep".utf8).write(to: sentinel)+ try FileManager.default.createSymbolicLink(at: layout.template.appending(path: "Documents"), withDestinationURL: outside)+ let linked = SupportPaths.prefixTemplates(forBuild: "26.3.0.39832", in: layout.library)[1]+ try FileManager.default.createSymbolicLink(at: linked, withDestinationURL: outside)++ let failures = RunnerInstaller.removeStalePrefixTemplates(runners: layout.runners, libraries: [layout.library])++ #expect(failures.isEmpty)+ #expect(try String(contentsOf: sentinel, encoding: .utf8) == "keep")+ #expect((try? FileManager.default.destinationOfSymbolicLink(atPath: linked.path)) == nil)+ }++ @Test("A busy template lock leaves the cache intact and reports the skipped cleanup")+ func reportsBusyLock() throws {+ let layout = try Layout()+ defer { try? FileManager.default.removeItem(at: layout.root) }+ let fd = open(layout.lock.path, O_RDWR | O_CREAT | O_NOFOLLOW, 0o600)+ try #require(fd >= 0)+ defer { close(fd) }+ try #require(flock(fd, LOCK_EX | LOCK_NB) == 0)++ #expect(throws: StepFailure.self) { try layout.removeBuild() }+ #expect(FileManager.default.fileExists(atPath: layout.template.path))+ #expect(!FileManager.default.fileExists(atPath: SupportPaths.runnerRoot(forBuild: "1.2.3.4567", runners: layout.runners).path))+ #expect(try String(contentsOf: layout.root.appending(path: "tools"), encoding: .utf8).isEmpty)+ }++ @Test("A linked lock file cannot authorize template cleanup")+ func refusesLinkedLock() throws {+ let layout = try Layout()+ defer { try? FileManager.default.removeItem(at: layout.root) }+ let outside = layout.root.appending(path: "lock-target")+ try Data("keep".utf8).write(to: outside)+ try FileManager.default.createSymbolicLink(at: layout.lock, withDestinationURL: outside)++ #expect(throws: StepFailure.self) { try layout.removeBuild() }+ #expect(FileManager.default.fileExists(atPath: layout.template.path))+ #expect(try String(contentsOf: outside, encoding: .utf8) == "keep")+ }++ @Test("A refused template deletion is reported after runner removal")+ func reportsDeletionFailure() throws {+ let layout = try Layout()+ defer { try? FileManager.default.removeItem(at: layout.root) }+ try #require(chflags(layout.template.path, UInt32(UF_IMMUTABLE)) == 0)+ defer { chflags(layout.template.path, 0) }++ #expect(throws: StepFailure.self) { try layout.removeBuild() }+ #expect(FileManager.default.fileExists(atPath: layout.template.path))+ }++ @MainActor+ @Test("Refresh retries mounted libraries with no runners and clears the cleanup report")+ func refreshRetriesWithoutRunners() async throws {+ let layout = try Layout()+ defer { try? FileManager.default.removeItem(at: layout.root) }+ let fd = open(layout.lock.path, O_RDWR | O_CREAT | O_NOFOLLOW, 0o600)+ try #require(fd >= 0)+ defer { close(fd) }+ try #require(flock(fd, LOCK_EX | LOCK_NB) == 0)+ let status = SystemStatus()++ await status.refreshRunnerStorage(runners: layout.runners, libraries: [layout.library])+ #expect(status.templateCleanupFailure?.contains(layout.library.compatdata.path) == true)+ #expect(FileManager.default.fileExists(atPath: layout.template.path))++ try #require(flock(fd, LOCK_UN) == 0)+ await status.refreshRunnerStorage(runners: layout.runners, libraries: [layout.library])+ #expect(status.templateCleanupFailure == nil)+ #expect(!FileManager.default.fileExists(atPath: layout.template.path))+ #expect(FileManager.default.fileExists(atPath: layout.lock.path))+ #expect(!FileManager.default.fileExists(atPath: layout.runners.path))+ }++ @MainActor+ @Test("A library that returns after runner removal is cleaned on refresh")+ func refreshCleansRemountedLibrary() async throws {+ let layout = try Layout()+ defer { try? FileManager.default.removeItem(at: layout.root) }+ let unmounted = layout.root.appending(path: "unmounted-library")+ try FileManager.default.moveItem(at: layout.library.root, to: unmounted)+ let status = SystemStatus()++ await status.refreshRunnerStorage(runners: layout.runners, libraries: [layout.library])+ #expect(!FileManager.default.fileExists(atPath: layout.library.root.path))+ #expect(status.templateCleanupFailure == nil)++ try FileManager.default.moveItem(at: unmounted, to: layout.library.root)+ await status.refreshRunnerStorage(runners: layout.runners, libraries: [layout.library])+ #expect(!FileManager.default.fileExists(atPath: layout.template.path))+ #expect(status.templateCleanupFailure == nil)+ }++ @MainActor+ @Test("Template allocated footprints include every mounted library and refresh after changes")+ func refreshesTemplateSizes() async throws {+ let layout = try Layout()+ defer { try? FileManager.default.removeItem(at: layout.root) }+ let build = "26.3.0.39832"+ try FileManager.default.createDirectory(+ at: SupportPaths.clonedRoot(forBuild: build, runners: layout.runners).appending(path: "lib/wine"),+ withIntermediateDirectories: true)+ let other = SteamLibrary(root: layout.root.appending(path: "second-library"))+ let otherTemplate = SupportPaths.prefixTemplates(forBuild: build, in: other)[1]+ try FileManager.default.createDirectory(at: otherTemplate, withIntermediateDirectories: true)+ let file = layout.template.appending(path: "ntdll.dll")+ try Data(repeating: 7, count: 4 << 20).write(to: file)+ try #require(clonefile(file.path, otherTemplate.appending(path: "ntdll.dll").path, 0) == 0)+ let status = SystemStatus()++ await status.refreshRunnerStorage(runners: layout.runners, libraries: [layout.library, other])+ #expect(try #require(status.templateSizes[build]?.values.reduce(0, +)) >= 8 << 20)+ #expect(try #require(status.runnerSizes[build]) < 1 << 20)+ let before = try #require(status.templateSizes[build]?.values.reduce(0, +))++ try Data(repeating: 8, count: 4 << 20).write(to: layout.template.appending(path: "new-file"))+ await status.refreshRunnerStorage(runners: layout.runners, libraries: [layout.library, other])+ #expect(try #require(status.templateSizes[build]?.values.reduce(0, +)) >= before + (4 << 20))++ await status.refreshRunnerStorage(runners: layout.runners, libraries: [other])+ #expect(try #require(status.templateSizes[build]?.values.reduce(0, +)) < 5 << 20)+ }++ @MainActor+ @Test("A build with a FEX and a Rosetta tool measures each tool's template on its own")+ func measuresTemplatesPerTool() async throws {+ let layout = try Layout()+ defer { try? FileManager.default.removeItem(at: layout.root) }+ let build = "27.0.0.40921-fex"+ try FileManager.default.createDirectory(+ at: SupportPaths.clonedRoot(forBuild: build, runners: layout.runners).appending(path: "lib/wine"),+ withIntermediateDirectories: true)+ for (flavor, size) in [(CompatTool.Flavor.fex, 4 << 20), (.rosetta, 1 << 20)] {+ let template = SupportPaths.prefixTemplate(forBuild: build, flavor: flavor, in: layout.library)+ try FileManager.default.createDirectory(at: template, withIntermediateDirectories: true)+ try Data(repeating: 7, count: size).write(to: template.appending(path: "system.reg"))+ }+ let status = SystemStatus()++ await status.refreshRunnerStorage(runners: layout.runners, libraries: [layout.library])+ let sizes = try #require(status.templateSizes[build])+ #expect(try #require(sizes[.fex]) >= 4 << 20)+ #expect(try #require(sizes[.rosetta]) >= 1 << 20)+ #expect(try #require(sizes[.rosetta]) < 2 << 20)+ }++ @Test("The size line names each tool's templates only when a build has more than one tool")+ func sizeTextNamesTools() {+ func labels(_ templates: [CompatTool.Flavor: Int64], _ flavors: [CompatTool.Flavor]) -> [String] {+ StatusView.sizeText(runner: 2_000_000, templates: templates, flavors: flavors)+ .components(separatedBy: "\n")+ .map { $0.components(separatedBy: " ").dropLast(2).joined(separator: " ") }+ }+ #expect(labels([.fex: 871_000_000, .rosetta: 417_000_000], [.fex, .rosetta])+ == ["Runner", "FEX templates", "Rosetta templates"])+ #expect(labels([.fex: 871_000_000, .rosetta: 0], [.fex, .rosetta]) == ["Runner", "FEX templates"])+ #expect(labels([.rosetta: 371_000_000], [.rosetta]) == ["Runner", "Templates"])+ #expect(labels([:], [.rosetta]) == ["Runner"])+ }++ @Test("A failed child does not prevent cleanup in other mounted libraries")+ func continuesAfterFailure() throws {+ let layout = try Layout()+ defer { try? FileManager.default.removeItem(at: layout.root) }+ let other = SteamLibrary(root: layout.root.appending(path: "other"))+ let template = SupportPaths.prefixTemplates(forBuild: "26.3.0.39832", in: other)[0]+ try FileManager.default.createDirectory(at: template, withIntermediateDirectories: true)+ try #require(chflags(layout.template.path, UInt32(UF_IMMUTABLE)) == 0)+ defer { chflags(layout.template.path, 0) }++ let failures = RunnerInstaller.removeStalePrefixTemplates(runners: layout.runners, libraries: [layout.library, other])++ #expect(failures.count == 1)+ #expect(failures.first?.detail.contains(layout.template.path) == true)+ #expect(!FileManager.default.fileExists(atPath: template.path))+ }++ @Test("An offline library is not created by template cleanup")+ func leavesOfflineLibrariesAbsent() throws {+ let root = try scratchDirectory("template-offline")+ defer { try? FileManager.default.removeItem(at: root) }+ let library = SteamLibrary(root: root.appending(path: "offline"))++ let failures = RunnerInstaller.removeStalePrefixTemplates(runners: root.appending(path: "runners"), libraries: [library])++ #expect(failures.isEmpty)+ #expect(!FileManager.default.fileExists(atPath: library.root.path))+ }++ @Test("A read-only library without a cache needs no cleanup lock")+ func skipsMissingCacheOnReadOnlyLibrary() throws {+ let layout = try Layout()+ defer { try? FileManager.default.removeItem(at: layout.root) }+ try FileManager.default.removeItem(at: layout.folder)+ try #require(chmod(layout.library.compatdata.path, 0o500) == 0)+ defer { chmod(layout.library.compatdata.path, 0o700) }++ let failures = RunnerInstaller.removePrefixTemplates(keeping: [], libraries: [layout.library])++ #expect(failures.isEmpty)+ #expect(!FileManager.default.fileExists(atPath: layout.lock.path))+ }++ @Test("A Swift template lock blocks the shell lock until released")+ func swiftLockBlocksShell() throws {+ let layout = try Layout()+ defer { try? FileManager.default.removeItem(at: layout.root) }+ let fd = open(layout.lock.path, O_RDWR | O_CREAT | O_NOFOLLOW, 0o600)+ try #require(fd >= 0)+ defer { close(fd) }+ try #require(flock(fd, LOCK_EX | LOCK_NB) == 0)+ let arguments = ["-c", #"exec 9>> "$1"; /usr/bin/lockf -s -t 0 9"#, "fixture", layout.lock.path]++ #expect(try Shell.run("/bin/sh", arguments).status == 75)+ try #require(flock(fd, LOCK_UN) == 0)+ #expect(try Shell.run("/bin/sh", arguments).status == 0)+ }++ @Test("A shell template lock blocks Swift cleanup until released")+ func shellLockBlocksCleanup() throws {+ let layout = try Layout()+ defer { try? FileManager.default.removeItem(at: layout.root) }+ let child = Process()+ let input = Pipe()+ let output = Pipe()+ child.executableURL = URL(filePath: "/bin/sh")+ child.arguments = ["-ec", #"exec 9>> "$1"; /usr/bin/lockf -s -t 0 9; printf 'ready\n'; read -r release"#, "fixture", layout.lock.path]+ child.standardInput = input+ child.standardOutput = output+ try child.run()+ defer { if child.isRunning { child.terminate(); child.waitUntilExit() } }+ let ready = try output.fileHandleForReading.read(upToCount: 6)+ try #require(ready == Data("ready\n".utf8))++ let failures = RunnerInstaller.removePrefixTemplates(keeping: [], libraries: [layout.library])+ #expect(failures.count == 1)+ #expect(FileManager.default.fileExists(atPath: layout.template.path))++ try input.fileHandleForWriting.write(contentsOf: Data("release\n".utf8))+ child.waitUntilExit()+ #expect(child.terminationStatus == 0)+ #expect(RunnerInstaller.removePrefixTemplates(keeping: [], libraries: [layout.library]).isEmpty)+ #expect(!FileManager.default.fileExists(atPath: layout.template.path))+ }+}diff --git a/app/Tests/NotProtonAppTests/UninstallTests.swift b/app/Tests/NotProtonAppTests/UninstallTests.swiftindex 5c13941..a74a58e 100644--- a/app/Tests/NotProtonAppTests/UninstallTests.swift+++ b/app/Tests/NotProtonAppTests/UninstallTests.swift@@ -208,6 +208,7 @@ struct UninstallTests {legacyCompat: layout.legacyCompat,compatTools: layout.compatTools,directories: [layout.support, layout.caches],+ libraries: [],repair: { _ in throw Offline() },stop: { _ in false })@@ -241,6 +242,7 @@ struct UninstallTests {legacyCompat: layout.legacyCompat,compatTools: layout.compatTools,directories: [layout.support, caches],+ libraries: [],repair: { _ inlet staged = caches.appending(path: "bundle")try FileManager.default.createDirectory(at: staged, withIntermediateDirectories: true)@@ -268,6 +270,7 @@ struct UninstallTests {legacyCompat: layout.legacyCompat,compatTools: layout.compatTools,directories: [layout.support, layout.caches],+ libraries: [],report: { log.add($0) },repair: { report inreport(.checking)@@ -290,4 +293,53 @@ struct UninstallTests {#expect(labels.contains(RepairPhase.replacing.label))}+ @Test("Uninstall removes templates of installed builds but keeps unrelated library data")+ func removesLibraryTemplates() async throws {+ let layout = try layout()+ defer { try? FileManager.default.removeItem(at: layout.root) }+ let library = SteamLibrary(root: layout.root.appending(path: "library"))+ let build = "26.3.0.39832"+ let templates = SupportPaths.prefixTemplates(forBuild: build, in: library)+ for template in templates {+ try FileManager.default.createDirectory(at: template, withIntermediateDirectories: true)+ }+ try FileManager.default.createDirectory(+ at: SupportPaths.clonedRoot(forBuild: build, runners: layout.support.appending(path: "runners")),+ withIntermediateDirectories: true)+ let unrelated = templates[0].deletingLastPathComponent().appending(path: "notes")+ try Data("keep".utf8).write(to: unrelated)++ _ = try await Uninstall.run(+ app: layout.app, innerPlist: layout.innerPlist, updateBlocks: [layout.updateBlock],+ legacyCompat: layout.legacyCompat, compatTools: layout.compatTools,+ directories: [layout.support, layout.caches], libraries: [library],+ repair: { _ in }, stop: { _ in false })++ for template in templates { #expect(!FileManager.default.fileExists(atPath: template.path)) }+ #expect(try String(contentsOf: unrelated, encoding: .utf8) == "keep")+ #expect(FileManager.default.fileExists(atPath: library.compatdata.appending(path: ".notproton-template.lock").path))+ }++ @Test("Uninstall reports template cleanup refusal rather than claiming completion")+ func reportsTemplateCleanupFailure() async throws {+ let layout = try layout()+ defer { try? FileManager.default.removeItem(at: layout.root) }+ let library = SteamLibrary(root: layout.root.appending(path: "library"))+ try FileManager.default.createDirectory(at: library.compatdata, withIntermediateDirectories: true)+ let outside = layout.root.appending(path: "outside")+ try FileManager.default.createDirectory(at: outside, withIntermediateDirectories: true)+ let sentinel = outside.appending(path: "crossover-26.3.0.39832-x86_64-unix")+ try Data("keep".utf8).write(to: sentinel)+ try FileManager.default.createSymbolicLink(+ at: library.compatdata.appending(path: SupportPaths.prefixTemplateFolder), withDestinationURL: outside)++ await #expect(throws: StepFailure.self) {+ _ = try await Uninstall.run(+ app: layout.app, innerPlist: layout.innerPlist, updateBlocks: [layout.updateBlock],+ legacyCompat: layout.legacyCompat, compatTools: layout.compatTools,+ directories: [layout.support, layout.caches], libraries: [library],+ repair: { _ in }, stop: { _ in false })+ }+ #expect(try String(contentsOf: sentinel, encoding: .utf8) == "keep")+ }}diff --git a/dylib/feats/compat_run.sh b/dylib/feats/compat_run.shindex 3ffa2ef..f7ad98a 100755--- a/dylib/feats/compat_run.sh+++ b/dylib/feats/compat_run.sh@@ -229,9 +229,7 @@ merge_user_dir() {src_dir="$src$rest"dst_dir="$dst$rest"if [ ! -r "$src_dir" ] || [ ! -x "$src_dir" ]; then failed=1; continue; fi- if [ -L "$dst_dir" ] && [ ! -e "$dst_dir" ]; then- rm -f "$dst_dir" 2>/dev/null || true- fi+ if [ -L "$dst_dir" ]; then failed=1; continue; fiprobe=$dst_dirthrough=while [ -n "$probe" ] && [ "$probe" != "$dst" ]; do@@ -243,7 +241,10 @@ merge_user_dir() {failed=1continuefi- if [ -n "$rest" ] && [ -e "$dst_dir" ]; then continue; fi+ if [ -e "$dst_dir" ] && [ ! -d "$dst_dir" ]; then+ failed=1+ continue+ fiif ! mkdir -p "$dst_dir" 2>/dev/null; then failed=1; continue; fifor entry in "$src_dir"/* "$src_dir"/.[!.]* "$src_dir"/..?*; do[ -e "$entry" ] || [ -L "$entry" ] || continue@@ -253,16 +254,21 @@ merge_user_dir() {continuefilanding="$dst_dir/$name"- if [ -e "$landing" ]; then continue; fi- if [ -L "$landing" ]; then rm -f "$landing" 2>/dev/null || true; fi+ if [ -e "$landing" ] || [ -L "$landing" ]; then+ if [ -L "$entry" ] && [ -L "$landing" ] \+ && [ "$(readlink "$entry")" = "$(readlink "$landing")" ]; then continue; fi+ if [ -f "$entry" ] && [ ! -L "$entry" ] && [ -f "$landing" ] \+ && [ ! -L "$landing" ] && cmp -s "$entry" "$landing"; then continue; fi+ echo "=== conflicting profile file: $landing ===" >> "$log" 2>&1 || true+ failed=1+ continue+ fiif [ -L "$entry" ]; then- if ! cp -Pp "$entry" "$landing" 2>/dev/null; then- rm -f "$landing" 2>/dev/null || true+ if ! cp -Ppn "$entry" "$landing" 2>/dev/null; thenfailed=1fielse- if ! cp -p "$entry" "$landing" 2>/dev/null; then- rm -f "$landing" 2>/dev/null || true+ if ! cp -pn "$entry" "$landing" 2>/dev/null || ! cmp -s "$entry" "$landing"; thenfailed=1fichmod u+w "$landing" 2>/dev/null || true@@ -275,6 +281,7 @@ merge_user_dir() {# Steam Cloud stuffmigrate_user_paths() {profile=$1+ migration_failed=0for pair in \"Local Settings/Application Data|AppData/Local|../AppData/Local" \"Application Data|AppData/Roaming|./AppData/Roaming" \@@ -291,6 +298,7 @@ migrate_user_paths() {if [ -L "$new" ]; thenecho "=== $new_rel is a link, rebuild the prefix for cloud saves ===" \>> "$log" 2>&1 || true+ migration_failed=1continuefiheld=@@ -305,19 +313,26 @@ migrate_user_paths() {if [ -n "$held" ]; thenecho "=== $held is a link, rebuild the prefix for cloud saves ===" \>> "$log" 2>&1 || true+ migration_failed=1continuefiif [ -e "$old" ] && [ ! -L "$old" ]; thenif ! merge_user_dir "$old" "$new"; thenecho "=== $old_rel did not merge into $new_rel, left in place ===" \>> "$log" 2>&1 || true+ migration_failed=1continuefi- rmdir "$old BACKUP" 2>/dev/null || true- if [ -e "$old BACKUP" ] || [ -L "$old BACKUP" ] \- || ! mv "$old" "$old BACKUP" 2>> "$log"; then+ backup="$old BACKUP"+ backup_number=2+ while [ -e "$backup" ] || [ -L "$backup" ]; do+ backup="$old BACKUP $backup_number"+ backup_number=$((backup_number + 1))+ done+ if ! mv "$old" "$backup" 2>> "$log"; thenecho "=== $old_rel could not be moved aside, cloud saves stay split ===" \>> "$log" 2>&1 || true+ migration_failed=1continuefifi@@ -333,6 +348,7 @@ migrate_user_paths() {|| truefidone+ [ "$migration_failed" -eq 0 ]}lay_out_proton_profile() {@@ -353,7 +369,7 @@ lay_out_proton_profile() {AppData/Local AppData/Roaming; domkdir -p "$profile/$folder" 2>/dev/null || truedone- migrate_user_paths "$profile"+ migrate_user_paths "$profile" || return 1if [ -L "$users/crossover" ] && [ ! -e "$users/crossover" ]; thenrm -f "$users/crossover" 2>/dev/null || truefi@@ -402,33 +418,56 @@ if [ -z "$np_build" ] || [ ! -d "$CX_ROOT/lib/wine" ]; thenfiecho "runner: build $np_build ($np_display) at $CX_ROOT" >> "$log" 2>&1 || true-# A fresh prefix is close to a gigabyte of files that wineboot copies out of the-# runner, and every game gets its own. Build one template per runner instead and seed-# each game from it. Within a single APFS volume "cp -c" clones, so the files share-# blocks and every prefix after the first costs almost nothing, as well as skipping-# the wineboot that building one needs. Seeding this way is safe because a wine prefix-# does not care where it lives: dosdevices holds "c: -> ../drive_c" and "z: -> /",-# which both survive the move, and the template is built through the same steps in the-# same order a game's prefix takes.-template_root="$np_support/templates"-# Keyed by the build this compatibility tool runs and by the unix arch. A build can be-# installed alongside others, and one runner serves both flavors, which populate a-# prefix from different PE sets, so both belong in the key.+# Each CrossOver build needs its own template.+# FEX builds need two, one for FEX/arm64 Wine and one for Rosetta/AMD64 Winerunner_id=""-if [ -n "$np_build" ]; then- runner_id="crossover-$np_build-${wine_unix##*/}"-fi-template="$template_root/$runner_id/pfx"+[ -z "$np_build" ] || runner_id="crossover-$np_build-${wine_unix##*/}"++in_template_env() {+ prefix="$1"+ shift+ env -i HOME="$HOME" USER="${USER:-}" LOGNAME="${LOGNAME:-}" TMPDIR="${TMPDIR:-/tmp}" \+ LANG="${LANG:-}" LC_ALL="${LC_ALL:-}" \+ PATH="$CX_ROOT/bin:/usr/bin:/bin:/usr/sbin:/sbin" CX_ROOT="$CX_ROOT" CX_HOME="$CX_HOME" \+ WINEDLLPATH="$CX_ROOT/lib/wine/x86_64-windows:$wine_unix" \+ WINELOADER="$WINELOADER" WINESERVER="$WINESERVER" WINEPREFIX="$prefix" "$@"+}-# A clone only shares blocks inside one volume, and a library can sit on a disk of its-# own, so the template belongs beside the prefixes it seeds. compatdata is where those-# prefixes already live, so it is always the right volume. The support directory stays-# as the fallback for a run with no library path to derive one from.-pick_template_dir() {- if [ -n "$STEAM_COMPAT_DATA_PATH" ]; then- template_root="$(dirname "$STEAM_COMPAT_DATA_PATH")/notproton-template"+seed_scratch=""+seed_building=0+# shellcheck disable=SC2329 # the traps in seed_prefix_from_template invoke this+abandon_seed() {+ if [ -n "$seed_scratch" ]; then+ if [ "$seed_building" -eq 1 ]; then+ in_template_env "$seed_scratch" "$WINESERVER" -k >/dev/null 2>&1 || true+ in_template_env "$seed_scratch" "$WINESERVER" -w >/dev/null 2>&1 || exit "$1"+ fi+ rm -rf "$seed_scratch" 2>/dev/null || truefi- template="$template_root/$runner_id/pfx"+ exit "$1"+}++prefix_server_dir() {+ [ -n "${1:-$WINEPREFIX}" ] || return 1+ ids=$(stat -f '%d-%i' "${1:-$WINEPREFIX}" 2>/dev/null) || return 1+ [ -n "$ids" ] || return 1+ printf '/tmp/.wine-%s/server-%s' "$(id -u)" \+ "$(printf '%s' "$ids" | awk -F- '{printf "%x-%x", $1, $2}')"+}++sweep_dead_seeds() {+ for leftover in "$@"; do+ [ -d "$leftover" ] && [ ! -L "$leftover" ] || continue+ case "${leftover##*.}" in ''|0|*[!0-9]*) continue ;; esac+ [ "$(stat -f %u "$leftover" 2>/dev/null)" = "$(id -u)" ] || continue+ kill -0 "${leftover##*.}" 2>/dev/null && continue+ stale_server=$(prefix_server_dir "$leftover") || continue+ if [ -d "$stale_server" ]; then+ stale_users=$(lsof -t +D "$stale_server" 2>&1 || true)+ [ -z "$stale_users" ] || continue+ fi+ rm -rf "$leftover" 2>/dev/null || true+ done}same_volume() {@@ -437,58 +476,248 @@ same_volume() {[ "$one" = "$two" ]}-# Built under a temporary name and moved into place, so a second game starting-# while this runs sees either no template or a finished one, never a partial tree.+# On non-APFS file systems, a full copy is made rather than a clone.+volume_clones() {+ device=$(stat -f %Sd "$1" 2>/dev/null) || return 1+ mount | grep -q "^/dev/$device on .* (apfs[,)]"+}++# Built in a temporary folder and renamed when the build finishes, so a broken template is never usedbuild_prefix_template() {- staging="$template_root/$runner_id/pfx.building.$$"- rm -rf "$staging" 2>/dev/null || true- mkdir -p "$staging" || return 1+ sweep_dead_seeds "$template_dir"/pfx.building.*+ seed_scratch="$template_dir/pfx.building.$$"+ mkdir "$seed_scratch" || return 1echo "=== building the prefix template for $runner_id ===" >> "$log" 2>&1 || true- # Through the same steps a game's prefix takes, in the same order. A bare wineboot- # leaves a real users/crossover directory behind, which lay_out_proton_profile- # refuses to convert, so a prefix seeded from such a template would lose the- # steamuser layout that cloud saves are written through.- lay_out_proton_profile "$staging"- WINEPREFIX="$staging" "$WINELOADER" wineboot --init >> "$log" 2>&1 || true- WINEPREFIX="$staging" "$WINESERVER" -w >> "$log" 2>&1 || true- if [ ! -f "$staging/system.reg" ]; then+ # The Steam user folders have to exist before wineboot runs, or wineboot will make its own+ # and cloud saves end up in the wrong place.+ lay_out_proton_profile "$seed_scratch" || return 1+ seed_building=1+ in_template_env "$seed_scratch" "$WINELOADER" wineboot --init >> "$log" 2>&1 &+ initialized=0+ wait $! || initialized=$?+ in_template_env "$seed_scratch" "$WINESERVER" -w >> "$log" 2>&1 &+ if ! wait $!; then+ echo "=== template server did not finish, leaving its staging folder intact ===" >> "$log" 2>&1 || true+ seed_scratch=""+ seed_building=0+ return 1+ fi+ seed_building=0+ if [ "$initialized" -ne 0 ] || [ ! -s "$seed_scratch/system.reg" ] \+ || [ ! -s "$seed_scratch/user.reg" ] || [ ! -s "$seed_scratch/userdef.reg" ]; thenecho "=== wineboot produced no template, this game gets its own prefix ===" \>> "$log" 2>&1 || true- rm -rf "$staging" 2>/dev/null || true+ rm -rf "$seed_scratch" 2>/dev/null || true+ seed_scratch=""return 1fi- if [ -f "$template/system.reg" ]; then- rm -rf "$staging" 2>/dev/null || true+ if [ ! -e "$template_dir/pfx" ] && [ ! -L "$template_dir/pfx" ]; then+ mv "$seed_scratch" "$template_dir/pfx" 2>/dev/null || true+ fi+ rm -rf "$seed_scratch" 2>/dev/null || true+ seed_scratch=""+ [ -f "$template_dir/pfx/system.reg" ]+}++install_seed_tree() (+ set -- ""+ while [ "$#" -gt 0 ]; do+ relative=$1+ shift+ source_dir="$seed_scratch$relative"+ target_dir="$WINEPREFIX$relative"+ [ -d "$target_dir" ] && [ ! -L "$target_dir" ] || return 1+ [ -r "$source_dir" ] && [ -x "$source_dir" ] || return 1+ for source in "$source_dir"/* "$source_dir"/.[!.]* "$source_dir"/..?*; do+ [ -e "$source" ] || [ -L "$source" ] || continue+ name=${source##*/}+ if [ -z "$relative" ]; then+ case "$name" in system.reg|.update-timestamp) continue ;; esac+ fi+ target="$target_dir/$name"+ if [ -d "$source" ] && [ ! -L "$source" ]; then+ if [ ! -e "$target" ] && [ ! -L "$target" ]; then+ mkdir "$target" || return 1+ fi+ [ -d "$target" ] && [ ! -L "$target" ] || return 1+ set -- "$@" "$relative/$name"+ elif [ -e "$target" ] || [ -L "$target" ]; then+ case "$relative/$name" in+ /drive_c/users/steamuser/*) continue ;;+ esac+ [ -L "$source" ] && [ -L "$target" ] \+ && [ "$(readlink "$source")" = "$(readlink "$target")" ] || return 1+ elif [ -L "$source" ]; then+ ln -sh "$(readlink "$source")" "$target" || return 1+ [ -L "$target" ] && [ "$(readlink "$source")" = "$(readlink "$target")" ] || return 1+ elif [ -f "$source" ]; then+ ln -h "$source" "$target" || return 1+ [ ! -L "$target" ] && [ "$source" -ef "$target" ] || return 1+ else+ return 1+ fi+ done+ done+ ln -h "$seed_scratch/system.reg" "$WINEPREFIX/system.reg" \+ && [ ! -L "$WINEPREFIX/system.reg" ] \+ && [ "$seed_scratch/system.reg" -ef "$WINEPREFIX/system.reg" ] || return 1+ if [ -f "$seed_scratch/.update-timestamp" ]; then+ ln -h "$seed_scratch/.update-timestamp" "$WINEPREFIX/.update-timestamp" || return 1+ fi+)++copy_template_into_prefix() {+ seed_scratch="$STEAM_COMPAT_DATA_PATH/pfx.seeding.$$"+ if ! mkdir "$seed_scratch" 2>/dev/null; then+ echo "=== prefix staging folder is occupied, skipping the template ===" >> "$log" 2>&1 || true+ seed_scratch=""+ return 0+ fi+ if same_volume "$template_dir" "$STEAM_COMPAT_DATA_PATH" && volume_clones "$template_dir"; then+ how="cloned this prefix from the $runner_id template"+ cp -c -R "$template_dir/pfx/." "$seed_scratch" 2>/dev/null && copied=0 || copied=$?else- mv "$staging" "$template" 2>/dev/null || rm -rf "$staging" 2>/dev/null || true+ how="copied this prefix from the $runner_id template, not a clone"+ cp -R "$template_dir/pfx/." "$seed_scratch" 2>/dev/null && copied=0 || copied=$?fi- [ -f "$template/system.reg" ]+ if [ "$copied" -eq 0 ] && prefix_is_bare && install_seed_tree; then+ echo "=== $how ===" >> "$log" 2>&1 || true+ else+ echo "=== could not seed from the template, wine builds this prefix itself ===" \+ >> "$log" 2>&1 || true+ fi+ rm -rf "$seed_scratch" 2>/dev/null || true+ seed_scratch=""}+prefix_is_bare() (+ set -- ""+ while [ "$#" -gt 0 ]; do+ relative=$1+ shift+ directory="$WINEPREFIX$relative"+ [ -d "$directory" ] && [ ! -L "$directory" ] \+ && [ -r "$directory" ] && [ -x "$directory" ] || return 1+ for node in "$directory"/* "$directory"/.[!.]* "$directory"/..?*; do+ [ -e "$node" ] || [ -L "$node" ] || continue+ part="$relative/${node##*/}"+ if [ -L "$node" ]; then+ case "$part:$(readlink "$node")" in+ /dosdevices/c::../drive_c|/dosdevices/z::/|/drive_c/users/crossover:steamuser|\+ '/drive_c/users/steamuser/My Documents:./Documents'|\+ '/drive_c/users/steamuser/Application Data:./AppData/Roaming'|\+ '/drive_c/users/steamuser/Local Settings/Application Data:../AppData/Local') continue ;;+ *) return 1 ;;+ esac+ fi+ case "$part" in+ /drive_c|/drive_c/users|/drive_c/users/steamuser|/dosdevices)+ [ -d "$node" ] || return 1 ;;+ /drive_c/users/steamuser/*)+ [ -d "$node" ] || [ -f "$node" ] || return 1 ;;+ *) return 1 ;;+ esac+ if [ -d "$node" ]; then set -- "$@" "$part"; fi+ done+ done+)++template_identity() (+ stat -f '%d:%i:%c' "$CX_ROOT" || return 1+ /usr/bin/shasum -a 256 < "$np_tool_dir/run" || return 1+ cd "$CX_ROOT" || return 1+ set -- "$WINELOADER" "$WINESERVER" share/wine/wine.inf+ for file in lib/wine/*-windows/ntdll.dll lib/wine/*-windows/lsteamclient.dll \+ lib/wine/*-unix/lsteamclient.so; do+ [ ! -f "$file" ] || set -- "$@" "$file"+ done+ /usr/bin/shasum -a 256 "$@"+)++# Each game's prefix is copied from one template (per runner) instead of running wineboot.+# On APFS the copy is a clone, so it takes almost no space.seed_prefix_from_template() {- if [ -z "$runner_id" ] || [ -f "$WINEPREFIX/system.reg" ]; then+ sweep_dead_seeds "$STEAM_COMPAT_DATA_PATH"/pfx.seeding.*+ [ -n "$runner_id" ] || return 0+ if ! prefix_is_bare; then+ [ -f "$WINEPREFIX/system.reg" ] \+ || echo "=== prefix is not empty or a standalone Steam profile, skipping the template ===" \+ >> "$log" 2>&1 || true+ return 0+ fi+ # Since a user can have more than one Steam library and libraries can be on different drives,+ # the template is stored alongside the Steam library to support APFS cloning.+ template_cache="$(dirname "$STEAM_COMPAT_DATA_PATH")/notproton-template"+ template_lock="$(dirname "$STEAM_COMPAT_DATA_PATH")/.notproton-template.lock"+ [ ! -L "$template_cache" ] && [ ! -L "$template_lock" ] || return 0+ [ ! -e "$template_lock" ] || [ -f "$template_lock" ] || return 0+ if ! { : >> "$template_lock"; } 2>/dev/null; then+ echo "=== prefix template cache is not writable, skipping the template ===" >> "$log" 2>&1 || true+ return 0+ fi+ exec 9>> "$template_lock"+ if ! /usr/bin/lockf -s -t 0 9; then+ exec 9>&-+ echo "=== prefix templates are busy, wine builds this prefix itself ===" >> "$log" 2>&1 || truereturn 0fi- pick_template_dir- if [ ! -f "$template/system.reg" ] && ! build_prefix_template; then+ template_dir="$template_cache/$runner_id"+ if [ -L "$template_cache" ] || [ -L "$template_dir" ] \+ || ! mkdir -p "$template_dir"; then exec 9>&-; return 0; fi+ if ! identity=$(template_identity); then exec 9>&-; return 0; fi+ trap 'abandon_seed 143' TERM+ trap 'abandon_seed 130' INT+ trap 'abandon_seed 129' HUP+ if [ -L "$template_dir/pfx" ] || [ -L "$template_dir/ready" ] \+ || { [ -e "$template_dir/pfx" ] && [ ! -d "$template_dir/pfx" ]; } \+ || { [ -e "$template_dir/ready" ] && [ ! -f "$template_dir/ready" ]; }; then+ exec 9>&-+ trap - TERM INT HUPreturn 0fi+ if [ ! -s "$template_dir/pfx/system.reg" ] \+ || [ "$(cat "$template_dir/ready" 2>/dev/null)" != "$identity" ]; then+ if ! rm -f "$template_dir/ready" || ! rm -rf "$template_dir/pfx"; then+ echo "=== could not invalidate the old prefix template, skipping it ===" >> "$log" 2>&1 || true+ exec 9>&-+ trap - TERM INT HUP+ return 0+ fi+ if build_prefix_template; then+ if ! printf '%s\n' "$identity" > "$template_dir/ready"; then+ rm -f "$template_dir/ready" 2>/dev/null || true+ fi+ fi+ fi+ if [ "$(cat "$template_dir/ready" 2>/dev/null)" = "$identity" ] \+ && [ -s "$template_dir/pfx/system.reg" ]; then+ copy_template_into_prefix+ fi+ exec 9>&-+ trap - TERM INT HUP+}- if same_volume "$template" "$WINEPREFIX" \- && cp -c -R "$template/." "$WINEPREFIX/" 2>/dev/null; then- echo "=== cloned this prefix from the $runner_id template ===" >> "$log" 2>&1 || true- elif cp -R "$template/." "$WINEPREFIX/" 2>/dev/null; then- echo "=== copied this prefix from the $runner_id template, not a clone ===" \- >> "$log" 2>&1 || true- else- echo "=== could not seed from the template, it will be built from scratch ===" \- >> "$log" 2>&1 || true+prepare_prefix_directory() {+ mkdir -p "$STEAM_COMPAT_DATA_PATH" || return 1+ prefix_lock="$STEAM_COMPAT_DATA_PATH/.notproton-prefix.lock"+ [ ! -L "$prefix_lock" ] && { [ ! -e "$prefix_lock" ] || [ -f "$prefix_lock" ]; } || return 1+ exec 8>> "$prefix_lock"+ if ! /usr/bin/lockf -s -t 0 8; then+ echo "=== another launch is preparing this prefix ===" >> "$log" 2>&1 || true+ return 1fi+ for interrupted in "$STEAM_COMPAT_DATA_PATH"/pfx.replaced.*; do+ [ -e "$interrupted" ] || [ -L "$interrupted" ] || continue+ echo "=== interrupted prefix replacement needs recovery: $interrupted ===" >> "$log" 2>&1 || true+ show_alert "Prefix recovery required" "An interrupted prefix replacement may hold saved games. Do not delete this prefix. Check its notproton-run.log for the recovery folder."+ exit 1+ done+ mkdir -p "$WINEPREFIX"}if [ -n "$STEAM_COMPAT_DATA_PATH" ]; thenexport WINEPREFIX="$STEAM_COMPAT_DATA_PATH/pfx"- mkdir -p "$WINEPREFIX"+ prepare_prefix_directorymsync_from=environmentif [ -z "$WINEMSYNC" ] && [ -r "$STEAM_COMPAT_DATA_PATH/notproton-msync" ]; thenWINEMSYNC=$(tr -d ' \t\n' \@@ -509,7 +738,10 @@ if [ -n "$STEAM_COMPAT_DATA_PATH" ]; thenstage_step="prefix seed"seed_prefix_from_templatestage_step="profile layout"- lay_out_proton_profile+ if ! lay_out_proton_profile; then+ show_alert "Saved-game folders need attention" "NotProton left the conflicting files in place. Open this prefix's notproton-run.log for details before trying again."+ exit 1+ fiecho "video: RetinaMode=${NOTPROTON_RETINA:-0}" >> "$log" 2>&1 || truestage_step="prefix settings"import_prefix_settings@@ -631,6 +863,7 @@ if [ -d "$bridge_src" ] && [ -n "$WINEPREFIX" ]; thenfiexport WINEDEBUG="${WINEDEBUG:-err+all,fixme-all}"+exec 8>&-trap - EXITecho "launch_args=$launch_args" >> "$log" 2>&1 || true[ -z "$launch_env" ] || echo "launch_env=$launch_env" >> "$log" 2>&1 || true@@ -848,14 +1081,6 @@ wine_helpers="$wine_helpers|wineboot\.exe|rundll32\.exe|tabtip\.exe"wine_helpers="$wine_helpers|vc_redist|vcredist|dxsetup\.exe|msiexec\.exe"wine_helpers="$wine_helpers|installinf|iscriptevaluator\.exe|regsvr32\.exe"wine_helpers="$wine_helpers|winedbg\.exe|unitycrashhandler"-prefix_server_dir() {- [ -n "$WINEPREFIX" ] || return 1- ids=$(stat -f '%d-%i' "$WINEPREFIX" 2>/dev/null) || return 1- [ -n "$ids" ] || return 1- printf '/tmp/.wine-%s/server-%s' "$(id -u)" \- "$(printf '%s' "$ids" | awk -F- '{printf "%x-%x", $1, $2}')"-}-prefix_game_running() {command -v lsof >/dev/null 2>&1 || return 1dir=$(prefix_server_dir) || return 1diff --git a/dylib/tests/seedcheck.sh b/dylib/tests/seedcheck.shnew file mode 100644index 0000000..368a135--- /dev/null+++ b/dylib/tests/seedcheck.sh@@ -0,0 +1,358 @@+#!/bin/sh+set -eu+SRC="${1:-$(dirname "$0")/../feats/compat_run.sh}"+work=$(mktemp -d "${TMPDIR:-/tmp}/np-seedcheck.XXXXXX")+test "$(stat -f %d "$work")" = "$(stat -f %d "${TMPDIR:-/tmp}")"+trap 'chmod -R u+rwX "$work"; rm -rf "$work"' EXIT+functions=$(awk '/^merge_user_dir\(\) \{/{take=1} /^import_prefix_settings\(\) \{/{take=0} take' "$SRC")+functions="$functions+$(awk '/^runner_id=""/{take=1} /^if \[ -n "\$STEAM_COMPAT_DATA_PATH" \]; then/{take=0} take' "$SRC")"+np_build=fixture+export np_build CX_ROOT CX_HOME wine_unix np_tool_dir WINELOADER WINESERVER+export STEAM_COMPAT_DATA_PATH WINEPREFIX template_dir log seed_scratch seed_building+CX_ROOT="$work/runner"+CX_HOME="$work/home"+wine_unix="$CX_ROOT/lib/wine/x86_64-unix"+np_tool_dir="$work/tool"+mkdir -p "$np_tool_dir" "$CX_ROOT/share/wine"+cp "$SRC" "$np_tool_dir/run"+printf inf > "$CX_ROOT/share/wine/wine.inf"+WINELOADER=/usr/bin/false+WINESERVER=/usr/bin/false+eval "$functions"+fails=0+check() {+ if "$@"; then printf ' ok %s\n' "$*"; else+ printf ' FAIL %s\n' "$*"+ fails=$((fails + 1))+ fi+}+fixture() {+ case_root=$(mktemp -d "$work/case.XXXXXX")+ STEAM_COMPAT_DATA_PATH="$case_root/game"+ WINEPREFIX="$STEAM_COMPAT_DATA_PATH/pfx"+ template_dir="$case_root/template"+ log="$case_root/log"+ seed_scratch=""+ seed_building=0+ mkdir -p "$WINEPREFIX" "$template_dir/pfx/drive_c/windows"+ printf reg > "$template_dir/pfx/system.reg"+ printf reg > "$template_dir/pfx/user.reg"+ printf reg > "$template_dir/pfx/userdef.reg"+ printf timestamp > "$template_dir/pfx/.update-timestamp"+ printf dll > "$template_dir/pfx/drive_c/windows/ntdll.dll"+ lay_out_proton_profile "$template_dir/pfx"+}++fixture+profile="$WINEPREFIX/drive_c/users/steamuser"+mkdir -p "$profile/Documents/Game" "$profile/My Documents/Game"+printf marker > "$profile/Documents/Game/steam_autocloud.vdf"+printf save > "$profile/My Documents/Game/slot.sav"+lay_out_proton_profile+check test -f "$profile/Documents/Game/slot.sav"+printf newer > "$profile/Documents/Game/slot.sav"+check lay_out_proton_profile+check test "$(cat "$profile/Documents/Game/slot.sav")" = newer++fixture+printf original > "$WINEPREFIX/drive_c"+check test "$(prefix_is_bare && echo unsafe || echo refused)" = refused++fixture+mkdir -p "$case_root/external" "$WINEPREFIX/drive_c/users"+ln -s "$case_root/external" "$WINEPREFIX/drive_c/users/steamuser"+check test "$(prefix_is_bare && echo unsafe || echo refused)" = refused++fixture+mkdir -p "$WINEPREFIX/drive_c/users/steamuser"+chmod 000 "$WINEPREFIX/drive_c/users/steamuser"+check test "$(prefix_is_bare && echo unsafe || echo refused)" = refused+chmod 700 "$WINEPREFIX/drive_c/users/steamuser"++fixture+mkdir -p "$WINEPREFIX/drive_c/users/steamuser/Documents/Game"+printf save > "$WINEPREFIX/drive_c/users/steamuser/Documents/Game/slot.sav"+before=$(stat -f %i "$WINEPREFIX")+copy_template_into_prefix+check test "$before" = "$(stat -f %i "$WINEPREFIX")"+check test -f "$WINEPREFIX/drive_c/users/steamuser/Documents/Game/slot.sav"+check test -f "$WINEPREFIX/.update-timestamp"+check test -f "$WINEPREFIX/system.reg"+check test ! "$template_dir/pfx/drive_c/windows/ntdll.dll" -ef "$WINEPREFIX/drive_c/windows/ntdll.dll"+printf changed > "$WINEPREFIX/drive_c/windows/ntdll.dll"+check test "$(cat "$template_dir/pfx/drive_c/windows/ntdll.dll")" = dll++fixture+mkdir -p "$WINEPREFIX/drive_c/users/steamuser/Documents/Game"+printf save > "$WINEPREFIX/drive_c/users/steamuser/Documents/Game/slot.sav"+interrupted_status=0+env functions="$functions" /bin/sh -c "+ eval \"\$functions\"+ ln() { command ln \"\$@\"; kill -KILL \"\$\$\"; return 1; }+ copy_template_into_prefix+" || interrupted_status=$?+check test "$interrupted_status" -eq 137+check test -f "$WINEPREFIX/drive_c/users/steamuser/Documents/Game/slot.sav"+check test ! -e "$WINEPREFIX/.update-timestamp"+check test ! -e "$WINEPREFIX/system.reg"+for abandoned in "$STEAM_COMPAT_DATA_PATH"/pfx.seeding.*; do+ check test -d "$abandoned"+ seed_prefix_from_template+ check test ! -e "$abandoned"+done++fixture+mkdir -p "$WINEPREFIX/drive_c/users/steamuser/Documents/Game"+printf save > "$WINEPREFIX/drive_c/users/steamuser/Documents/Game/slot.sav"+interrupted_status=0+env functions="$functions" /bin/sh -c "+ eval \"\$functions\"+ ln() { command ln \"\$@\"; kill -TERM \"\$\$\"; return 1; }+ trap 'abandon_seed 143' TERM+ copy_template_into_prefix+" || interrupted_status=$?+check test "$interrupted_status" -eq 143+check test -f "$WINEPREFIX/drive_c/users/steamuser/Documents/Game/slot.sav"+check test ! -e "$WINEPREFIX/.update-timestamp"++fixture+mkdir -p "$template_dir/pfx.building.$$"+printf partial > "$template_dir/pfx.building.$$/system.reg"+rm -rf "$template_dir/pfx"+check test "$(build_prefix_template && echo accepted || echo refused)" = refused+check test ! -e "$template_dir/pfx"++fixture+profile="$WINEPREFIX/drive_c/users/steamuser"+mkdir -p "$profile/Documents/Game" "$profile/My Documents/Game"+printf modern > "$profile/Documents/Game/slot.sav"+printf legacy > "$profile/My Documents/Game/slot.sav"+check test "$(lay_out_proton_profile && echo accepted || echo refused)" = refused+check test "$(cat "$profile/Documents/Game/slot.sav")" = modern+check test "$(cat "$profile/My Documents/Game/slot.sav")" = legacy+check test ! -L "$profile/My Documents"++fixture+profile="$WINEPREFIX/drive_c/users/steamuser"+mkdir -p "$profile/Documents/Game" "$profile/My Documents BACKUP/Game"+ln -s ./Documents "$profile/My Documents"+printf save > "$profile/My Documents BACKUP/Game/slot.sav"+lay_out_proton_profile+check test ! -e "$profile/Documents/Game/slot.sav"+check test -f "$profile/My Documents BACKUP/Game/slot.sav"++fixture+mkdir -p "$STEAM_COMPAT_DATA_PATH/pfx.seeding.$$"+printf stale > "$STEAM_COMPAT_DATA_PATH/pfx.seeding.$$/system.reg"+copy_template_into_prefix+check test ! -e "$WINEPREFIX/system.reg"+check test "$(cat "$STEAM_COMPAT_DATA_PATH/pfx.seeding.$$/system.reg")" = stale+check test ! -e "$STEAM_COMPAT_DATA_PATH/pfx.seeding.$$/pfx"++fixture+profile="$WINEPREFIX/drive_c/users/steamuser"+mkdir -p "$profile/Documents" "$profile/My Documents BACKUP/Game"+ln -s ./Documents "$profile/My Documents"+ln -s "$case_root/offline" "$profile/Documents/Game"+printf historical > "$profile/My Documents BACKUP/Game/slot.sav"+check lay_out_proton_profile+check test -L "$profile/Documents/Game"+check test "$(readlink "$profile/Documents/Game")" = "$case_root/offline"++fixture+mkdir -p "$WINEPREFIX/drive_c/users/steamuser/Documents/Game"+printf original > "$WINEPREFIX/drive_c/users/steamuser/Documents/Game/save"+(+ eval 'cp() { return 1; }'+ copy_template_into_prefix+)+check test "$(cat "$WINEPREFIX/drive_c/users/steamuser/Documents/Game/save")" = original+check test ! -e "$WINEPREFIX/system.reg"++fixture+mkdir -p "$WINEPREFIX/drive_c/users/steamuser/Documents/Game"+printf original > "$WINEPREFIX/drive_c/users/steamuser/Documents/Game/save"+(+ eval 'ln() { return 1; }'+ copy_template_into_prefix+)+check test "$(cat "$WINEPREFIX/drive_c/users/steamuser/Documents/Game/save")" = original+check test ! -e "$WINEPREFIX/system.reg"++fixture+mkdir -p "$WINEPREFIX/dosdevices"+ln -s ../drive_c "$WINEPREFIX/dosdevices/c:"+ln -s / "$WINEPREFIX/dosdevices/z:"+check prefix_is_bare+ln -s /outside "$WINEPREFIX/dosdevices/d:"+check test "$(prefix_is_bare && echo unsafe || echo refused)" = refused++fixture+mkdir -p "$WINEPREFIX/drive_c/users/steamuser"+mkfifo "$WINEPREFIX/drive_c/users/steamuser/fifo"+check test "$(prefix_is_bare && echo unsafe || echo refused)" = refused++fixture+export WINEDLLOVERRIDES=leak WINEARCH=win32 WINEMSYNC=1 SteamAppId=123+isolated=$(in_template_env "$WINEPREFIX" /usr/bin/env)+check test "$(printf '%s\n' "$isolated" | grep -Ec '^(WINEDLLOVERRIDES|WINEARCH|WINEMSYNC|SteamAppId)=' || true)" = 0++fixture+prepare_prefix_directory+check test "$(env functions="$functions" /bin/sh -c "+ exec 8>&- 9>&-+ eval \"\$functions\"+ prepare_prefix_directory && echo unlocked || echo locked+")" = locked+exec 8>&-+check prepare_prefix_directory+exec 8>&-++fixture+mkdir -p "$STEAM_COMPAT_DATA_PATH/pfx.replaced.123"+printf save > "$STEAM_COMPAT_DATA_PATH/pfx.replaced.123/save"+recovery_status=0+env functions="$functions" /bin/sh -ec "+ eval \"\$functions\"+ show_alert() { :; }+ prepare_prefix_directory+ : > \"\$STEAM_COMPAT_DATA_PATH/continued\"+" || recovery_status=$?+check test "$recovery_status" -eq 1+check test ! -e "$STEAM_COMPAT_DATA_PATH/continued"+check test -f "$STEAM_COMPAT_DATA_PATH/pfx.replaced.123/save"++fixture+identity_before=$(template_identity)+printf changed > "$CX_ROOT/share/wine/wine.inf"+check test "$identity_before" != "$(template_identity)"+identity_before=$(template_identity)+printf '\n' >> "$np_tool_dir/run"+check test "$identity_before" != "$(template_identity)"++export fake_initializer="in_template_env() (+ if [ \"\$3\" = wineboot ]; then+ mkdir -p \"\$1/drive_c/windows\"+ printf system > \"\$1/system.reg\"+ printf user > \"\$1/user.reg\"+ printf defaults > \"\$1/userdef.reg\"+ printf dll > \"\$1/drive_c/windows/ntdll.dll\"+ if [ -n \"\${ready_pipe:-}\" ]; then+ printf ready > \"\$ready_pipe\"+ read -r proceed < \"\$resume_pipe\"+ fi+ return \"\${fake_init_status:-0}\"+ fi+ return \"\${fake_wait_status:-0}\"+)"+eval "$fake_initializer"++fixture+rm -rf "$template_dir/pfx"+export fake_init_status=1+check test "$(build_prefix_template && echo accepted || echo refused)" = refused+check test ! -e "$template_dir/pfx"+fake_init_status=0+export fake_wait_status=1+check test "$(build_prefix_template && echo accepted || echo refused)" = refused+check test ! -e "$template_dir/pfx"+fake_wait_status=0++fixture+set -- dosbox.exe -conf '.\base\plutoniam.conf'+seed_prefix_from_template+check test -f "$WINEPREFIX/system.reg"+check test "$#" -eq 3+check test "$3" = '.\base\plutoniam.conf'+set --++fixture+seed_prefix_from_template+check test -f "$WINEPREFIX/system.reg"+check test -f "$template_dir/ready"+check test ! -e "$STEAM_COMPAT_DATA_PATH/pfx.replaced.$$"+first_prefix="$WINEPREFIX"+printf first-game > "$first_prefix/system.reg"+printf obsolete > "$template_dir/pfx/obsolete"+printf updated-inf > "$CX_ROOT/share/wine/wine.inf"+STEAM_COMPAT_DATA_PATH="$case_root/next-game"+WINEPREFIX="$STEAM_COMPAT_DATA_PATH/pfx"+mkdir -p "$WINEPREFIX"+seed_prefix_from_template+check test "$(cat "$first_prefix/system.reg")" = first-game+check test "$(cat "$WINEPREFIX/system.reg")" = system+check test ! -e "$template_dir/pfx/obsolete"+check test ! -e "$WINEPREFIX/obsolete"++fixture+export ready_pipe="$case_root/ready" resume_pipe="$case_root/resume"+mkfifo "$ready_pipe" "$resume_pipe"+first_prefix="$WINEPREFIX"+env functions="$functions" /bin/sh -ec "+ eval \"\$functions\"+ eval \"\$fake_initializer\"+ prepare_prefix_directory+ seed_prefix_from_template+" &+builder=$!+read -r ready < "$ready_pipe" || true+check test "$ready" = ready+STEAM_COMPAT_DATA_PATH="$case_root/second"+WINEPREFIX="$STEAM_COMPAT_DATA_PATH/pfx"+mkdir -p "$WINEPREFIX"+unset ready_pipe resume_pipe+seed_prefix_from_template+check test ! -e "$WINEPREFIX/system.reg"+printf 'continue\n' > "$case_root/resume"+wait "$builder"+check test -f "$first_prefix/system.reg"+seed_prefix_from_template+check test -f "$WINEPREFIX/system.reg"+check test "$(find "$template_dir/pfx" -name 'pfx.building.*' | wc -l | tr -d ' ')" = 0++fixture+chmod 500 "$case_root"+cache_status=0+env functions="$functions" /bin/sh -ec "+ eval \"\$functions\"+ eval \"\$fake_initializer\"+ seed_prefix_from_template+" || cache_status=$?+chmod 700 "$case_root"+check test "$cache_status" -eq 0+check test ! -e "$WINEPREFIX/system.reg"++fixture+: > "$case_root/.notproton-template.lock"+chmod 400 "$case_root/.notproton-template.lock"+cache_status=0+env functions="$functions" /bin/sh -ec "+ eval \"\$functions\"+ eval \"\$fake_initializer\"+ seed_prefix_from_template+" || cache_status=$?+chmod 600 "$case_root/.notproton-template.lock"+check test "$cache_status" -eq 0+check test ! -e "$WINEPREFIX/system.reg"++fixture+seed_prefix_from_template+printf stale > "$template_dir/ready"+chmod 500 "$template_dir"+STEAM_COMPAT_DATA_PATH="$case_root/second"+WINEPREFIX="$STEAM_COMPAT_DATA_PATH/pfx"+mkdir -p "$WINEPREFIX"+cache_status=0+env functions="$functions" /bin/sh -ec "+ eval \"\$functions\"+ eval \"\$fake_initializer\"+ seed_prefix_from_template+" || cache_status=$?+chmod 700 "$template_dir"+check test "$cache_status" -eq 0+check test ! -e "$WINEPREFIX/system.reg"+check test "$(cat "$template_dir/ready")" = stale++printf 'seedcheck: %s failures\n' "$fails"+test "$fails" -eq 0