Run a virtual iPhone on an Apple Silicon Mac.
Swift
Converge public flows on JB and require vphoned
Lakrb04425d1658a
diff --git a/Makefile b/Makefileindex 23ef4e7d..6a113bb7 100644--- a/Makefile+++ b/Makefile@@ -90,8 +90,6 @@ help:@echo " make amfi_off Remove the allowlist and restart amfid clean"@echo " make boot_host_preflight Diagnose whether host can launch signed PV=3 binary"@echo " make boot Boot VM (reads from config.plist)"- @echo " make boot_less Boot VM in vphoned patchless compatibility mode"- @echo " Options: NO_VPHONED=1 Skip installing vphoned"@echo " make boot_dfu Boot VM in DFU mode (reads from config.plist)"@echo ""@echo "Firmware pipeline:"@@ -102,28 +100,11 @@ help:@echo " IPHONE_BUILD= Resolve a downloadable iPhone build to an IPSW URL"@echo " IPHONE_SOURCE= URL or local path to iPhone IPSW"@echo " CLOUDOS_SOURCE= URL or local path to cloudOS IPSW"- @echo " make fw_patch Patch boot chain with Swift pipeline (regular variant)"+ @echo " make fw_patch Patch boot chain with the JB Swift pipeline"@echo " Options: FORCE_EXC_GUARD=1 Force the EXC_GUARD Mach-port-guard disable patch even on bases"@echo " that don't strictly need it to boot (e.g. a 3rd-party app's"@echo " crash-reporting SDK trips a fatal GUARD_TYPE_MACH_PORT violation)"- @echo " make fw_patch_less Patch boot chain with Swift pipeline (less patches)"- @echo " Options: NO_BINPACK=1 Skip installing the SSH, VNC and other bundled binaries"- @echo " NO_VPHONED=1 Skip installing vphoned"- @echo " make fw_patch_dev Patch boot chain with Swift pipeline (dev mode TXM patches)"- @echo " make fw_patch_jb Patch boot chain with Swift pipeline (dev + JB extensions)"- @echo " Options: FORCE_EXC_GUARD=1 (see fw_patch above)"@echo " FRIDA=1 Opt in to the Frida Stalker kernel relaxations"- @echo " make fw_patch_exp Patch boot chain with Swift pipeline (JB + EXP experimental)"- @echo " Options: FORCE_EXC_GUARD=1 (see fw_patch above)"- @echo " FRIDA=1 Opt in to the Frida Stalker kernel relaxations"- @echo ""- @echo "Testing:"- @echo " make test_jb_patches Run all JB kernel patches (incl. Sandbox) over every supported cloudOS kernel"- @echo " Options: QUICK=1 Only the local/newest kernel (fast dev loop)"- @echo " make test_fw_patches Run the FULL patch-firmware pipeline (boot chain + base kernel + JB + EXP) over"- @echo " each local cloudOS firmware; fails if any sub-patch is skipped"- @echo " Options: QUICK=1 Only the newest local cloudOS firmware"- @echo " VARIANTS=\"exp\" Limit to specific variants (default: jb exp)"@echo ""@echo "Restore:"@echo " make restore_get_shsh Dump SHSH response from Apple"@@ -131,11 +112,7 @@ help:@echo " make restore_offline Restore offline from the cached .shsh file (decrypts AEA images in place)"@echo ""@echo "CFW (host-mount install; VM must be off, re-execs sudo):"- @echo " make cfw_install Install base CFW mods"- @echo " make cfw_install_dev Install CFW mods (dev mode)"- @echo " make cfw_install_jb Install CFW + JB extensions (jetsam/procursus/basebin)"- @echo " make cfw_install_exp Install CFW + JB + EXP experimental (hv_vmm rename, post-restore DT, build spoof)"- @echo " make cfw_install_host Select variant: VARIANT=regular|dev|jb|exp (default exp) SPOOF_BUILD=<id> (exp)"+ @echo " make cfw_install Install JB CFW via host mount"@echo ""@echo "Variables: VM_DIR=$(VM_DIR) SWIFT_JOBS=$(SWIFT_JOBS)"@@ -252,83 +229,29 @@ $(AMFI_BINARY): $(AMFI_SOURCE)@codesign --force --sign - $(AMFI_BINARY)@echo " signed: vphone-amfi-allow"-# `bundle` produces the SAME bundle scripts/build.sh does, Resources included.-#-# It did not, until now: build.sh staged Contents/Resources/scripts and this-# target did not, so `make check-aux` — which depends on this — was inspecting a-# five-binary bundle while the thing users actually get carried twenty scripts-# and a Homebrew-linked trustcache. The gate was green because it was looking at-# the wrong artifact. Both paths now read the same allowlist.-bundle: build $(AMFI_BINARY) guest_binaries $(INFO_PLIST)- @# `build` re-signs unconditionally now, so the copies below are always- @# made from a freshly entitled vphone-vm rather than from whatever a bare- @# `swift build` last left in .build/release.- @mkdir -p $(BUNDLE)/Contents/MacOS $(BUNDLE)/Contents/Resources- @cp -f $(BINARY) $(BUNDLE_BIN)- @cp -f $(VM_BINARY) $(BUNDLE_VM)- @cp -f $(ARCHIVE_BINARY) $(BUNDLE_ARCHIVE)- @cp -f $(ASKPASS_BINARY) $(BUNDLE_ASKPASS)- @cp -f $(AMFI_BINARY) $(BUNDLE_AMFI)- @cp -f $(INFO_PLIST) $(BUNDLE)/Contents/Info.plist- @cp -f sources/AppIcon.icns $(BUNDLE)/Contents/Resources/AppIcon.icns- @cp -f $(SCRIPTS)/vphoned/signcert.p12 $(BUNDLE)/Contents/Resources/signcert.p12- @# The bundle is built over whatever is already there, so these are removed- @# although nothing copies any of them any more: bundles built before- @# VPhoneSign replaced ldid carry the Homebrew ldid; bundles built before the- @# AMFI bypass became ours carry vphone-letmein, which patched amfid's __TEXT- @# — a write the kernel kills amfid for wherever vm.cs_system_enforcement is- @# 1; and .tools/bin/trustcache linked /opt/homebrew's libcrypto.3 while- @# nothing ever invoked it. They have to go BEFORE the seal below, not after- @# — removing nested code from a sealed bundle is what makes `codesign -v`- @# report it modified.- @rm -f $(BUNDLE)/Contents/MacOS/ldid $(BUNDLE)/Contents/MacOS/vphone-letmein- @rm -rf $(BUNDLE)/Contents/Resources/scripts $(BUNDLE)/Contents/Resources/guest \- $(BUNDLE)/Contents/Resources/.tools $(BUNDLE)/Contents/Resources/tools- @mkdir -p $(BUNDLE)/Contents/Resources/scripts- @zsh $(SCRIPTS)/dist_manifest.sh \- | rsync -a --files-from=- $(SCRIPTS)/ $(BUNDLE)/Contents/Resources/scripts/- @cp -R $(GUEST_DIR) $(BUNDLE)/Contents/Resources/guest- @cp -f debs.list $(BUNDLE)/Contents/Resources/debs.list- @cp -f README.md $(BUNDLE)/Contents/Resources/README.md- @# Order matters: vphone-vm is CFBundleExecutable, so signing it seals the- @# whole bundle and everything beside it counts as nested code. Sign the- @# nested binaries FIRST, or `codesign -v` reports "nested code is modified".- @codesign --force --sign - $(BUNDLE_BIN)- @codesign --force --sign - $(BUNDLE_ARCHIVE)- @codesign --force --sign - $(BUNDLE_ASKPASS)- @codesign --force --sign - $(BUNDLE_AMFI)- @codesign --force --sign - --entitlements $(ENTITLEMENTS) $(BUNDLE_VM)- @codesign -v $(BUNDLE_VM) \- || (echo "Error: the bundle seal did not verify after signing." >&2; exit 1)- @echo " bundled → $(BUNDLE)"+# One packaging implementation: direct builds and `make bundle` stage the same resources.+bundle:+ @zsh $(SCRIPTS)/build.sh# The five iOS binaries the guest runs. Compiled here, on the build machine,# because compiling them at CFW-install time is what made Xcode a prerequisite# for running a VM. See scripts/guest_binaries.mk.include $(SCRIPTS)/guest_binaries.mk-# vphoned for a LIVE guest: the copy the host pushes over vsock, signed here-# because there is no VM cfw_input in that flow. `vphone-cli sign` replaces the-# `ldid` this used to need, so the build has no Homebrew dependency either.+# vphoned for a live guest. This target only prepares the build artifact;+# `boot` stages it into its VM after `bundle` has completed..PHONY: vphonedvphoned: $(GUEST_DIR)/vphoned $(BINARY)@cp -f $(GUEST_DIR)/vphoned .build/vphoned.signed@$(BINARY) sign --entitlements $(SCRIPTS)/vphoned/entitlements.plist --merge \--pkcs12 $(SCRIPTS)/vphoned/signcert.p12 .build/vphoned.signed@echo " signed → .build/vphoned.signed"- @# The VM-local copy the guest auto-update path reads. Same bytes, second- @# location; the `ldid` invocation that used to be here is the same- @# `vphone-cli sign` above.- @if [ -d "$(VM_DIR_ABS)" ]; then \- cp -f .build/vphoned.signed $(VM_DIR_ABS)/.vphoned.signed; \- echo " signed → $(VM_DIR)/.vphoned.signed"; \- fi# ═══════════════════════════════════════════════════════════════════# VM management# ═══════════════════════════════════════════════════════════════════-.PHONY: amfi_allow amfi_status amfi_off boot_host_preflight boot boot_less boot_dfu boot_binary_check boot_binary_check_less+.PHONY: amfi_allow amfi_status amfi_off boot_host_preflight boot boot_dfu boot_binary_check# Self-containment checks over the complete application bundle.# CHECK_AUX_FAST=1 skips smoke checks for local source checks only.@@ -410,22 +333,14 @@ define BOOT_BINARY_CHECKrm -f "$$tmp_log"endef-boot_binary_check_less: $(BINARY)- $(call BOOT_BINARY_CHECK,--assert-bootable --less)-boot_binary_check: $(BINARY)$(call BOOT_BINARY_CHECK,--assert-bootable)-boot: bundle vphoned boot_binary_check+boot: bundle boot_binary_check+ @cp -f "$(BUNDLE)/Contents/Resources/vphoned.signed" "$(VM_DIR_ABS)/.vphoned.signed"cd "$(VM_DIR)" && "$(CURDIR)/$(BUNDLE_BIN)" \--config ./config.plist-boot_less: bundle boot_binary_check_less- cd "$(VM_DIR)" && "$(CURDIR)/$(BUNDLE_BIN)" \- --config ./config.plist \- --variant less \- $(if $(call truthy,$(NO_VPHONED)),--no-vphoned,)-boot_dfu: build boot_binary_checkcd "$(VM_DIR)" && "$(CURDIR)/$(BINARY)" \--config ./config.plist \@@ -435,64 +350,16 @@ boot_dfu: build boot_binary_check# Firmware pipeline# ═══════════════════════════════════════════════════════════════════-.PHONY: fw_prepare fw_patch fw_patch_less fw_patch_dev fw_patch_jb fw_patch_exp+.PHONY: fw_prepare fw_patchfw_prepare:cd "$(VM_DIR)" && bash "$(CURDIR)/$(SCRIPTS)/fw_prepare.sh"fw_patch: patcher_build- "$(CURDIR)/$(PATCHER_BINARY)" patch-firmware --vm-directory "$(VM_DIR_ABS)" --variant regular \- $(if $(call truthy,$(FORCE_EXC_GUARD)),--force-exc-guard,)--UID := $(shell id -u)-ifeq ($(UID),0)-fw_patch_less: patcher_build"$(CURDIR)/$(PATCHER_BINARY)" patch-firmware --vm-directory "$(VM_DIR_ABS)" \- --variant less \- $(if $(call truthy,$(NO_BINPACK)),--no-binpack,) \- $(if $(call truthy,$(NO_VPHONED)),--no-vphoned,)-else-fw_patch_less:- @echo "Error: fw_patch_less needs root. Run: sudo make fw_patch_less"- @exit 1-endif--fw_patch_dev: patcher_build- "$(CURDIR)/$(PATCHER_BINARY)" patch-firmware --vm-directory "$(VM_DIR_ABS)" --variant dev--fw_patch_jb: patcher_build- "$(CURDIR)/$(PATCHER_BINARY)" patch-firmware --vm-directory "$(VM_DIR_ABS)" --variant jb \$(if $(call truthy,$(FORCE_EXC_GUARD)),--force-exc-guard,) \$(if $(call truthy,$(FRIDA)),--frida,)-fw_patch_exp: patcher_build- "$(CURDIR)/$(PATCHER_BINARY)" patch-firmware --vm-directory "$(VM_DIR_ABS)" --variant exp \- $(if $(call truthy,$(FORCE_EXC_GUARD)),--force-exc-guard,) \- $(if $(call truthy,$(FRIDA)),--frida,)--.PHONY: test_jb_patches--# Run the full JB kernel patch layer (every hook, incl. all Sandbox ops hooks)-# over EVERY cloudOS kernel the README supports — correctness + backward-compat.-# Downloads each version's kernelcache on demand (cached under /tmp/vphone_kjb_versions).-# Options: QUICK=1 Only the local/newest kernel (fast dev loop)-test_jb_patches: patcher_build- zsh "$(CURDIR)/tests/test_jb_kernel_patches.sh" --no-build \- $(if $(call truthy,$(QUICK)),--quick,)--.PHONY: test_fw_patches--# Run the FULL patch-firmware pipeline (boot chain + base kernel + JB + EXP, every-# component) over each locally-prepared cloudOS firmware, for the jb and exp-# variants, and fail if ANY component skips a sub-patch (a `[-]` line). This is the-# broad gate that catches drift outside the JB kernel layer (iBSS/iBEC/LLB, base-# KernelPatcher, TXM, DeviceTree) — which test_jb_patches structurally cannot see.-# Options: QUICK=1 Only the newest local cloudOS firmware-# VARIANTS="exp" Limit to specific variants (default: jb exp)-test_fw_patches: patcher_build- zsh "$(CURDIR)/tests/test_firmware_patches.sh" --no-build \- $(if $(call truthy,$(QUICK)),--quick,)-# ═══════════════════════════════════════════════════════════════════# Restore# ═══════════════════════════════════════════════════════════════════@@ -578,22 +445,7 @@ restore_offline: build# CFW# ═══════════════════════════════════════════════════════════════════-.PHONY: cfw_install cfw_install_dev cfw_install_jb cfw_install_exp cfw_install_host+.PHONY: cfw_installcfw_install:- $(MAKE) cfw_install_host VARIANT=regular--cfw_install_dev:- $(MAKE) cfw_install_host VARIANT=dev--cfw_install_jb:- $(MAKE) cfw_install_host VARIANT=jb FRIDA="$(FRIDA)"--cfw_install_exp:- $(MAKE) cfw_install_host VARIANT=exp SPOOF_BUILD="$(SPOOF_BUILD)" FRIDA="$(FRIDA)"--# CFW install: place files via host mount + flip the boot snapshot offline.-# VM must be off; re-execs under sudo.-# Options: VARIANT=regular|dev|jb|exp (default exp) SPOOF_BUILD=<id> (exp)-cfw_install_host:- $(if $(SPOOF_BUILD),SPOOF_BUILD="$(SPOOF_BUILD)") $(if $(call truthy,$(FRIDA)),VPHONE_FRIDA=1) zsh "$(CURDIR)/$(SCRIPTS)/cfw_install_host.sh" --variant $(if $(VARIANT),$(VARIANT),exp) "$(VM_DIR_ABS)"+ $(if $(call truthy,$(FRIDA)),VPHONE_FRIDA=1) zsh "$(CURDIR)/$(SCRIPTS)/cfw_install_host.sh" --variant jb "$(VM_DIR_ABS)"diff --git a/scripts/build.sh b/scripts/build.shindex a2cd43c5..6bc54fa4 100755--- a/scripts/build.sh+++ b/scripts/build.sh@@ -10,7 +10,6 @@## Usage:# ./scripts/build.sh # build + sign + bundle + vphoned-# ./scripts/build.sh --no-vphoned # skip the vphoned cross-compileset -euo pipefailSCRIPT_DIR="${0:A:h}"@@ -46,11 +45,9 @@ ENTITLEMENTS="sources/vphone.entitlements"BUILD_INFO="sources/VPhoneCore/VPhoneBuildInfo.swift"GIT_HASH="$(git rev-parse --short HEAD 2>/dev/null || echo unknown)"-BUILD_VPHONED=1for arg in "$@"; docase "$arg" in- --no-vphoned) BUILD_VPHONED=0 ;;- -h|--help) echo "Usage: $0 [--no-vphoned]"; exit 0 ;;+ -h|--help) echo "Usage: $0"; exit 0 ;;*) echo "Unknown option: $arg" >&2; exit 1 ;;esacdone@@ -139,20 +136,15 @@ echo " bundled → ${BUNDLE}"# --- Guest binaries (cross-compiled for iOS; see scripts/guest_binaries.mk) ---# All five of them, because compiling them at CFW-install time is what made# Xcode a requirement for running a VM. This is the build machine; it has Xcode.-if [[ "$BUILD_VPHONED" -eq 1 ]]; then- make -f scripts/guest_binaries.mk guest_binaries GIT_HASH="$GIT_HASH"- # vphoned.signed is the copy the host pushes into a *running* guest over vsock,- # so it is signed here rather than at install time. ldid used to do this;- # `vphone-cli sign` writes the same bytes and needs no Homebrew, which takes- # the last external program out of the build as well as out of dist.- echo "=== Signing vphoned ==="- cp .build/guest/vphoned .build/vphoned.signed- "$BINARY" sign \- --entitlements scripts/vphoned/entitlements.plist --merge \- --pkcs12 scripts/vphoned/signcert.p12 \- .build/vphoned.signed- echo " signed → .build/vphoned.signed"-fi+make -f scripts/guest_binaries.mk guest_binaries GIT_HASH="$GIT_HASH"+# vphoned.signed is the copy the host pushes into a running guest over vsock.+echo "=== Signing vphoned ==="+cp .build/guest/vphoned .build/vphoned.signed+"$BINARY" sign \+ --entitlements scripts/vphoned/entitlements.plist --merge \+ --pkcs12 scripts/vphoned/signcert.p12 \+ .build/vphoned.signed+echo " signed → .build/vphoned.signed"# --- Bundle the standalone runtime mini-repo into Contents/Resources ---RES="${BUNDLE}/Contents/Resources"@@ -210,7 +202,7 @@ echo " vphone-archive : ${ARCHIVE_BINARY}"echo " vphone-ask-for-permission : ${ASKPASS_BINARY}"echo " vphone-amfi-allow : ${AMFI_BINARY} (arm64e)"echo " bundle : ${BUNDLE}"-[[ "$BUILD_VPHONED" -eq 1 ]] && echo " vphoned : .build/vphoned.signed"+echo " vphoned : .build/vphoned.signed"echo ""echo "Run: ${BINARY} --help"echo "If vphone-vm is killed the moment it launches, amfid refused its entitlements."diff --git a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcher.swift b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcher.swiftindex ad041a36..18814190 100644--- a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcher.swift+++ b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcher.swift@@ -26,7 +26,6 @@ public final class CryptexFilesystemPatcher: Patcher {public let restoreDir: URLpublic let verbose: Boolpublic let noBinpack: Bool- public let noVphoned: Boollet vphoneCliDirectory = URL(filePath: "./")let resources = VPhoneResources.resolve()@@ -40,14 +39,12 @@ public final class CryptexFilesystemPatcher: Patcher {buildManiest: Data,restoreDir: URL,verbose: Bool = true,- noBinpack: Bool = false,- noVphoned: Bool = false+ noBinpack: Bool = false) {self.buildManiest = buildManiestself.restoreDir = restoreDirself.verbose = verboseself.noBinpack = noBinpack- self.noVphoned = noVphoned}deinit {@@ -154,23 +151,18 @@ public final class CryptexFilesystemPatcher: Patcher {print("- Patching mobile activation…")try patchMobileActivation(targetMount: targetMount, cfwInput: cfwInputPath)- if !noVphoned {- print("- Adding vphoned…")- try addVphoned(targetMount: targetMount, cfwInput: cfwInputPath)- }+ print("- Adding vphoned…")+ try addVphoned(targetMount: targetMount, cfwInput: cfwInputPath)if !noBinpack {print("- Adding binpack…")try addExtraServices(targetMount: targetMount, cfwInput: cfwInputPath)}- if !noVphoned || !noBinpack {- try injectLaunchDaemons(- targetMount: targetMount,- cfwInput: cfwInputPath,- vphoned: !noVphoned,- cfw: !noBinpack- )- try patchLaunchdCacheLoader(targetMount: targetMount, cfwInput: cfwInputPath)- }+ try injectLaunchDaemons(+ targetMount: targetMount,+ cfwInput: cfwInputPath,+ cfw: !noBinpack+ )+ try patchLaunchdCacheLoader(targetMount: targetMount, cfwInput: cfwInputPath)}print("- Finalizing merged image…")diff --git a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherGuestPayload.swift b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherGuestPayload.swiftindex 5427e0e1..03d663ed 100644--- a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherGuestPayload.swift+++ b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherGuestPayload.swift@@ -54,7 +54,7 @@ extension CryptexFilesystemPatcher {)}- func injectLaunchDaemons(targetMount: String, cfwInput: URL, vphoned: Bool = true, cfw: Bool = true) throws {+ func injectLaunchDaemons(targetMount: String, cfwInput: URL, cfw: Bool = true) throws {let target = URL.init(filePath: targetMount)let scriptDir = resources.scriptsDir@@ -65,18 +65,16 @@ extension CryptexFilesystemPatcher {try FileManager.default.createDirectory(at: launchDaemonsPath, withIntermediateDirectories: false)try FileManager.default.moveItem(at: launchdOgPath, to: launchdPath)- if vphoned {- let vphonedSrc = scriptDir.appendingPathComponent("vphoned")- let vphonedLaunchdPlist = vphonedSrc.appending(path: "vphoned.plist")- try FileManager.default.copyItem(- at: vphonedLaunchdPlist,- to: target.appending(path: "System/Library/LaunchDaemons/vphoned.plist")- )- try FileManager.default.copyItem(- at: vphonedLaunchdPlist,- to: launchDaemonsPath.appending(path: vphonedLaunchdPlist.lastPathComponent)- )- }+ let vphonedSrc = scriptDir.appendingPathComponent("vphoned")+ let vphonedLaunchdPlist = vphonedSrc.appending(path: "vphoned.plist")+ try FileManager.default.copyItem(+ at: vphonedLaunchdPlist,+ to: target.appending(path: "System/Library/LaunchDaemons/vphoned.plist")+ )+ try FileManager.default.copyItem(+ at: vphonedLaunchdPlist,+ to: launchDaemonsPath.appending(path: vphonedLaunchdPlist.lastPathComponent)+ )if cfw {let launchDaemonsDir = cfwInput.appending(path: "cfw_input/jb/LaunchDaemons")let launchDaemons = try FileManager.default.contentsOfDirectory(atPath: launchDaemonsDir.path)diff --git a/sources/FirmwarePatcher/Pipeline/FirmwarePipeline.swift b/sources/FirmwarePatcher/Pipeline/FirmwarePipeline.swiftindex 998b7b1c..038d803a 100644--- a/sources/FirmwarePatcher/Pipeline/FirmwarePipeline.swift+++ b/sources/FirmwarePatcher/Pipeline/FirmwarePipeline.swift@@ -82,7 +82,6 @@ public final class FirmwarePipeline {let variant: Variantlet verbose: Boollet noBinpack: Bool- let noVphoned: Boollet forceExcGuard: Boollet enableFrida: Boollet loader: any FirmwareLoader@@ -94,7 +93,6 @@ public final class FirmwarePipeline {variant: Variant = .regular,verbose: Bool = true,noBinpack: Bool = false,- noVphoned: Bool = false,forceExcGuard: Bool = false,enableFrida: Bool = false,loader: (any FirmwareLoader)? = nil@@ -103,7 +101,6 @@ public final class FirmwarePipeline {self.variant = variantself.verbose = verboseself.noBinpack = noBinpack- self.noVphoned = noVphonedself.forceExcGuard = forceExcGuardself.enableFrida = enableFridaself.loader = loader ?? ContainerFirmwareLoader()diff --git a/sources/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift b/sources/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swiftindex da7ee82a..42df9de3 100644--- a/sources/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift+++ b/sources/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift@@ -226,8 +226,7 @@ extension FirmwarePipeline {buildManiest: data,restoreDir: restoreDir,verbose: verbose,- noBinpack: self.noBinpack,- noVphoned: self.noVphoned+ noBinpack: self.noBinpack)}]case .regular, .dev, .jb, .exp:diff --git a/sources/VPhoneCore/VPhoneBootCLI.swift b/sources/VPhoneCore/VPhoneBootCLI.swiftindex 6887ffec..ae224cd1 100644--- a/sources/VPhoneCore/VPhoneBootCLI.swift+++ b/sources/VPhoneCore/VPhoneBootCLI.swift@@ -1,24 +1,6 @@import ArgumentParserimport Foundation-// MARK: - VPhoneVariant--/// Which firmware variant a guest is running.-///-/// This used to be nested inside `VPhoneVirtualMachine`, which put it on the-/// far side of the Virtualization framework. It is a five-case string enum with-/// no VM in it, and both binaries need it — `vphone-cli` to accept `--variant`,-/// `vphone-vm` to configure the machine — so it belongs down here. The kit-/// keeps a `VPhoneVirtualMachine.Variant` typealias so existing call sites read-/// the same as before.-public enum VPhoneVariant: String, Sendable, CaseIterable, ExpressibleByArgument {- case less- case regular- case dev- case jb- case exp-}-// MARK: - Manifest values the CLI can take as arguments// Kept here, with the other ArgumentParser conformances, rather than beside@@ -34,8 +16,8 @@ extension VPhoneVirtualMachineManifest.PlatformFusing: ExpressibleByArgument {}/// the machine and becomes the NSApplication. `vphone-cli` only *forwards* it,/// re-rendering itself through `bootArguments` and spawning `vphone-vm`.///-/// Keeping one declaration is what makes the two agree about what `--dfu` or-/// `--variant jb` mean, and it means `vphone-cli boot --help` and+/// Keeping one declaration is what makes the two agree about `--dfu`, and+/// means `vphone-cli boot --help` and/// `vphone-vm --help` cannot drift apart.////// Note it has no `run()` that boots. `vphone-cli`'s entry point recognises@@ -81,18 +63,12 @@ public struct VPhoneBootCLI: ParsableCommand {@Option(help: "Path to signed vphoned binary for guest auto-update")public var vphonedBin: String = ".vphoned.signed"- @Option(name: [.customShort("V"), .long], help: "Firmware variant to execute.")- public var variant: VPhoneVariant = .regular-@Option(help: "Automatically install the given IPA/TIPA after the guest control channel connects. Unavailable with --dfu.",transform: URL.init(fileURLWithPath:))public var installIPA: URL?- @Flag(name: .customLong("no-vphoned"), help: "Exclude vphoned usage (patchless-only).")- public var noVphoned: Bool = false-public init() {}/// DFU mode is always headless.@@ -105,6 +81,15 @@ public struct VPhoneBootCLI: ParsableCommand {}public mutating func validate() throws {+ if !dfu,+ let bundle = try? VPhoneBundle.load(at: config.deletingLastPathComponent()),+ let existingVariant = VPhoneRestoreInfo.load(fromBundle: bundle)?.variant,+ existingVariant != "jb" {+ throw ValidationError(+ "This VM was created as '\(existingVariant)'. Only JB VMs are supported by this build."+ )+ }+if dfu, let packageURL = installPackageURL {throw ValidationError("`--install-ipa` is unavailable with `--dfu` because DFU mode does not start the guest control channel: \(packageURL.path)"@@ -140,8 +125,6 @@ public struct VPhoneBootCLI: ParsableCommand {var args = ["--config", config.path]if dfu { args.append("--dfu") }if headless { args.append("--headless") }- if noVphoned { args.append("--no-vphoned") }- if variant != .regular { args += ["--variant", variant.rawValue] }if vphonedBin != ".vphoned.signed" { args += ["--vphoned-bin", vphonedBin] }if let port = kernelDebugPort { args += ["--kernel-debug-port", String(port)] }if let ipa = installIPA { args += ["--install-ipa", ipa.path] }diff --git a/sources/VPhoneCore/VPhoneLaunchLayout.swift b/sources/VPhoneCore/VPhoneLaunchLayout.swiftindex 764f8424..f4359b28 100644--- a/sources/VPhoneCore/VPhoneLaunchLayout.swift+++ b/sources/VPhoneCore/VPhoneLaunchLayout.swift@@ -15,7 +15,9 @@ public struct VPhoneLaunchLayout: Sendable {@discardableResultpublic func stageVphoned(into bundle: VPhoneBundle) throws -> Bool {let fm = FileManager.default- guard fm.fileExists(atPath: vphoned.path) else { return false }+ guard fm.fileExists(atPath: vphoned.path) else {+ throw VPhoneGuestBinaries.Error.missing("vphoned.signed", [vphoned])+ }let dst = bundle.url.appendingPathComponent(".vphoned.signed")if fm.fileExists(atPath: dst.path),let a = try? Data(contentsOf: vphoned, options: .mappedIfSafe),diff --git a/sources/VPhoneVMKit/Guest/VPhoneControl.swift b/sources/VPhoneVMKit/Guest/VPhoneControl.swiftindex 7c48ef3c..e2731625 100644--- a/sources/VPhoneVMKit/Guest/VPhoneControl.swift+++ b/sources/VPhoneVMKit/Guest/VPhoneControl.swift@@ -55,11 +55,7 @@ class VPhoneControl {private var nextRequestId: UInt64 = 0private var connectionAttemptToken: UInt64 = 0private var reconnectWorkItem: DispatchWorkItem?- public var variant: VPhoneVirtualMachine.Variant = .regular-- init(variant: VPhoneVirtualMachine.Variant) {- self.variant = variant- }+ init() {}// MARK: - Pending Requests@@ -222,7 +218,7 @@ class VPhoneControl {print("[control] guest-side touch injection enabled (iOS \(iosVersion ?? "?"))")}- if needUpdate && self.variant != .less {+ if needUpdate {self.pushUpdate(fd: fd)} else {self.startReadLoop(fd: fd, attemptToken: attemptToken)diff --git a/sources/VPhoneVMKit/VM/VPhoneVirtualMachine.swift b/sources/VPhoneVMKit/VM/VPhoneVirtualMachine.swiftindex 21f6ca3f..c72798cd 100644--- a/sources/VPhoneVMKit/VM/VPhoneVirtualMachine.swift+++ b/sources/VPhoneVMKit/VM/VPhoneVirtualMachine.swift@@ -14,12 +14,6 @@ class VPhoneVirtualMachine: NSObject, VZVirtualMachineDelegate {/// Synthetic battery source for runtime charge/connectivity updates.private var batterySource: AnyObject?- /// Moved to VPhoneCore so vphone-cli can accept `--variant` without linking- /// Virtualization. The alias keeps every existing `VPhoneVirtualMachine.Variant`- /// spelling working.- public typealias Variant = VPhoneVariant--struct Options {var configURL: URLvar romURL: URL?@@ -34,8 +28,6 @@ class VPhoneVirtualMachine: NSObject, VZVirtualMachineDelegate {var screenPPI: Int = 460var screenScale: Double = 3.0var kernelDebugPort: Int?- var variant: Variant- var noVphoned: Bool}private struct DeviceIdentity {@@ -223,10 +215,8 @@ class VPhoneVirtualMachine: NSObject, VZVirtualMachineDelegate {config.keyboards = [VZUSBKeyboardConfiguration()]- if !options.noVphoned {- // Vsock (host <-> guest control channel, no IP/TCP involved)- config.socketDevices = [VZVirtioSocketDeviceConfiguration()]- }+ // Vsock (host <-> guest control channel, no IP/TCP involved)+ config.socketDevices = [VZVirtioSocketDeviceConfiguration()]// Power source (synthetic battery - guest sees full charge, charging)let source = Dynamic._VZMacSyntheticBatterySource()diff --git a/sources/VPhoneVMKit/VPhoneAppDelegate.swift b/sources/VPhoneVMKit/VPhoneAppDelegate.swiftindex 734448c5..5ae0cee4 100644--- a/sources/VPhoneVMKit/VPhoneAppDelegate.swift+++ b/sources/VPhoneVMKit/VPhoneAppDelegate.swift@@ -54,7 +54,6 @@ class VPhoneAppDelegate: NSObject, NSApplicationDelegate {}print("=== vphone-cli ===")- print("Variant : \(options.variant)")print("ROM : \(options.romURL?.path ?? "None")")print("Disk : \(options.diskURL.path)")print("NVRAM : \(options.nvramURL.path)")@@ -79,7 +78,7 @@ class VPhoneAppDelegate: NSObject, NSApplicationDelegate {try await vm.start(forceDFU: cli.dfu)- let control = VPhoneControl(variant: options.variant)+ let control = VPhoneControl()self.control = controlif !cli.dfu {let vphonedURL = URL(fileURLWithPath: cli.vphonedBin)diff --git a/sources/VPhoneVMKit/VPhoneBootCLI+VirtualMachine.swift b/sources/VPhoneVMKit/VPhoneBootCLI+VirtualMachine.swiftindex ac91f77b..e3f951ab 100644--- a/sources/VPhoneVMKit/VPhoneBootCLI+VirtualMachine.swift+++ b/sources/VPhoneVMKit/VPhoneBootCLI+VirtualMachine.swift@@ -29,9 +29,7 @@ extension VPhoneBootCLI {screenHeight: manifest.screenConfig.height,screenPPI: manifest.screenConfig.pixelsPerInch,screenScale: manifest.screenConfig.scale,- kernelDebugPort: kernelDebugPort,- variant: variant,- noVphoned: noVphoned+ kernelDebugPort: kernelDebugPort)}}diff --git a/sources/vphone-cli/VPhoneCLI.swift b/sources/vphone-cli/VPhoneCLI.swiftindex acfa7391..41d7dc32 100644--- a/sources/vphone-cli/VPhoneCLI.swift+++ b/sources/vphone-cli/VPhoneCLI.swift@@ -21,25 +21,6 @@ struct VPhoneCLI: ParsableCommand {// only forwards it — see main.swift.struct PatchFirmwareCLI: ParsableCommand {- enum VariantOption: String, CaseIterable, ExpressibleByArgument {- case less- case regular- case dev- case jb- case exp-- var pipelineVariant: FirmwarePipeline.Variant {- switch self {- case .less: .less- case .regular: .regular- case .dev: .dev- case .jb: .jb- case .exp: .exp- }- }-- }-static let configuration = CommandConfiguration(commandName: "patch-firmware",abstract: "Patch boot-chain firmware in a VM directory using the Swift pipeline"@@ -52,9 +33,6 @@ struct PatchFirmwareCLI: ParsableCommand {)var vmDirectory: URL- @Option(name: [.customShort("V"), .long], help: "Firmware variant to patch.")- var variant: VariantOption = .regular-@Option(name: .customLong("records-out"),help: "Optional path to write emitted PatchRecord JSON."@@ -64,15 +42,6 @@ struct PatchFirmwareCLI: ParsableCommand {@Flag(name: [.customShort("q"), .customLong("quiet")], help: "Suppress per-component progress output.")var quiet: Bool = false- @Flag(- name: .customLong("no-binpack"),- help: "Exclude the SSH, VNC, ... binaries from being installed (patchless-only)."- )- var noBinpack: Bool = false-- @Flag(name: .customLong("no-vphoned"), help: "Exclude vphoned from being installed (patchless-only).")- var noVphoned: Bool = false-@Flag(name: .customLong("force-exc-guard"),help: "Force-enable the EXC_GUARD (Mach port guard) disable patch on regular/jb/exp, even on bases where it isn't required to boot. Use if a third-party app's crash-reporting/RASP SDK trips a fatal GUARD_TYPE_MACH_PORT violation on launch. Always on for iOS 18 bases regardless of this flag."@@ -88,10 +57,9 @@ struct PatchFirmwareCLI: ParsableCommand {mutating func run() throws {let pipeline = FirmwarePipeline(vmDirectory: vmDirectory,- variant: variant.pipelineVariant,+ variant: .jb,verbose: !quiet,- noBinpack: noBinpack,- noVphoned: noVphoned,+ noBinpack: true,forceExcGuard: forceExcGuard,enableFrida: frida)@@ -104,7 +72,7 @@ struct PatchFirmwareCLI: ParsableCommand {try encoder.encode(records).write(to: url)print("[patch-firmware] wrote \(records.count) patch records to \(url.path)")} else {- print("[patch-firmware] applied \(records.count) patches for \(variant.rawValue)")+ print("[patch-firmware] applied \(records.count) JB patches")}}}@@ -114,7 +82,7 @@ struct PatchComponentCLI: ParsableCommand {case txmcase kernelBase = "kernel-base"// TESTING/DIAGNOSTICS ONLY — not part of any production flow.- // Production JB patching runs through `patch-firmware --variant jb`; this+ // Production JB patching runs through `patch-firmware`; this// standalone option exists so `tests/test_jb_kernel_patches.sh` can run the// JB kernel layer over a single kernelcache and dump records via --records-out.// (txm / kernel-base, by contrast, are standalone single-component patchers.)diff --git a/sources/vphone-cli/VPhoneCreateOptions.swift b/sources/vphone-cli/VPhoneCreateOptions.swiftindex 3667b214..81a8b524 100644--- a/sources/vphone-cli/VPhoneCreateOptions.swift+++ b/sources/vphone-cli/VPhoneCreateOptions.swift@@ -5,11 +5,9 @@ import VPhoneCoreextension VPhoneCreateOrchestrator {public struct Options {public var name: String- public var variant: Stringpublic var iphoneSource: String?public var cloudosSource: String?public var sudoPassword: String?- public var spoofBuild: String?public var forceDSCMaxSlide: Boolpublic var enableFrida: Boolpublic var rootPopup: Bool@@ -22,11 +20,9 @@ extension VPhoneCreateOrchestrator {public init(name: String,- variant: String,iphoneSource: String? = nil,cloudosSource: String? = nil,sudoPassword: String? = nil,- spoofBuild: String? = nil,forceDSCMaxSlide: Bool = false,enableFrida: Bool = false,rootPopup: Bool = false,@@ -38,11 +34,9 @@ extension VPhoneCreateOrchestrator {keepArtifacts: Bool = false) {self.name = name- self.variant = variantself.iphoneSource = iphoneSourceself.cloudosSource = cloudosSourceself.sudoPassword = sudoPassword- self.spoofBuild = spoofBuildself.forceDSCMaxSlide = forceDSCMaxSlideself.enableFrida = enableFridaself.rootPopup = rootPopupdiff --git a/sources/vphone-cli/VPhoneCreateOrchestrator.swift b/sources/vphone-cli/VPhoneCreateOrchestrator.swiftindex 893702e1..88744818 100644--- a/sources/vphone-cli/VPhoneCreateOrchestrator.swift+++ b/sources/vphone-cli/VPhoneCreateOrchestrator.swift@@ -10,8 +10,6 @@ import VPhoneRestore/// `wait_for_recovery` / `wait_for_first_boot_prompt_auto` / `run_boot_analysis`.private enum VPhoneCreateError: Error, CustomStringConvertible {case nestedVirtualization- case unknownVariant(String)- case lessRequiresRootcase fwPrepareFailed(Int32)case identityTimedOut(URL)case invalidUDID(String)@@ -27,16 +25,11 @@ private enum VPhoneCreateError: Error, CustomStringConvertible {case bootAnalysisPaniccase bootAnalysisExited(Int32)case bootAnalysisTimeout- case lessBootFailed(Int32)var description: String {switch self {case .nestedVirtualization:"Guest boot is unavailable inside a VM. Run vm create on a macOS 15 or later host that is not itself a VM."- case let .unknownVariant(v):- "Unknown variant '\(v)'. Choose regular, dev, jb, exp, or less."- case .lessRequiresRoot:- "The 'less' variant requires root. Run vm create with sudo."case let .fwPrepareFailed(code):"Firmware preparation failed (exit code \(code))."case let .identityTimedOut(path):@@ -71,8 +64,6 @@ private enum VPhoneCreateError: Error, CustomStringConvertible {"Boot analysis ended before the guest finished booting (exit code \(code))."case .bootAnalysisTimeout:"Boot analysis timed out."- case let .lessBootFailed(code):- "The VM failed to start with the 'less' variant (exit code \(code))."}}}@@ -124,11 +115,6 @@ public struct VPhoneCreateOrchestrator {throw VPhoneCreateError.nestedVirtualization}- guard let variantOption = PatchFirmwareCLI.VariantOption(rawValue: options.variant) else {- throw VPhoneCreateError.unknownVariant(options.variant)- }- let isLess = variantOption == .less-let bundleURL = library.url(forName: options.name)if FileManager.default.fileExists(atPath: bundleURL.path) {throw VPhoneLibraryError.alreadyExists(name: options.name)@@ -139,25 +125,23 @@ public struct VPhoneCreateOrchestrator {// via the askpass helper. Otherwise sudo prompts on the terminal itself —// the CFW-install step runs as a foreground job (runForeground) so sudo's// process group owns the tty and reads the password directly; our code- // never sees it. `less` runs the whole create as root, so needs no password.+ // never sees it.var sudoEnvExtras: [String: String] = [:]var askpassScript: URL?defer { if let askpassScript { try? FileManager.default.removeItem(at: askpassScript) } }- if !isLess {- if let password = options.sudoPassword, !password.isEmpty {- let script = try makeSudoAskpassScript()- askpassScript = script- sudoEnvExtras = ["SUDO_ASKPASS": script.path, "SUDO_PASSWORD": password]- if preloadSudoCredential(env: sudoEnvExtras, verbosity: v) {- print("[+] sudo credential preloaded via --sudo-password")- } else {- print("[!] --sudo-password failed validation; will still try at CFW-install time")- }- } else if !options.rootPopup && isatty(FileHandle.standardInput.fileDescriptor) == 0 {- // No password, no popup, no terminal for sudo to prompt on — fail- // before the long download/restore, not at the eventual sudo prompt.- throw VPhoneCreateError.sudoPasswordRequired+ if let password = options.sudoPassword, !password.isEmpty {+ let script = try makeSudoAskpassScript()+ askpassScript = script+ sudoEnvExtras = ["SUDO_ASKPASS": script.path, "SUDO_PASSWORD": password]+ if preloadSudoCredential(env: sudoEnvExtras, verbosity: v) {+ print("[+] sudo credential preloaded via --sudo-password")+ } else {+ print("[!] --sudo-password failed validation; will still try at CFW-install time")}+ } else if !options.rootPopup && isatty(FileHandle.standardInput.fileDescriptor) == 0 {+ // No password, no popup, no terminal for sudo to prompt on — fail+ // before the long download/restore, not at the eventual sudo prompt.+ throw VPhoneCreateError.sudoPasswordRequired}print("\n=== vm new ===")@@ -173,26 +157,18 @@ public struct VPhoneCreateOrchestrator {print("created \(bundle.url.path)")print("\n=== fw prepare ===")- try runFWPrepare(options: options, isLess: isLess, bundleURL: bundleURL)+ try runFWPrepare(options: options, bundleURL: bundleURL)print("\n=== fw patch ===")- try runFWPatch(- variant: variantOption,- isLess: isLess,- enableFrida: options.enableFrida,- bundleURL: bundleURL,- verbosity: v- )+ try runFWPatch(enableFrida: options.enableFrida, bundleURL: bundleURL, verbosity: v)print("\n=== Restore phase ===")try runRestorePhase(bundleURL: bundleURL, verbosity: v)- if !isLess {- print("[*] Waiting 5s for cleanup before CFW install...")- Thread.sleep(forTimeInterval: 5)- print("\n=== CFW install (host-mount) ===")- try runCFWInstall(options: options, bundleURL: bundleURL, sudoEnvExtras: sudoEnvExtras)- }+ print("[*] Waiting 5s for cleanup before CFW install...")+ Thread.sleep(forTimeInterval: 5)+ print("\n=== CFW install (host-mount) ===")+ try runCFWInstall(options: options, bundleURL: bundleURL, sudoEnvExtras: sudoEnvExtras)// CFW install is the last consumer of the built restore tree (it copies// the SystemOS/AppOS cryptexes from it onto Disk.img); reclaim it now.@@ -202,24 +178,13 @@ public struct VPhoneCreateOrchestrator {}print("\n=== First boot ===")- try runFirstBoot(options: options, isLess: isLess, bundleURL: bundleURL)-- if variantOption == .jb || variantOption == .exp {- print("\n=== JB Finalize ===")- print("[*] JB finalization will run automatically on first normal boot")- print(" via /cores/vphone_jb_setup.sh (LaunchDaemon).")- print(" Monitor progress via vphoned file browser: /var/log/vphone_jb_setup.log")- }+ try runFirstBoot(options: options, bundleURL: bundleURL)print("\n=== Done ===")print("Setup completed.")print("\n=== Boot analysis ===")- if isLess {- try startVMForeground(bundleURL: bundleURL, verbosity: v)- } else {- try runBootAnalysis(bundleURL: bundleURL, verbosity: v)- }+ try runBootAnalysis(bundleURL: bundleURL, verbosity: v)}// MARK: - trace@@ -278,7 +243,7 @@ public struct VPhoneCreateOrchestrator {// MARK: - fw prepare / fw patch- private func runFWPrepare(options: Options, isLess: Bool, bundleURL: URL) throws {+ private func runFWPrepare(options: Options, bundleURL: URL) throws {let v = options.verbositytry FileManager.default.createDirectory(at: resources.ipswCacheDir, withIntermediateDirectories: true)try FileManager.default.createDirectory(at: resources.sealVolumeCacheDir, withIntermediateDirectories: true)@@ -289,7 +254,6 @@ public struct VPhoneCreateOrchestrator {// No VPHONE_PYTHON: fw_prepare.sh no longer runs any Python.env["IPSW_DIR"] = resources.ipswCacheDir.pathenv["VPHONE_SEAL_DIR"] = resources.sealVolumeCacheDir.path- if isLess { env["VARIANT"] = "less" }if options.keepArtifacts { env["VPHONE_KEEP_ARTIFACTS"] = "1" }trace(@@ -309,36 +273,27 @@ public struct VPhoneCreateOrchestrator {}private func runFWPatch(- variant: PatchFirmwareCLI.VariantOption,- isLess: Bool,enableFrida: Bool,bundleURL: URL,verbosity v: VPhoneVerbosity) throws {- // Mirrors the Makefile's `ifeq ($(UID),0)` gate on `fw_patch_less` —- // only the `less` variant requires root.- if isLess, getuid() != 0 {- throw VPhoneCreateError.lessRequiresRoot- }-// In-process pipeline (no subprocess) — CryptexFilesystemPatcher's// apfs_sealvolume read honors VPHONE_SEAL_DIR from *this* process's// environment, so set it here to agree with `fw prepare`'s write.try FileManager.default.createDirectory(at: resources.sealVolumeCacheDir, withIntermediateDirectories: true)setenv("VPHONE_SEAL_DIR", resources.sealVolumeCacheDir.path, 1)- trace("in-process FirmwarePipeline.patchAll variant=\(variant.rawValue)", v)+ trace("in-process FirmwarePipeline.patchAll variant=jb", v)let pipeline = FirmwarePipeline(vmDirectory: bundleURL,- variant: variant.pipelineVariant,+ variant: .jb,verbose: v.showsToolDetail,- noBinpack: false,- noVphoned: false,+ noBinpack: true,forceExcGuard: false,enableFrida: enableFrida)let records = try pipeline.patchAll()- print("[fw patch] applied \(records.count) patches for \(variant.rawValue)")+ print("[fw patch] applied \(records.count) JB patches")}// MARK: - restore phase@@ -510,12 +465,11 @@ public struct VPhoneCreateOrchestrator {"VPHONE_SEAL_DIR": resources.sealVolumeCacheDir.path,"VPHONE_DEBS_DIR": resources.debsCacheDir.path,]- if let spoofBuild = options.spoofBuild { scriptEnv["SPOOF_BUILD"] = spoofBuild }if options.forceDSCMaxSlide { scriptEnv["FORCE_DSC_MAXSLIDE"] = "1" }if options.enableFrida { scriptEnv["VPHONE_FRIDA"] = "1" }if options.keepArtifacts { scriptEnv["VPHONE_KEEP_ARTIFACTS"] = "1" }- let args = [resources.cfwInstallHostScript.path, "--variant", options.variant, bundleURL.path]+ let args = [resources.cfwInstallHostScript.path, "--variant", "jb", bundleURL.path]// --sudo-password (askpass) wins over --root-popup.let usePopup = options.rootPopup && sudoEnvExtras["SUDO_ASKPASS"] == nillet code: Int32@@ -557,20 +511,19 @@ public struct VPhoneCreateOrchestrator {}}guard code == 0 else { throw VPhoneCreateError.cfwInstallFailed(code) }- print("[+] CFW installed (\(options.variant)).")+ print("[+] JB CFW installed.")if let bundle = try? VPhoneBundle.load(at: bundleURL),- let info = try? VPhoneRestoreInfo.recordVariant(options.variant, toBundle: bundle), info.variant != nil {- print("[+] Recorded variant \(options.variant), device \(info.device ?? "?")")+ let info = try? VPhoneRestoreInfo.recordVariant("jb", toBundle: bundle), info.variant != nil {+ print("[+] Recorded variant jb, device \(info.device ?? "?")")}}// MARK: - first boot- private func runFirstBoot(options: Options, isLess: Bool, bundleURL: URL) throws {+ private func runFirstBoot(options: Options, bundleURL: URL) throws {let v = options.verbositylet configURL = bundleURL.appendingPathComponent("config.plist")var args = ["--config", configURL.path]- if isLess { args += ["--variant", "less"] }// --interactive keeps the window: it is the operator's only boot-progress cue.if !options.interactive { args.append("--headless") }@@ -644,20 +597,4 @@ public struct VPhoneCreateOrchestrator {}}- /// `less` variant: `run_make "Start VM" boot_less` — a plain foreground- /// boot, no panic/prompt analysis (patchless compat mode has no CFW-driven- /// success marker to watch for).- private func startVMForeground(bundleURL: URL, verbosity v: VPhoneVerbosity) throws {- let configURL = bundleURL.appendingPathComponent("config.plist")- print("\n=== Start VM ===")- let (exe, args) = launcher.plan(["--config", configURL.path, "--variant", "less"])- trace("spawn \(exe.path) \(args.joined(separator: " ")) (echo=\(v.showsToolDetail))", v)- let code = try VPhoneProcessRunner.runStreaming(- exe,- args,- cwd: bundleURL,- echo: v.showsToolDetail- )- guard code == 0 else { throw VPhoneCreateError.lessBootFailed(code) }- }}diff --git a/sources/vphone-cli/VPhoneFWCLI.swift b/sources/vphone-cli/VPhoneFWCLI.swiftindex 174d031f..2389dc30 100644--- a/sources/vphone-cli/VPhoneFWCLI.swift+++ b/sources/vphone-cli/VPhoneFWCLI.swift@@ -214,8 +214,6 @@ struct VPhoneFWPatchCommand: ParsableCommand {@OptionGroup var lib: VPhoneLibraryOption@Argument(help: "VM name") var name: String?- @Option(name: [.customShort("V"), .long], help: "variant: regular | dev | jb | exp | less")- var variant: PatchFirmwareCLI.VariantOption = .regular@Flag(name: .customLong("force-exc-guard"), help: "Force the EXC_GUARD disable patch") var forceExcGuard = false@Flag(name: .customLong("frida"), help: "Opt in to Frida Stalker kernel relaxations (jb/exp only)")var frida = false@@ -234,14 +232,13 @@ struct VPhoneFWPatchCommand: ParsableCommand {let pipeline = FirmwarePipeline(vmDirectory: bundle.url,- variant: variant.pipelineVariant,+ variant: .jb,verbose: !quiet,- noBinpack: false,- noVphoned: false,+ noBinpack: true,forceExcGuard: forceExcGuard,enableFrida: frida)let records = try pipeline.patchAll()- print("[fw patch] applied \(records.count) patches for \(variant.rawValue)")+ print("[fw patch] applied \(records.count) JB patches")}}diff --git a/sources/vphone-cli/VPhoneRestoreCLI.swift b/sources/vphone-cli/VPhoneRestoreCLI.swiftindex 7b27ff1b..a2a3d7b9 100644--- a/sources/vphone-cli/VPhoneRestoreCLI.swift+++ b/sources/vphone-cli/VPhoneRestoreCLI.swift@@ -222,9 +222,6 @@ struct VPhoneCFWInstallCommand: ParsableCommand {@OptionGroup var lib: VPhoneLibraryOption@Argument(help: "VM name") var name: String?- @Option(name: [.customShort("V"), .long], help: "variant: regular | dev | jb | exp") var variant: String = "exp"- @Option(name: [.customShort("b"), .long], help: "(exp only) rewrite ProductBuildVersion to this build id")- var spoofBuild: String?@Flag(name: .customLong("force-dsc-maxslide"),help: "Zero the dyld cache maxSlide on non-27 bases (opt-in DSC-map fit)"@@ -247,9 +244,6 @@ struct VPhoneCFWInstallCommand: ParsableCommand {func run() throws {let v = max(VPhoneVerbosity.info, VPhoneVerbosity(count: verboseCount))- guard ["regular", "dev", "jb", "exp"].contains(variant) else {- throw ValidationError("unknown cfw variant '\(variant)' (regular|dev|jb|exp)")- }let name = try VPhoneVMSelection.resolveExisting(name, in: lib.library)let bundle = try lib.library.bundle(named: name)let resources = projectRoot.map { VPhoneResources(base: URL(fileURLWithPath: $0)) } ?? .resolve()@@ -270,11 +264,10 @@ struct VPhoneCFWInstallCommand: ParsableCommand {"VPHONE_SEAL_DIR": resources.sealVolumeCacheDir.path,"VPHONE_DEBS_DIR": resources.debsCacheDir.path,]- if let spoofBuild { scriptEnv["SPOOF_BUILD"] = spoofBuild }if forceDSCMaxSlide { scriptEnv["FORCE_DSC_MAXSLIDE"] = "1" }if keepArtifacts { scriptEnv["VPHONE_KEEP_ARTIFACTS"] = "1" }- let args = [resources.cfwInstallHostScript.path, "--variant", variant, bundle.url.path]+ let args = [resources.cfwInstallHostScript.path, "--variant", "jb", bundle.url.path]let code: Int32if rootPopup {// Forward SUDO_USER (sudo would set it) so the script's chown-back runs.@@ -299,8 +292,8 @@ struct VPhoneCFWInstallCommand: ParsableCommand {)}if code == 0 {- if let info = try? VPhoneRestoreInfo.recordVariant(variant, toBundle: bundle), info.variant != nil {- print("[cfw] recorded variant \(variant), device \(info.device ?? "?")")+ if let info = try? VPhoneRestoreInfo.recordVariant("jb", toBundle: bundle), info.variant != nil {+ print("[cfw] recorded variant jb, device \(info.device ?? "?")")}if !keepArtifacts, let removed = try? VPhoneRestoreInfo.removeBuiltFirmware(fromBundle: bundle) {print("[cfw] removed built firmware \(removed)/ to save space (--keep-artifacts to keep)")diff --git a/sources/vphone-cli/VPhoneVMCreateCLI.swift b/sources/vphone-cli/VPhoneVMCreateCLI.swiftindex 6133e67a..2463df9b 100644--- a/sources/vphone-cli/VPhoneVMCreateCLI.swift+++ b/sources/vphone-cli/VPhoneVMCreateCLI.swift@@ -6,23 +6,17 @@ struct VPhoneVMCreateCommand: ParsableCommand {static let configuration = CommandConfiguration(commandName: "create",abstract: "Create a VM end-to-end (prepare → patch → restore → CFW → first boot)",- discussion: "Runs the full pipeline for a fresh VM. Needs an internet connection "- + "(IPSW download), a non-nested macOS host, and sudo (CFW host-mount). "- + "The 'less' (patchless) variant must itself be run with sudo — the whole "- + "create runs as root, not just the fw-patch stage."+ discussion: "Runs the JB pipeline for a fresh VM. Needs an internet connection "+ + "(IPSW download), a non-nested macOS host, and sudo (CFW host-mount).")@OptionGroup var lib: VPhoneLibraryOption@Argument(help: "new VM name") var name: String- @Option(name: [.customShort("V"), .long], help: "variant: regular | dev | jb | exp | less")- var variant: String = "regular"@Option(name: .shortAndLong, help: "iPhone IPSW URL or local path") var iphoneSource: String?@Option(name: .shortAndLong, help: "cloudOS IPSW URL or local path") var cloudosSource: String?@Option(name: .shortAndLong, help: "Disk size (GB)") var diskSize: UInt64 = 64@Option(name: .shortAndLong, help: "sudo password for the CFW host-mount install (via askpass; never logged)")var sudoPassword: String?- @Option(name: [.customShort("b"), .long], help: "(exp only) rewrite ProductBuildVersion to this build id")- var spoofBuild: String?@Flag(name: .customLong("force-dsc-maxslide"),help: "Zero the dyld cache maxSlide on non-27 bases (opt-in DSC-map fit)"@@ -64,11 +58,9 @@ struct VPhoneVMCreateCommand: ParsableCommand {)try orchestrator.run(.init(name: name,- variant: variant,iphoneSource: sources.iphoneSource,cloudosSource: sources.cloudosSource,sudoPassword: sudoPassword,- spoofBuild: spoofBuild,forceDSCMaxSlide: forceDSCMaxSlide,enableFrida: frida,rootPopup: rootPopup,diff --git a/sources/vphone-cli/VPhoneVMLaunchCLI.swift b/sources/vphone-cli/VPhoneVMLaunchCLI.swiftindex 60c97a45..c8ea1b88 100644--- a/sources/vphone-cli/VPhoneVMLaunchCLI.swift+++ b/sources/vphone-cli/VPhoneVMLaunchCLI.swift@@ -12,8 +12,6 @@ struct VPhoneVMLaunchCommand: ParsableCommand {@Argument(help: "VM name") var name: String?@Flag(name: .shortAndLong, help: "Boot into DFU mode (headless)") var dfu = false@Flag(name: .customLong("headless"), help: "Boot without a VM window or menu bar") var headless = false- @Option(name: [.customShort("V"), .long], help: "Firmware variant") var variant: String?- @Flag(name: .customLong("no-vphoned"), help: "Do not stage/use vphoned") var noVphoned = false@Option(help: "Kernel GDB debug stub port on host (omit for system-assigned; valid: 6000...65535)")var kernelDebugPort: Int?@Option(name: .shortAndLong, help: "Resource base override (default: inferred from the running binary path)")@@ -44,8 +42,7 @@ struct VPhoneVMLaunchCommand: ParsableCommand {// Host preflight — same gate make boot applies. Point it at the guest// binary (VPHONE_CLI_BIN) so it checks what actually has to launch, not// a dev .build/release path that doesn't exist inside the bundled .app.- var preflightArgs = ["--assert-bootable"]- if variant == "less" { preflightArgs.append("--less") }+ let preflightArgs = ["--assert-bootable"]var preflightEnv = ProcessInfo.processInfo.environmentpreflightEnv["VPHONE_CLI_BIN"] = bootBinary.pathlet pre = try VPhoneProcessRunner.runCapturing(@@ -60,20 +57,13 @@ struct VPhoneVMLaunchCommand: ParsableCommand {throw ExitCode(pre.exitCode == 0 ? 1 : pre.exitCode)}- if !dfu && !noVphoned {- do {- _ = try layout.stageVphoned(into: bundle)- } catch {- FileHandle.standardError.write(Data(- "warning: could not stage vphoned into \(bundle.name): \(error)\n".utf8))- }+ if !dfu {+ _ = try layout.stageVphoned(into: bundle)}var args = ["--config", bundle.configURL.path]if dfu { args.append("--dfu") }if headless { args.append("--headless") }- if let variant { args += ["--variant", variant] }- if noVphoned { args.append("--no-vphoned") }if let kernelDebugPort { args += ["--kernel-debug-port", String(kernelDebugPort)] }if v.tracesInternals {diff --git a/tests/VPhoneCoreTests/LaunchLayoutTests.swift b/tests/VPhoneCoreTests/LaunchLayoutTests.swiftindex 21877ad3..b7fe8aad 100644--- a/tests/VPhoneCoreTests/LaunchLayoutTests.swift+++ b/tests/VPhoneCoreTests/LaunchLayoutTests.swift@@ -44,7 +44,7 @@ struct LaunchLayoutTests {#expect(try layout.stageVphoned(into: bundle) == false)}- @Test func stageVphonedReturnsFalseWhenSourceAbsent() throws {+ @Test func stageVphonedFailsWhenSourceAbsent() throws {let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)defer { try? FileManager.default.removeItem(at: root) }@@ -58,7 +58,9 @@ struct LaunchLayoutTests {)let bundle = VPhoneBundle(url: bundleDir, manifest: manifest)- #expect(try VPhoneLaunchLayout(projectRoot: root).stageVphoned(into: bundle) == false)+ #expect(throws: VPhoneGuestBinaries.Error.self) {+ try VPhoneLaunchLayout(projectRoot: root).stageVphoned(into: bundle)+ }#expect(!FileManager.default.fileExists(atPath: bundleDir.appendingPathComponent(".vphoned.signed").path))}diff --git a/tests/VPhoneCoreTests/RestoreInfoTests.swift b/tests/VPhoneCoreTests/RestoreInfoTests.swiftindex cc273ed6..07f22b99 100644--- a/tests/VPhoneCoreTests/RestoreInfoTests.swift+++ b/tests/VPhoneCoreTests/RestoreInfoTests.swift@@ -143,6 +143,25 @@ struct RestoreInfoTests {#expect(try VPhoneRestoreInfo.recordVariant("jb", toBundle: b) == nil)}+ @Test func normalBootRejectsAnExplicitOldVariantButDFUStillParses() throws {+ let b = try makeBundle()+ defer { try? FileManager.default.removeItem(at: b.url) }+ try b.manifest.write(to: b.configURL)+ try VPhoneRestoreInfo(+ ios: .init(version: "26.6.2", build: "23G90"),+ cloudOS: .init(version: "26.4", build: "23E5207q"),+ variant: "exp"+ ).write(toBundle: b)++ do {+ _ = try VPhoneBootCLI.parseAsRoot(["--config", b.configURL.path])+ Issue.record("Boot accepted an explicitly unsupported VM variant")+ } catch {+ #expect(String(describing: error).contains("Only JB VMs are supported"))+ }+ _ = try VPhoneBootCLI.parseAsRoot(["--config", b.configURL.path, "--dfu"])+ }+@Test func bundleReportCarriesUDID() throws {let b = try makeBundle()defer { try? FileManager.default.removeItem(at: b.url) }diff --git a/tests/test_firmware_patches.sh b/tests/test_firmware_patches.shdeleted file mode 100755index 558f21c9..00000000--- a/tests/test_firmware_patches.sh+++ /dev/null@@ -1,197 +0,0 @@-#!/usr/bin/env zsh-# test_firmware_patches.sh — full-pipeline firmware patch gate across cloudOS versions.-#-# WHY THIS EXISTS (vs test_jb_kernel_patches.sh):-# test_jb_kernel_patches.sh runs ONLY the `kernel-jb` component. That misses-# every patcher outside the JB kernel layer — the boot chain (iBSS/iBEC/LLB),-# the base KernelPatcher (regular-variant kernel patches), TXM, and DeviceTree.-# Real 26.x builds have shown silent per-patch skips in exactly those layers-# (e.g. iBEC "bootx precondition", LLB "cmp x8,#0x400", kernel-# "handle_get_dev_by_role") that the kernel-jb test structurally cannot see.-#-# This harness runs the WHOLE `patch-firmware` pipeline — every component, for-# the `jb` and `exp` variants — over each available cloudOS firmware, and fails-# if ANY component emits a `[-]` line (a skipped/failed sub-patch).-#-# WHY GREP FOR `[-]` (not exit code):-# FirmwarePipeline.patchAll() only throws when a whole component finds ZERO-# patches. A patcher whose OTHER sub-patches succeed still returns records, so a-# single silently-skipped gate never changes the exit code — it only prints a-# `[-]` line. So the only reliable signal for a partial skip is that line.-#-# INPUTS (no network needed for the README cloudOS builds):-# Sources are the already-extracted cloudOS firmware trees under `ipsws/<hash>/`-# (each has BuildManifest.plist, Firmware/, and kernelcache.research.vphone600).-# We assemble a DISPOSABLE VM dir per (version, variant) — patch-firmware edits-# firmware in place, so each run gets its own copy — and never touch ipsws/.-#-# tests/test_firmware_patches.sh # all local cloudOS firmwares, variants jb+exp-# tests/test_firmware_patches.sh --quick # newest local cloudOS only-# tests/test_firmware_patches.sh 23B85 23E5207q # only these cloudOS builds-# VARIANTS="exp" tests/test_firmware_patches.sh # only the exp variant-# tests/test_firmware_patches.sh --no-build # skip rebuilding the patcher-#-# Exit code: 0 iff EVERY (version, variant) patches with NO `[-]` lines and no crash.-set -euo pipefail--HERE=${0:a:h}-ROOT=${HERE:h}-cd "$ROOT"--WORK=${WORK:-/tmp/vphone_fw_versions}-BIN=".build/debug/vphone-cli"-IPSWS="$ROOT/ipsws"-AVPBOOTER_SRC="/System/Library/Frameworks/Virtualization.framework/Versions/A/Resources/AVPBooter.vresearch1.bin"-VARIANTS=${VARIANTS:-"jb exp"}-mkdir -p "$WORK"--# cloudOS firmware components we must stage into the disposable Restore dir-# (relative paths == the patterns FirmwarePipeline.buildComponentList searches).-typeset -a COMPONENTS=(- "Firmware/dfu/iBSS.vresearch101.RELEASE.im4p"- "Firmware/dfu/iBEC.vresearch101.RELEASE.im4p"- "Firmware/all_flash/LLB.vresearch101.RELEASE.im4p"- "Firmware/all_flash/DeviceTree.vphone600ap.im4p"- "Firmware/txm.iphoneos.research.im4p"- "kernelcache.research.vphone600"- "BuildManifest.plist"-)--NO_BUILD=0-QUICK=0-typeset -a ARG_BUILDS=()-for a in "$@"; do- case "$a" in- --no-build) NO_BUILD=1 ;;- --quick) QUICK=1 ;;- -*) echo "unknown option: $a" >&2; exit 2 ;;- *) ARG_BUILDS+=("$a") ;;- esac-done--[[ -f "$AVPBOOTER_SRC" ]] || { echo "[-] AVPBooter not found at $AVPBOOTER_SRC"; exit 2; }--plist() { /usr/libexec/PlistBuddy -c "Print :$2" "$1" 2>/dev/null || true; }--# --- 1. Discover cloudOS firmware sources (ver, build, dir) --------------------# A valid source is any ipsws/<hash>/ with both a vphone600 research kernel and-# the Firmware/ tree. Version/build come from SystemVersion.plist.-typeset -a SRC_DIRS SRC_VERS SRC_BUILDS-for d in "$IPSWS"/*/; do- [[ -f "$d/kernelcache.research.vphone600" && -d "$d/Firmware" ]] || continue- ver=$(plist "$d/SystemVersion.plist" ProductVersion)- build=$(plist "$d/SystemVersion.plist" ProductBuildVersion)- [[ -n "$ver" && -n "$build" ]] || continue- SRC_DIRS+=("${d%/}"); SRC_VERS+=("$ver"); SRC_BUILDS+=("$build")-done-[[ ${#SRC_DIRS} -gt 0 ]] || { echo "[-] no extracted cloudOS firmware found under $IPSWS (need kernelcache.research.vphone600 + Firmware/)"; exit 2; }--# Filter to requested builds, or --quick (highest version), if asked.-typeset -a IDX=({1..${#SRC_DIRS}})-if (( ${#ARG_BUILDS} )); then- typeset -a keep=()- for i in "${IDX[@]}"; do- for b in "${ARG_BUILDS[@]}"; do [[ "${SRC_BUILDS[$i]}" == "$b" ]] && keep+=("$i"); done- done- IDX=("${keep[@]}")- [[ ${#IDX} -gt 0 ]] || { echo "[-] none of the requested builds (${ARG_BUILDS[*]}) found locally"; exit 2; }-elif (( QUICK )); then- best=${IDX[1]}- for i in "${IDX[@]}"; do- hi=$(printf '%s\n%s\n' "${SRC_VERS[$i]}" "${SRC_VERS[$best]}" | sort -V | tail -1)- [[ "$hi" == "${SRC_VERS[$i]}" ]] && best=$i- done- IDX=("$best")-fi--echo "cloudOS firmwares to test:"-for i in "${IDX[@]}"; do echo " ${SRC_VERS[$i]}-${SRC_BUILDS[$i]} (${SRC_DIRS[$i]:t})"; done-echo "variants: ${VARIANTS}"--# Warn about README-listed cloudOS builds that are not present locally.-README_BUILDS=(23B85 23D128 23E5207q)-for rb in "${README_BUILDS[@]}"; do- found=0; for i in "${IDX[@]}"; do [[ "${SRC_BUILDS[$i]}" == "$rb" ]] && found=1; done- (( found )) || echo " [!] README cloudOS build $rb not available locally — NOT tested (prepare it to cover it)"-done--# --- 2. Build the patcher -----------------------------------------------------if (( ! NO_BUILD )); then- echo "==> building patcher ..."- if ! make patcher_build > "$WORK/build.log" 2>&1; then- echo "[-] patcher build failed:"; tail -20 "$WORK/build.log"; exit 1- fi-fi-[[ -x "$BIN" ]] || { echo "[-] $BIN missing (run without --no-build)"; exit 1; }--# --- 3. Assemble a disposable VM dir and run patch-firmware -------------------typeset -A RESULT-overall=0--run_one() {- local src="$1" ver="$2" build="$3" variant="$4"- local key="$ver-$build/$variant"- local vm="$WORK/$build/$variant/vm"- local restore="$vm/iPhone17,3_${ver}_${build}_Restore"- rm -rf "$vm"; mkdir -p "$restore"-- # AVPBooter lives in the VM root and is patched for every non-less variant.- cp -f "$AVPBOOTER_SRC" "$vm/AVPBooter.vresearch1.bin"; chmod u+w "$vm/AVPBooter.vresearch1.bin"-- # Stage cloudOS components (clone-on-write where supported; falls back to copy).- local rel- for rel in "${COMPONENTS[@]}"; do- [[ -f "$src/$rel" ]] || { echo " [-] source missing: $rel"; RESULT[$key]="NO-INPUT"; overall=1; return; }- mkdir -p "$restore/${rel:h}"- cp -c "$src/$rel" "$restore/$rel" 2>/dev/null || cp -f "$src/$rel" "$restore/$rel"- chmod u+w "$restore/$rel"- done-- local log="$WORK/$build/$variant/run.log"- if ! "$BIN" patch-firmware --vm-directory "$vm" --variant "$variant" > "$log" 2>&1; then- echo " ❌ $key — patch-firmware exited nonzero:"; tail -6 "$log" | sed 's/^/ /'- RESULT[$key]="CRASH"; overall=1; return- fi-- # Partial skips never change the exit code — they only print `[-]` lines.- local fails- fails=$(grep -nE "\[-\]" "$log" || true)- if [[ -n "$fails" ]]; then- echo " ❌ $key — $(print -r -- "$fails" | grep -c .) skipped sub-patch(es):"- print -r -- "$fails" | sed 's/^/ /'- RESULT[$key]="FAIL"; overall=1; return- fi-- if ! grep -q "components patched successfully" "$log"; then- echo " ❌ $key — pipeline did not report success"; RESULT[$key]="INCOMPLETE"; overall=1; return- fi-- local applied; applied=$(grep -oE "\([0-9]+ total patches\)" "$log" | grep -oE "[0-9]+" | head -1 || echo "?")- echo " ✅ $key — $applied patches, 0 skips"- RESULT[$key]="PASS ($applied patches)"-}--for i in "${IDX[@]}"; do- echo ""- echo "──────────── ${SRC_VERS[$i]}-${SRC_BUILDS[$i]} ────────────"- for variant in ${=VARIANTS}; do- run_one "${SRC_DIRS[$i]}" "${SRC_VERS[$i]}" "${SRC_BUILDS[$i]}" "$variant"- done-done--# --- 4. Summary matrix --------------------------------------------------------echo ""-echo "════════════════ summary ════════════════"-for i in "${IDX[@]}"; do- for variant in ${=VARIANTS}; do- key="${SRC_VERS[$i]}-${SRC_BUILDS[$i]}/$variant"- printf " %-22s %s\n" "$key" "${RESULT[$key]:-?}"- done-done-echo ""-if (( overall == 0 )); then- echo "ALL FIRMWARES PASS — every component patches cleanly (0 skipped sub-patches)."-else- echo "ONE OR MORE FIRMWARES FAILED — a component skipped a sub-patch (see [-] lines above)."-fi-exit $overalldiff --git a/tests/test_jb_kernel_patches.sh b/tests/test_jb_kernel_patches.shdeleted file mode 100755index a6ee8705..00000000--- a/tests/test_jb_kernel_patches.sh+++ /dev/null@@ -1,251 +0,0 @@-#!/usr/bin/env zsh-# test_jb_kernel_patches.sh — the single test for the JB kernel patch layer.-#-# Runs the WHOLE `kernel-jb` patcher (every JB hook, including all the Sandbox-# MACF ops hooks) over each cloudOS kernel the README lists as supported, and-# requires that every version applies with 0 failures and emits every expected-# patch. This is both the correctness check and the backward-compatibility gate-# (we develop against the newest kernel but must not regress older ones).-#-# The kernel we patch (`kernelcache.research.vphone600`) ships inside the cloudOS-# (PCC) firmware, so "kernel versions" == the cloudOS builds in the README's-# "Tested Environments" table. For each build we resolve its PCC "OS" asset URL-# from `ipsw dl pcc --info`, pull ONLY `kernelcache.research.vphone600` via remote-# extraction (~14 MB, not the full IPSW), run `patch-component --component-# kernel-jb`, and validate. Anything cached under the work dir is reused.-#-# tests/test_jb_kernel_patches.sh # all supported cloudOS builds-# tests/test_jb_kernel_patches.sh --quick # only the local/newest kernel (fast dev loop)-# tests/test_jb_kernel_patches.sh 23B85 23D128 # only these builds-# tests/test_jb_kernel_patches.sh --no-build # skip rebuilding the patcher-# BUILDS="23B85 23D128 23E5207q" tests/test_jb_kernel_patches.sh-#-# Exit code: 0 iff EVERY tested kernel applies all expected patches with 0 failures.-set -euo pipefail--HERE=${0:a:h}-ROOT=${HERE:h} # tests/ lives at the repo root-cd "$ROOT"--WORK=${WORK:-/tmp/vphone_kjb_versions}-BIN=".build/debug/vphone-cli"-README="$ROOT/README.md"-PCC_INFO="$WORK/pcc_info.txt" # cached `ipsw dl pcc --info` dump-mkdir -p "$WORK"--# Patch IDs that MUST emit on every supported kernel: the P0 sudo hook plus the-# eight routines retargeted for 26.5. If any is missing, that hook silently-# skipped. (The 0-failure gate below additionally catches every OTHER routine —-# including all the Sandbox ops hooks — since the pipeline counts a routine that-# emits nothing as a failure.)-REQUIRED_IDS=(- jb.hook_cred_label.c23_cave- task_conversion_eval- jb.proc_security_policy.mov_x0_0- jb.proc_pidinfo.nop_guard_a- jb.io_secure_bsd_root.zero_return- kernelcache_jb.mac_mount.flag_gate- kernelcache_jb.spawn_validate_persona.cbz1- kernelcache_jb.vm_map_protect- jb.kcall10.sy_call-)--NO_BUILD=0-QUICK=0-ARG_BUILDS=()-for a in "$@"; do- case "$a" in- --no-build) NO_BUILD=1 ;;- --quick) QUICK=1 ;;- -*) echo "unknown option: $a" >&2; exit 2 ;;- *) ARG_BUILDS+=("$a") ;;- esac-done--command -v ipsw >/dev/null 2>&1 || { echo "[-] 'ipsw' CLI not found (brew install blacktop/tap/ipsw)"; exit 2; }--# --- 1. Determine which cloudOS builds to test --------------------------------# Priority: --quick (local kernel) > CLI args > $BUILDS env > README cloudOS column.-typeset -a BUILD_LIST-if (( QUICK )); then- BUILD_LIST=(local)-elif (( ${#ARG_BUILDS} )); then- BUILD_LIST=("${ARG_BUILDS[@]}")-elif [[ -n "${BUILDS:-}" ]]; then- BUILD_LIST=(${=BUILDS})-else- # cloudOS column entries look like `26.4-23E5207q` (version-dash-build); the- # iPhone column uses `17,3_26.5_23F77` (commas/underscores), so filter those out.- #- # awk, not the `python3 - <<'PY'` heredoc this was until P2.4. A bare `python3`- # here resolved whatever interpreter happened to be on PATH, which is the exact- # silent fallback the repo spent D1 removing — and it survived the venv because- # nothing linked it to the venv in the first place. awk ships with macOS.- BUILD_LIST=($(awk '- /^## Tested Environments/ { insec = 1; next }- insec && /^## / { exit }- !insec { next }- {- rest = $0- while (match(rest, /`[^`]+`/)) {- tok = substr(rest, RSTART + 1, RLENGTH - 2)- rest = substr(rest, RSTART + RLENGTH)- if (tok ~ /^[0-9]+\.[0-9][0-9.]*-[0-9A-Za-z]+$/) {- sub(/^[0-9]+\.[0-9][0-9.]*-/, "", tok)- if (!(tok in seen)) { seen[tok] = 1; order[++n] = tok }- }- }- }- END { for (i = 1; i <= n; i++) print order[i] }- ' "$README"))-fi-[[ ${#BUILD_LIST} -gt 0 ]] || { echo "[-] no cloudOS builds resolved"; exit 2; }-echo "kernel builds to test: ${BUILD_LIST[*]}"--# --- 2. Build the patcher -----------------------------------------------------if (( ! NO_BUILD )); then- echo "==> building patcher ..."- if ! make patcher_build > "$WORK/build.log" 2>&1; then- echo "[-] patcher build failed:"; tail -20 "$WORK/build.log"; exit 1- fi-fi-[[ -x "$BIN" ]] || { echo "[-] $BIN missing (run without --no-build)"; exit 1; }--# --- 3. Cache the PCC release index (build -> OS asset URL) -------------------ensure_pcc_info() {- [[ -s "$PCC_INFO" ]] && return 0- echo "==> fetching PCC release index (ipsw dl pcc --info) ..."- if ! ipsw dl pcc --info > "$PCC_INFO" 2>&1; then- echo "[-] 'ipsw dl pcc --info' failed:"; tail -5 "$PCC_INFO"; return 1- fi-}--# Resolve one cloudOS build -> its PCC "OS" asset URL (only releases that still-# carry the vphone600 firmware). Empty output => not found.-# Also awk rather than a python3 heredoc — see the note above BUILD_LIST. The-# release index is a flat text dump, so this walks it as blocks: a numbered-# digest line opens one, and everything up to the next digest line belongs to-# it. A block qualifies only if it advertises vphone firmware, carries a PCC-# asset URL, and mentions the build we were asked about; the first qualifying-# block wins, exactly as the reading of the whole index into a list then-# scanning it in order did.-resolve_url() {- local build="$1"- awk -v want="$build" '- function close_block() {- if (!found && open && vphone && url != "" && (want in builds)) {- found = 1- print url- }- open = 0; vphone = 0; url = ""; delete builds- }- BEGIN { esc = sprintf("%c", 27) }- {- line = $0- gsub(esc "\\[[0-9;]*m", "", line) # ipsw colourises its output- }- # A release block opens on `<n>) <hex digest>`.- match(line, /^[0-9]+\)[ \t]+[0-9a-f]+/) {- digest = substr(line, RSTART, RLENGTH)- sub(/^[0-9]+\)[ \t]+/, "", digest)- if (length(digest) >= 16) { close_block(); open = 1; next }- }- !open { next }- {- if (index(line, "📱 VPHONE") > 0) vphone = 1 # the vphone firmware marker- if (url == "" \- && match(line, /https:\/\/updates\.cdn-apple\.com\/private-cloud-compute\/[0-9a-f]+/)) {- url = substr(line, RSTART, RLENGTH)- }- # Build ids (23B85, 24A5380h) as whole words. Splitting on non-word- # characters is what keeps `17,3_26.5_23F77` out: an id glued to its- # neighbours by underscores is not a word on its own.- k = split(line, word, /[^A-Za-z0-9_]+/)- for (i = 1; i <= k; i++) {- if (word[i] ~ /^2[0-9][A-Z][0-9A-Za-z]+$/) builds[word[i]] = 1- }- }- END { close_block() }- ' "$PCC_INFO"-}--# --- 4. Obtain kernelcache.research.vphone600 for a build --------------------# "local" => reuse the pristine kernelcache already extracted under ipsws/.-# Otherwise reuse an already-extracted copy in the work dir; else remote-extract.-get_kernelcache() {- local build="$1"- if [[ "$build" == local ]]; then- ls ipsws/*/kernelcache.research.vphone600 2>/dev/null | grep -v Restore | head -1- return- fi- local dir="$WORK/$build" kc- kc=$(find "$dir" -name 'kernelcache.research.vphone600' -type f 2>/dev/null | head -1)- if [[ -n "$kc" && -f "$kc" ]]; then echo "$kc"; return 0; fi-- ensure_pcc_info || { echo ""; return 1; }- local url; url=$(resolve_url "$build")- [[ -n "$url" ]] || { echo ""; return 1; }- mkdir -p "$dir"- if ! ipsw extract --kernel --remote "$url" --output "$dir" >> "$WORK/$build.extract.log" 2>&1; then- echo "" ; return 1- fi- find "$dir" -name 'kernelcache.research.vphone600' -type f 2>/dev/null | head -1-}--# --- 5. Run the patcher + validate one kernelcache ---------------------------typeset -A RESULT-overall=0-for build in "${BUILD_LIST[@]}"; do- echo ""- echo "──────────── kernel $build ────────────"- kc=$(get_kernelcache "$build") || true- if [[ -z "$kc" || ! -f "$kc" ]]; then- echo " [-] could not obtain kernelcache (no vphone release / download failed)"- RESULT[$build]="NO-KERNEL"; overall=1; continue- fi- echo " kernel: $kc"-- out="$WORK/$build"; mkdir -p "$out"- if ! "$BIN" patch-component --component kernel-jb \- --input "$kc" --output "$out/kc.patched.bin" --records-out "$out/records.json" \- > "$out/run.log" 2>&1; then- echo " [-] patcher crashed:"; tail -8 "$out/run.log" | sed 's/^/ /'- RESULT[$build]="CRASH"; overall=1; continue- fi-- applied=$(grep -oE "applied [0-9]+ patches" "$out/run.log" | grep -oE "[0-9]+" | head -1 || echo "?")- fails=$(grep -cE "\[-\]" "$out/run.log" || true)- sandbox=$(grep -oE 'sandbox_ext_[0-9]+' "$out/records.json" 2>/dev/null | sort -u | wc -l | tr -d ' ')-- # Every required patch ID must have emitted.- missing=()- for id in "${REQUIRED_IDS[@]}"; do- grep -q "\"$id\"" "$out/records.json" 2>/dev/null || missing+=("$id")- done-- echo " applied: $applied failures: $fails sandbox hooks: $sandbox"- if (( fails == 0 )) && (( ${#missing} == 0 )) && (( sandbox >= 1 )); then- echo " ✅ PASS"- RESULT[$build]="PASS ($applied applied, $sandbox sandbox)"- else- echo " ❌ FAIL"- (( fails > 0 )) && { echo " failures:"; grep -E "\[-\]" "$out/run.log" | sed 's/^/ /'; }- (( ${#missing} )) && echo " missing patch IDs: ${missing[*]}"- (( sandbox < 1 )) && echo " no sandbox hooks emitted"- RESULT[$build]="FAIL"; overall=1- fi-done--# --- 6. Summary matrix --------------------------------------------------------echo ""-echo "════════════════ summary ════════════════"-for build in "${BUILD_LIST[@]}"; do- printf " %-12s %s\n" "$build" "${RESULT[$build]:-?}"-done-echo ""-if (( overall == 0 )); then- echo "ALL KERNELS PASS — every JB hook (incl. Sandbox) applies, backward-compatible."-else- echo "ONE OR MORE KERNELS FAILED — see above."-fi-exit $overall