Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Link kernel-first kernelcaches with another Mac's kmutil over ssh

Maximilian Paß3854472a27c6
diff --git a/Documents/Guides/create-and-run.md b/Documents/Guides/create-and-run.md
index 0b313f3b..41d6b870 100644
--- a/Documents/Guides/create-and-run.md
+++ b/Documents/Guides/create-and-run.md
@@ -26,6 +26,8 @@ By default that pipeline builds a [template](#templates) rather than the VM itse
A cloudOS after the 26.4 beta has no vphone600 components, and the research board stands in ([Compatibility](compatibility.md)). Its kernelcache is rebuilt with the vphone600 virtualisation kexts, which needs an `ipsw` with `kernel extract --kdk` and root for the link. Run the whole creation as `sudo VPHONE_IPSW=/path/to/ipsw vphone-cli vm create ...`, or stage the mix as yourself after `fw prepare` with `VPHONE_IPSW=/path/to/ipsw vphone-cli fw kernelcache <vm>`, link it with `sudo vphone-cli fw kernelcache <vm>`, and continue with `fw patch` as usual.
+A kernel only boots in the layout Apple linked it with, and kmutil takes the layout from the Mac it runs on: macOS 26.4 and later link the iOS 26.4+ kernelcaches (kernel-last), macOS 15 and 26.0–26.3 the older ones (kernel-first). When this Mac has the other layout, another Mac or a macOS VM links the mix over ssh: set `VPHONE_KMUTIL_SSH=<user>@<host>` (and `VPHONE_KMUTIL_SSH_PASSWORD=<password>` without ssh keys and passwordless sudo there) for `fw kernelcache` or the creation. The staged volume is uploaded to that Mac's `/private/var/tmp`, linked there as root and removed; nothing on this Mac needs root for it. Remote Login must be on, and the user must be allowed to use sudo.
+
The build also ships an arm64e GPU compiler plugin in the bundle. `fw prepare` copies it into the staged GPU bundle before firmware patching and installation.
Success ends with `First boot: vphoned ping succeeded` and `JB VM created; vphoned connected`. **The verification VM is then stopped.** The ping proves the daemon answered over the host control socket during that boot; it does not leave a running VM behind.
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KernelCacheMixer.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KernelCacheMixer.swift
index 3421e532..add6177a 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KernelCacheMixer.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KernelCacheMixer.swift
@@ -107,8 +107,7 @@ public final class KernelCacheMixer {
let mixer = try KernelCacheMixer(recipes: .locate(), verbose: false)
let state = try mixer.state(for: input)
guard state != .mixed else { return }
- try KernelCollectionBuilder.checkLayout(for: mixer.locations(for: input).base)
- guard geteuid() == 0 else {
+ guard try geteuid() == 0 || mixer.linksRemotely(input) else {
throw PatcherError.invalidFormat(linkInstructions(staged: state == .staged))
}
if state == .missing {
@@ -152,7 +151,7 @@ public final class KernelCacheMixer {
log(" [kc] using the cached mix \(paths.mixed.path)")
return data
}
- guard geteuid() == 0 else {
+ guard try geteuid() == 0 || linksRemotely(input) else {
throw PatcherError.invalidFormat(Self.linkInstructions(staged: Self.isStaged(paths.staged)))
}
if !Self.isStaged(paths.staged) {
@@ -167,7 +166,7 @@ public final class KernelCacheMixer {
public func stage(_ input: Input, ipsw ipswPath: String? = nil) throws {
let (base, paths) = try locations(for: input)
guard !FileManager.default.fileExists(atPath: paths.mixed.path), !Self.isStaged(paths.staged) else { return }
- try KernelCollectionBuilder.checkLayout(for: base)
+ let location = try KernelCollectionBuilder.location(for: base)
let donors = try base.donors.map { try recipes.donor(id: $0) }
let ipsw = try Self.ipsw(ipswPath)
@@ -204,7 +203,11 @@ public final class KernelCacheMixer {
if geteuid() == 0 {
try VPhoneHostFilePermissions.makeAccessible(at: cacheDirectory)
}
- log(" [kc] staged; linking needs root")
+ if case .remote = location {
+ log(" [kc] staged")
+ } else {
+ log(" [kc] staged; linking needs root")
+ }
}
/// Links a staged volume, as root, and caches the result. Runs no `ipsw`:
@@ -216,8 +219,8 @@ public final class KernelCacheMixer {
if let data = try? Data(contentsOf: paths.mixed), !data.isEmpty {
return data
}
- try KernelCollectionBuilder.checkLayout(for: base)
- guard geteuid() == 0 else {
+ let location = try KernelCollectionBuilder.location(for: base)
+ if case .host = location, geteuid() != 0 {
throw PatcherError.invalidFormat(Self.linkInstructions(staged: Self.isStaged(paths.staged)))
}
guard Self.isStaged(paths.staged) else {
@@ -225,6 +228,9 @@ public final class KernelCacheMixer {
}
let payload = try Self.payload(of: input.kernelcache)
+ if case let .remote(builder) = location {
+ return try linkRemotely(base: base, paths: paths, payload: payload, builder: builder)
+ }
let copy = try KernelCacheVolumeCopy(
staged: paths.staged.appending(path: "volume"), kdk: base.kernel.kdk, pathLength: Self.buildRootLength(of: payload),
)
@@ -248,6 +254,44 @@ public final class KernelCacheMixer {
return output
}
+ /// Links the staged volume on the Mac `VPHONE_KMUTIL_SSH` names. Root there
+ /// links what it is sent, so this side needs no root: the stage is checked
+ /// for links outside it and sent as it is.
+ func linkRemotely(
+ base: KernelCacheBase, paths: (mixed: URL, staged: URL), payload: Data, builder: RemoteKernelCollectionBuilder,
+ ) throws -> Data {
+ let volume = paths.staged.appending(path: "volume")
+ try KernelCacheVolumeCopy.checkLinks(in: volume, kdk: base.kernel.kdk)
+ let work = paths.staged.appending(path: "link")
+ try? FileManager.default.removeItem(at: work)
+ try FileManager.default.createDirectory(at: work, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: work) }
+ let kmutilLog = work.appending(path: "kmutil.log")
+ defer {
+ if let text = try? Data(contentsOf: kmutilLog) {
+ try? storeMix(text, at: paths.mixed.deletingPathExtension().appendingPathExtension("kmutil.log"))
+ }
+ }
+ let identifiers = try base.kextIdentifiers()
+ var output = try builder.link(
+ staged: volume, kernel: "Library/Developer/KDKs/\(base.kernel.kdk)/System/Library/Kernels/kernel",
+ identifiers: identifiers, pathLength: Self.buildRootLength(of: payload), work: work, log: kmutilLog,
+ )
+ output = try finalize(output, original: payload, identifiers: identifiers, work: work)
+ try storeMix(output, at: paths.mixed)
+ log(" [kc] mixed kernelcache: \(output.count) bytes, cached at \(paths.mixed.path)")
+ return output
+ }
+
+ /// Whether `input` is linked by another Mac over ssh, which needs no root here.
+ public func linksRemotely(_ input: Input) throws -> Bool {
+ let (base, _) = try locations(for: input)
+ if case .remote = try KernelCollectionBuilder.location(for: base) {
+ return true
+ }
+ return false
+ }
+
// MARK: - Cache
static let stagedMarker = ".staged"
@@ -276,6 +320,10 @@ public final class KernelCacheMixer {
let relative = String(url.standardizedFileURL.path.dropFirst(cache.count + 1))
let (directory, leaf) = try root.parent(of: relative, create: true)
try directory.writeFile(leaf, contents: data, mode: 0o644, owner: user.map { ($0.uid, $0.gid) })
+ // Under sudo, so the user's later runs, which link over ssh, can store here too.
+ if geteuid() == 0 {
+ try VPhoneHostFilePermissions.makeAccessible(at: cacheDirectory)
+ }
}
public static func linkInstructions(staged: Bool) -> String {
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KernelCollectionBuilder.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KernelCollectionBuilder.swift
index 6db93582..f5095b1e 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KernelCollectionBuilder.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KernelCollectionBuilder.swift
@@ -5,11 +5,17 @@
// puts the kernel's `__TEXT_EXEC` after the kexts ("kernel-last"), macOS 15 and
// 26.0–26.3 put it first ("kernel-first"), and a kernel only boots in the layout
// Apple linked it with. Every iOS 26.4+ base is kernel-last, so the host links
-// it when it runs macOS 26.4 or later.
+// it when it runs macOS 26.4 or later; the iOS 18 bases are kernel-first.
+//
+// When the host's builder has the other layout, a Mac (or macOS VM) running one
+// with the right layout links the volume over ssh (`RemoteKernelCollectionBuilder`):
+//
+// VPHONE_KMUTIL_SSH=user@host the ssh destination (key or password)
+// VPHONE_KMUTIL_SSH_PASSWORD=... optional: the password for ssh and sudo
//
// kmutil reads only kexts owned by root:wheel. Others it skips without a word
// and takes the host's own from /System/Library/Extensions, so the link runs as
-// root on a volume chowned to root.
+// root on a volume chowned to root, here or on the remote Mac.
import Foundation
import VPhonePatchKit
@@ -20,37 +26,259 @@ enum KernelCollectionBuilder {
static let createFlags = ["-a", "arm64e", "-n", "boot", "-s", "all", "-z", "-x"]
static let packageFlags = ["--compress", "--img4-encode", "--split-ro-rx-tags"]
+ static let sshEnvironmentVariable = "VPHONE_KMUTIL_SSH"
+ static let sshPasswordEnvironmentVariable = "VPHONE_KMUTIL_SSH_PASSWORD"
+
+ /// Where a base is linked.
+ enum Location {
+ case host
+ case remote(RemoteKernelCollectionBuilder)
+ }
+
static func layout(forMacOS version: OperatingSystemVersion) -> KernelCacheBase.BuilderLayout {
let atLeast264 = version.majorVersion > 26 || (version.majorVersion == 26 && version.minorVersion >= 4)
return atLeast264 ? .kernelLast : .kernelFirst
}
- /// Refuses before anything is extracted when this Mac cannot link `base`.
- static func checkLayout(for base: KernelCacheBase) throws {
+ static func layout(forMacOS version: String) -> KernelCacheBase.BuilderLayout {
+ let parts = version.split(separator: ".").compactMap { Int($0) }
+ return layout(forMacOS: OperatingSystemVersion(
+ majorVersion: parts.first ?? 0,
+ minorVersion: parts.count > 1 ? parts[1] : 0,
+ patchVersion: parts.count > 2 ? parts[2] : 0,
+ ))
+ }
+
+ /// The host when its builder has the base's layout, else the ssh builder
+ /// `VPHONE_KMUTIL_SSH` names, once its macOS is checked. Refuses before
+ /// anything is extracted when neither can link `base`.
+ static func location(
+ for base: KernelCacheBase,
+ environment: [String: String] = ProcessInfo.processInfo.environment,
+ ) throws -> Location {
let host = ProcessInfo.processInfo.operatingSystemVersion
- let layout = layout(forMacOS: host)
- guard layout == base.builderLayout else {
+ let hostLayout = layout(forMacOS: host)
+ if hostLayout == base.builderLayout {
+ return .host
+ }
+ guard let destination = environment[sshEnvironmentVariable], !destination.isEmpty else {
+ let needed = base.builderLayout == .kernelLast ? "macOS 26.4 or later" : "macOS 15, or 26.0 to 26.3"
throw PatcherError.invalidFormat(
"the iOS \(base.productVersion) kernelcache must be linked \(base.builderLayout.rawValue), "
- + "and the kmutil of macOS \(host.majorVersion).\(host.minorVersion) links \(layout.rawValue): "
- + (base.builderLayout == .kernelLast ? "update this Mac to macOS 26.4 or later" : "link it on macOS 15"),
+ + "and the kmutil of macOS \(host.majorVersion).\(host.minorVersion) links \(hostLayout.rawValue). "
+ + "Link it on a Mac or macOS VM running \(needed) with Remote Login on: "
+ + "\(sshEnvironmentVariable)=<user>@<host> (and \(sshPasswordEnvironmentVariable)=<password> without ssh keys "
+ + "and passwordless sudo) vphone-cli fw kernelcache <vm>",
+ )
+ }
+ let remote = RemoteKernelCollectionBuilder(destination: destination, password: environment[sshPasswordEnvironmentVariable])
+ let version = try remote.macOSVersion()
+ guard layout(forMacOS: version) == base.builderLayout else {
+ throw PatcherError.invalidFormat(
+ "\(destination) runs macOS \(version), whose kmutil links \(layout(forMacOS: version).rawValue); "
+ + "the iOS \(base.productVersion) kernelcache must be linked \(base.builderLayout.rawValue)",
)
}
+ return .remote(remote)
+ }
+
+ /// kmutil's arguments for the volume at `volume`, writing `<volume>.kc` beside it.
+ static func kmutilArguments(volume: String, kernel: String, identifiers: [String]) -> [String] {
+ var arguments = ["create"] + createFlags + ["-R", volume, "-k", kernel, "-r", "\(volume)/System/Library/Extensions"]
+ for identifier in identifiers {
+ arguments += ["-b", identifier]
+ }
+ // -B is relative to the volume root.
+ let name = (volume as NSString).lastPathComponent
+ return arguments + packageFlags + ["-B", "/../\(name).kc"]
}
- /// Link the volume at `volume` and return kmutil's IMG4 kernelcache.
+ /// Link the volume at `volume` on this Mac and return kmutil's IMG4 kernelcache.
static func link(volume: URL, kernel: URL, identifiers: [String], log: URL) throws -> Data {
try KernelCacheMixer.run("/usr/sbin/chown", ["-R", "0:0", volume.path], log: log)
let output = volume.deletingLastPathComponent().appending(path: "\(volume.lastPathComponent).kc")
try? FileManager.default.removeItem(at: output)
- var arguments = ["create"] + createFlags
- + ["-R", volume.path, "-k", kernel.path, "-r", volume.appending(path: "System/Library/Extensions").path]
- for identifier in identifiers {
- arguments += ["-b", identifier]
+ try KernelCacheMixer.run(
+ "/usr/bin/kmutil", kmutilArguments(volume: volume.path, kernel: kernel.path, identifiers: identifiers), log: log,
+ )
+ return try Data(contentsOf: output)
+ }
+}
+
+/// Links a staged volume with the kmutil of another Mac, over the system ssh.
+///
+/// The volume is uploaded as a tar into a fresh directory in the remote
+/// `/private/var/tmp`, renamed so its absolute path has the length the base
+/// needs (`KernelCacheMixer.buildRootLength`); there root owns it, takes the
+/// write bits kmutil skips a kext for, and links it. The result comes back
+/// over the same connection and the directory is removed.
+///
+/// A password is passed to ssh through `SSH_ASKPASS` and to sudo on its
+/// standard input, so nothing but the system's ssh is needed.
+struct RemoteKernelCollectionBuilder {
+ let destination: String
+ let password: String?
+
+ func macOSVersion() throws -> String {
+ let output = try run(command: "sw_vers -productVersion")
+ return String(decoding: output, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)
+ }
+
+ /// Links `staged` (a staged volume whose kernel is at `kernel`, relative to
+ /// it) and returns kmutil's IMG4 kernelcache. kmutil's output goes to `log`.
+ func link(staged: URL, kernel: String, identifiers: [String], pathLength: Int, work: URL, log: URL) throws -> Data {
+ let directory = "/private/var/tmp/vphone-kc-\(UUID().uuidString.prefix(8).lowercased())"
+ let nameLength = pathLength - directory.count - 1
+ guard (1 ... 255).contains(nameLength) else {
+ throw PatcherError.invalidFormat("a kernelcache volume path of \(pathLength) characters does not fit below \(directory)")
}
- // -B is relative to the volume root.
- arguments += packageFlags + ["-B", "/../\(output.lastPathComponent)"]
- try KernelCacheMixer.run("/usr/bin/kmutil", arguments, log: log)
+ let name = String(repeating: "b", count: nameLength)
+ let archive = work.appending(path: "volume.tar")
+ try? FileManager.default.removeItem(at: archive)
+ try KernelCacheMixer.run(
+ "/usr/bin/tar",
+ ["-C", staged.deletingLastPathComponent().path, "-cf", archive.path, "-s", ",^\(staged.lastPathComponent),\(name),", staged.lastPathComponent],
+ log: log,
+ )
+ defer { try? FileManager.default.removeItem(at: archive) }
+
+ print(" [kc] uploading the volume to \(destination):\(directory)")
+ try run(command: "mkdir -m 700 \(directory) && tar -C \(directory) -xf -", input: .file(archive))
+ defer { _ = try? sudo("rm -rf \(directory)") }
+
+ let volume = "\(directory)/\(name)"
+ let kmutil = KernelCollectionBuilder.kmutilArguments(volume: volume, kernel: "\(volume)/\(kernel)", identifiers: identifiers)
+ .map(Self.quote).joined(separator: " ")
+ print(" [kc] linking with the kmutil of \(destination)")
+ try sudo(
+ "chown -R root:wheel \(volume) && chmod -R go-w \(volume) && /usr/bin/kmutil \(kmutil) && chown \"$SUDO_UID\" \(volume).kc",
+ log: log,
+ )
+ let output = work.appending(path: "remote.kc")
+ try run(command: "cat \(volume).kc", output: output)
+ defer { try? FileManager.default.removeItem(at: output) }
return try Data(contentsOf: output)
}
+
+ // MARK: - ssh
+
+ enum Input {
+ case none
+ case file(URL)
+ case data(Data)
+ }
+
+ /// Runs `command` as root on the remote Mac; with a password, sudo reads it
+ /// from its standard input.
+ @discardableResult
+ func sudo(_ command: String, log: URL? = nil) throws -> Data {
+ if let password {
+ return try run(command: "sudo -S -p '' sh -c \(Self.quote(command))", input: .data(Data((password + "\n").utf8)), log: log)
+ }
+ return try run(command: "sudo -n sh -c \(Self.quote(command))", log: log)
+ }
+
+ /// Runs `command` on the remote Mac and returns its standard output, or
+ /// writes it to `output`. With `log`, both streams go there instead.
+ @discardableResult
+ func run(command: String, input: Input = .none, output: URL? = nil, log: URL? = nil) throws -> Data {
+ var options = ["-o", "ConnectTimeout=15", "-o", "ServerAliveInterval=30", "-o", "StrictHostKeyChecking=accept-new"]
+ var environment = ProcessInfo.processInfo.environment
+ var askpass: URL?
+ if let password {
+ let script = try Self.askpassScript()
+ askpass = script
+ environment["SSH_ASKPASS"] = script.appending(path: "askpass").path
+ environment["SSH_ASKPASS_REQUIRE"] = "force"
+ environment["VPHONE_KMUTIL_SSH_ASKPASS_SECRET"] = password
+ options += ["-o", "PubkeyAuthentication=no", "-o", "PreferredAuthentications=password,keyboard-interactive", "-o", "NumberOfPasswordPrompts=1"]
+ } else {
+ options += ["-o", "BatchMode=yes"]
+ }
+ defer { askpass.map { try? FileManager.default.removeItem(at: $0) } }
+
+ var executable = "/usr/bin/ssh"
+ var arguments = options + [destination, command]
+ // Under sudo, connect as the invoking user, with their keys and known hosts.
+ if geteuid() == 0, let user = environment["SUDO_USER"], !user.isEmpty, user != "root" {
+ if let askpass, let uid = environment["SUDO_UID"].flatMap(UInt32.init) {
+ _ = chown(askpass.path, uid, gid_t(0))
+ _ = chown(askpass.appending(path: "askpass").path, uid, gid_t(0))
+ }
+ let kept = "SSH_ASKPASS,SSH_ASKPASS_REQUIRE,VPHONE_KMUTIL_SSH_ASKPASS_SECRET"
+ arguments = ["-u", user, "-H", "--preserve-env=\(kept)", executable] + arguments
+ executable = "/usr/bin/sudo"
+ }
+
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: executable)
+ process.arguments = arguments
+ process.environment = environment
+ let stdout = Pipe()
+ var outputHandle: FileHandle?
+ var logHandle: FileHandle?
+ if let log {
+ if !FileManager.default.fileExists(atPath: log.path) {
+ FileManager.default.createFile(atPath: log.path, contents: nil)
+ }
+ let handle = try FileHandle(forWritingTo: log)
+ try handle.seekToEnd()
+ logHandle = handle
+ process.standardOutput = handle
+ process.standardError = handle
+ } else if let output {
+ FileManager.default.createFile(atPath: output.path, contents: nil)
+ let handle = try FileHandle(forWritingTo: output)
+ outputHandle = handle
+ process.standardOutput = handle
+ } else {
+ process.standardOutput = stdout
+ }
+ let stderr = Pipe()
+ if log == nil {
+ process.standardError = stderr
+ }
+ let stdin = Pipe()
+ switch input {
+ case .none: process.standardInput = FileHandle.nullDevice
+ case let .file(url): process.standardInput = try FileHandle(forReadingFrom: url)
+ case .data: process.standardInput = stdin
+ }
+ try process.run()
+ if case let .data(data) = input {
+ stdin.fileHandleForWriting.write(data)
+ try? stdin.fileHandleForWriting.close()
+ }
+ let collected = output == nil && log == nil ? stdout.fileHandleForReading.readDataToEndOfFile() : Data()
+ let errors = log == nil ? stderr.fileHandleForReading.readDataToEndOfFile() : Data()
+ process.waitUntilExit()
+ try? outputHandle?.close()
+ try? logHandle?.close()
+ guard process.terminationStatus == 0 else {
+ var detail = String(decoding: errors, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)
+ if let log, let text = try? String(contentsOf: log, encoding: .utf8) {
+ detail = text.split(separator: "\n", omittingEmptySubsequences: false).suffix(25).joined(separator: "\n")
+ }
+ throw PatcherError.invalidFormat("ssh \(destination) `\(command.prefix(80))` failed with exit code \(process.terminationStatus): \(detail)")
+ }
+ return collected
+ }
+
+ /// A private directory holding a script that prints the password from the
+ /// environment, so the password never appears in an argument or a file.
+ static func askpassScript() throws -> URL {
+ var template = Array("/private/var/tmp/vphone-askpass.XXXXXX".utf8CString)
+ guard let made = mkdtemp(&template) else {
+ throw PatcherError.invalidFormat("could not create a private directory for ssh: \(String(cString: strerror(errno)))")
+ }
+ let directory = URL(fileURLWithPath: String(cString: made), isDirectory: true)
+ let script = directory.appending(path: "askpass")
+ try Data("#!/bin/sh\nprintf '%s\\n' \"$VPHONE_KMUTIL_SSH_ASKPASS_SECRET\"\n".utf8).write(to: script)
+ try FileManager.default.setAttributes([.posixPermissions: NSNumber(value: 0o700)], ofItemAtPath: script.path)
+ return directory
+ }
+
+ static func quote(_ text: String) -> String {
+ "'" + text.replacingOccurrences(of: "'", with: "'\\''") + "'"
+ }
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/KernelCacheMixerTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/KernelCacheMixerTests.swift
index 75d11ebb..e9abdc52 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/KernelCacheMixerTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/KernelCacheMixerTests.swift
@@ -48,6 +48,39 @@ struct KernelCacheMixerTests {
#expect(try Self.recipes.donor(id: "watch7c_26.4_23T240").cloudOSSource == nil)
}
+ @Test("A kernel-first base on a kernel-last Mac needs an ssh builder, and says how to name one")
+ func remoteBuilderSelection() throws {
+ let host = ProcessInfo.processInfo.operatingSystemVersion
+ let hostLayout = KernelCollectionBuilder.layout(forMacOS: host)
+ func base(_ layout: KernelCacheBase.BuilderLayout) throws -> KernelCacheBase {
+ let json = """
+ {"id": "t", "productVersion": "18.7", "symbols": "s", "kexts": "k", "builderLayout": "\(layout.rawValue)",
+ "kernel": {"file": "f", "sha256": "a", "decompressedSHA256": "b", "kdk": "KDK_18.7_22H42.kdk"}}
+ """
+ return try JSONDecoder().decode(KernelCacheBase.self, from: Data(json.utf8))
+ }
+ let other = try base(hostLayout == .kernelLast ? .kernelFirst : .kernelLast)
+ #expect {
+ try KernelCollectionBuilder.location(for: other, environment: [:])
+ } throws: { error in
+ "\(error)".contains(KernelCollectionBuilder.sshEnvironmentVariable)
+ }
+ let same = try base(hostLayout)
+ guard case .host = try KernelCollectionBuilder.location(for: same, environment: [:]) else {
+ Issue.record("a base of the host's layout links on the host")
+ return
+ }
+ #expect(KernelCollectionBuilder.layout(forMacOS: "15.6.1") == .kernelFirst)
+ #expect(KernelCollectionBuilder.layout(forMacOS: "26.4") == .kernelLast)
+ }
+
+ @Test("kmutil writes the collection beside the volume")
+ func kmutilArguments() {
+ let arguments = KernelCollectionBuilder.kmutilArguments(volume: "/tmp/x/bbb", kernel: "/tmp/x/bbb/k", identifiers: ["a", "b"])
+ #expect(arguments.suffix(2) == ["-B", "/../bbb.kc"])
+ #expect(arguments.contains("-R") && arguments.filter { $0 == "-b" }.count == 2)
+ }
+
@Test("A kernelcache is matched by the SHA-256 of its container or of its payload, and nothing else")
func matchesByHash() throws {
let base = try #require(try Self.recipes.bases().first)
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift
index a2da94b1..5f2b421b 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift
@@ -711,10 +711,22 @@ struct VPhoneFirmwareKernelcacheCommand: ParsableCommand {
print("[+] The kernelcache mix is ready; `fw patch` takes it from the cache.")
return
}
- guard !linkOnly else {
+ // Another Mac's kmutil (VPHONE_KMUTIL_SSH) links as root there.
+ let remote = try mixer.linksRemotely(input)
+ guard !linkOnly || remote else {
throw ValidationError("Linking the kernelcache mix needs root. Run this command with sudo.")
}
- try mixer.stage(input, ipsw: ipsw)
- print("[+] Staged. Link it with: sudo vphone-cli fw kernelcache \(name)")
+ if state == .missing {
+ guard !linkOnly else {
+ throw ValidationError("\(name)'s kernelcache mix is not staged. Stage it first: \(KernelCacheMixer.ipswEnvironmentVariable)=<ipsw> vphone-cli fw kernelcache \(name)")
+ }
+ try mixer.stage(input, ipsw: ipsw)
+ }
+ guard remote else {
+ print("[+] Staged. Link it with: sudo vphone-cli fw kernelcache \(name)")
+ return
+ }
+ try mixer.link(input)
+ print("[+] The kernelcache mix is ready; `fw patch` takes it from the cache.")
}
}