Run a virtual iPhone on an Apple Silicon Mac.
Swift
Add cfw update-environment, for a VM whose restore tree is gone
Lakr2debf877dcc9
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swiftindex 1d853ab2..ac9eb2df 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift@@ -21,8 +21,39 @@ import VPhoneSign/// - root hands back only the files it created, by descriptor. It never walks/// the caller's folder to chown or chmod it.struct VPhoneCustomFirmwareInstaller {+ /// What a run does to the guest.+ enum Mode: String, Sendable {+ /// The whole install: cryptexes, the GPU bundle, every shared-cache and+ /// Mach-O patch the VM's plan selects, and the guest payload. Needs a+ /// prepared restore tree.+ case full+ /// Only the files this bundle ships into the guest — vphoned, its+ /// launch daemon, the guest dylibs and the libmisfix defaults — put+ /// back where a full install already placed them.+ ///+ /// No patch runs, nothing is injected, no cryptex or GPU work happens+ /// and no restore tree is needed. That last part is the point: the+ /// restore tree is deleted after a VM first boots, so a machine in+ /// normal use cannot be given an updated guest dylib by any other+ /// route, and the alternative — replacing the files in a running guest+ /// over the API — cannot update a library that is already mapped by a+ /// daemon that will not restart.+ ///+ /// Refuses a VM that has never had a full install: with nothing to put+ /// files back *over*, this would be laying down half an install.+ case environmentOnly++ var summary: String {+ switch self {+ case .full: "CFW system install"+ case .environmentOnly: "guest environment update"+ }+ }+ }+let bundle: URLlet resources: VPhoneResources+ var mode: Mode = .full/// Guest system files belong to root:wheel.private static let guestOwner: (uid: uid_t, gid: gid_t) = (0, 0)@@ -46,12 +77,16 @@ struct VPhoneCustomFirmwareInstaller {return build}- static func elevate(bundle: URL, resources: VPhoneResources) throws -> Int32 {+ static func elevate(+ bundle: URL,+ resources: VPhoneResources,+ mode: Mode = .full,+ ) throws -> Int32 {if geteuid() == 0 {- try VPhoneCustomFirmwareInstaller(bundle: bundle, resources: resources).run()+ try VPhoneCustomFirmwareInstaller(bundle: bundle, resources: resources, mode: mode).run()return 0}- throw ValidationError("CFW installation needs root. Run this command with sudo.")+ throw ValidationError("\(mode.summary.capitalized) needs root. Run this command with sudo.")}// MARK: - Work folder@@ -73,7 +108,9 @@ struct VPhoneCustomFirmwareInstaller {// MARK: - Installfunc run() throws {- guard geteuid() == 0 else { throw ValidationError("CFW installation needs root. Run this command with sudo.") }+ guard geteuid() == 0 else {+ throw ValidationError("\(mode.summary.capitalized) needs root. Run this command with sudo.")+ }// Ownership checks apply when the caller is known (SUDO_UID, which// the Launchpad helper also sets). Plain root trusts its own files.let invokingUser = VPhoneInvokingUser.current@@ -92,9 +129,13 @@ struct VPhoneCustomFirmwareInstaller {// openDiskImage holds our verified descriptor throughout the install,// so lsof always lists this process even when the VM is stopped.guard !VPhoneLsof.parsePIDs(busy.stdout).contains(where: { $0 != getpid() }) else {- throw ValidationError("The VM disk is in use. Stop the VM, then install CFW again.")+ throw ValidationError("The VM disk is in use. Stop the VM, then run \(mode.summary) again.")}- let restore = try restoreTree(in: bundleDirectory, path: bundlePath, owner: callerUID)+ // An environment update is exactly the case where there is no restore+ // tree left: it is deleted once the VM has booted.+ let restore = mode == .full+ ? try restoreTree(in: bundleDirectory, path: bundlePath, owner: callerUID)+ : nillet work = try makeWorkDirectory()defer {@@ -205,32 +246,48 @@ struct VPhoneCustomFirmwareInstaller {try mountGuestVolume("\(container)s1", at: system)dataMounted = truetry mountGuestVolume("\(container)s3", at: data)- print("[*] CFW system install: \(bundle.lastPathComponent)")+ print("[*] \(mode.summary.capitalized): \(bundle.lastPathComponent)")do {// Every descriptor on a guest volume lives in this scope, so none// is left open to hold the volume busy when it is unmounted.let systemRoot = try openGuestVolume("system", device: "\(container)s1", in: work)let dataRoot = try openGuestVolume("data", device: "\(container)s3", in: work)- try installMounted(- system: systemRoot,- data: dataRoot,- restore: restore,- work: work,- owner: callerUID,- plan: plan,- )+ switch mode {+ case .full:+ guard let restore else {+ throw ValidationError("A full CFW install needs a prepared restore tree.")+ }+ try installMounted(+ system: systemRoot,+ data: dataRoot,+ restore: restore,+ work: work,+ owner: callerUID,+ plan: plan,+ )+ case .environmentOnly:+ try updateEnvironmentMounted(system: systemRoot, work: work)+ }+ }+ // Both of these belong to a full install only. The Preboot patches go+ // with the boot chain, and the snapshot has already been renamed on any+ // VM an environment update is allowed to run against — this run creates+ // no new snapshot to flip.+ if mode == .full {+ try patchPreboot(volumes: volumes, work: work, plan: plan)}- try patchPreboot(volumes: volumes, work: work, plan: plan)_ = try tool("/sbin/umount", [data.path])dataMounted = false_ = try tool("/sbin/umount", [system.path])systemMounted = false_ = try tool("/usr/bin/hdiutil", ["detach", baseDisk], quiet: true)diskAttached = false- if cloned {- try VPhoneAPFSSnapshot.rename(imageAt: image)- } else {- try renameSnapshot(in: bundleDirectory, verified: disk, label: image)+ if mode == .full {+ if cloned {+ try VPhoneAPFSSnapshot.rename(imageAt: image)+ } else {+ try renameSnapshot(in: bundleDirectory, verified: disk, label: image)+ }}if cloned {// Hand the clone back with the original's owner and mode, then@@ -244,7 +301,57 @@ struct VPhoneCustomFirmwareInstaller {work: work,owner: invokingUser.map { ($0.uid, $0.gid) },)- print("[+] CFW system install complete; vphoned is installed, no package bootstrap was staged")+ switch mode {+ case .full:+ print("[+] CFW system install complete; vphoned is installed, no package bootstrap was staged")+ case .environmentOnly:+ print("[+] Guest environment updated; start the VM to pick it up")+ }+ }++ // MARK: - Environment update++ /// Put this bundle's guest payload back over the copies a full install+ /// already placed, and change nothing else.+ ///+ /// Every file written here is one `installVphoned` and `installEnvironment`+ /// write during a full install, through the same confined descriptors, with+ /// the same modes and owners. What is deliberately absent is everything+ /// that makes a guest a CFW guest in the first place: no shared-cache or+ /// Mach-O patch runs, no load command is injected, no cryptex or GPU work+ /// happens, and the recorded variant is untouched.+ ///+ /// A missing target is left missing. The libraries are not all+ /// unconditional — a VM whose plan left a patch out never received the+ /// library that goes with it — and an update is not the place to add one.+ private func updateEnvironmentMounted(system: VPhoneConfinedDirectory, work: WorkDirectory) throws {+ // Evidence that a full install ran. `launchd.plist.bak` is written by+ // the first `installVphoned` and by nothing else, so its absence means+ // this guest has never been installed and there is nothing to update.+ guard try system.exists("System/Library/xpc/launchd.plist.bak") else {+ throw ValidationError(+ "This VM has no CFW install to update. Run `vphone-cli cfw install` first.",+ )+ }++ try installVphoned(system: system, work: work)+ print(" [+] vphoned and its launch daemon")++ for name in VPhoneGuestEnvironment.libraries {+ let path = "usr/lib/\(name)"+ guard try system.exists(path) else {+ print(" [·] \(path): not on this VM, left out")+ continue+ }+ let source = try VPhoneGuestBinaries.resolve(name)+ try system.replaceFile(path, fromFileAt: source, mode: 0o755, owner: Self.guestOwner)+ print(" [+] \(path)")+ }++ // Only when the guest has none, exactly as a full install does: the+ // file carries a per-machine UDID choice and is not the bundle's to+ // overwrite.+ try installMISFixDefaults(system: system)}/// Host bookkeeping in the caller's folder, written with the caller'sdiff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swiftindex 949e6e70..32abf654 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swift@@ -171,6 +171,7 @@ struct VPhoneCustomFirmwareCommand: ParsableCommand {subcommands: [VPhoneCustomFirmwareInstallCommand.self,VPhoneCustomFirmwareInstallRootCommand.self,+ VPhoneCustomFirmwareUpdateEnvironmentCommand.self,VPhoneCustomFirmwareFlipSnapshotCommand.self,// The per-step patchers the installers used to reach through// scripts/patchers/cfw.py for — see VPhoneCustomFirmwarePatchCommand.swift.@@ -277,3 +278,49 @@ struct VPhoneCustomFirmwareInstallCommand: ParsableCommand {}}}++/// Redeploy this bundle's guest payload into a VM that is already installed.+///+/// The gap it fills: `cfw install` needs a prepared restore tree, and the+/// restore tree is deleted once a VM has booted. So until now an existing+/// machine could not be given an updated vphoned or guest dylib at all — and+/// replacing a library in a running guest over the API cannot help either,+/// because a daemon keeps the copy it mapped at launch.+///+/// Deliberately narrow. It writes only the files a full install writes into the+/// guest, runs no patch, injects nothing, and leaves the recorded variant+/// alone, so it cannot turn a half-built VM into something that looks+/// installed. A VM that was never installed is refused rather than half-filled.+struct VPhoneCustomFirmwareUpdateEnvironmentCommand: ParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "update-environment",+ abstract: "Redeploy vphoned and the guest dylibs into an installed VM (VM must be off)",+ discussion: """+ Puts back only what this bundle ships into the guest: vphoned and its+ launch daemon, the guest dylibs in /usr/lib, and the libmisfix defaults+ if the VM has none. No firmware patch runs, no load command is injected,+ no cryptex or GPU work happens, and the VM's recorded variant does not+ change.++ Use it to move an existing VM onto a newer bundle without rebuilding it.+ A library the VM does not already have is left out, because its absence+ means the VM's patch plan never selected it.++ Needs root, and the VM must be powered off.+ """,+ )++ @OptionGroup var lib: VPhoneLibraryOption+ @Argument(help: "VM name") var name: String?++ func run() throws {+ let name = try VPhoneVirtualMachineSelection.resolveExisting(name, in: lib.library)+ let bundle = try lib.library.bundle(named: name)+ let code = try VPhoneCustomFirmwareInstaller.elevate(+ bundle: bundle.url,+ resources: VPhoneResources.resolve(),+ mode: .environmentOnly,+ )+ throw ExitCode(code)+ }+}