Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Stage the kernelcache mix as the user, link it as root

Maximilian Paß01182f4b649a
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.md
index 0845061d..b6ab72e0 100644
--- a/Research/0_binary_patch_comparison.md
+++ b/Research/0_binary_patch_comparison.md
@@ -3437,8 +3437,20 @@ it too. The pipeline keeps kmutil's container (its `PAYP` properties describe
the new layout) and saves the preset's kernel patches into it
(`ComponentDescriptor.replacement`); `minimal` adds none. The shipped kernels stay
in `FirmwareOriginals`. Mixes are cached in `~/.vphone/kernelcache/mix`, keyed
-by the kernelcaches, the maps and bundle list, the `ipsw` binary's hash and the
-builder layout.
+by the kernelcaches, the maps and bundle list and the builder layout.
+
+Only the link needs root, and root runs no `ipsw`. `fw kernelcache <vm>` stages
+the mix as the user (both extractions and the volume) and links it under sudo:
+root copies the staged volume into a fresh root-only directory, walking it by
+descriptor, refusing every symbolic link but the KDK's pointer to the volume's
+extensions and normalising modes (kmutil skips a kext with a group- or
+world-writable file as silently as one root does not own), and runs kmutil on
+the copy. The Launchpad helper's link runs with `--link-only`, which never
+stages. kmutil records the absolute path of every codeless kext, which moves
+the end of `__PRELINK_INFO`: the volume path takes the length of the build root
+Apple linked the base in, read from the base's own prelink info, so a mix no
+longer depends on where it is built. The 26.6 mix then has the segment layout
+of the hand-built research mix that booted.
Requirements: an `ipsw` with `kernel extract --kdk`, named by `VPHONE_IPSW`
(vphone-cli does not ship it); root; and for every base here (26.4–26.7, all
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KernelCacheMixer.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KernelCacheMixer.swift
index 92941bed..76a60555 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KernelCacheMixer.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KernelCacheMixer.swift
@@ -30,12 +30,25 @@ public final class KernelCacheMixer {
let cacheDirectory: URL
let verbose: Bool
- /// The length of Apple's build volume name. kmutil records the plug-in
- /// paths, and the `__PRELINK_INFO` page rounding then matches Apple's builds.
- static let volumeName = String(repeating: "b", count: 170)
+ /// kmutil records the absolute path of every codeless kext, so the length of
+ /// the volume's path decides where `__PRELINK_INFO` ends and every page after
+ /// it. The link gives it the length of the build root Apple linked the base
+ /// with, read from the base itself: the output then depends on nothing about
+ /// this Mac, and the base rebuilt from its own extraction is Apple's
+ /// kernelcache byte for byte, apart from the CPU subtype.
+ static func buildRootLength(of payload: Data) throws -> Int {
+ let key = Data("<key>_CodelessKextBundlePath</key>".utf8)
+ guard let keyRange = payload.range(of: key),
+ let open = payload.range(of: Data("<string>".utf8), in: keyRange.upperBound ..< payload.endIndex),
+ let extensions = payload.range(of: Data("/System/Library/Extensions/".utf8), in: open.upperBound ..< min(open.upperBound + 2048, payload.endIndex))
+ else {
+ throw PatcherError.invalidFormat("the base kernelcache records no codeless kext path to take its build root from")
+ }
+ return extensions.lowerBound - open.upperBound
+ }
/// Bump when the steps change, so cached mixes are rebuilt.
- static let revision = 1
+ static let revision = 3
public static let ipswEnvironmentVariable = "VPHONE_IPSW"
@@ -74,11 +87,16 @@ public final class KernelCacheMixer {
/// `vm create` asks as soon as `fw prepare` finds the recipe, not at
/// `fw patch` after the restores.
public static func checkMixable(restoreTree restoreDir: URL) throws {
+ let kernelcache = try kernelcache(inRestoreTree: restoreDir)
let mixer = try KernelCacheMixer(recipes: .locate(), verbose: false)
- let base = try mixer.base(for: kernelcache(inRestoreTree: restoreDir))
- let cached = try mixer.cachedMix(base: base, ipsw: ipsw())
- if !FileManager.default.fileExists(atPath: cached.path) {
- try KernelCollectionBuilder.checkHost(for: base)
+ let state = try mixer.state(for: kernelcache)
+ guard state != .mixed else { return }
+ try KernelCollectionBuilder.checkLayout(for: mixer.locations(for: kernelcache).base)
+ guard geteuid() == 0 else {
+ throw PatcherError.invalidFormat(linkInstructions(staged: state == .staged))
+ }
+ if state == .missing {
+ _ = try ipsw()
}
}
@@ -89,31 +107,60 @@ public final class KernelCacheMixer {
// MARK: - Mix
- /// The mixed kernelcache (an IMG4 `krnl` container) for a research board one.
+ /// What becomes of a research board kernelcache in the cache.
+ public enum State: Equatable, Sendable {
+ /// Linked: `fw patch` takes it from the cache.
+ case mixed
+ /// Extracted and staged; linking it needs root.
+ case staged
+ /// Neither yet.
+ case missing
+ }
+
+ public func state(for kernelcache: Data) throws -> State {
+ let (_, paths) = try locations(for: kernelcache)
+ if FileManager.default.fileExists(atPath: paths.mixed.path) {
+ return .mixed
+ }
+ return Self.isStaged(paths.staged) ? .staged : .missing
+ }
+
+ /// The mixed kernelcache (an IMG4 `krnl` container) for a research board
+ /// one: from the cache, linked from a staged volume (root), or staged and
+ /// linked in one go (root with `VPHONE_IPSW`).
public func mix(kernelcache: Data) throws -> Data {
- let base = try base(for: kernelcache)
- let donor = try recipes.donor(id: base.donor)
- let ipsw = try Self.ipsw()
- let cached = try cachedMix(base: base, ipsw: ipsw)
- log(" [kc] base \(base.id) (iOS \(base.productVersion)), donor \(donor.id)")
- if let data = try? Data(contentsOf: cached), !data.isEmpty {
- log(" [kc] using the cached mix \(cached.path)")
+ let (base, paths) = try locations(for: kernelcache)
+ log(" [kc] base \(base.id) (iOS \(base.productVersion)), donor \(base.donor)")
+ if let data = try? Data(contentsOf: paths.mixed), !data.isEmpty {
+ log(" [kc] using the cached mix \(paths.mixed.path)")
return data
}
- try KernelCollectionBuilder.checkHost(for: base)
+ guard geteuid() == 0 else {
+ throw PatcherError.invalidFormat(Self.linkInstructions(staged: Self.isStaged(paths.staged)))
+ }
+ if !Self.isStaged(paths.staged) {
+ try stage(kernelcache: kernelcache)
+ }
+ return try link(kernelcache: kernelcache)
+ }
+
+ /// Extracts both kernelcaches and stages the volume kmutil links, as the
+ /// invoking user: the one step that runs `ipsw`. Does nothing when the mix
+ /// or its volume is already in the cache.
+ public func stage(kernelcache: Data) throws {
+ let (base, paths) = try locations(for: kernelcache)
+ guard !FileManager.default.fileExists(atPath: paths.mixed.path), !Self.isStaged(paths.staged) else { return }
+ try KernelCollectionBuilder.checkLayout(for: base)
+ let donor = try recipes.donor(id: base.donor)
+ let ipsw = try Self.ipsw()
- // A directory per run: a failed run keeps its logs.
let fm = FileManager.default
- let workRoot = cacheDirectory.appending(path: "work")
- for stale in (try? fm.contentsOfDirectory(atPath: workRoot.path)) ?? [] where stale.hasPrefix(base.id + ".") {
- try? fm.removeItem(at: workRoot.appending(path: stale))
- }
- let work = workRoot.appending(path: "\(base.id).\(UUID().uuidString.prefix(8))")
+ try? fm.removeItem(at: paths.staged)
+ let work = paths.staged.appending(path: "work")
try fm.createDirectory(at: work, withIntermediateDirectories: true)
- log(" [kc] work directory \(work.path)")
+ log(" [kc] staging in \(paths.staged.path)")
let donorKDK = try donorKDK(donor, ipsw: ipsw)
-
let payload = try Self.payload(of: kernelcache)
try Self.check(payload, base.kernel.decompressedSHA256, "decompressed \(base.kernel.file)")
let decompressed = work.appending(path: "\(base.kernel.file).decompressed")
@@ -128,23 +175,95 @@ public final class KernelCacheMixer {
let mixKDK = work.appending(path: "mix/\(base.kernel.kdk)")
let (removed, added) = try KernelCacheKDK.mix(base: baseKDK, donor: donorKDK, wanted: identifiers, output: mixKDK)
log(" [kc] mix: \(identifiers.count) kexts, \(removed.count) research board kexts removed, \(added.count) added from the donor")
+ try KernelCacheKDK.makeVolume(kdk: mixKDK, identifiers: identifiers, output: paths.staged.appending(path: "volume"))
+ try fm.removeItem(at: work)
+ try Data(ipsw.hash.utf8).write(to: paths.staged.appending(path: "ipsw.sha256"))
+ try Data().write(to: paths.staged.appending(path: Self.stagedMarker))
+ // Under sudo, so the user's later runs can replace it.
+ if geteuid() == 0 {
+ try VPhoneHostFilePermissions.makeAccessible(at: cacheDirectory)
+ }
+ log(" [kc] staged; linking needs root")
+ }
+
+ /// Links a staged volume, as root, and caches the result. Runs no `ipsw`:
+ /// the volume is copied into a directory only root can reach, with nothing
+ /// in it that points outside, and kmutil links that copy.
+ @discardableResult
+ public func link(kernelcache: Data) throws -> Data {
+ let (base, paths) = try locations(for: kernelcache)
+ if let data = try? Data(contentsOf: paths.mixed), !data.isEmpty {
+ return data
+ }
+ try KernelCollectionBuilder.checkLayout(for: base)
+ guard geteuid() == 0 else {
+ throw PatcherError.invalidFormat(Self.linkInstructions(staged: Self.isStaged(paths.staged)))
+ }
+ guard Self.isStaged(paths.staged) else {
+ throw PatcherError.fileNotFound("the staged \(base.id) kernelcache volume in \(paths.staged.path); run `vphone-cli fw kernelcache` with \(Self.ipswEnvironmentVariable) first")
+ }
- let volume = work.appending(path: "volume/\(Self.volumeName)")
- let kernel = try KernelCacheKDK.makeVolume(kdk: mixKDK, identifiers: identifiers, output: volume)
+ let payload = try Self.payload(of: kernelcache)
+ let copy = try KernelCacheVolumeCopy(
+ staged: paths.staged.appending(path: "volume"), kdk: base.kernel.kdk, pathLength: Self.buildRootLength(of: payload),
+ )
+ defer { copy.remove() }
log(" [kc] linking with kmutil")
+ let identifiers = try base.kextIdentifiers()
+ let kmutilLog = copy.root.appending(path: "kmutil.log")
+ // Beside the mix, whether the link worked or not: kmutil leaves out a
+ // kext it does not accept without failing.
+ defer {
+ if let text = try? Data(contentsOf: kmutilLog) {
+ try? storeMix(text, at: paths.mixed.deletingPathExtension().appendingPathExtension("kmutil.log"))
+ }
+ }
var output = try KernelCollectionBuilder.link(
- volume: volume, kernel: kernel, identifiers: identifiers, log: work.appending(path: "kmutil.log"),
+ volume: copy.volume, kernel: copy.kernel, identifiers: identifiers, log: kmutilLog,
)
-
- output = try finalize(output, original: payload, identifiers: identifiers, work: work)
- try fm.createDirectory(at: cached.deletingLastPathComponent(), withIntermediateDirectories: true)
- try output.write(to: cached)
- try? fm.removeItem(at: work)
- try VPhoneHostFilePermissions.makeAccessible(at: cacheDirectory)
- log(" [kc] mixed kernelcache: \(output.count) bytes, cached at \(cached.path)")
+ output = try finalize(output, original: payload, identifiers: identifiers, work: copy.root)
+ try storeMix(output, at: paths.mixed)
+ log(" [kc] mixed kernelcache: \(output.count) bytes, cached at \(paths.mixed.path)")
return output
}
+ // MARK: - Cache
+
+ static let stagedMarker = ".staged"
+
+ static func isStaged(_ directory: URL) -> Bool {
+ FileManager.default.fileExists(atPath: directory.appending(path: stagedMarker).path)
+ }
+
+ /// The recipe and where its mix and staged volume are kept.
+ func locations(for kernelcache: Data) throws -> (base: KernelCacheBase, paths: (mixed: URL, staged: URL)) {
+ let base = try base(for: kernelcache)
+ let key = try cacheKey(base: base, donor: recipes.donor(id: base.donor))
+ return (base, (
+ cacheDirectory.appending(path: "mix/\(base.id)/\(key).im4p"),
+ cacheDirectory.appending(path: "staged/\(base.id)/\(key)"),
+ ))
+ }
+
+ /// Writes the mix into the invoking user's cache without following a link:
+ /// root writes there.
+ func storeMix(_ data: Data, at url: URL) throws {
+ let user = VPhoneInvokingUser.current
+ let cache = cacheDirectory.standardizedFileURL.path
+ try FileManager.default.createDirectory(atPath: cache, withIntermediateDirectories: true)
+ let root = try VPhoneConfinedDirectory.pin(absolutePath: cache)
+ 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) })
+ }
+
+ public static func linkInstructions(staged: Bool) -> String {
+ let link = "sudo vphone-cli fw kernelcache <vm>"
+ return staged
+ ? "the kernelcache mix is staged; linking it needs root (kmutil only reads kexts owned by root). Run `\(link)`, or this command with sudo."
+ : "the kernelcache mix is not built yet. Stage it with `\(ipswEnvironmentVariable)=<ipsw> vphone-cli fw kernelcache <vm>`, then link it with `\(link)`, or run this command as `sudo \(ipswEnvironmentVariable)=<ipsw> vphone-cli ...`."
+ }
+
// MARK: - Steps
/// Puts back Apple's CPU subtype (the 26.x builder writes 0xc0000002 where
@@ -267,20 +386,16 @@ public final class KernelCacheMixer {
// MARK: - Helpers
- /// Where the mix of `base` is cached.
- func cachedMix(base: KernelCacheBase, ipsw: (url: URL, hash: String)) throws -> URL {
- let key = try cacheKey(base: base, donor: recipes.donor(id: base.donor), ipswHash: ipsw.hash)
- return cacheDirectory.appending(path: "mix/\(base.id)/\(key).im4p")
- }
-
- /// Everything that decides the output: the kernelcaches, maps and bundle
- /// list, the extracting ipsw, the layout and this file's steps.
- func cacheKey(base: KernelCacheBase, donor: KernelCacheDonor, ipswHash: String) throws -> String {
+ /// What decides the output: the kernelcaches, maps and bundle list, the
+ /// layout and this file's steps. Not the ipsw, which the root link does not
+ /// run: a stage records which one made it (`ipsw.sha256`), and removing
+ /// `~/.vphone/kernelcache` rebuilds everything.
+ func cacheKey(base: KernelCacheBase, donor: KernelCacheDonor) throws -> String {
var material = Data("\(Self.identity(base.kernel))|\(Self.identity(donor.kernel))|".utf8)
for url in [base.symbolsURL, base.kextsURL] + (donor.symbolsURL.map { [$0] } ?? []) {
material += try Data(contentsOf: url)
}
- material += Data("\(Self.revision)|\(ipswHash)|\(base.builderLayout.rawValue)|\(Self.volumeName.count)".utf8)
+ material += Data("\(Self.revision)|\(base.builderLayout.rawValue)".utf8)
return String(KernelCacheRecipes.sha256(material).prefix(16))
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KernelCacheVolumeCopy.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KernelCacheVolumeCopy.swift
new file mode 100644
index 00000000..300e51e6
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KernelCacheVolumeCopy.swift
@@ -0,0 +1,104 @@
+// KernelCacheVolumeCopy.swift — A staged volume where only root can reach it.
+//
+// The volume kmutil links is staged by the user (`fw kernelcache`, which runs
+// `ipsw`), and linked by root, which reads every file in it into a kernelcache
+// the user receives. So root does not link the staged folder: it copies it into
+// a fresh directory of its own, walking it by descriptor and recreating no link
+// but the KDK's own pointer to the volume's extensions. Nothing a user puts in
+// the stage can make kmutil read a file outside it, and nothing can change
+// under kmutil once the copy is made.
+
+import Foundation
+import VPhoneCoreKit
+import VPhonePatchKit
+
+struct KernelCacheVolumeCopy {
+ /// The private directory, removed by `remove()`.
+ let root: URL
+ let volume: URL
+ let kernel: URL
+
+ /// The one symbolic link a staged volume has, and where it points.
+ static func allowedLink(kdk: String) -> (path: String, target: String) {
+ ("Library/Developer/KDKs/\(kdk)/System/Library/Extensions", "../../../../../../System/Library/Extensions")
+ }
+
+ /// `pathLength` is the length the volume's absolute path must have
+ /// (`KernelCacheMixer.buildRootLength`); the volume's name makes it up.
+ init(staged: URL, kdk: String, pathLength: Int) throws {
+ var template = Array("/private/var/tmp/vphone-kc.XXXXXX".utf8CString)
+ guard let made = mkdtemp(&template) else {
+ throw PatcherError.invalidFormat("could not create a private directory for the kernelcache link: \(String(cString: strerror(errno)))")
+ }
+ root = URL(fileURLWithPath: String(cString: made), isDirectory: true)
+ let nameLength = pathLength - root.path.count - 1
+ guard (1 ... 255).contains(nameLength) else {
+ try? FileManager.default.removeItem(at: root)
+ throw PatcherError.invalidFormat("a kernelcache volume path of \(pathLength) characters does not fit below \(root.path)")
+ }
+ let name = String(repeating: "b", count: nameLength)
+ volume = root.appending(path: name)
+ kernel = volume.appending(path: "Library/Developer/KDKs/\(kdk)/System/Library/Kernels/kernel")
+ do {
+ // Refuses a symbolic link anywhere on the way to the stage.
+ let source = try VPhoneConfinedDirectory.pin(absolutePath: staged.standardizedFileURL.path)
+ let owner = try source.metadata().st_uid
+ guard owner == 0 || owner == VPhoneInvokingUser.current?.uid else {
+ throw PatcherError.invalidFormat("the staged kernelcache volume belongs to user \(owner), not to the invoking user")
+ }
+ let destination = try VPhoneConfinedDirectory.pin(absolutePath: root.path, requireOwner: 0)
+ try destination.copyTree(from: source, to: name, requireSourceOwner: owner, owner: (0, 0))
+ try Self.checkLinks(in: volume, kdk: kdk)
+ try Self.normaliseModes(in: volume)
+ var isDirectory: ObjCBool = false
+ guard FileManager.default.fileExists(atPath: kernel.path, isDirectory: &isDirectory), !isDirectory.boolValue else {
+ throw PatcherError.fileNotFound("the kernel in the staged kernelcache volume")
+ }
+ } catch {
+ remove()
+ throw error
+ }
+ }
+
+ /// Fails on any symbolic link but the KDK's link to the extensions.
+ static func checkLinks(in volume: URL, kdk: String) throws {
+ let allowed = allowedLink(kdk: kdk)
+ let fm = FileManager.default
+ guard let walk = fm.enumerator(atPath: volume.path) else {
+ throw PatcherError.fileNotFound(volume.path)
+ }
+ while let relative = walk.nextObject() as? String {
+ let path = volume.appending(path: relative).path
+ guard try fm.attributesOfItem(atPath: path)[.type] as? FileAttributeType == .typeSymbolicLink else { continue }
+ guard relative == allowed.path, try fm.destinationOfSymbolicLink(atPath: path) == allowed.target else {
+ throw PatcherError.invalidFormat("the staged kernelcache volume links \(relative) outside itself")
+ }
+ }
+ }
+
+ /// kmutil skips a kext with a group- or world-writable file as silently as
+ /// one it does not own, and the caches the stage reads from are shared with
+ /// mode 0777. The copy is root's own, so its modes are set here: 0755 for
+ /// directories and executables, 0644 for the rest.
+ static func normaliseModes(in volume: URL) throws {
+ let fm = FileManager.default
+ guard let walk = fm.enumerator(atPath: volume.path) else {
+ throw PatcherError.fileNotFound(volume.path)
+ }
+ for case let relative as String in walk {
+ let path = volume.appending(path: relative).path
+ let attributes = try fm.attributesOfItem(atPath: path)
+ let type = attributes[.type] as? FileAttributeType
+ guard type != .typeSymbolicLink else { continue }
+ let mode = (attributes[.posixPermissions] as? NSNumber)?.uint16Value ?? 0
+ let wanted: UInt16 = type == .typeDirectory || mode & 0o111 != 0 ? 0o755 : 0o644
+ if mode != wanted {
+ try fm.setAttributes([.posixPermissions: NSNumber(value: wanted)], ofItemAtPath: path)
+ }
+ }
+ }
+
+ func remove() {
+ try? FileManager.default.removeItem(at: root)
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KernelCollectionBuilder.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KernelCollectionBuilder.swift
index 17ac6aff..6db93582 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KernelCollectionBuilder.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KernelCollectionBuilder.swift
@@ -26,7 +26,7 @@ enum KernelCollectionBuilder {
}
/// Refuses before anything is extracted when this Mac cannot link `base`.
- static func checkHost(for base: KernelCacheBase) throws {
+ static func checkLayout(for base: KernelCacheBase) throws {
let host = ProcessInfo.processInfo.operatingSystemVersion
let layout = layout(forMacOS: host)
guard layout == base.builderLayout else {
@@ -36,11 +36,6 @@ enum KernelCollectionBuilder {
+ (base.builderLayout == .kernelLast ? "update this Mac to macOS 26.4 or later" : "link it on macOS 15"),
)
}
- guard geteuid() == 0 else {
- throw PatcherError.invalidFormat(
- "linking the kernelcache needs root: kmutil only reads kexts owned by root. Run this command with sudo.",
- )
- }
}
/// Link the volume at `volume` and return kmutil's IMG4 kernelcache.
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineDiscovery.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineDiscovery.swift
index d088b910..db2c9c3d 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineDiscovery.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineDiscovery.swift
@@ -35,6 +35,17 @@ extension FirmwarePipeline {
return restoreDir
}
+ /// The research board kernelcache the VM's mix is built from, as shipped:
+ /// its `RestoreKernelCache`, from the originals once `fw patch` has put it
+ /// aside. Nil when the restore tree has vphone600 components.
+ public func researchBoardKernelcache() throws -> Data? {
+ let restoreDir = try findRestoreDirectory()
+ guard Self.researchBoardStandsIn(restoreDir: restoreDir) else { return nil }
+ let file = try restoreDir.appending(path: Self.manifestComponentPath("RestoreKernelCache", in: restoreDir))
+ let stashed = originalURL(for: file).flatMap { FileManager.default.fileExists(atPath: $0.path) ? $0 : nil }
+ return try Data(contentsOf: stashed ?? file)
+ }
+
/// `ProductVersion` from a manifest in `restoreDir`, or nil if absent/unreadable.
static func readProductVersion(_ restoreDir: URL, manifest: String) -> String? {
let url = restoreDir.appendingPathComponent(manifest)
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/KernelCacheMixerTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/KernelCacheMixerTests.swift
index fce040df..6cc52f8d 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/KernelCacheMixerTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/KernelCacheMixerTests.swift
@@ -46,14 +46,22 @@ struct KernelCacheMixerTests {
#expect(!base.kernel.matches(sha: String(repeating: "0", count: 64)))
}
- @Test("A cached mix is keyed by the ipsw binary that extracted it")
- func cacheKeyFollowsIPSW() throws {
- let base = try #require(try Self.recipes.bases().first)
- let donor = try Self.recipes.donor(id: base.donor)
+ @Test("A mix is keyed by its recipe alone, which the root link can compute without ipsw")
+ func cacheKeyFollowsRecipe() throws {
+ let bases = try Self.recipes.bases()
let mixer = KernelCacheMixer(recipes: Self.recipes, verbose: false)
- let first = try mixer.cacheKey(base: base, donor: donor, ipswHash: "1")
- #expect(try mixer.cacheKey(base: base, donor: donor, ipswHash: "1") == first)
- #expect(try mixer.cacheKey(base: base, donor: donor, ipswHash: "2") != first)
+ let keys = try bases.map { try mixer.cacheKey(base: $0, donor: Self.recipes.donor(id: $0.donor)) }
+ #expect(Set(keys).count == bases.count)
+ let first = try #require(bases.first)
+ #expect(try mixer.cacheKey(base: first, donor: Self.recipes.donor(id: first.donor)) == keys.first)
+ }
+
+ @Test("The volume path takes the length of the build root the base records")
+ func buildRootLength() throws {
+ let root = "/AppleInternal/Library/BuildRoots/4~X/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS26.6.Internal.sdk"
+ let prelink = "<dict><key>_CodelessKextBundlePath</key><string>\(root)/System/Library/Extensions/A.kext</string></dict>"
+ #expect(try KernelCacheMixer.buildRootLength(of: Data(repeating: 0, count: 64) + Data(prelink.utf8)) == root.count)
+ #expect(throws: PatcherError.self) { try KernelCacheMixer.buildRootLength(of: Data("no prelink info".utf8)) }
}
@Test("macOS 26.4 is the first builder that links kernel-last")
@@ -121,5 +129,15 @@ struct KernelCacheMixerTests {
#expect(throws: PatcherError.self) {
try KernelCacheKDK.mix(base: base, donor: donor, wanted: wanted + ["com.apple.nowhere"], output: output)
}
+
+ // The staged volume root links holds no link but the KDK's own.
+ try KernelCacheVolumeCopy.checkLinks(in: volume, kdk: "KDK_26.6_23G71.kdk")
+ try FileManager.default.createSymbolicLink(
+ atPath: volume.appending(path: "System/Library/Extensions/Kept.kext/Kept2").path,
+ withDestinationPath: "/etc/master.passwd",
+ )
+ #expect(throws: PatcherError.self) {
+ try KernelCacheVolumeCopy.checkLinks(in: volume, kdk: "KDK_26.6_23G71.kdk")
+ }
}
}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift
index bc1749b7..b9384ea2 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift
@@ -14,6 +14,7 @@ struct VPhoneFirmwareCommand: ParsableCommand {
VPhoneFirmwareInspectCommand.self,
VPhoneFirmwarePrepareCommand.self,
VPhoneFirmwarePatchCommand.self,
+ VPhoneFirmwareKernelcacheCommand.self,
VPhoneFirmwarePatchesCommand.self,
VPhoneFirmwareSetPatchesCommand.self,
VPhoneFirmwareManifestCommand.self,
@@ -392,6 +393,16 @@ struct VPhoneFirmwarePatchCommand: ParsableCommand {
if mergesRestoreImage, geteuid() != 0 {
throw ValidationError("The \(selection.presetIdentifier) preset rebuilds the system image, which needs root. Run this command with sudo.")
}
+ // A research board kernelcache is mixed beforehand (`fw kernelcache`),
+ // since linking it needs root; root builds it here if need be.
+ if geteuid() != 0, !selection.blockedPatches.contains(FirmwareResearchBoardPatchSet.kernelMix),
+ let kernelcache = try FirmwarePipeline(vmDirectory: bundle.url, variant: .jb).researchBoardKernelcache()
+ {
+ let state = try KernelCacheMixer(recipes: .locate()).state(for: kernelcache)
+ if state != .mixed {
+ throw ValidationError(KernelCacheMixer.linkInstructions(staged: state == .staged).replacingOccurrences(of: "<vm>", with: name))
+ }
+ }
let pipeline = FirmwarePipeline(
vmDirectory: bundle.url,
@@ -653,3 +664,55 @@ extension VPhoneLibraryOption {
return " --library-root \(quoted)"
}
}
+
+// MARK: - kernelcache
+
+/// Builds the kernelcache mix of a VM on a cloudOS without vphone600
+/// components, in the two steps that need different users: staging runs `ipsw`
+/// and is the invoking user's, linking runs kmutil and is root's. `fw patch`
+/// then takes the mix from the cache. See KernelCacheMixer.
+struct VPhoneFirmwareKernelcacheCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "kernelcache",
+ abstract: "Build a research board VM's kernelcache mix: stage it as yourself (VPHONE_IPSW), link it with sudo",
+ )
+
+ @OptionGroup var lib: VPhoneLibraryOption
+ @Argument(help: "VM name") var name: String?
+ @Flag(help: ArgumentHelp(
+ "Only link a staged volume; never stage, so no ipsw runs (the Launchpad helper's root run)",
+ visibility: .hidden,
+ ))
+ var linkOnly = false
+
+ func run() throws {
+ let name = try VPhoneVirtualMachineSelection.resolveExisting(name, in: lib.library)
+ let bundle = try lib.library.bundle(named: name)
+ guard let kernelcache = try FirmwarePipeline(vmDirectory: bundle.url, variant: .jb).researchBoardKernelcache() else {
+ print("[=] \(name)'s cloudOS has vphone600 components; its kernelcache needs no mix.")
+ return
+ }
+ let mixer = try KernelCacheMixer(recipes: .locate())
+ let state = try mixer.state(for: kernelcache)
+ if state == .mixed {
+ print("[+] The kernelcache mix is ready; `fw patch` takes it from the cache.")
+ return
+ }
+ if geteuid() == 0 {
+ if state == .missing {
+ guard !linkOnly else {
+ throw ValidationError("\(name)'s kernelcache mix is not staged. Stage it first, as yourself: \(KernelCacheMixer.ipswEnvironmentVariable)=<ipsw> vphone-cli fw kernelcache \(name)")
+ }
+ try mixer.stage(kernelcache: kernelcache)
+ }
+ try mixer.link(kernelcache: kernelcache)
+ print("[+] The kernelcache mix is ready; `fw patch` takes it from the cache.")
+ return
+ }
+ guard !linkOnly else {
+ throw ValidationError("Linking the kernelcache mix needs root. Run this command with sudo.")
+ }
+ try mixer.stage(kernelcache: kernelcache)
+ print("[+] Staged. Link it with: sudo vphone-cli fw kernelcache \(name)")
+ }
+}
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/kernelcache_recipes/README.md b/VPhoneExecutable/VPhoneVirtualization/Resources/kernelcache_recipes/README.md
index 56a0a24c..5252e2b5 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/kernelcache_recipes/README.md
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/kernelcache_recipes/README.md
@@ -40,13 +40,23 @@ from the cloudOS IPSW, once, and kept with its extraction in
## Requirements
- An `ipsw` with `kernel extract --kdk` (blacktop/ipsw), named by `VPHONE_IPSW`.
- vphone-cli does not ship it.
-- Root: kmutil only reads kexts owned by root:wheel, and links the host's own
- kexts in place of any others without a word.
+ vphone-cli does not ship it, and runs it only as the invoking user.
+- Root for the link: kmutil only reads kexts owned by root:wheel, and links the
+ host's own kexts in place of any others without a word.
- A kmutil of the base's `builderLayout`: macOS 26.4 or later for every base here.
-Mixed kernelcaches are cached in `~/.vphone/kernelcache/mix`, keyed by everything
-that decides their bytes.
+`vphone-cli fw kernelcache <vm>` stages the mix as the user (the extractions
+and the volume, in `~/.vphone/kernelcache/staged`), and under sudo links it:
+root copies the volume into a directory of its own, refusing any link out of
+it, and runs kmutil on the copy. `fw patch` then takes the mix from the cache;
+run as `sudo VPHONE_IPSW=<ipsw> vphone-cli fw patch` it does both itself.
+
+Mixed kernelcaches are cached in `~/.vphone/kernelcache/mix`, keyed by the recipe,
+with kmutil's log beside each. Remove `~/.vphone/kernelcache` to rebuild them.
+
+kmutil records the absolute path of every codeless kext, so the volume is linked
+at a path as long as the build root Apple linked the base in, read from the
+base. The mix then does not depend on where it is built.
## Adding a base