Run Windows games on Apple Silicon — free, open source, with an open compatibility database that tells you what actually works.
Swift apple-silicond3dmetaldxmtdxvkfexgame-porting-toolkitgamingmac-gamingmacosmetalmoltenvksteamswiftuivkd3d-protonwhisky-alternativewindows-gameswinewine-wrapper
Stop a bottle for real: reap the prefix's processes the server leaves behind
Gauthier Piarrette4e58a03b5ee3
diff --git a/Sources/HighballKit/ProcessTable.swift b/Sources/HighballKit/ProcessTable.swiftnew file mode 100644index 0000000..cfefade--- /dev/null+++ b/Sources/HighballKit/ProcessTable.swift@@ -0,0 +1,88 @@+import Foundation+import Darwin++/// The processes of a Wine prefix, seen from outside, and how to end them.+///+/// `wineserver -k` asks the server to kill its clients, and the server does so by signalling+/// each client thread. A client parked in the Mac driver's Cocoa run loop does not always act+/// on that before the server is gone, and once the server is gone nobody kills it: on this+/// machine a bottle's `services.exe`, `svchost.exe`, `plugplay.exe`, `explorer.exe` and+/// `rpcss.exe` outlived a day of stops, still holding the prefix's server directory (issue #48).+/// A server that died abnormally leaves the same debris, and `wineserver -w` only waits for+/// the server.+///+/// Every Wine process of a prefix runs with its working directory inside the prefix (Highball+/// launches into `drive_c`, Wine's own system processes sit in `drive_c/windows`), and the+/// server's working directory is the prefix's server directory, named from the prefix path's+/// device and inode. Both come from `proc_pidinfo`, no `lsof` or `ps` parsing. The one gap is+/// a program started with a working directory outside the prefix (a Z: drive launch), which+/// the server itself still kills on a normal stop.+public enum ProcessTable {+ /// Wine's server directory for a prefix: `/tmp/.wine-<uid>/server-<dev>-<inode>`.+ public static func serverDirectory(forPrefix prefix: URL) -> URL? {+ var st = stat()+ guard stat(prefix.path, &st) == 0 else { return nil }+ return URL(fileURLWithPath: "/tmp/.wine-\(getuid())/server-\(String(UInt64(st.st_dev), radix: 16))-\(String(st.st_ino, radix: 16))")+ }++ /// All process ids visible to this user.+ static func allPIDs() -> [pid_t] {+ let bytes = proc_listpids(UInt32(PROC_ALL_PIDS), 0, nil, 0)+ guard bytes > 0 else { return [] }+ var buf = [pid_t](repeating: 0, count: Int(bytes) / MemoryLayout<pid_t>.size + 64)+ let got = proc_listpids(UInt32(PROC_ALL_PIDS), 0, &buf, Int32(buf.count * MemoryLayout<pid_t>.size))+ guard got > 0 else { return [] }+ return buf[0..<Int(got) / MemoryLayout<pid_t>.size].filter { $0 > 0 }+ }++ /// Working directory of a process, or nil when it cannot be read (not ours, gone).+ public static func workingDirectory(of pid: pid_t) -> String? {+ var info = proc_vnodepathinfo()+ let size = Int32(MemoryLayout<proc_vnodepathinfo>.size)+ guard proc_pidinfo(pid, PROC_PIDVNODEPATHINFO, 0, &info, size) == size else { return nil }+ return withUnsafePointer(to: &info.pvi_cdir.vip_path) {+ $0.withMemoryRebound(to: CChar.self, capacity: Int(MAXPATHLEN)) { String(cString: $0) }+ }+ }++ /// Resolves symlinks and private/tmp aliases the way the kernel reports them.+ static func canonical(_ path: String) -> String {+ URL(fileURLWithPath: path).resolvingSymlinksInPath().path+ }++ /// Whether a working directory belongs to the prefix: inside it, or its server directory.+ /// Pure, so it is tested without processes.+ public static func belongs(workingDirectory cwd: String, toPrefix prefix: String, serverDirectory: String?) -> Bool {+ let root = prefix.hasSuffix("/") ? prefix : prefix + "/"+ if cwd == prefix || cwd.hasPrefix(root) { return true }+ if let server = serverDirectory, cwd == server || cwd.hasPrefix(server + "/") { return true }+ return false+ }++ /// Process ids that belong to the prefix, never our own.+ public static func processes(ofPrefix prefix: URL) -> [pid_t] {+ let root = canonical(prefix.path)+ let server = serverDirectory(forPrefix: prefix).map { canonical($0.path) }+ let me = getpid()+ return allPIDs().filter { pid in+ guard pid != me, let cwd = workingDirectory(of: pid) else { return false }+ return belongs(workingDirectory: canonical(cwd), toPrefix: root, serverDirectory: server)+ }+ }++ /// Ends the given processes: SIGTERM, a grace period, then SIGKILL for whatever is left.+ /// Returns the ids that had to be killed the hard way.+ @discardableResult+ public static func terminate(_ pids: [pid_t], grace: TimeInterval = 2) -> [pid_t] {+ guard !pids.isEmpty else { return [] }+ for pid in pids { kill(pid, SIGTERM) }+ let deadline = Date().addingTimeInterval(grace)+ var alive = pids+ while !alive.isEmpty && Date() < deadline {+ usleep(100_000)+ alive = alive.filter { kill($0, 0) == 0 }+ }+ for pid in alive { kill(pid, SIGKILL) }+ return alive+ }+}diff --git a/Sources/HighballKit/WineRunner.swift b/Sources/HighballKit/WineRunner.swiftindex 70e7c3c..d2b85c3 100644--- a/Sources/HighballKit/WineRunner.swift+++ b/Sources/HighballKit/WineRunner.swift@@ -292,9 +292,28 @@ public struct WineRunner: Sendable {restoreMscoreeFirst: false)}- public func kill() throws {+ /// Stops the bottle: asks the server to kill its clients, waits for the server to go, then+ /// ends whatever is still attached to the prefix. Returns the process ids it had to end+ /// itself, which is normally none (see `ProcessTable` for why it is not always none).+ @discardableResult+ public func kill() throws -> [pid_t] {let env = try bottle.environment(engine: engine, renderer: .wined3d)- try Shell.run(engine.wineserverBinary.path, ["-k"], env: env)+ // `-k` fails when no server holds the lock, which is exactly the crashed-server case+ // the reaper below exists for, so its failure must not end the stop early.+ try? Shell.run(engine.wineserverBinary.path, ["-k"], env: env)+ // `wineserver -w` blocks until the server has released its lock. Bounded: a wedged+ // server must not turn a Stop into a hang, the reaper below covers that case too.+ let waiter = Process()+ waiter.executableURL = engine.wineserverBinary+ waiter.arguments = ["-w"]+ waiter.environment = ProcessInfo.processInfo.environment.merging(env) { $1 }+ try? waiter.run()+ let deadline = Date().addingTimeInterval(10)+ while waiter.isRunning && Date() < deadline { usleep(100_000) }+ if waiter.isRunning { waiter.terminate() }+ let leftovers = ProcessTable.processes(ofPrefix: bottle.url)+ ProcessTable.terminate(leftovers)+ return leftovers}// MARK: Registry helpersdiff --git a/Sources/highball/main.swift b/Sources/highball/main.swiftindex a221d88..4d82c74 100644--- a/Sources/highball/main.swift+++ b/Sources/highball/main.swift@@ -213,8 +213,8 @@ struct Bottle: AsyncParsableCommand {func run() async throws {let b = try BottleStore().get(name)let eng = try EngineStore().engine(b.settings.engineID)- try WineRunner(engine: eng, bottle: b).kill()- print("wineserver -k sent")+ let ended = try WineRunner(engine: eng, bottle: b).kill()+ print(ended.isEmpty ? "stopped \(name)" : "stopped \(name), ended \(ended.count) leftover process\(ended.count == 1 ? "" : "es") the server did not")}}}diff --git a/Tests/HighballKitTests/RegressionTests.swift b/Tests/HighballKitTests/RegressionTests.swiftindex 7b28771..af46254 100644--- a/Tests/HighballKitTests/RegressionTests.swift+++ b/Tests/HighballKitTests/RegressionTests.swift@@ -582,6 +582,53 @@ extension RegressionTests {XCTAssertEqual(try Data(contentsOf: wow64.appending(path: "mscoree.dll")), real)}+ // Stopping a bottle used to be `wineserver -k` and nothing else, and clients parked in the+ // Mac driver's run loop outlived it by a day (issue #48). The reaper identifies a prefix's+ // processes by working directory (inside the prefix, or the prefix's server directory) and+ // ends them. Tested on real processes: a sleep started inside a temp prefix is found and+ // terminated; one started elsewhere is left alone; our own process is never a candidate.+ func testProcessTableFindsAndEndsPrefixProcessesOnly() throws {+ let prefix = FileManager.default.temporaryDirectory.appending(path: "hb-prefix-\(UUID().uuidString)")+ let elsewhere = FileManager.default.temporaryDirectory.appending(path: "hb-elsewhere-\(UUID().uuidString)")+ for d in [prefix.appending(path: "drive_c/windows"), elsewhere] {+ try FileManager.default.createDirectory(at: d, withIntermediateDirectories: true)+ }+ defer { try? FileManager.default.removeItem(at: prefix); try? FileManager.default.removeItem(at: elsewhere) }+ func sleeper(in dir: URL) throws -> Process {+ let p = Process(); p.executableURL = URL(fileURLWithPath: "/bin/sleep"); p.arguments = ["60"]+ p.currentDirectoryURL = dir; try p.run(); return p+ }+ let inside = try sleeper(in: prefix.appending(path: "drive_c/windows"))+ let outside = try sleeper(in: elsewhere)+ defer { if outside.isRunning { outside.terminate() } }++ let found = ProcessTable.processes(ofPrefix: prefix)+ XCTAssertTrue(found.contains(inside.processIdentifier), "process working inside the prefix must be found")+ XCTAssertFalse(found.contains(outside.processIdentifier), "process working elsewhere must not")+ XCTAssertFalse(found.contains(getpid()), "never ourselves")++ let hard = ProcessTable.terminate(found)+ inside.waitUntilExit()+ XCTAssertFalse(inside.isRunning)+ XCTAssertTrue(hard.isEmpty, "sleep exits on SIGTERM, no SIGKILL needed: \(hard)")+ XCTAssertTrue(ProcessTable.processes(ofPrefix: prefix).isEmpty)+ XCTAssertTrue(outside.isRunning, "the unrelated process is untouched")++ // The pure matcher: prefix root, anything below it, and the server directory count;+ // a sibling directory that merely shares the name prefix does not.+ XCTAssertTrue(ProcessTable.belongs(workingDirectory: "/b/Gaming", toPrefix: "/b/Gaming", serverDirectory: nil))+ XCTAssertTrue(ProcessTable.belongs(workingDirectory: "/b/Gaming/drive_c", toPrefix: "/b/Gaming", serverDirectory: nil))+ XCTAssertFalse(ProcessTable.belongs(workingDirectory: "/b/Gaming2/drive_c", toPrefix: "/b/Gaming", serverDirectory: nil))+ XCTAssertTrue(ProcessTable.belongs(workingDirectory: "/tmp/.wine-501/server-1-2", toPrefix: "/b/Gaming", serverDirectory: "/tmp/.wine-501/server-1-2"))+ XCTAssertFalse(ProcessTable.belongs(workingDirectory: "/tmp/.wine-501/server-1-3", toPrefix: "/b/Gaming", serverDirectory: "/tmp/.wine-501/server-1-2"))++ // The server directory is derived from the prefix path's device and inode, the way+ // Wine names it.+ var st = stat(); XCTAssertEqual(stat(prefix.path, &st), 0)+ XCTAssertEqual(ProcessTable.serverDirectory(forPrefix: prefix)?.lastPathComponent,+ "server-\(String(UInt64(st.st_dev), radix: 16))-\(String(st.st_ino, radix: 16))")+ }+func testRendererSuggestionCyclesAndNeverSuggestsItself() {for r in Renderer.allCases {XCTAssertNotEqual(Renderer.suggestion(after: r), r)