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
Rosetta prep: every architecture path comes from the manifest, and an arm64 engine runs through Highball's signed Wine loader
Gauthier Piarrettef8c5e93059b5
diff --git a/Scripts/make-app.sh b/Scripts/make-app.shindex 7818207..6dc6966 100755--- a/Scripts/make-app.sh+++ b/Scripts/make-app.sh@@ -42,6 +42,52 @@ cp ".build/$CONFIG/HighballApp" "$APP/Contents/MacOS/Highball"SPARKLE_FW=$(ls -d .build/artifacts/sparkle/Sparkle/Sparkle.xcframework/macos-*/Sparkle.framework | head -1)cp -R "$SPARKLE_FW" "$APP/Contents/Frameworks/"+# Highball's signed Wine loader for the arm64 engines (WineLoaderHelper.swift, private/notes/+# rosetta-transition-plan.md): a helper bundle, app.highball.WineLoader, whose one binary is built+# from spike/wineloader. Apple's cross-architecture entitlement is restricted, so the bundle carries+# the Developer ID provisioning profile from private/signing (gitignored; the account holder made it+# in the developer portal on 2026-10-04, it expires 2044-09-29) and is signed with the entitlements+# below. An arm64 engine points its `wine` at this binary; nothing is ever copied into the bundle.+spike/wineloader/build.sh >/dev/null+HELPER="$APP/Contents/Helpers/WineLoader.app"+mkdir -p "$HELPER/Contents/MacOS"+cp .build/wineloader/wine "$HELPER/Contents/MacOS/wine"+cat > "$HELPER/Contents/Info.plist" <<PLIST+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0"><dict>+ <key>CFBundleIdentifier</key><string>app.highball.WineLoader</string>+ <key>CFBundleExecutable</key><string>wine</string>+ <key>CFBundleName</key><string>Highball Wine Loader</string>+ <key>CFBundlePackageType</key><string>APPL</string>+ <key>CFBundleShortVersionString</key><string>${VERSION}</string>+ <key>CFBundleVersion</key><string>${VERSION}</string>+ <key>LSBackgroundOnly</key><true/>+ <key>LSMinimumSystemVersion</key><string>26.5</string>+</dict></plist>+PLIST+LOADER_PROFILE=private/signing/Highball_Wine_Loader_Developer_ID.provisionprofile+if [ -f "$LOADER_PROFILE" ]; then+ cp "$LOADER_PROFILE" "$HELPER/Contents/embedded.provisionprofile"+elif [ "$CONFIG" = release ]; then+ echo "error: release build without $LOADER_PROFILE: the Wine loader would ship without the cross-architecture entitlement and no arm64 engine could start" >&2; exit 1+else+ echo "note: no $LOADER_PROFILE, the Wine loader helper is signed without its entitlements (debug build)"+fi+cat > dist/wineloader.entitlements <<'ENTITLEMENTS'+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0"><dict>+ <key>com.apple.developer.cross-architecture-support</key><true/>+ <key>com.apple.application-identifier</key><string>B95M7DARU4.app.highball.WineLoader</string>+ <key>com.apple.developer.team-identifier</key><string>B95M7DARU4</string>+ <key>com.apple.security.cs.allow-jit</key><true/>+ <key>com.apple.security.cs.disable-library-validation</key><true/>+ <key>com.apple.security.cs.allow-dyld-environment-variables</key><true/>+ <key>com.apple.security.cs.allow-unsigned-executable-memory</key><true/>+</dict></plist>+ENTITLEMENTS+# Resources: engine manifest, GPTK license, recipes and DB entries (from highball-db).cp spike/engine-manifest.json "$APP/Contents/Resources/engine-manifest.json"# Other engines the app can offer (previous ones for rollback, candidates for Advanced).@@ -156,6 +202,13 @@ if [ -n "$IDENTITY" ]; thenfor tool in "$APP"/Contents/Resources/tools/*; docase "$tool" in *.LICENSE) ;; *) codesign --force --options runtime --timestamp -s "$IDENTITY" "$tool" ;; esacdone+ # The Wine loader helper: its restricted entitlement is only honoured next to the profile, and a+ # binary claiming it without one is killed at exec, so without the profile it is signed plain.+ if [ -f "$HELPER/Contents/embedded.provisionprofile" ]; then+ codesign --force --options runtime --timestamp --entitlements dist/wineloader.entitlements -s "$IDENTITY" "$HELPER"+ else+ codesign --force --options runtime --timestamp -s "$IDENTITY" "$HELPER"+ ficodesign --force --options runtime --timestamp --entitlements dist/entitlements.plist -s "$IDENTITY" "$APP"elsecodesign --force --deep -s - "$APP"diff --git a/Sources/HighballApp/AppState.swift b/Sources/HighballApp/AppState.swiftindex 725400a..5aae15d 100644--- a/Sources/HighballApp/AppState.swift+++ b/Sources/HighballApp/AppState.swift@@ -83,8 +83,16 @@ final class AppState {// Onboardingvar rosettaInstalled = true- /// Rosetta stopped working on a Mac that already has an engine: the app asks to install it.+ /// Rosetta stopped working on a Mac that already has an engine that needs it: the app asks to install it.var rosettaMissing = false+ /// Get started will install Rosetta first: the Mac lacks it and the bundled engine needs it.+ var setupInstallsRosetta = false+ /// Whether the engine Get started installs is Intel code. Every engine shipped so far is; the+ /// arm64 line (private/notes/rosetta-transition-plan.md) says `requires: []` and skips Rosetta.+ static var bundledEngineRequiresRosetta: Bool {+ guard let url = bundledManifest, let m = try? EngineManifest.load(from: url) else { return true }+ return m.requiresRosetta+ }/// Installs Rosetta for an existing install, from the ask that rosettaMissing raises.func installRosettaNow() {@@ -786,8 +794,10 @@ final class AppState {needsOnboarding = engines.isEmpty && homeUnavailable == nil // an unplugged drive is not a first runrosettaInstalled = Self.rosettaWorks()// An existing install can lose Rosetta (two Macs did after the macOS 27 update, #101 and- // #106) and onboarding is the only place that used to install it. Offer it here instead.- rosettaMissing = !rosettaInstalled && !engines.isEmpty+ // #106) and onboarding is the only place that used to install it. Offer it here instead,+ // and only while an engine that needs it is installed: the arm64 line never does.+ rosettaMissing = !rosettaInstalled && engines.contains { $0.manifest.requiresRosetta }+ setupInstallsRosetta = !rosettaInstalled && Self.bundledEngineRequiresRosetta// Drop a selection whose bottle is gone, not merely a nil one: a delete that threw after// the bottle had in fact been removed (the losing side of a race) left the selection// pinned to a name nothing could resolve.@@ -1097,13 +1107,13 @@ final class AppState {done: DoneState(title: L("Highball is ready"), ctaTitle: nil, cta: nil),stop: .cancelTask(label: L("Stop"))) { [self] infunnel(.installStarted)- if !rosettaInstalled {+ let manifest = try EngineManifest.load(from: manifestURL)+ if manifest.requiresRosetta, !rosettaInstalled {await MainActor.run { self.stage = L("Installing Rosetta, Apple's compatibility layer") }try await Self.installRosetta()await MainActor.run { self.rosettaInstalled = true; self.appendLog("Rosetta installed") }}if engines.isEmpty {- let manifest = try EngineManifest.load(from: manifestURL)_ = try await engineStore.install(manifest, accepted: []) { name, received, total inTask { @MainActor in self.reportDownload(name, received: received, total: total) }}diff --git a/Sources/HighballApp/BottleView.swift b/Sources/HighballApp/BottleView.swiftindex 040758b..f4a76dd 100644--- a/Sources/HighballApp/BottleView.swift+++ b/Sources/HighballApp/BottleView.swift@@ -467,7 +467,10 @@ struct BottleSettingsSheet: View {Picker(L("Windows version"), selection: binding(\.windowsVersion)) {ForEach(WindowsVersion.allCases, id: \.self) { Text($0.rawValue).tag($0) }}- Toggle(L("Advertise AVX to games (Rosetta)"), isOn: binding(\.advertiseAVX))+ // Rosetta's switch; an arm64 engine runs x86 code through FEX and has none.+ if engine?.manifest.requiresRosetta ?? true {+ Toggle(L("Advertise AVX to games (Rosetta)"), isOn: binding(\.advertiseAVX))+ }Toggle(L("Use ⌘C / ⌘V inside Windows apps"), isOn: binding(\.commandIsControl))Text(L("Maps the Command keys to Ctrl, so Mac copy and paste work in Steam and games. Option becomes Alt so Alt-based bindings keep working. Off = Wine's default, where Command acts as Alt.")).font(.caption).foregroundStyle(.secondary)@@ -608,9 +611,9 @@ struct OnboardingView: View {.buttonStyle(.borderedProminent).controlSize(.large).tint(HB.amber).disabled(state.busy).padding(.top, 6)- Text(state.rosettaInstalled- ? L("Nothing to choose. The download takes a few minutes on most connections.")- : L("Nothing to choose. Highball installs Rosetta for you, then the download takes a few minutes."))+ Text(state.setupInstallsRosetta+ ? L("Nothing to choose. Highball installs Rosetta for you, then the download takes a few minutes.")+ : L("Nothing to choose. The download takes a few minutes on most connections.")).font(.callout).foregroundStyle(.secondary).multilineTextAlignment(.center).frame(maxWidth: 440)Spacer().frame(height: 30)Text(L("Highball downloads a Wine engine from public upstream releases. Nothing is hosted by us."))diff --git a/Sources/HighballKit/Bottle.swift b/Sources/HighballKit/Bottle.swiftindex 21393e5..a81ec5d 100644--- a/Sources/HighballKit/Bottle.swift+++ b/Sources/HighballKit/Bottle.swift@@ -52,7 +52,7 @@ public enum Renderer: String, Codable, CaseIterable, Sendable {overlays = shim.appending(path: "wine").path + ":" + overlays// The shim loads D3DMetal's d3d12.dll by this path: under its own name the real one// would come back as the shim (see InstalledEngine.timestampShimDir for the layout).- env["HB_D3D12_REAL"] = "Z:" + shim.appending(path: "wine/x86_64-windows/\(InstalledEngine.shimRealName).dll").path.replacingOccurrences(of: "/", with: "\\")+ env["HB_D3D12_REAL"] = "Z:" + shim.appending(path: "wine/\(engine.manifest.pe64LibDir)/\(InstalledEngine.shimRealName).dll").path.replacingOccurrences(of: "/", with: "\\")}// d3dmetal is 64-bit only, so 32-bit d3d10/11 falls through to dxmt instead of wined3dif let dxmt = engine.rendererDir("dxmt") { overlays += ":" + dxmt.appending(path: "wine").path }@@ -683,7 +683,8 @@ public struct Bottle: Sendable {case .msync: env["WINEMSYNC"] = "1"; env["WINEESYNC"] = "0"}if settings.metalHUD { env["MTL_HUD_ENABLED"] = "1" }- if settings.advertiseAVX { env["ROSETTA_ADVERTISE_AVX"] = "1" }+ // Rosetta's switch: on an arm64 engine x86 code runs through FEX and nothing reads it.+ if settings.advertiseAVX, engine.manifest.requiresRosetta { env["ROSETTA_ADVERTISE_AVX"] = "1" }// OpenGL games that ask for a 3.2+ core context without the forward-compatible bit get NULL// from Wine's Mac driver ("OS X only supports forward-compatible 3.2+ contexts") and crash// on the first GL call. macOS makes every 3.2+ core context forward-compatible anyway, so the@@ -817,13 +818,13 @@ public struct Bottle: Sendable {guard let dir = engine.rendererDir(selected.rawValue) else { return false }switch selected {case .dxmt:- return FileManager.default.fileExists(atPath: dir.appending(path: "wine/x86_64-windows/nvngx.dll").path)+ return FileManager.default.fileExists(atPath: dir.appending(path: "wine/\(engine.manifest.pe64LibDir)/nvngx.dll").path)case .d3dmetal:let windows = ["nvngx.dll", "nvngx-on-metalfx.dll"].contains {- FileManager.default.fileExists(atPath: dir.appending(path: "wine/x86_64-windows/\($0)").path)+ FileManager.default.fileExists(atPath: dir.appending(path: "wine/\(engine.manifest.pe64LibDir)/\($0)").path)}let unix = ["nvngx.so", "nvngx-on-metalfx.so"].contains {- FileManager.default.fileExists(atPath: dir.appending(path: "wine/x86_64-unix/\($0)").path)+ FileManager.default.fileExists(atPath: dir.appending(path: "wine/\(engine.manifest.unixLibDir)/\($0)").path)}return windows && unixdefault:@@ -834,10 +835,11 @@ public struct Bottle: Sendable {private func needsDLSSBridgeAliases(engine: InstalledEngine) -> Bool {guard let dir = engine.rendererDir("d3dmetal") else { return false }let wine = dir.appending(path: "wine")- let needsWindowsAlias = !FileManager.default.fileExists(atPath: wine.appending(path: "x86_64-windows/nvngx.dll").path)- && FileManager.default.fileExists(atPath: wine.appending(path: "x86_64-windows/nvngx-on-metalfx.dll").path)- let needsUnixAlias = !FileManager.default.fileExists(atPath: wine.appending(path: "x86_64-unix/nvngx.so").path)- && FileManager.default.fileExists(atPath: wine.appending(path: "x86_64-unix/nvngx-on-metalfx.so").path)+ let pe = engine.manifest.pe64LibDir, unix = engine.manifest.unixLibDir+ let needsWindowsAlias = !FileManager.default.fileExists(atPath: wine.appending(path: "\(pe)/nvngx.dll").path)+ && FileManager.default.fileExists(atPath: wine.appending(path: "\(pe)/nvngx-on-metalfx.dll").path)+ let needsUnixAlias = !FileManager.default.fileExists(atPath: wine.appending(path: "\(unix)/nvngx.so").path)+ && FileManager.default.fileExists(atPath: wine.appending(path: "\(unix)/nvngx-on-metalfx.so").path)return needsWindowsAlias || needsUnixAlias}@@ -945,9 +947,10 @@ public struct Bottle: Sendable {guard settings.dlssEnabled, renderer == .d3dmetal,supportsDLSS(engine: engine, renderer: renderer),let dir = engine.rendererDir("d3dmetal") else { return }+ let pe = engine.manifest.pe64LibDir, unix = engine.manifest.unixLibDirlet sources = [- (dir.appending(path: "wine/x86_64-windows/nvngx.dll"), dir.appending(path: "wine/x86_64-windows/nvngx-on-metalfx.dll"), "x86_64-windows/nvngx.dll"),- (dir.appending(path: "wine/x86_64-unix/nvngx.so"), dir.appending(path: "wine/x86_64-unix/nvngx-on-metalfx.so"), "x86_64-unix/nvngx.so"),+ (dir.appending(path: "wine/\(pe)/nvngx.dll"), dir.appending(path: "wine/\(pe)/nvngx-on-metalfx.dll"), "\(pe)/nvngx.dll"),+ (dir.appending(path: "wine/\(unix)/nvngx.so"), dir.appending(path: "wine/\(unix)/nvngx-on-metalfx.so"), "\(unix)/nvngx.so"),]let fm = FileManager.defaultlet wineDir = url.appending(path: ".highball-dlss/wine", directoryHint: .isDirectory)diff --git a/Sources/HighballKit/EngineIntegrity.swift b/Sources/HighballKit/EngineIntegrity.swiftindex 31e9af0..15945d6 100644--- a/Sources/HighballKit/EngineIntegrity.swift+++ b/Sources/HighballKit/EngineIntegrity.swift@@ -25,9 +25,10 @@ public enum EngineIntegrity {"comctl32.dll", "comdlg32.dll", "winmm.dll", "win32u.dll", "sechost.dll", "crypt32.dll",]- /// Where an engine keeps its builtins, 64-bit half first.- public static func libraryDirectories(engineRoot: URL) -> [URL] {- ["engine/lib/wine/x86_64-windows", "engine/lib/wine/i386-windows"]+ /// Where an engine keeps its builtins, 64-bit half first. The 64-bit directory follows the+ /// engine's architecture (`aarch64-windows` on the arm64 line).+ public static func libraryDirectories(engineRoot: URL, arch: String = "x86_64") -> [URL] {+ ["engine/lib/wine/\(EngineManifest.pe64LibDir(arch: arch))", "engine/lib/wine/\(EngineManifest.pe32LibDir)"].map { engineRoot.appending(path: $0, directoryHint: .isDirectory) }}@@ -46,8 +47,8 @@ public enum EngineIntegrity {/// Of the DLLs Wine could not find, its own that are absent from this engine on disk./// Empty when the engine is intact, which is the normal answer.- public static func gone(fromEngineAt root: URL, notFound: [String]) -> [String] {- let dirs = libraryDirectories(engineRoot: root)+ public static func gone(fromEngineAt root: URL, notFound: [String], arch: String = "x86_64") -> [String] {+ let dirs = libraryDirectories(engineRoot: root, arch: arch)return notFound.filter { name inbuiltins.contains(name) && !dirs.contains { FileManager.default.fileExists(atPath: $0.appending(path: name).path) }}diff --git a/Sources/HighballKit/EngineStore.swift b/Sources/HighballKit/EngineStore.swiftindex 903907a..a2a3cf1 100644--- a/Sources/HighballKit/EngineStore.swift+++ b/Sources/HighballKit/EngineStore.swift@@ -48,6 +48,7 @@ public struct EngineStore: Sendable {let manifest = dir.appending(path: "manifest.json")guard let m = try? EngineManifest.load(from: manifest) else { return nil }try? linkRuntime(dir) // heals broken runtime links from pre-0.7.9 installs+ try? linkSignedLoader(dir, manifest: m) // an app that moved repoints its arm64 enginesreturn InstalledEngine(manifest: m, root: dir)}.sorted { $0.manifest.id < $1.manifest.id }}@@ -184,6 +185,7 @@ public struct EngineStore: Sendable {let root = paths.engine(id)let m = try EngineManifest.load(from: root.appending(path: "manifest.json"))try? linkRuntime(root) // heals broken runtime links from pre-0.7.9 installs+ try? linkSignedLoader(root, manifest: m)return InstalledEngine(manifest: m, root: root)}@@ -217,6 +219,11 @@ public struct EngineStore: Sendable {progress: DownloadProgress? = nil) async throws -> InstalledEngine {try paths.ensure()+ // An arm64 engine runs through the signed loader in Highball.app and nothing else, so+ // without it the download would only end in an engine that cannot start (WineLoaderHelper).+ if manifest.isNativeARM64, WineLoaderHelper.locate() == nil {+ throw HighballError.failed("The \(manifest.displayName) engine runs through Highball's signed Wine loader, which comes with Highball.app. Install Highball in Applications (or point \(WineLoaderHelper.environmentKey) at its WineLoader.app) and try again.")+ }let root = paths.engine(manifest.id)let staging = paths.engines.appending(path: ".\(manifest.id).partial", directoryHint: .isDirectory)try? FileManager.default.removeItem(at: staging)@@ -244,6 +251,7 @@ public struct EngineStore: Sendable {saved.acceptedLicenses = Self.acceptances(requested: accepted, installed: (try? installedEngines()) ?? [])try saved.save(to: staging.appending(path: "manifest.json"))try linkRuntime(staging)+ try linkSignedLoader(staging, manifest: saved)// The unpacked tree must be a whole engine before it replaces anything: an archive that// unpacked short (a full disk, a file the archive lacks) used to install all the same and// fail every launch afterwards (highball#118). The archive was checksummed, so the fault@@ -471,6 +479,32 @@ public struct EngineStore: Sendable {link("GStreamer.framework", to: "../../frameworks/GStreamer.framework")}+ /// Points an arm64 engine's `wine` at Highball's signed loader (WineLoaderHelper). Wine's ntdll+ /// starts every child process through `<directory of ntdll.so>/wine`, so that file becomes a+ /// symlink to the helper and `bin/wine` a relative link to it, the way Wine installs its own;+ /// the engine's loader, built unsigned by CI, is set aside once as `wine.unsigned`. Redone on+ /// every read of the engine, like linkRuntime, so an app that moved, or was updated (the helper+ /// is the app's), heals its engines on the next launch. Nothing happens for an Intel engine, or+ /// when no helper is on this Mac (the CLI without the app; `missingFiles` then says so).+ func linkSignedLoader(_ root: URL, manifest: EngineManifest, helper: URL? = WineLoaderHelper.locate()) throws {+ guard manifest.isNativeARM64, let helper else { return }+ let fm = FileManager.default+ let unixDir = root.appending(path: "engine/lib/wine/\(manifest.unixLibDir)", directoryHint: .isDirectory)+ for (link, target) in [(unixDir.appending(path: "wine"), helper.path),+ (root.appending(path: "engine/bin/wine"), "../lib/wine/\(manifest.unixLibDir)/wine")] {+ if let existing = try? fm.destinationOfSymbolicLink(atPath: link.path) {+ if existing == target { continue }+ try fm.removeItem(at: link) // a stale link, dangling or to an old app location+ } else if fm.fileExists(atPath: link.path) {+ let aside = link.appendingPathExtension("unsigned")+ try? fm.removeItem(at: aside)+ try fm.moveItem(at: link, to: aside) // the engine's own loader: kept, never used+ }+ try fm.createDirectory(at: link.deletingLastPathComponent(), withIntermediateDirectories: true)+ try fm.createSymbolicLink(atPath: link.path, withDestinationPath: target)+ }+ }+func stripQuarantine(_ url: URL) throws {try? Shell.run("/usr/bin/xattr", ["-dr", "com.apple.quarantine", url.path])}@@ -515,16 +549,37 @@ public struct InstalledEngine: Sendable {/// halves and the Unix side of ntdll. An engine missing any of them fails every launch/// with "could not load kernel32.dll" (highball#118, an unpack that stopped early), so an/// install refuses to finish without them and the app reinstalls its own when they are gone.- public static let requiredFiles = [- "engine/bin/wine", "engine/bin/wineserver",- "engine/lib/wine/x86_64-windows/kernel32.dll", "engine/lib/wine/x86_64-windows/ntdll.dll",- "engine/lib/wine/i386-windows/kernel32.dll", "engine/lib/wine/x86_64-unix/ntdll.so",- ]+ public static let requiredFiles = requiredFiles(for: EngineManifest(id: "", displayName: "", arch: "x86_64", minMacOS: "", components: [:]))+ /// The same list for an engine of either architecture. An arm64 engine also needs FEX, in the+ /// two DLLs Wine loads under its emulator names and the Unix helper each of them loads by name:+ /// without them it runs ARM64 Windows programs only, which no game is.+ public static func requiredFiles(for manifest: EngineManifest) -> [String] {+ var files = ["engine/bin/wine", "engine/bin/wineserver",+ "engine/lib/wine/\(manifest.pe64LibDir)/kernel32.dll", "engine/lib/wine/\(manifest.pe64LibDir)/ntdll.dll",+ "engine/lib/wine/\(EngineManifest.pe32LibDir)/kernel32.dll", "engine/lib/wine/\(manifest.unixLibDir)/ntdll.so"]+ if manifest.isNativeARM64 {+ files += ["engine/lib/wine/\(manifest.pe64LibDir)/xtajit64.dll", "engine/lib/wine/\(manifest.pe64LibDir)/xtajit.dll",+ "engine/lib/wine/\(manifest.unixLibDir)/libarm64ecfex.so", "engine/lib/wine/\(manifest.unixLibDir)/libwow64fex.so"]+ }+ return files+ }+ /// How the loader shows up in `missingFiles` when an arm64 engine's `wine` is not Highball's+ /// signed helper: its own loader is there, so the file check alone would pass.+ public static let signedLoaderName = "engine/bin/wine (Highball's signed Wine loader)"/// Which of `requiredFiles` are absent, relative to the engine's root.public var missingFiles: [String] {- Self.requiredFiles.filter { !FileManager.default.fileExists(atPath: root.appending(path: $0).path) }+ var missing = Self.requiredFiles(for: manifest).filter { !FileManager.default.fileExists(atPath: root.appending(path: $0).path) }+ if manifest.isNativeARM64, !usesSignedLoader { missing.append(Self.signedLoaderName) }+ return missing}public var isComplete: Bool { missingFiles.isEmpty }+ /// Whether this engine's Unix-side `wine`, the path Wine's ntdll starts child processes+ /// through, is a link to Highball's signed loader (EngineStore.linkSignedLoader).+ public var usesSignedLoader: Bool {+ let link = engineDir.appending(path: "lib/wine/\(manifest.unixLibDir)/wine")+ guard let dest = try? FileManager.default.destinationOfSymbolicLink(atPath: link.path) else { return false }+ return WineLoaderHelper.isHelperPath(dest) && FileManager.default.isExecutableFile(atPath: dest)+ }/// resolves the shim directory and repairs the real-driver link; it touches the disk, so the app caches it per enginepublic func resolveLsfgShimDir() -> URL? {@@ -589,10 +644,10 @@ public struct InstalledEngine: Sendable {public func timestampShimDir(d3dmetal: URL) -> URL? {guard let shim = rendererDir("d3dmetal-tsshim") else { return nil }let fm = FileManager.default- let realPE = d3dmetal.appending(path: "wine/x86_64-windows/d3d12.dll")- let realSO = d3dmetal.appending(path: "wine/x86_64-unix/d3d12.so")- let pe = shim.appending(path: "wine/x86_64-windows/\(Self.shimRealName).dll")- let so = shim.appending(path: "wine/x86_64-unix/\(Self.shimRealName).so")+ let realPE = d3dmetal.appending(path: "wine/\(manifest.pe64LibDir)/d3d12.dll")+ let realSO = d3dmetal.appending(path: "wine/\(manifest.unixLibDir)/d3d12.so")+ let pe = shim.appending(path: "wine/\(manifest.pe64LibDir)/\(Self.shimRealName).dll")+ let so = shim.appending(path: "wine/\(manifest.unixLibDir)/\(Self.shimRealName).so")do {let realAttrs = try fm.attributesOfItem(atPath: realPE.path)let current = (try? fm.attributesOfItem(atPath: pe.path))@@ -610,7 +665,7 @@ public struct InstalledEngine: Sendable {try fm.createSymbolicLink(at: so, withDestinationURL: realSO)}// The 0.9.0 layout (a hard link under this name) is the one that collided.- for stale in ["wine/x86_64-windows/d3d12_d3dmetal.dll", "wine/x86_64-unix/d3d12_d3dmetal.so"] {+ for stale in ["wine/\(manifest.pe64LibDir)/d3d12_d3dmetal.dll", "wine/\(manifest.unixLibDir)/d3d12_d3dmetal.so"] {try? fm.removeItem(at: shim.appending(path: stale))}return shimdiff --git a/Sources/HighballKit/Manifest.swift b/Sources/HighballKit/Manifest.swiftindex edb137a..2ef0959 100644--- a/Sources/HighballKit/Manifest.swift+++ b/Sources/HighballKit/Manifest.swift@@ -63,6 +63,27 @@ public struct EngineManifest: Codable, Sendable, Identifiable {}public var requires: [String]?public var notes: [String]?++ // MARK: Architecture++ /// The Unix side of this engine is native arm64 code: Wine's own builtins are ARM64X images in+ /// `aarch64-windows`, x86 and x86-64 programs run through FEX inside Wine, and the loader is+ /// Highball's signed helper (WineLoaderHelper) rather than the engine's own binary. Every other+ /// engine is Intel code that runs under Rosetta (private/notes/rosetta-transition-plan.md).+ public var isNativeARM64: Bool { arch == "arm64" }+ /// Whether the engine needs Rosetta at all. The Intel engines say so in `requires`; an engine+ /// that does not is installed, offered and run without a word about Rosetta.+ public var requiresRosetta: Bool { (requires ?? []).contains("rosetta2") }+ /// The directory under `lib/wine` of the Unix halves of Wine's builtins (`ntdll.so`, `winemac.so`).+ public var unixLibDir: String { Self.unixLibDir(arch: arch) }+ /// The directory under `lib/wine` of the 64-bit PE builtins and of a renderer overlay's 64-bit+ /// DLLs: ARM64X images on an arm64 engine, which carry the ARM64EC code x86-64 programs call+ /// into, x86-64 images otherwise.+ public var pe64LibDir: String { Self.pe64LibDir(arch: arch) }+ /// The 32-bit PE builtins, the same directory on both: 32-bit programs run through WoW64.+ public static let pe32LibDir = "i386-windows"+ public static func unixLibDir(arch: String) -> String { arch == "arm64" ? "aarch64-unix" : "x86_64-unix" }+ public static func pe64LibDir(arch: String) -> String { arch == "arm64" ? "aarch64-windows" : "x86_64-windows" }/// Which Direct3D 9 a game gets in the automatic modes (DXMT, D3DMetal): nil attaches DXVK's/// d3d9 (the d9vk overlay) beside the Metal backend, "wined3d" leaves Direct3D 9 to Wine's/// own, because on this engine that is the fast path. Measured on the Wine 11 tree: Half-Lifediff --git a/Sources/HighballKit/WineLoaderHelper.swift b/Sources/HighballKit/WineLoaderHelper.swiftnew file mode 100644index 0000000..b760428--- /dev/null+++ b/Sources/HighballKit/WineLoaderHelper.swift@@ -0,0 +1,48 @@+import Foundation++/// Highball's signed Wine loader for arm64 engines.+///+/// A Wine that runs x86 programs natively on Apple silicon needs Apple's cross-architecture+/// entitlement on the loader process: it is what lets the process keep the x18 register for the+/// Windows thread block, map the low 4 GB, and set total store ordering per thread (macOS 26.5+/// and later, private/notes/rosetta-transition-plan.md). The entitlement is granted to a signed app+/// bundle carrying a provisioning profile, so the loader cannot be a file inside a downloaded+/// engine. It ships inside Highball.app as Contents/Helpers/WineLoader.app (bundle id+/// app.highball.WineLoader, built by Scripts/make-app.sh from spike/wineloader), and every arm64+/// engine's `wine` becomes a symlink to it (EngineStore.linkSignedLoader). Wine's ntdll starts child+/// processes through `<directory of ntdll.so>/wine`, and the helper looks for ntdll.so beside the+/// path it was started by, so one sealed bundle serves every engine and nothing is copied into it.+/// Measured on an M4, macOS 27.0, 2026-10-04.+public enum WineLoaderHelper {+ public static let bundleName = "WineLoader.app"+ public static let bundleIdentifier = "app.highball.WineLoader"+ /// Path to the helper bundle, or to its `wine` binary, for the CLI and the test harness, which+ /// run outside Highball.app.+ public static let environmentKey = "HIGHBALL_WINELOADER"++ /// Where a bundle keeps the helper.+ public static func binary(inAppBundle app: URL) -> URL {+ app.appending(path: "Contents/Helpers/\(bundleName)/Contents/MacOS/wine")+ }++ /// The helper's `wine` binary: named in the environment, then inside this app's own bundle,+ /// then inside the installed Highball.app. nil when no copy is on this Mac, which is the CLI on+ /// a Mac without the app.+ public static func locate(environment: [String: String] = ProcessInfo.processInfo.environment,+ appBundle: URL? = Bundle.main.bundleURL,+ applications: URL = URL(fileURLWithPath: "/Applications/Highball.app")) -> URL? {+ var candidates: [URL] = []+ if let p = environment[environmentKey], !p.isEmpty {+ let url = URL(fileURLWithPath: p)+ candidates.append(url.pathExtension == "app" ? url.appending(path: "Contents/MacOS/wine") : url)+ }+ if let appBundle, appBundle.pathExtension == "app" { candidates.append(binary(inAppBundle: appBundle)) }+ candidates.append(binary(inAppBundle: applications))+ return candidates.first { FileManager.default.isExecutableFile(atPath: $0.path) }+ }++ /// Whether a symlink destination is the helper's binary.+ public static func isHelperPath(_ path: String) -> Bool {+ path.hasSuffix("/\(bundleName)/Contents/MacOS/wine")+ }+}diff --git a/Sources/HighballKit/WineRunner.swift b/Sources/HighballKit/WineRunner.swiftindex 07012e1..75621a3 100644--- a/Sources/HighballKit/WineRunner.swift+++ b/Sources/HighballKit/WineRunner.swift@@ -172,7 +172,13 @@ public struct WineRunner: Sendable {// EBADARCH: macOS will not run Intel code, so Rosetta is missing or broken. Say that,// not "Bad CPU type in executable" (issue #101).if (error as NSError).code == 86 || error.localizedDescription.contains("Bad CPU type") {- throw HighballError.failed("Rosetta, Apple's layer for Intel programs, is not working on this Mac, and Highball's Wine engine needs it. In Terminal run: softwareupdate --install-rosetta --agree-to-license, then try again.")+ // Only an Intel engine can mean that. An arm64 engine's loader is a link to the+ // signed helper in Highball.app (WineLoaderHelper), and this error there means the+ // link points at something that is not a Mac program any more.+ if engine.manifest.requiresRosetta {+ throw HighballError.failed("Rosetta, Apple's layer for Intel programs, is not working on this Mac, and Highball's Wine engine needs it. In Terminal run: softwareupdate --install-rosetta --agree-to-license, then try again.")+ }+ throw HighballError.failed("macOS refused to start the Wine loader of engine \(engine.id) (\(engine.wineBinary.path)). Quit and reopen Highball, which repairs the link to its loader, then try again.")}throw error}@@ -245,7 +251,8 @@ public struct WineRunner: Sendable {// again. Say so here, once, rather than leaving each caller to offer "try again with a// fresh copy" for a download that was never the problem (highball#151, #153).let gone = EngineIntegrity.gone(fromEngineAt: engine.root,- notFound: EngineIntegrity.librariesNotFound(in: importFailures.lines.joined(separator: "\n")))+ notFound: EngineIntegrity.librariesNotFound(in: importFailures.lines.joined(separator: "\n")),+ arch: engine.manifest.arch)if status != 0, !gone.isEmpty {throw HighballError.engineDamaged(engine: engine.id, files: gone)}@@ -349,8 +356,8 @@ public struct WineRunner: Sendable {/// The bottle's two `mscoree.dll` copies and the engine builtin each would be on a Wine-made/// prefix, as (bottle file, engine file) pairs.static func mscoreePairs(engine: InstalledEngine, bottle: Bottle) -> [(URL, URL)] {- [("windows/system32/mscoree.dll", "lib/wine/x86_64-windows/mscoree.dll"),- ("windows/syswow64/mscoree.dll", "lib/wine/i386-windows/mscoree.dll")].map {+ [("windows/system32/mscoree.dll", "lib/wine/\(engine.manifest.pe64LibDir)/mscoree.dll"),+ ("windows/syswow64/mscoree.dll", "lib/wine/\(EngineManifest.pe32LibDir)/mscoree.dll")].map {(bottle.driveC.appending(path: $0.0), engine.engineDir.appending(path: $0.1))}}diff --git a/Tests/HighballKitTests/EngineArchTests.swift b/Tests/HighballKitTests/EngineArchTests.swiftnew file mode 100644index 0000000..a246069--- /dev/null+++ b/Tests/HighballKitTests/EngineArchTests.swift@@ -0,0 +1,141 @@+import XCTest+@testable import HighballKit++/// The arm64 engine line (private/notes/rosetta-transition-plan.md, for macOS 28's end of Rosetta):+/// the app derives every architecture-specific path from the manifest, needs Rosetta only for the+/// engines that say so, and runs an arm64 engine through the signed loader helper in Highball.app,+/// never through the engine's own loader. Nothing here runs Wine; the layouts are what the M4 spike+/// of 2026-10-04 measured working.+final class EngineArchTests: XCTestCase {+ private func manifest(_ arch: String, requires: [String]? = nil) -> EngineManifest {+ var m = EngineManifest(id: "\(arch == "arm64" ? "arm64" : "x64")-test-r1", displayName: "test", arch: arch, minMacOS: "26.5", components: [:])+ m.requires = requires+ return m+ }++ private func tempRoot(_ name: String) -> URL {+ let root = FileManager.default.temporaryDirectory.appending(path: "\(name)-\(UUID().uuidString)")+ addTeardownBlock { try? FileManager.default.removeItem(at: root) }+ return root+ }++ private func touch(_ url: URL) throws {+ try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)+ try Data("x".utf8).write(to: url)+ try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: url.path)+ }++ func testDirectoriesFollowTheArchitecture() {+ let intel = manifest("x86_64"), arm = manifest("arm64")+ XCTAssertEqual(intel.pe64LibDir, "x86_64-windows")+ XCTAssertEqual(intel.unixLibDir, "x86_64-unix")+ XCTAssertEqual(arm.pe64LibDir, "aarch64-windows", "Wine's ARM64X builtins, with the ARM64EC code x86-64 programs call into")+ XCTAssertEqual(arm.unixLibDir, "aarch64-unix")+ XCTAssertEqual(EngineManifest.pe32LibDir, "i386-windows", "32-bit programs run through WoW64 on both lines")+ XCTAssertFalse(intel.isNativeARM64); XCTAssertTrue(arm.isNativeARM64)+ XCTAssertEqual(EngineIntegrity.libraryDirectories(engineRoot: URL(fileURLWithPath: "/e"), arch: "arm64").map(\.lastPathComponent),+ ["aarch64-windows", "i386-windows"])+ XCTAssertEqual(EngineIntegrity.libraryDirectories(engineRoot: URL(fileURLWithPath: "/e")).map(\.lastPathComponent),+ ["x86_64-windows", "i386-windows"], "the default stays the Intel layout every shipped engine has")+ }++ func testOnlyEnginesThatSaySoNeedRosetta() throws {+ XCTAssertTrue(manifest("x86_64", requires: ["rosetta2"]).requiresRosetta)+ XCTAssertFalse(manifest("arm64", requires: []).requiresRosetta)+ XCTAssertFalse(manifest("arm64").requiresRosetta, "no requires at all means nothing is required")+ // Every engine shipped today is Intel code and must keep saying so, or the app would stop+ // installing Rosetta for it.+ let dir = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().appending(path: "spike")+ var files = try FileManager.default.contentsOfDirectory(at: dir.appending(path: "engines"), includingPropertiesForKeys: nil).filter { $0.pathExtension == "json" }+ files.append(dir.appending(path: "engine-manifest.json"))+ for f in files {+ let m = try EngineManifest.load(from: f)+ XCTAssertEqual(m.arch, "x86_64", "\(m.id) is not an Intel engine")+ XCTAssertTrue(m.requiresRosetta, "\(m.id) no longer declares rosetta2")+ }+ }++ func testAnARM64EngineNeedsFEXAndTheSignedLoader() throws {+ let arm = manifest("arm64")+ let files = InstalledEngine.requiredFiles(for: arm)+ XCTAssertTrue(files.contains("engine/lib/wine/aarch64-windows/kernel32.dll"))+ XCTAssertTrue(files.contains("engine/lib/wine/aarch64-unix/ntdll.so"))+ XCTAssertTrue(files.contains("engine/lib/wine/i386-windows/kernel32.dll"))+ XCTAssertFalse(files.contains { $0.contains("x86_64") }, "nothing Intel is expected of an arm64 engine")+ for fex in ["engine/lib/wine/aarch64-windows/xtajit64.dll", "engine/lib/wine/aarch64-windows/xtajit.dll",+ "engine/lib/wine/aarch64-unix/libarm64ecfex.so", "engine/lib/wine/aarch64-unix/libwow64fex.so"] {+ XCTAssertTrue(files.contains(fex), "\(fex) is what makes x86 programs run at all")+ }+ XCTAssertEqual(InstalledEngine.requiredFiles, InstalledEngine.requiredFiles(for: manifest("x86_64")), "the Intel list is unchanged")++ // A tree with every file, but the loader is the engine's own: not complete.+ let root = tempRoot("arm64-engine")+ for f in files { try touch(root.appending(path: f)) }+ let engine = InstalledEngine(manifest: arm, root: root)+ XCTAssertEqual(engine.missingFiles, [InstalledEngine.signedLoaderName])+ XCTAssertFalse(engine.usesSignedLoader)++ // Linking the signed helper completes it, sets the engine's loader aside once, and makes+ // bin/wine the relative link Wine itself installs, so a start through either path reaches+ // the helper and finds ntdll.so beside the Unix-side link.+ let app = tempRoot("Highball.app").appendingPathExtension("app")+ let helper = WineLoaderHelper.binary(inAppBundle: app)+ try touch(helper)+ try EngineStore().linkSignedLoader(root, manifest: arm, helper: helper)+ let unixLink = root.appending(path: "engine/lib/wine/aarch64-unix/wine")+ XCTAssertEqual(try FileManager.default.destinationOfSymbolicLink(atPath: unixLink.path), helper.path)+ XCTAssertEqual(try FileManager.default.destinationOfSymbolicLink(atPath: root.appending(path: "engine/bin/wine").path), "../lib/wine/aarch64-unix/wine")+ XCTAssertTrue(FileManager.default.fileExists(atPath: root.appending(path: "engine/bin/wine.unsigned").path), "the engine's own loader is kept aside")+ XCTAssertTrue(engine.usesSignedLoader)+ XCTAssertEqual(engine.missingFiles, [])+ XCTAssertEqual(engine.wineBinary.resolvingSymlinksInPath().path, helper.resolvingSymlinksInPath().path, "a launch runs the helper")++ // The app moved: the next read repoints the link and nothing else changes.+ let moved = tempRoot("Moved.app").appendingPathExtension("app")+ let helper2 = WineLoaderHelper.binary(inAppBundle: moved)+ try touch(helper2)+ try EngineStore().linkSignedLoader(root, manifest: arm, helper: helper2)+ XCTAssertEqual(try FileManager.default.destinationOfSymbolicLink(atPath: unixLink.path), helper2.path)+ XCTAssertEqual(engine.missingFiles, [])++ // An Intel engine is never touched.+ let intelRoot = tempRoot("x64-engine")+ try touch(intelRoot.appending(path: "engine/bin/wine"))+ try EngineStore().linkSignedLoader(intelRoot, manifest: manifest("x86_64", requires: ["rosetta2"]), helper: helper)+ XCTAssertNil(try? FileManager.default.destinationOfSymbolicLink(atPath: intelRoot.appending(path: "engine/bin/wine").path))+ }++ func testTheHelperIsFoundInTheEnvironmentThenTheAppThenApplications() throws {+ let app = tempRoot("App").appendingPathExtension("app"), installed = tempRoot("Installed").appendingPathExtension("app")+ let nowhere = URL(fileURLWithPath: "/nonexistent/Highball.app")+ XCTAssertNil(WineLoaderHelper.locate(environment: [:], appBundle: app, applications: nowhere), "nothing on disk yet")+ try touch(WineLoaderHelper.binary(inAppBundle: installed))+ XCTAssertEqual(WineLoaderHelper.locate(environment: [:], appBundle: app, applications: installed), WineLoaderHelper.binary(inAppBundle: installed))+ try touch(WineLoaderHelper.binary(inAppBundle: app))+ XCTAssertEqual(WineLoaderHelper.locate(environment: [:], appBundle: app, applications: installed), WineLoaderHelper.binary(inAppBundle: app),+ "the running app's own helper wins over the one in Applications")+ let override = tempRoot("Override").appendingPathExtension("app")+ try touch(WineLoaderHelper.binary(inAppBundle: override))+ let bundlePath = override.appending(path: "Contents/Helpers/WineLoader.app").path+ XCTAssertEqual(WineLoaderHelper.locate(environment: [WineLoaderHelper.environmentKey: bundlePath], appBundle: app, applications: installed),+ WineLoaderHelper.binary(inAppBundle: override), "the environment names the bundle")+ XCTAssertEqual(WineLoaderHelper.locate(environment: [WineLoaderHelper.environmentKey: WineLoaderHelper.binary(inAppBundle: override).path], appBundle: app, applications: installed),+ WineLoaderHelper.binary(inAppBundle: override), "or the binary")+ XCTAssertEqual(WineLoaderHelper.locate(environment: [WineLoaderHelper.environmentKey: "/nonexistent/wine"], appBundle: app, applications: installed),+ WineLoaderHelper.binary(inAppBundle: app), "a wrong override falls through")+ // The CLI on a Mac without the app: a non-bundle main executable has no helper of its own.+ XCTAssertEqual(WineLoaderHelper.locate(environment: [:], appBundle: URL(fileURLWithPath: "/usr/local/bin/highball"), applications: installed),+ WineLoaderHelper.binary(inAppBundle: installed))+ }++ func testTheRosettaSwitchOnlyReachesRosettaEngines() throws {+ // Bottle.environment sets ROSETTA_ADVERTISE_AVX for an Intel engine (EnvironmentTests) and+ // must not for an arm64 one, where x86 code runs through FEX and the variable means nothing.+ var bottle = Bottle(url: URL(fileURLWithPath: "/tmp/hb-arch-test-bottle"), settings: BottleSettings(name: "t", engineID: "arm64-test-r1"))+ bottle.settings.advertiseAVX = true+ let arm = InstalledEngine(manifest: manifest("arm64"), root: tempRoot("arm64-engine"))+ XCTAssertNil(try bottle.environment(engine: arm, renderer: .wined3d)["ROSETTA_ADVERTISE_AVX"])+ let intel = InstalledEngine(manifest: manifest("x86_64", requires: ["rosetta2"]), root: tempRoot("x64-engine"))+ XCTAssertEqual(try bottle.environment(engine: intel, renderer: .wined3d)["ROSETTA_ADVERTISE_AVX"], "1")+ }+}diff --git a/spike/wineloader/build.sh b/spike/wineloader/build.shnew file mode 100755index 0000000..64ac656--- /dev/null+++ b/spike/wineloader/build.sh@@ -0,0 +1,25 @@+#!/bin/zsh+# Builds Highball's arm64 Wine loader (spike/wineloader/main.c, see the header there) for the signed+# helper bundle Scripts/make-app.sh puts in Highball.app/Contents/Helpers/WineLoader.app.+# Output: .build/wineloader/wine. Needs Xcode 26.4 or later for -x86_64_layout_emulation.+set -euo pipefail+cd "$(dirname "$0")/../.."+OUT=.build/wineloader; mkdir -p "$OUT"+# Why these flags (measured on an M4, macOS 27.0, 2026-10-04; private/notes/rosetta-transition-plan.md, 9):+# - platform and SDK version macOS 11.0: a binary built against an SDK older than 26.5 keeps x18, the+# register Windows ARM64 code holds its thread block in, across context switches (CodeWeavers'+# interim rule, wine-devel 2026-08-07). The SDK field is the one that counts, hence -platform_version.+# - PAGEZERO and image base at 0x170000000 with the layout flag: a loader with Wine's default 4 KB+# segment alignment is killed at exec on arm64, and the big PAGEZERO needs the raised base.+# - Wine's own Info.plist embedded in the binary: a child process is started through a symlink in the+# engine, where Cocoa finds no bundle, and reads it from here (LSUIElement, the principal class).+MACOSX_DEPLOYMENT_TARGET=11.0 clang -arch arm64 -O2 -Wall -mmacos-version-min=11.0 \+ -o "$OUT/wine" spike/wineloader/main.c \+ -Wl,-platform_version,macos,11.0,11.0 \+ -Wl,-pagezero_size,0x170000000 -Wl,-image_base,0x170000000 -Wl,-x86_64_layout_emulation \+ -Wl,-sectcreate,__TEXT,__info_plist,spike/wineloader/wine_info.plist 2> "$OUT/build.log" \+ || { cat "$OUT/build.log" >&2; exit 1; }+# The two warnings the linker always prints here are not errors; anything else is.+grep -v "pagezero_size is too large\|prefered load addresses\|^$" "$OUT/build.log" >&2 || true+otool -l "$OUT/wine" | grep -A3 "segname __PAGEZERO" | grep -q "vmsize 0x0000000170000000" || { echo "error: the loader's PAGEZERO is not 0x170000000" >&2; exit 1; }+echo "built $OUT/wine ($(stat -f %z "$OUT/wine") bytes)"diff --git a/spike/wineloader/main.c b/spike/wineloader/main.cnew file mode 100644index 0000000..62b0260--- /dev/null+++ b/spike/wineloader/main.c@@ -0,0 +1,305 @@+/*+ * Emulator initialisation code+ *+ * Copyright 2000 Alexandre Julliard+ * Copyright 2026 Gauthier Piarrette (the parts marked Highball)+ *+ * This library is free software; you can redistribute it and/or+ * modify it under the terms of the GNU Lesser General Public+ * License as published by the Free Software Foundation; either+ * version 2.1 of the License, or (at your option) any later version.+ *+ * This library is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU+ * Lesser General Public License for more details.+ *+ * You should have received a copy of the GNU Lesser General Public+ * License along with this library; if not, write to the Free Software+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA+ */++/*+ * Highball's Wine loader for arm64 macOS.+ *+ * This is Wine 11.18's loader/main.c, the `wine` program that reserves memory, loads ntdll.so and+ * hands over to __wine_main, with two changes, both marked "Highball" below:+ *+ * 1. On arm64 it hands Wine the __PAGEZERO range as its reserved low memory. Linked with a+ * PAGEZERO of 0x170000000 and the linker's -x86_64_layout_emulation, and signed with Apple's+ * cross-architecture entitlement, the kernel lets the process map there, which is where 32-bit+ * and 64-bit Windows programs expect their memory (highball-engine patch 0018 is the same change+ * for the engine's own, unsigned loader).+ *+ * 2. It looks for ntdll.so next to the path it was started by, one symlink hop at a time, before+ * the resolved path. The binary lives sealed and signed inside Highball.app+ * (Contents/Helpers/WineLoader.app); an arm64 engine points `engine/lib/wine/aarch64-unix/wine`+ * at it and `engine/bin/wine` at that (EngineStore.linkSignedLoader). Wine's ntdll starts every+ * child process through the first of those, and the kernel reports the exec path with its+ * symlinks intact, so the loader finds the engine's ntdll.so without a copy of anything inside+ * the bundle.+ *+ * Why a copy of the file rather than a patch: Scripts/make-app.sh has to build and sign this binary+ * with the Developer ID and the provisioning profile at app build time, without a Wine tree. The+ * interface it relies on (__wine_main, wine_main_preload_info) has not changed in years. Built by+ * spike/wineloader/build.sh. Measured on an M4, macOS 27.0, 2026-10-04+ * (private/notes/rosetta-transition-plan.md, section 9).+ */++#include <fcntl.h>+#include <pthread.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <sys/mman.h>+#include <sys/types.h>+#include <sys/stat.h>+#include <unistd.h>+#include <dlfcn.h>+#include <limits.h>+#ifdef __APPLE__+# include <mach-o/dyld.h>+#endif++struct wine_preload_info+{+ void *addr;+ size_t size;+};++#if defined(__APPLE__) && defined(__x86_64__)++/* Not using the preloader on x86_64:+ * Reserve the same areas as the preloader does, but using zero-fill sections+ * (the only way to prevent system frameworks from using them, including allocations+ * before main() runs).+ */+__asm__(".zerofill WINE_RESERVE,WINE_RESERVE");+static char __wine_reserve[0x1fffff000] __attribute__((section("WINE_RESERVE, WINE_RESERVE")));++__asm__(".zerofill WINE_TOP_DOWN,WINE_TOP_DOWN");+static char __wine_top_down[0x001ff0000] __attribute__((section("WINE_TOP_DOWN, WINE_TOP_DOWN")));++static const struct wine_preload_info preload_info[] =+{+ { __wine_reserve, sizeof(__wine_reserve) }, /* 0x1000 - 0x200000000: low 8GB */+ { __wine_top_down, sizeof(__wine_top_down) }, /* 0x7ff000000000 - 0x7ff001ff0000: top-down allocations + virtual heap */+ { 0, 0 } /* end of list */+};++const __attribute((visibility("default"))) struct wine_preload_info *wine_main_preload_info = preload_info;++static void init_reserved_areas(void)+{+ int i;++ for (i = 0; wine_main_preload_info[i].size != 0; i++)+ {+ /* Match how the preloader maps reserved areas: */+ mmap(wine_main_preload_info[i].addr, wine_main_preload_info[i].size, PROT_NONE,+ MAP_FIXED | MAP_NORESERVE | MAP_PRIVATE | MAP_ANON, -1, 0);+ }+}++#elif defined(__APPLE__) && defined(__aarch64__)++/* Highball: arm64 macOS has no preloader and a PAGEZERO of 4 GB or more. With the+ * cross-architecture entitlement the kernel lets the process map over __PAGEZERO, so hand that+ * range to Wine as its reserved low memory (CrossOver links its loader with a PAGEZERO of about+ * 0x170000000 for the same reason). */+#include <mach-o/loader.h>++static struct wine_preload_info preload_info[2];++const __attribute((visibility("default"))) struct wine_preload_info *wine_main_preload_info = preload_info;++/* the size of this executable's __PAGEZERO segment, from its own load commands */+static uint64_t pagezero_size(void)+{+ const struct mach_header_64 *mh = (const struct mach_header_64 *)_dyld_get_image_header( 0 );+ const struct load_command *lc = (const struct load_command *)(mh + 1);+ uint32_t i;++ for (i = 0; i < mh->ncmds; i++)+ {+ if (lc->cmd == LC_SEGMENT_64)+ {+ const struct segment_command_64 *seg = (const struct segment_command_64 *)lc;+ if (!strcmp( seg->segname, "__PAGEZERO" )) return seg->vmsize;+ }+ lc = (const struct load_command *)((const char *)lc + lc->cmdsize);+ }+ return 0;+}++static void init_reserved_areas(void)+{+ uint64_t size = pagezero_size();++ if (size > 0x10000)+ {+ preload_info[0].addr = (void *)0x10000; /* host page aligned, Wine allocation granularity */+ preload_info[0].size = size - 0x10000;+ /* no PROT_NONE pre-mapping here: nothing else can allocate inside __PAGEZERO, and Wine+ * maps into the reserved range with MAP_FIXED and the final protection itself */+ }+}++#else++const __attribute((visibility("default"))) struct wine_preload_info *wine_main_preload_info = NULL;++static void init_reserved_areas(void)+{+}++#endif++/* canonicalize path and return its directory name */+static char *realpath_dirname( const char *name )+{+ char *p, *fullpath = realpath( name, NULL );++ if (fullpath)+ {+ p = strrchr( fullpath, '/' );+ if (p == fullpath) p++;+ if (p) *p = 0;+ }+ return fullpath;+}++/* if string ends with tail, remove it */+static char *remove_tail( const char *str, const char *tail )+{+ size_t len = strlen( str );+ size_t tail_len = strlen( tail );+ char *ret;++ if (len < tail_len) return NULL;+ if (strcmp( str + len - tail_len, tail )) return NULL;+ ret = malloc( len - tail_len + 1 );+ memcpy( ret, str, len - tail_len );+ ret[len - tail_len] = 0;+ return ret;+}++/* build a path from the specified dir and name */+static char *build_path( const char *dir, const char *name )+{+ size_t len = strlen( dir );+ char *ret = malloc( len + strlen( name ) + 2 );++ memcpy( ret, dir, len );+ if (len && ret[len - 1] != '/') ret[len++] = '/';+ strcpy( ret + len, name );+ return ret;+}++static const char *get_self_exe(void)+{+#if defined(__linux__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__)+ return "/proc/self/exe";+#elif defined(__APPLE__)+ uint32_t path_size = PATH_MAX;+ char *path = malloc( path_size );+ if (path && !_NSGetExecutablePath( path, &path_size ))+ return path;+ free( path );+#endif+ return NULL;+}++/* Highball: the directory part of a path, symlinks left alone; NULL for a bare name */+static char *plain_dirname( const char *name )+{+ const char *p = strrchr( name, '/' );+ char *ret;++ if (!p) return NULL;+ if (p == name) p++;+ ret = malloc( p - name + 1 );+ memcpy( ret, name, p - name );+ ret[p - name] = 0;+ return ret;+}++/* Highball: ntdll.so beside the path we were started by, then beside each symlink target on the+ * way to the real file. An engine starts us through engine/bin/wine -> ../lib/wine/aarch64-unix/wine+ * -> Highball.app/Contents/Helpers/WineLoader.app/Contents/MacOS/wine, and ntdll.so sits in the+ * middle one; the realpath lookup below would only ever look inside the app bundle. */+static void *try_dlopen_along_links( const char *argv0 )+{+ char *current = strdup( argv0 ), *dir, *path, *target;+ void *handle = NULL;+ ssize_t len;+ int hops;++ for (hops = 0; current && hops < 8 && !handle; hops++)+ {+ if (!(dir = plain_dirname( current ))) break;+ path = build_path( dir, "ntdll.so" );+ if (!access( path, R_OK )) handle = dlopen( path, RTLD_NOW );+ free( path );+ if (handle) { free( dir ); break; }++ target = malloc( PATH_MAX );+ if ((len = readlink( current, target, PATH_MAX - 1 )) <= 0)+ {+ free( target );+ free( dir );+ break; /* a real file: nothing further to follow */+ }+ target[len] = 0;+ if (target[0] == '/') { free( current ); current = target; }+ else { free( current ); current = build_path( dir, target ); free( target ); }+ free( dir );+ }+ free( current );+ return handle;+}++static void *try_dlopen( const char *argv0 )+{+ char *dir, *path, *p;+ void *handle;++ if (!argv0) return NULL;+ if ((handle = try_dlopen_along_links( argv0 ))) return handle; /* Highball */+ if (!(dir = realpath_dirname( argv0 ))) return NULL;++ if ((p = remove_tail( dir, "/loader" )))+ path = build_path( p, "dlls/ntdll/ntdll.so" );+ else+ path = build_path( dir, "ntdll.so" );++ handle = dlopen( path, RTLD_NOW );+ free( p );+ free( dir );+ free( path );+ return handle;+}+++/**********************************************************************+ * main+ */+int main( int argc, char *argv[] )+{+ void *handle;++ init_reserved_areas();++ if ((handle = try_dlopen( get_self_exe() )) ||+ (handle = try_dlopen( argv[0] )))+ {+ void (*init_func)(int, char **) = dlsym( handle, "__wine_main" );+ if (init_func) init_func( argc, argv );+ fprintf( stderr, "wine: __wine_main function not found in ntdll.so\n" );+ exit(1);+ }++ fprintf( stderr, "wine: could not load ntdll.so: %s\n", dlerror() );+ pthread_detach( pthread_self() ); /* force importing libpthread for OpenGL */+ exit(1);+}diff --git a/spike/wineloader/wine_info.plist b/spike/wineloader/wine_info.plistnew file mode 100644index 0000000..683042c--- /dev/null+++ b/spike/wineloader/wine_info.plist@@ -0,0 +1,30 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>CFBundleAllowMixedLocalizations</key>+ <true/>+ <key>CFBundleDevelopmentRegion</key>+ <string>English</string>+ <key>CFBundleExecutable</key>+ <string>wine</string>+ <key>CFBundleIdentifier</key>+ <string>org.winehq.wine</string>+ <key>CFBundleInfoDictionaryVersion</key>+ <string>6.0</string>+ <key>CFBundleName</key>+ <string>Wine</string>+ <key>CFBundlePackageType</key>+ <string>APPL</string>+ <key>CFBundleShortVersionString</key>+ <string>11.18</string>+ <key>CFBundleSignature</key>+ <string>????</string>+ <key>CFBundleVersion</key>+ <string>11.18</string>+ <key>NSPrincipalClass</key>+ <string>WineApplication</string>+ <key>LSUIElement</key>+ <string>1</string>+</dict>+</plist>